text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Provide a correct Python 3 solution for this coding contest problem.
For a given weighted undirected graph G(V, E), find the distance of the shortest route that meets the following criteria:
* It is a closed cycle where it ends at the same point it starts.
* The route must go through every edge at least once.
Constraints
* 2 ≤ |V| ≤ 15
* 0 ≤ |E| ≤ 1,000
* 0 ≤ di ≤ 1,000
* si ≠ ti
* The graph is connected
Input
|V| |E|
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
, where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target verticess of i-th edge (undirected) and di represents the distance between si and ti (the i-th edge).
Note that there can be multiple edges between a pair of vertices.
Output
Print the shortest distance in a line.
Examples
Input
4 4
0 1 1
0 2 2
1 3 3
2 3 4
Output
10
Input
4 5
0 1 1
0 2 2
1 3 3
2 3 4
1 2 5
Output
18
Input
2 3
0 1 1
0 1 2
0 1 3
Output
7
"Correct Solution:
```
import sys
f_i = sys.stdin
V, E = map(int, f_i.readline().split())
# adjacency matrix
no_edge = 14001
adj = [[no_edge] * V for i in range(V)]
for i in range(V):
adj[i][i] = 0
odd_b = 0 # bit DP to record odd vertex
ans = 0
# acceptance of input
for l_i in f_i:
s, t, d = map(int, l_i.split())
t_d = min(d, adj[s][t])
adj[s][t] = t_d
adj[t][s] = t_d
odd_b ^= 1 << s
odd_b ^= 1 << t
ans += d
import math
if odd_b:
# Warshall???Floyd Algorithm
for k in range(V):
for i in range(V):
for j in range(V):
adj[i][j] = min(adj[i][j], adj[i][k] + adj[k][j])
# Minimum weighted matching
mw = [no_edge] * (odd_b + 1)
mw[0] = 0
digits = int(math.log2(odd_b)) + 1
for b in range(odd_b):
for i in range(0, digits):
if not (b & (1 << i)):
for j in range(i + 1, digits):
if not (b & (1 << j)):
t_b = b + (1 << i) + (1 << j)
if t_b == t_b & odd_b:
t_w = mw[t_b]
mw[t_b] = min(t_w, mw[b] + adj[i][j])
# Output
ans += mw[odd_b]
print(ans)
else:
print(ans)
```
| 87,500 |
Provide a correct Python 3 solution for this coding contest problem.
For a given weighted undirected graph G(V, E), find the distance of the shortest route that meets the following criteria:
* It is a closed cycle where it ends at the same point it starts.
* The route must go through every edge at least once.
Constraints
* 2 ≤ |V| ≤ 15
* 0 ≤ |E| ≤ 1,000
* 0 ≤ di ≤ 1,000
* si ≠ ti
* The graph is connected
Input
|V| |E|
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
, where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target verticess of i-th edge (undirected) and di represents the distance between si and ti (the i-th edge).
Note that there can be multiple edges between a pair of vertices.
Output
Print the shortest distance in a line.
Examples
Input
4 4
0 1 1
0 2 2
1 3 3
2 3 4
Output
10
Input
4 5
0 1 1
0 2 2
1 3 3
2 3 4
1 2 5
Output
18
Input
2 3
0 1 1
0 1 2
0 1 3
Output
7
"Correct Solution:
```
def warshall_floyd(n, dists):
prev = [t.copy() for t in dists]
for k in range(n):
current = [t.copy() for t in prev]
prev_k = prev[k]
for i in range(n):
prev_i, current_i = prev[i], current[i]
prev_i_k = prev_i[k]
for j in range(n):
current_i[j] = min(prev_i[j], prev_i_k + prev_k[j])
prev = current
return prev
def solve(n, links, total_d, odd_vertices):
if not odd_vertices:
return total_d
d_table = warshall_floyd(n, links)
d_table = [[d for oj, d in enumerate(d_table[oi]) if oj in odd_vertices] for ni, oi in enumerate(odd_vertices)]
ndt = len(d_table)
bit_dict = {1 << i: i for i in range(ndt)}
def minimum_pair(remains):
if not remains:
return 0
b = remains & -remains
remains ^= b
i = bit_dict[b]
return min(minimum_pair(remains ^ (1 << j)) + d_table[i][j] for j in range(ndt) if remains & (1 << j))
return total_d + minimum_pair((1 << ndt) - 1)
v, e = map(int, input().split())
dists = [[float('inf')] * v for _ in range(v)]
for i in range(v):
dists[i][i] = 0
odd_vertices = [0] * v
total_d = 0
for _ in range(e):
s, t, d = map(int, input().split())
dists[s][t] = min(dists[s][t], d)
dists[t][s] = min(dists[t][s], d)
odd_vertices[s] ^= 1
odd_vertices[t] ^= 1
total_d += d
print(solve(v, dists, total_d, [i for i, v in enumerate(odd_vertices) if v]))
```
| 87,501 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a given weighted undirected graph G(V, E), find the distance of the shortest route that meets the following criteria:
* It is a closed cycle where it ends at the same point it starts.
* The route must go through every edge at least once.
Constraints
* 2 ≤ |V| ≤ 15
* 0 ≤ |E| ≤ 1,000
* 0 ≤ di ≤ 1,000
* si ≠ ti
* The graph is connected
Input
|V| |E|
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
, where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target verticess of i-th edge (undirected) and di represents the distance between si and ti (the i-th edge).
Note that there can be multiple edges between a pair of vertices.
Output
Print the shortest distance in a line.
Examples
Input
4 4
0 1 1
0 2 2
1 3 3
2 3 4
Output
10
Input
4 5
0 1 1
0 2 2
1 3 3
2 3 4
1 2 5
Output
18
Input
2 3
0 1 1
0 1 2
0 1 3
Output
7
Submitted Solution:
```
#! /usr/bin/python
# -*- coding: utf-8 -*-
"""Chinese Postman Problem."""
import sys
f_i = sys.stdin
V, E = map(int, f_i.readline().split())
# adjacency matrix
no_edge = 14001
adj = [[no_edge] * V for i in range(V)]
for i in range(V):
adj[i][i] = 0
odd_b = 0 # bit DP to record odd vertex
ans = 0
# acceptance of input
for l_i in f_i:
s, t, d = map(int, l_i.split())
t_d = min(d, adj[s][t])
adj[s][t] = t_d
adj[t][s] = t_d
odd_b ^= 1 << s
odd_b ^= 1 << t
ans += d
# A function to check if the number of 1 is odd in binary notation
def odd_one(n):
ans = 0
while n:
ans ^= (n & 1)
n >>= 1
return ans
import math
if odd_b:
# Warshall???Floyd Algorithm
for k in range(V):
for i in range(V):
for j in range(V):
adj[i][j] = min(adj[i][j], adj[i][k] + adj[k][j])
# Minimum weighted matching
mw = [no_edge] * (odd_b + 1)
mw[0] = 0
digits = int(math.log2(odd_b)) + 1
for b in range(odd_b):
if odd_one(b):
continue
for i in range(0, digits):
if not (b & (1 << i)):
for j in range(i + 1, digits):
if not (b & (1 << j)):
t_b = b + (1 << i) + (1 << j)
if t_b == t_b & odd_b:
t_w = mw[t_b]
mw[t_b] = min(t_w, mw[b] + adj[i][j])
# Output
ans += mw[odd_b]
print(ans)
else:
print(ans)
```
Yes
| 87,502 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a given weighted undirected graph G(V, E), find the distance of the shortest route that meets the following criteria:
* It is a closed cycle where it ends at the same point it starts.
* The route must go through every edge at least once.
Constraints
* 2 ≤ |V| ≤ 15
* 0 ≤ |E| ≤ 1,000
* 0 ≤ di ≤ 1,000
* si ≠ ti
* The graph is connected
Input
|V| |E|
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
, where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target verticess of i-th edge (undirected) and di represents the distance between si and ti (the i-th edge).
Note that there can be multiple edges between a pair of vertices.
Output
Print the shortest distance in a line.
Examples
Input
4 4
0 1 1
0 2 2
1 3 3
2 3 4
Output
10
Input
4 5
0 1 1
0 2 2
1 3 3
2 3 4
1 2 5
Output
18
Input
2 3
0 1 1
0 1 2
0 1 3
Output
7
Submitted Solution:
```
def warshall_floyd(n, dists):
prev = [t.copy() for t in dists]
for k in range(n):
current = [t.copy() for t in prev]
prev_k = prev[k]
for i in range(n):
prev_i, current_i = prev[i], current[i]
prev_i_k = prev_i[k]
for j in range(n):
current_i[j] = min(prev_i[j], prev_i_k + prev_k[j])
prev = current
return prev
def solve(n, links, total_d, odd_vertices):
if not odd_vertices:
return total_d
d_table = warshall_floyd(n, links)
d_table = [[d for oj, d in enumerate(d_table[oi]) if oj in odd_vertices] for ni, oi in enumerate(odd_vertices)] ## odd_verticesのみ抽出したwarshall_floydテーブルになおす
ndt = len(d_table)
bit_dict = {1 << i: i for i in range(ndt)}
def minimum_pair(remains):
if not remains:
return 0
b = remains & -remains ## 1であるbitのうち一番下のbit 1桁をとってくる
remains ^= b ## bで選んだbitを反転 こいつは1確定なので、それが0になるってこと
i = bit_dict[b] ## i=2**b
return min(minimum_pair(remains ^ (1 << j)) + d_table[i][j] for j in range(ndt) if remains & (1 << j)) ## remainsは訪れてないとこのbit管理、iが現在地点、jが次の奇点、これで末尾の1から各odd_verticesに再帰で訪れていく odd_vertices個分の辺を足す
return total_d + minimum_pair((1 << ndt) - 1)
v, e = map(int, input().split())
dists = [[float('inf')] * v for _ in range(v)]
for i in range(v):
dists[i][i] = 0
odd_vertices = [0] * v
total_d = 0
for _ in range(e):
s, t, d = map(int, input().split())
dists[s][t] = min(dists[s][t], d)
dists[t][s] = min(dists[t][s], d)
odd_vertices[s] ^= 1
odd_vertices[t] ^= 1
total_d += d
print(solve(v, dists, total_d, [i for i, v in enumerate(odd_vertices) if v]))
```
Yes
| 87,503 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a given weighted undirected graph G(V, E), find the distance of the shortest route that meets the following criteria:
* It is a closed cycle where it ends at the same point it starts.
* The route must go through every edge at least once.
Constraints
* 2 ≤ |V| ≤ 15
* 0 ≤ |E| ≤ 1,000
* 0 ≤ di ≤ 1,000
* si ≠ ti
* The graph is connected
Input
|V| |E|
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
, where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target verticess of i-th edge (undirected) and di represents the distance between si and ti (the i-th edge).
Note that there can be multiple edges between a pair of vertices.
Output
Print the shortest distance in a line.
Examples
Input
4 4
0 1 1
0 2 2
1 3 3
2 3 4
Output
10
Input
4 5
0 1 1
0 2 2
1 3 3
2 3 4
1 2 5
Output
18
Input
2 3
0 1 1
0 1 2
0 1 3
Output
7
Submitted Solution:
```
import sys
f_i = sys.stdin
V, E = map(int, f_i.readline().split())
# adjacency matrix
no_edge = 14001
adj = [[no_edge] * V for i in range(V)]
for i in range(V):
adj[i][i] = 0
odd_b = 0 # bit DP to record odd vertex
ans = 0
# acceptance of input
for l_i in f_i:
s, t, d = map(int, l_i.split())
t_d = min(d, adj[s][t])
adj[s][t] = t_d
adj[t][s] = t_d
odd_b ^= 1 << s
odd_b ^= 1 << t
ans += d
# A function to check if the number of 1 in binary notation is odd
def odd_one(n):
ans = 0
while n:
ans ^= (n & 1)
n >>= 1
return ans
import math
if odd_b:
# Warshall???Floyd Algorithm
for k in range(V):
for i in range(V):
for j in range(V):
adj[i][j] = min(adj[i][j], adj[i][k] + adj[k][j])
# Minimum weighted matching
mw = [no_edge] * (odd_b + 1)
mw[0] = 0
digits = int(math.log2(odd_b)) + 1
for b, mw_b in enumerate(mw):
if odd_one(b):
continue
for i in range(0, digits):
if b & (1 << i):
continue
for j in range(i + 1, digits):
if b & (1 << j):
continue
t_b = b + (1 << i) + (1 << j)
if t_b == t_b & odd_b:
t_w = mw[t_b]
mw[t_b] = min(t_w, mw_b + adj[i][j])
# Output
ans += mw[odd_b]
print(ans)
else:
print(ans)
```
Yes
| 87,504 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a given weighted undirected graph G(V, E), find the distance of the shortest route that meets the following criteria:
* It is a closed cycle where it ends at the same point it starts.
* The route must go through every edge at least once.
Constraints
* 2 ≤ |V| ≤ 15
* 0 ≤ |E| ≤ 1,000
* 0 ≤ di ≤ 1,000
* si ≠ ti
* The graph is connected
Input
|V| |E|
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
, where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target verticess of i-th edge (undirected) and di represents the distance between si and ti (the i-th edge).
Note that there can be multiple edges between a pair of vertices.
Output
Print the shortest distance in a line.
Examples
Input
4 4
0 1 1
0 2 2
1 3 3
2 3 4
Output
10
Input
4 5
0 1 1
0 2 2
1 3 3
2 3 4
1 2 5
Output
18
Input
2 3
0 1 1
0 1 2
0 1 3
Output
7
Submitted Solution:
```
def warshall_floyd(distance_table, point_size):
for k in range(point_size):
for i in range(point_size):
for j in range(point_size):
if distance_table[i][j] > distance_table[i][k] + distance_table[k][j]:
distance_table[i][j] = distance_table[i][k] + distance_table[k][j]
class bit:
__hash = 0x03F566ED27179461
__mask64 = (1 << 64) - 1
__table = bit.__createtable()
def __createtable():
table = [None] * 64
hash = bit.__hash
for i in range(64):
table[hash >> 58] = i
hash = (hash << 1) & bit.__mask64
return table
def number_of_trailing_zeros(x):
if x == 0:return 64
return bit.__table[((bit.lowest_one(x) * bit.__hash) & bit.__mask64) >> 58]
def lowest_one(i):
return i & -i
def ccp(distance_table, point_size, v):
if v:
i = bit.number_of_trailing_zeros(v)
v ^= (1 << i)
return min(ccp(distance_table, point_size, v ^ (1 << j)) + distance_table[i][j] for j in range(point_size) if v & 1 << j)
else:
return 0
point_size, e = map(int, readline().split())
distance_table = [[float('inf')] * point_size for _ in range(point_size)]
cost = 0
v = 0
for _ in range(e):
s, t, d = map(int, readline().split())
distance_table[s][t] = min(distance_table[s][t], d)
distance_table[t][s] = min(distance_table[t][s], d)
v ^= 1 << s ^ 1 << t
cost += d
warshall_floyd(distance_table, point_size)
print(cost + ccp(distance_table, point_size, v))
```
No
| 87,505 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a given weighted undirected graph G(V, E), find the distance of the shortest route that meets the following criteria:
* It is a closed cycle where it ends at the same point it starts.
* The route must go through every edge at least once.
Constraints
* 2 ≤ |V| ≤ 15
* 0 ≤ |E| ≤ 1,000
* 0 ≤ di ≤ 1,000
* si ≠ ti
* The graph is connected
Input
|V| |E|
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
, where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target verticess of i-th edge (undirected) and di represents the distance between si and ti (the i-th edge).
Note that there can be multiple edges between a pair of vertices.
Output
Print the shortest distance in a line.
Examples
Input
4 4
0 1 1
0 2 2
1 3 3
2 3 4
Output
10
Input
4 5
0 1 1
0 2 2
1 3 3
2 3 4
1 2 5
Output
18
Input
2 3
0 1 1
0 1 2
0 1 3
Output
7
Submitted Solution:
```
def warshall_floyd(n, links):
prev = [t.copy() for t in links]
for i in range(n):
prev[i][i] = 0
for k in range(n - 1):
current = [t.copy() for t in prev]
prev_k = prev[k]
for i in range(n):
prev_i, current_i = prev[i], current[i]
prev_i_k = prev_i[k]
for j in range(n):
current_i[j] = min(prev_i[j], prev_i_k + prev_k[j])
prev = current
return prev
def solve(n, links, total_d, odd_vertices):
if not odd_vertices:
return total_d
d_table = warshall_floyd(n, links)
d_table = [[d for oj, d in enumerate(d_table[oi]) if oj in odd_vertices] for ni, oi in enumerate(odd_vertices)]
ndt = len(d_table)
bit_dict = {1 << i: i for i in range(ndt)}
def minimum_pair(remains):
if not remains:
return 0
b = remains & -remains
remains ^= b
i = bit_dict[b]
return min(minimum_pair(remains ^ (1 << j)) + d_table[i][j] for j in range(ndt) if remains & (1 << j))
return total_d + minimum_pair((1 << ndt) - 1)
v, e = map(int, input().split())
links = [[float('inf')] * v for _ in range(v)]
odd_vertices = [0] * v
total_d = 0
for _ in range(e):
s, t, d = map(int, input().split())
links[s][t] = min(links[s][t], d)
links[t][s] = min(links[t][s], d)
odd_vertices[s] ^= 1
odd_vertices[t] ^= 1
total_d += d
print(solve(v, links, total_d, [i for i, v in enumerate(odd_vertices) if v]))
```
No
| 87,506 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a given weighted undirected graph G(V, E), find the distance of the shortest route that meets the following criteria:
* It is a closed cycle where it ends at the same point it starts.
* The route must go through every edge at least once.
Constraints
* 2 ≤ |V| ≤ 15
* 0 ≤ |E| ≤ 1,000
* 0 ≤ di ≤ 1,000
* si ≠ ti
* The graph is connected
Input
|V| |E|
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
, where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target verticess of i-th edge (undirected) and di represents the distance between si and ti (the i-th edge).
Note that there can be multiple edges between a pair of vertices.
Output
Print the shortest distance in a line.
Examples
Input
4 4
0 1 1
0 2 2
1 3 3
2 3 4
Output
10
Input
4 5
0 1 1
0 2 2
1 3 3
2 3 4
1 2 5
Output
18
Input
2 3
0 1 1
0 1 2
0 1 3
Output
7
Submitted Solution:
```
from collections import defaultdict
v, e = map(int, input().split())
links = [defaultdict(int) for _ in range(v)]
bests = [None] * (1 << v)
for _ in range(e):
s, t, d = map(int, input().split())
links[s][t] = max(links[s][t], d)
bests[0] = {0: 0}
for visited, best in enumerate(bests):
if best is None:
continue
for last, cost in best.items():
for t, d in links[last].items():
new_visited = visited | (1 << t)
if visited == new_visited:
continue
new_best = bests[new_visited]
if new_best is None:
bests[new_visited] = defaultdict(lambda: 15001, [(t, cost + d)])
else:
new_best[t] = min(new_best[t], cost + d)
print(bests[-1][0])
```
No
| 87,507 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a given weighted undirected graph G(V, E), find the distance of the shortest route that meets the following criteria:
* It is a closed cycle where it ends at the same point it starts.
* The route must go through every edge at least once.
Constraints
* 2 ≤ |V| ≤ 15
* 0 ≤ |E| ≤ 1,000
* 0 ≤ di ≤ 1,000
* si ≠ ti
* The graph is connected
Input
|V| |E|
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
, where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target verticess of i-th edge (undirected) and di represents the distance between si and ti (the i-th edge).
Note that there can be multiple edges between a pair of vertices.
Output
Print the shortest distance in a line.
Examples
Input
4 4
0 1 1
0 2 2
1 3 3
2 3 4
Output
10
Input
4 5
0 1 1
0 2 2
1 3 3
2 3 4
1 2 5
Output
18
Input
2 3
0 1 1
0 1 2
0 1 3
Output
7
Submitted Solution:
```
from collections import defaultdict
v, e = map(int, input().split())
links = [defaultdict(int) for _ in range(v)]
bests = [None] * (1 << v)
for _ in range(e):
s, t, d = map(int, input().split())
links[s][t] = max(links[s][t], d)
links[t][s] = max(links[t][s], d)
bests[0] = {0: 0}
for visited, best in enumerate(bests):
if best is None:
continue
for last, cost in best.items():
for t, d in links[last].items():
new_visited = visited | (1 << t)
if visited == new_visited:
continue
new_best = bests[new_visited]
if new_best is None:
bests[new_visited] = defaultdict(lambda: 15001, {t: cost + d})
else:
new_best[t] = min(new_best[t], cost + d)
print(bests[-1][0])
```
No
| 87,508 |
Provide a correct Python 3 solution for this coding contest problem.
Find the least common multiple (LCM) of given n integers.
Constraints
* 2 ≤ n ≤ 10
* 1 ≤ ai ≤ 1000
* Product of given integers ai(i = 1, 2, ... n) does not exceed 231-1
Input
n
a1 a2 ... an
n is given in the first line. Then, n integers are given in the second line.
Output
Print the least common multiple of the given integers in a line.
Examples
Input
3
3 4 6
Output
12
Input
4
1 2 3 5
Output
30
"Correct Solution:
```
import sys,collections as cl,bisect as bs
sys.setrecursionlimit(100000)
Max = sys.maxsize
def l(): #intのlist
return list(map(int,input().split()))
def m(): #複数文字
return map(int,input().split())
def onem(): #Nとかの取得
return int(input())
def s(x): #圧縮
a = []
aa = x[0]
su = 1
for i in range(len(x)-1):
if aa == x[i+1]:
a.append([aa,su])
aa = x[i+1]
su = 1
else:
su += 1
a.append([aa,su])
return a
def jo(x): #listをスペースごとに分ける
return " ".join(map(str,x))
def max2(x): #他のときもどうように作成可能
return max(map(max,x))
import fractions
from functools import reduce
def gcd(*numbers):
return reduce(fractions.gcd, numbers)
def gcd_list(numbers):
return reduce(fractions.gcd, numbers)
def lcm_base(x, y):
return (x * y) // fractions.gcd(x, y)
def lcm(*numbers):
return reduce(lcm_base, numbers, 1)
def lcm_list(numbers):
return reduce(lcm_base, numbers, 1)
n = onem()
l = l()
print(lcm_list(l))
```
| 87,509 |
Provide a correct Python 3 solution for this coding contest problem.
Find the least common multiple (LCM) of given n integers.
Constraints
* 2 ≤ n ≤ 10
* 1 ≤ ai ≤ 1000
* Product of given integers ai(i = 1, 2, ... n) does not exceed 231-1
Input
n
a1 a2 ... an
n is given in the first line. Then, n integers are given in the second line.
Output
Print the least common multiple of the given integers in a line.
Examples
Input
3
3 4 6
Output
12
Input
4
1 2 3 5
Output
30
"Correct Solution:
```
# python template for atcoder1
from functools import reduce
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline
def gcd(a, b):
"""
return gcd of a,b
ユークリッド
"""
while b:
a, b = b, a % b
return a
def list_gcd(l):
"""
l: list
l のgcd を返す
"""
return reduce(gcd, l)
def lcm(a, b):
"""
a,bの最小公倍数
"""
return a*b//gcd(a, b)
def list_lcm(l):
"""
l:list
lのlcmを返す
"""
return reduce(lcm, l)
n = int(input())
l = list(map(int, input().split()))
print(list_lcm(l))
```
| 87,510 |
Provide a correct Python 3 solution for this coding contest problem.
Find the least common multiple (LCM) of given n integers.
Constraints
* 2 ≤ n ≤ 10
* 1 ≤ ai ≤ 1000
* Product of given integers ai(i = 1, 2, ... n) does not exceed 231-1
Input
n
a1 a2 ... an
n is given in the first line. Then, n integers are given in the second line.
Output
Print the least common multiple of the given integers in a line.
Examples
Input
3
3 4 6
Output
12
Input
4
1 2 3 5
Output
30
"Correct Solution:
```
from functools import reduce
def gcd(a,b): #最小公約数
if ((a%b) == 0 ):
return b
else:
return (gcd(b,a%b))
def lcm(a,b):
return a * b // gcd(a,b)
n = int(input())
l = list(map(int,input().split()))
print (reduce(lcm,l))
```
| 87,511 |
Provide a correct Python 3 solution for this coding contest problem.
Find the least common multiple (LCM) of given n integers.
Constraints
* 2 ≤ n ≤ 10
* 1 ≤ ai ≤ 1000
* Product of given integers ai(i = 1, 2, ... n) does not exceed 231-1
Input
n
a1 a2 ... an
n is given in the first line. Then, n integers are given in the second line.
Output
Print the least common multiple of the given integers in a line.
Examples
Input
3
3 4 6
Output
12
Input
4
1 2 3 5
Output
30
"Correct Solution:
```
import math
from functools import reduce
n=int(input())
z=list(map(int,input().split()))
def lcm_b(x,y):
return (x*y)//(math.gcd(x,y))
def lcm(*z):
return reduce(lcm_b,z,1)
print(lcm(*z))
```
| 87,512 |
Provide a correct Python 3 solution for this coding contest problem.
Find the least common multiple (LCM) of given n integers.
Constraints
* 2 ≤ n ≤ 10
* 1 ≤ ai ≤ 1000
* Product of given integers ai(i = 1, 2, ... n) does not exceed 231-1
Input
n
a1 a2 ... an
n is given in the first line. Then, n integers are given in the second line.
Output
Print the least common multiple of the given integers in a line.
Examples
Input
3
3 4 6
Output
12
Input
4
1 2 3 5
Output
30
"Correct Solution:
```
n = int(input())
A = tuple(map(int, input().split()))
def gcd(a, b):
if a < b:
a, b = b, a
while b != 0:
a, b = b, a % b
return a
b = A[0]
for a in A:
b = a * b // gcd(a, b)
print(b)
```
| 87,513 |
Provide a correct Python 3 solution for this coding contest problem.
Find the least common multiple (LCM) of given n integers.
Constraints
* 2 ≤ n ≤ 10
* 1 ≤ ai ≤ 1000
* Product of given integers ai(i = 1, 2, ... n) does not exceed 231-1
Input
n
a1 a2 ... an
n is given in the first line. Then, n integers are given in the second line.
Output
Print the least common multiple of the given integers in a line.
Examples
Input
3
3 4 6
Output
12
Input
4
1 2 3 5
Output
30
"Correct Solution:
```
import math
input()
b = 1
for a in [int(x) for x in input().split()]:
b = a * b // math.gcd(a, b)
print(b)
```
| 87,514 |
Provide a correct Python 3 solution for this coding contest problem.
Find the least common multiple (LCM) of given n integers.
Constraints
* 2 ≤ n ≤ 10
* 1 ≤ ai ≤ 1000
* Product of given integers ai(i = 1, 2, ... n) does not exceed 231-1
Input
n
a1 a2 ... an
n is given in the first line. Then, n integers are given in the second line.
Output
Print the least common multiple of the given integers in a line.
Examples
Input
3
3 4 6
Output
12
Input
4
1 2 3 5
Output
30
"Correct Solution:
```
from fractions import gcd
def lcm(a,n):
x = a[0]
for i in range(1,n):
x = (x * a[i]) // gcd(x,a[i])
return x
n = int(input())
a = list(map(int,input().split()))
print(lcm(a,n))
```
| 87,515 |
Provide a correct Python 3 solution for this coding contest problem.
Find the least common multiple (LCM) of given n integers.
Constraints
* 2 ≤ n ≤ 10
* 1 ≤ ai ≤ 1000
* Product of given integers ai(i = 1, 2, ... n) does not exceed 231-1
Input
n
a1 a2 ... an
n is given in the first line. Then, n integers are given in the second line.
Output
Print the least common multiple of the given integers in a line.
Examples
Input
3
3 4 6
Output
12
Input
4
1 2 3 5
Output
30
"Correct Solution:
```
import fractions
n=int(input())
a=list(map(int, input().split()))
b=a[0]
for i in range(1, n):
b=b*a[i]//fractions.gcd(b, a[i])
print(b)
```
| 87,516 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Find the least common multiple (LCM) of given n integers.
Constraints
* 2 ≤ n ≤ 10
* 1 ≤ ai ≤ 1000
* Product of given integers ai(i = 1, 2, ... n) does not exceed 231-1
Input
n
a1 a2 ... an
n is given in the first line. Then, n integers are given in the second line.
Output
Print the least common multiple of the given integers in a line.
Examples
Input
3
3 4 6
Output
12
Input
4
1 2 3 5
Output
30
Submitted Solution:
```
def gcd(a,b):
while b != 0:
a,b = b,a%b
return a
def lcm(a,b):
return a*b//gcd(a,b)
N = int(input())
a = list(map(int,input().split()))
f = a[0]
for i in range(1,N):
f = lcm(f,a[i])
print(f)
```
Yes
| 87,517 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Find the least common multiple (LCM) of given n integers.
Constraints
* 2 ≤ n ≤ 10
* 1 ≤ ai ≤ 1000
* Product of given integers ai(i = 1, 2, ... n) does not exceed 231-1
Input
n
a1 a2 ... an
n is given in the first line. Then, n integers are given in the second line.
Output
Print the least common multiple of the given integers in a line.
Examples
Input
3
3 4 6
Output
12
Input
4
1 2 3 5
Output
30
Submitted Solution:
```
n=int(input())
*a,=map(int, input().split())
def gcd(a,b):
while b: a,b=b,a%b
return a
def lcm(a,b): return a*b//gcd(a,b)
ans = 1
for ai in a:
ans = lcm(ans, ai)
print(ans)
```
Yes
| 87,518 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Find the least common multiple (LCM) of given n integers.
Constraints
* 2 ≤ n ≤ 10
* 1 ≤ ai ≤ 1000
* Product of given integers ai(i = 1, 2, ... n) does not exceed 231-1
Input
n
a1 a2 ... an
n is given in the first line. Then, n integers are given in the second line.
Output
Print the least common multiple of the given integers in a line.
Examples
Input
3
3 4 6
Output
12
Input
4
1 2 3 5
Output
30
Submitted Solution:
```
import math
def LCM(x, y):
return (x * y) // math.gcd(x, y)
n = int(input())
a = list(map(int,input().split()))
lcm = 1
for ai in a:
lcm =LCM(ai,lcm)
print(lcm)
```
Yes
| 87,519 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Find the least common multiple (LCM) of given n integers.
Constraints
* 2 ≤ n ≤ 10
* 1 ≤ ai ≤ 1000
* Product of given integers ai(i = 1, 2, ... n) does not exceed 231-1
Input
n
a1 a2 ... an
n is given in the first line. Then, n integers are given in the second line.
Output
Print the least common multiple of the given integers in a line.
Examples
Input
3
3 4 6
Output
12
Input
4
1 2 3 5
Output
30
Submitted Solution:
```
from functools import reduce
def gcd(a, b):
while b:
a, b = b, a % b
return a
def lcm(x, y):
# saisyou koubaisuu
return (x * y) // gcd(x, y)
def lcm_list(numbers):
return reduce(lcm, numbers)
n = int(input())
a = list(map(int, input().split()))
print(lcm_list(a))
```
Yes
| 87,520 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Find the least common multiple (LCM) of given n integers.
Constraints
* 2 ≤ n ≤ 10
* 1 ≤ ai ≤ 1000
* Product of given integers ai(i = 1, 2, ... n) does not exceed 231-1
Input
n
a1 a2 ... an
n is given in the first line. Then, n integers are given in the second line.
Output
Print the least common multiple of the given integers in a line.
Examples
Input
3
3 4 6
Output
12
Input
4
1 2 3 5
Output
30
Submitted Solution:
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
input:
4
1 2 3 5
output:
30
"""
import sys
import math
from functools import reduce
def gcd(x, y):
if x < y:
x, y = y, x
while y > 0:
r = x % y
x = y
y = r
return x
def lcm(a, b):
return a * b // math.gcd(a, b)
def solve(_n_list):
return reduce(lcm, _n_list)
if __name__ == '__main__':
_input = sys.stdin.readlines()
cnt = int(_input[0])
n_list = tuple(map(int, _input[1].split()))
print(solve(n_list))
```
No
| 87,521 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Find the least common multiple (LCM) of given n integers.
Constraints
* 2 ≤ n ≤ 10
* 1 ≤ ai ≤ 1000
* Product of given integers ai(i = 1, 2, ... n) does not exceed 231-1
Input
n
a1 a2 ... an
n is given in the first line. Then, n integers are given in the second line.
Output
Print the least common multiple of the given integers in a line.
Examples
Input
3
3 4 6
Output
12
Input
4
1 2 3 5
Output
30
Submitted Solution:
```
def GCD(x,y):
r = x%y
if r == 0:
return y
else:
return GCD(y,r)
n = int(input())
list1 = list(map(int,input().split()))
result = list1[0]
for i in list1[1:]:
result = result*i/GCD(i,result)
print(result)
```
No
| 87,522 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Find the least common multiple (LCM) of given n integers.
Constraints
* 2 ≤ n ≤ 10
* 1 ≤ ai ≤ 1000
* Product of given integers ai(i = 1, 2, ... n) does not exceed 231-1
Input
n
a1 a2 ... an
n is given in the first line. Then, n integers are given in the second line.
Output
Print the least common multiple of the given integers in a line.
Examples
Input
3
3 4 6
Output
12
Input
4
1 2 3 5
Output
30
Submitted Solution:
```
import numpy
```
No
| 87,523 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Find the least common multiple (LCM) of given n integers.
Constraints
* 2 ≤ n ≤ 10
* 1 ≤ ai ≤ 1000
* Product of given integers ai(i = 1, 2, ... n) does not exceed 231-1
Input
n
a1 a2 ... an
n is given in the first line. Then, n integers are given in the second line.
Output
Print the least common multiple of the given integers in a line.
Examples
Input
3
3 4 6
Output
12
Input
4
1 2 3 5
Output
30
Submitted Solution:
```
from math import sqrt, floor
from collections import deque
from functools import reduce
from operator import mul
def divide(p):
global a, lcm, limit
c, d, f = a.copy(), set(), False
while True:
b = set(i for i in c if not (i % p))
d |= c - b
b = set(i // p for i in b)
if not b:
a = d
break
lcm.append(p)
c = b
f = True
if f:
limit = floor(sqrt(max(c)))
n, a = int(input()), set(map(int, input().split()))
p, lcm, limit = 3, deque(), floor(sqrt(max(a)))
divide(2)
while p <= limit:
divide(p)
p += 2
print(reduce(mul, lcm, 1) * reduce(mul, a, 1))
```
No
| 87,524 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on n - 2 intermediate planets. Formally: we number all the planets from 1 to n. 1 is Earth, n is Mars. Natasha will make exactly n flights: 1 → 2 → … n → 1.
Flight from x to y consists of two phases: take-off from planet x and landing to planet y. This way, the overall itinerary of the trip will be: the 1-st planet → take-off from the 1-st planet → landing to the 2-nd planet → 2-nd planet → take-off from the 2-nd planet → … → landing to the n-th planet → the n-th planet → take-off from the n-th planet → landing to the 1-st planet → the 1-st planet.
The mass of the rocket together with all the useful cargo (but without fuel) is m tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that 1 ton of fuel can lift off a_i tons of rocket from the i-th planet or to land b_i tons of rocket onto the i-th planet.
For example, if the weight of rocket is 9 tons, weight of fuel is 3 tons and take-off coefficient is 8 (a_i = 8), then 1.5 tons of fuel will be burnt (since 1.5 ⋅ 8 = 9 + 3). The new weight of fuel after take-off will be 1.5 tons.
Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.
Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
Input
The first line contains a single integer n (2 ≤ n ≤ 1000) — number of planets.
The second line contains the only integer m (1 ≤ m ≤ 1000) — weight of the payload.
The third line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 1000), where a_i is the number of tons, which can be lifted off by one ton of fuel.
The fourth line contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ 1000), where b_i is the number of tons, which can be landed by one ton of fuel.
It is guaranteed, that if Natasha can make a flight, then it takes no more than 10^9 tons of fuel.
Output
If Natasha can fly to Mars through (n - 2) planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number -1.
It is guaranteed, that if Natasha can make a flight, then it takes no more than 10^9 tons of fuel.
The answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}. Formally, let your answer be p, and the jury's answer be q. Your answer is considered correct if \frac{|p - q|}{max{(1, |q|)}} ≤ 10^{-6}.
Examples
Input
2
12
11 8
7 5
Output
10.0000000000
Input
3
1
1 4 1
2 5 3
Output
-1
Input
6
2
4 6 3 3 5 6
2 6 3 6 5 3
Output
85.4800000000
Note
Let's consider the first example.
Initially, the mass of a rocket with fuel is 22 tons.
* At take-off from Earth one ton of fuel can lift off 11 tons of cargo, so to lift off 22 tons you need to burn 2 tons of fuel. Remaining weight of the rocket with fuel is 20 tons.
* During landing on Mars, one ton of fuel can land 5 tons of cargo, so for landing 20 tons you will need to burn 4 tons of fuel. There will be 16 tons of the rocket with fuel remaining.
* While taking off from Mars, one ton of fuel can raise 8 tons of cargo, so to lift off 16 tons you will need to burn 2 tons of fuel. There will be 14 tons of rocket with fuel after that.
* During landing on Earth, one ton of fuel can land 7 tons of cargo, so for landing 14 tons you will need to burn 2 tons of fuel. Remaining weight is 12 tons, that is, a rocket without any fuel.
In the second case, the rocket will not be able even to take off from Earth.
Tags: binary search, math
Correct Solution:
```
n = int(input())
m = int(input())
aj = list(map(int, input().split()))
bj = list(map(int, input().split()))
res = 0
if not (1 in aj) and not (1 in bj):
i = 0
for num in range(len(aj) * 2):
if num % 2 == 0:
i -= 1
x = (m + res) / (bj[i] - 1)
res += x
else:
x = (m + res) / (aj[i] - 1)
res += x
print(res)
else:
print('-1')
```
| 87,525 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on n - 2 intermediate planets. Formally: we number all the planets from 1 to n. 1 is Earth, n is Mars. Natasha will make exactly n flights: 1 → 2 → … n → 1.
Flight from x to y consists of two phases: take-off from planet x and landing to planet y. This way, the overall itinerary of the trip will be: the 1-st planet → take-off from the 1-st planet → landing to the 2-nd planet → 2-nd planet → take-off from the 2-nd planet → … → landing to the n-th planet → the n-th planet → take-off from the n-th planet → landing to the 1-st planet → the 1-st planet.
The mass of the rocket together with all the useful cargo (but without fuel) is m tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that 1 ton of fuel can lift off a_i tons of rocket from the i-th planet or to land b_i tons of rocket onto the i-th planet.
For example, if the weight of rocket is 9 tons, weight of fuel is 3 tons and take-off coefficient is 8 (a_i = 8), then 1.5 tons of fuel will be burnt (since 1.5 ⋅ 8 = 9 + 3). The new weight of fuel after take-off will be 1.5 tons.
Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.
Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
Input
The first line contains a single integer n (2 ≤ n ≤ 1000) — number of planets.
The second line contains the only integer m (1 ≤ m ≤ 1000) — weight of the payload.
The third line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 1000), where a_i is the number of tons, which can be lifted off by one ton of fuel.
The fourth line contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ 1000), where b_i is the number of tons, which can be landed by one ton of fuel.
It is guaranteed, that if Natasha can make a flight, then it takes no more than 10^9 tons of fuel.
Output
If Natasha can fly to Mars through (n - 2) planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number -1.
It is guaranteed, that if Natasha can make a flight, then it takes no more than 10^9 tons of fuel.
The answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}. Formally, let your answer be p, and the jury's answer be q. Your answer is considered correct if \frac{|p - q|}{max{(1, |q|)}} ≤ 10^{-6}.
Examples
Input
2
12
11 8
7 5
Output
10.0000000000
Input
3
1
1 4 1
2 5 3
Output
-1
Input
6
2
4 6 3 3 5 6
2 6 3 6 5 3
Output
85.4800000000
Note
Let's consider the first example.
Initially, the mass of a rocket with fuel is 22 tons.
* At take-off from Earth one ton of fuel can lift off 11 tons of cargo, so to lift off 22 tons you need to burn 2 tons of fuel. Remaining weight of the rocket with fuel is 20 tons.
* During landing on Mars, one ton of fuel can land 5 tons of cargo, so for landing 20 tons you will need to burn 4 tons of fuel. There will be 16 tons of the rocket with fuel remaining.
* While taking off from Mars, one ton of fuel can raise 8 tons of cargo, so to lift off 16 tons you will need to burn 2 tons of fuel. There will be 14 tons of rocket with fuel after that.
* During landing on Earth, one ton of fuel can land 7 tons of cargo, so for landing 14 tons you will need to burn 2 tons of fuel. Remaining weight is 12 tons, that is, a rocket without any fuel.
In the second case, the rocket will not be able even to take off from Earth.
Tags: binary search, math
Correct Solution:
```
import sys
n = int(input()) # number planets
m = int(input()) # weight of payload
a = list(map(int,input().split())) # tons lifted
b = list(map(int,input().split())) # tons landed
# no more than 10**9 tons of fuel
def get_landing(w,stage):
#w +x = y*x
#x = w / (y-1)
return w/ (b[stage]-1)
def get_takeoff(w,stage):
return w/ (a[stage]-1)
try:
total_fuel = 0
land_earth = get_landing(m,0)
total_fuel += land_earth
m += land_earth
for i in range(n-1,0,-1):
take = get_takeoff(m,i)
m += take
total_fuel += take
land = get_landing(m,i)
total_fuel += land
m += land
total_fuel += get_takeoff(m,0)
print (total_fuel)
except:
print (-1)
```
| 87,526 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on n - 2 intermediate planets. Formally: we number all the planets from 1 to n. 1 is Earth, n is Mars. Natasha will make exactly n flights: 1 → 2 → … n → 1.
Flight from x to y consists of two phases: take-off from planet x and landing to planet y. This way, the overall itinerary of the trip will be: the 1-st planet → take-off from the 1-st planet → landing to the 2-nd planet → 2-nd planet → take-off from the 2-nd planet → … → landing to the n-th planet → the n-th planet → take-off from the n-th planet → landing to the 1-st planet → the 1-st planet.
The mass of the rocket together with all the useful cargo (but without fuel) is m tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that 1 ton of fuel can lift off a_i tons of rocket from the i-th planet or to land b_i tons of rocket onto the i-th planet.
For example, if the weight of rocket is 9 tons, weight of fuel is 3 tons and take-off coefficient is 8 (a_i = 8), then 1.5 tons of fuel will be burnt (since 1.5 ⋅ 8 = 9 + 3). The new weight of fuel after take-off will be 1.5 tons.
Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.
Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
Input
The first line contains a single integer n (2 ≤ n ≤ 1000) — number of planets.
The second line contains the only integer m (1 ≤ m ≤ 1000) — weight of the payload.
The third line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 1000), where a_i is the number of tons, which can be lifted off by one ton of fuel.
The fourth line contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ 1000), where b_i is the number of tons, which can be landed by one ton of fuel.
It is guaranteed, that if Natasha can make a flight, then it takes no more than 10^9 tons of fuel.
Output
If Natasha can fly to Mars through (n - 2) planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number -1.
It is guaranteed, that if Natasha can make a flight, then it takes no more than 10^9 tons of fuel.
The answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}. Formally, let your answer be p, and the jury's answer be q. Your answer is considered correct if \frac{|p - q|}{max{(1, |q|)}} ≤ 10^{-6}.
Examples
Input
2
12
11 8
7 5
Output
10.0000000000
Input
3
1
1 4 1
2 5 3
Output
-1
Input
6
2
4 6 3 3 5 6
2 6 3 6 5 3
Output
85.4800000000
Note
Let's consider the first example.
Initially, the mass of a rocket with fuel is 22 tons.
* At take-off from Earth one ton of fuel can lift off 11 tons of cargo, so to lift off 22 tons you need to burn 2 tons of fuel. Remaining weight of the rocket with fuel is 20 tons.
* During landing on Mars, one ton of fuel can land 5 tons of cargo, so for landing 20 tons you will need to burn 4 tons of fuel. There will be 16 tons of the rocket with fuel remaining.
* While taking off from Mars, one ton of fuel can raise 8 tons of cargo, so to lift off 16 tons you will need to burn 2 tons of fuel. There will be 14 tons of rocket with fuel after that.
* During landing on Earth, one ton of fuel can land 7 tons of cargo, so for landing 14 tons you will need to burn 2 tons of fuel. Remaining weight is 12 tons, that is, a rocket without any fuel.
In the second case, the rocket will not be able even to take off from Earth.
Tags: binary search, math
Correct Solution:
```
n = int(input())
m = int(input())
coeffs = []
coeffs.append(list(map(int, input().split())))
coeffs.append(list(map(int, input().split())))
coeffs[1].append(coeffs[1][0])
m_orig = m
#print(coeffs)
def getFuel():
global m
for i in range(n):
for parity in range(2):
coeff = coeffs[1-parity][-1-i]
if coeff == 1:
return -1
else:
f = m / (coeff-1)
m = m+f
#print(m, coeff)
return m - m_orig
print(getFuel())
```
| 87,527 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on n - 2 intermediate planets. Formally: we number all the planets from 1 to n. 1 is Earth, n is Mars. Natasha will make exactly n flights: 1 → 2 → … n → 1.
Flight from x to y consists of two phases: take-off from planet x and landing to planet y. This way, the overall itinerary of the trip will be: the 1-st planet → take-off from the 1-st planet → landing to the 2-nd planet → 2-nd planet → take-off from the 2-nd planet → … → landing to the n-th planet → the n-th planet → take-off from the n-th planet → landing to the 1-st planet → the 1-st planet.
The mass of the rocket together with all the useful cargo (but without fuel) is m tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that 1 ton of fuel can lift off a_i tons of rocket from the i-th planet or to land b_i tons of rocket onto the i-th planet.
For example, if the weight of rocket is 9 tons, weight of fuel is 3 tons and take-off coefficient is 8 (a_i = 8), then 1.5 tons of fuel will be burnt (since 1.5 ⋅ 8 = 9 + 3). The new weight of fuel after take-off will be 1.5 tons.
Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.
Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
Input
The first line contains a single integer n (2 ≤ n ≤ 1000) — number of planets.
The second line contains the only integer m (1 ≤ m ≤ 1000) — weight of the payload.
The third line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 1000), where a_i is the number of tons, which can be lifted off by one ton of fuel.
The fourth line contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ 1000), where b_i is the number of tons, which can be landed by one ton of fuel.
It is guaranteed, that if Natasha can make a flight, then it takes no more than 10^9 tons of fuel.
Output
If Natasha can fly to Mars through (n - 2) planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number -1.
It is guaranteed, that if Natasha can make a flight, then it takes no more than 10^9 tons of fuel.
The answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}. Formally, let your answer be p, and the jury's answer be q. Your answer is considered correct if \frac{|p - q|}{max{(1, |q|)}} ≤ 10^{-6}.
Examples
Input
2
12
11 8
7 5
Output
10.0000000000
Input
3
1
1 4 1
2 5 3
Output
-1
Input
6
2
4 6 3 3 5 6
2 6 3 6 5 3
Output
85.4800000000
Note
Let's consider the first example.
Initially, the mass of a rocket with fuel is 22 tons.
* At take-off from Earth one ton of fuel can lift off 11 tons of cargo, so to lift off 22 tons you need to burn 2 tons of fuel. Remaining weight of the rocket with fuel is 20 tons.
* During landing on Mars, one ton of fuel can land 5 tons of cargo, so for landing 20 tons you will need to burn 4 tons of fuel. There will be 16 tons of the rocket with fuel remaining.
* While taking off from Mars, one ton of fuel can raise 8 tons of cargo, so to lift off 16 tons you will need to burn 2 tons of fuel. There will be 14 tons of rocket with fuel after that.
* During landing on Earth, one ton of fuel can land 7 tons of cargo, so for landing 14 tons you will need to burn 2 tons of fuel. Remaining weight is 12 tons, that is, a rocket without any fuel.
In the second case, the rocket will not be able even to take off from Earth.
Tags: binary search, math
Correct Solution:
```
from itertools import chain
n = int(input())
m = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
res = m
cont = 1
for x in chain(a, b):
if cont == 1:
if x == 1:
cont = 2
else:
res /= 1-1/x
if cont == 1:
print(res-m)
else:
print('-1')
```
| 87,528 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on n - 2 intermediate planets. Formally: we number all the planets from 1 to n. 1 is Earth, n is Mars. Natasha will make exactly n flights: 1 → 2 → … n → 1.
Flight from x to y consists of two phases: take-off from planet x and landing to planet y. This way, the overall itinerary of the trip will be: the 1-st planet → take-off from the 1-st planet → landing to the 2-nd planet → 2-nd planet → take-off from the 2-nd planet → … → landing to the n-th planet → the n-th planet → take-off from the n-th planet → landing to the 1-st planet → the 1-st planet.
The mass of the rocket together with all the useful cargo (but without fuel) is m tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that 1 ton of fuel can lift off a_i tons of rocket from the i-th planet or to land b_i tons of rocket onto the i-th planet.
For example, if the weight of rocket is 9 tons, weight of fuel is 3 tons and take-off coefficient is 8 (a_i = 8), then 1.5 tons of fuel will be burnt (since 1.5 ⋅ 8 = 9 + 3). The new weight of fuel after take-off will be 1.5 tons.
Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.
Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
Input
The first line contains a single integer n (2 ≤ n ≤ 1000) — number of planets.
The second line contains the only integer m (1 ≤ m ≤ 1000) — weight of the payload.
The third line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 1000), where a_i is the number of tons, which can be lifted off by one ton of fuel.
The fourth line contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ 1000), where b_i is the number of tons, which can be landed by one ton of fuel.
It is guaranteed, that if Natasha can make a flight, then it takes no more than 10^9 tons of fuel.
Output
If Natasha can fly to Mars through (n - 2) planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number -1.
It is guaranteed, that if Natasha can make a flight, then it takes no more than 10^9 tons of fuel.
The answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}. Formally, let your answer be p, and the jury's answer be q. Your answer is considered correct if \frac{|p - q|}{max{(1, |q|)}} ≤ 10^{-6}.
Examples
Input
2
12
11 8
7 5
Output
10.0000000000
Input
3
1
1 4 1
2 5 3
Output
-1
Input
6
2
4 6 3 3 5 6
2 6 3 6 5 3
Output
85.4800000000
Note
Let's consider the first example.
Initially, the mass of a rocket with fuel is 22 tons.
* At take-off from Earth one ton of fuel can lift off 11 tons of cargo, so to lift off 22 tons you need to burn 2 tons of fuel. Remaining weight of the rocket with fuel is 20 tons.
* During landing on Mars, one ton of fuel can land 5 tons of cargo, so for landing 20 tons you will need to burn 4 tons of fuel. There will be 16 tons of the rocket with fuel remaining.
* While taking off from Mars, one ton of fuel can raise 8 tons of cargo, so to lift off 16 tons you will need to burn 2 tons of fuel. There will be 14 tons of rocket with fuel after that.
* During landing on Earth, one ton of fuel can land 7 tons of cargo, so for landing 14 tons you will need to burn 2 tons of fuel. Remaining weight is 12 tons, that is, a rocket without any fuel.
In the second case, the rocket will not be able even to take off from Earth.
Tags: binary search, math
Correct Solution:
```
n = int(input())
m = int(input())
A = [int(x) for x in input().split()]
B = [int(x) for x in input().split()]
k = 1
for i in A:
k *= (1 - (1 / i))
for i in B:
k *= (1 - (1 / i))
if k == 0:
ans = -1
else:
ans = (m - (k * m)) / k
print(ans)
```
| 87,529 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on n - 2 intermediate planets. Formally: we number all the planets from 1 to n. 1 is Earth, n is Mars. Natasha will make exactly n flights: 1 → 2 → … n → 1.
Flight from x to y consists of two phases: take-off from planet x and landing to planet y. This way, the overall itinerary of the trip will be: the 1-st planet → take-off from the 1-st planet → landing to the 2-nd planet → 2-nd planet → take-off from the 2-nd planet → … → landing to the n-th planet → the n-th planet → take-off from the n-th planet → landing to the 1-st planet → the 1-st planet.
The mass of the rocket together with all the useful cargo (but without fuel) is m tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that 1 ton of fuel can lift off a_i tons of rocket from the i-th planet or to land b_i tons of rocket onto the i-th planet.
For example, if the weight of rocket is 9 tons, weight of fuel is 3 tons and take-off coefficient is 8 (a_i = 8), then 1.5 tons of fuel will be burnt (since 1.5 ⋅ 8 = 9 + 3). The new weight of fuel after take-off will be 1.5 tons.
Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.
Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
Input
The first line contains a single integer n (2 ≤ n ≤ 1000) — number of planets.
The second line contains the only integer m (1 ≤ m ≤ 1000) — weight of the payload.
The third line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 1000), where a_i is the number of tons, which can be lifted off by one ton of fuel.
The fourth line contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ 1000), where b_i is the number of tons, which can be landed by one ton of fuel.
It is guaranteed, that if Natasha can make a flight, then it takes no more than 10^9 tons of fuel.
Output
If Natasha can fly to Mars through (n - 2) planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number -1.
It is guaranteed, that if Natasha can make a flight, then it takes no more than 10^9 tons of fuel.
The answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}. Formally, let your answer be p, and the jury's answer be q. Your answer is considered correct if \frac{|p - q|}{max{(1, |q|)}} ≤ 10^{-6}.
Examples
Input
2
12
11 8
7 5
Output
10.0000000000
Input
3
1
1 4 1
2 5 3
Output
-1
Input
6
2
4 6 3 3 5 6
2 6 3 6 5 3
Output
85.4800000000
Note
Let's consider the first example.
Initially, the mass of a rocket with fuel is 22 tons.
* At take-off from Earth one ton of fuel can lift off 11 tons of cargo, so to lift off 22 tons you need to burn 2 tons of fuel. Remaining weight of the rocket with fuel is 20 tons.
* During landing on Mars, one ton of fuel can land 5 tons of cargo, so for landing 20 tons you will need to burn 4 tons of fuel. There will be 16 tons of the rocket with fuel remaining.
* While taking off from Mars, one ton of fuel can raise 8 tons of cargo, so to lift off 16 tons you will need to burn 2 tons of fuel. There will be 14 tons of rocket with fuel after that.
* During landing on Earth, one ton of fuel can land 7 tons of cargo, so for landing 14 tons you will need to burn 2 tons of fuel. Remaining weight is 12 tons, that is, a rocket without any fuel.
In the second case, the rocket will not be able even to take off from Earth.
Tags: binary search, math
Correct Solution:
```
n=int(input())
m=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
ans=m
if b[0]-1==0:
print(-1)
else:
m=m+(m/(b[0]-1))
counter=False
for i in range(n-1,0,-1):
if a[i]-1 ==0 or b[i]-1 ==0:
counter=True
else:
m=m+(m/(a[i]-1))
m=m+(m/(b[i]-1))
#print(m)
if counter==True or a[0]-1 ==0 :
print(-1)
else:
m=m+(m/(a[0]-1))
print(m-ans)
```
| 87,530 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on n - 2 intermediate planets. Formally: we number all the planets from 1 to n. 1 is Earth, n is Mars. Natasha will make exactly n flights: 1 → 2 → … n → 1.
Flight from x to y consists of two phases: take-off from planet x and landing to planet y. This way, the overall itinerary of the trip will be: the 1-st planet → take-off from the 1-st planet → landing to the 2-nd planet → 2-nd planet → take-off from the 2-nd planet → … → landing to the n-th planet → the n-th planet → take-off from the n-th planet → landing to the 1-st planet → the 1-st planet.
The mass of the rocket together with all the useful cargo (but without fuel) is m tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that 1 ton of fuel can lift off a_i tons of rocket from the i-th planet or to land b_i tons of rocket onto the i-th planet.
For example, if the weight of rocket is 9 tons, weight of fuel is 3 tons and take-off coefficient is 8 (a_i = 8), then 1.5 tons of fuel will be burnt (since 1.5 ⋅ 8 = 9 + 3). The new weight of fuel after take-off will be 1.5 tons.
Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.
Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
Input
The first line contains a single integer n (2 ≤ n ≤ 1000) — number of planets.
The second line contains the only integer m (1 ≤ m ≤ 1000) — weight of the payload.
The third line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 1000), where a_i is the number of tons, which can be lifted off by one ton of fuel.
The fourth line contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ 1000), where b_i is the number of tons, which can be landed by one ton of fuel.
It is guaranteed, that if Natasha can make a flight, then it takes no more than 10^9 tons of fuel.
Output
If Natasha can fly to Mars through (n - 2) planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number -1.
It is guaranteed, that if Natasha can make a flight, then it takes no more than 10^9 tons of fuel.
The answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}. Formally, let your answer be p, and the jury's answer be q. Your answer is considered correct if \frac{|p - q|}{max{(1, |q|)}} ≤ 10^{-6}.
Examples
Input
2
12
11 8
7 5
Output
10.0000000000
Input
3
1
1 4 1
2 5 3
Output
-1
Input
6
2
4 6 3 3 5 6
2 6 3 6 5 3
Output
85.4800000000
Note
Let's consider the first example.
Initially, the mass of a rocket with fuel is 22 tons.
* At take-off from Earth one ton of fuel can lift off 11 tons of cargo, so to lift off 22 tons you need to burn 2 tons of fuel. Remaining weight of the rocket with fuel is 20 tons.
* During landing on Mars, one ton of fuel can land 5 tons of cargo, so for landing 20 tons you will need to burn 4 tons of fuel. There will be 16 tons of the rocket with fuel remaining.
* While taking off from Mars, one ton of fuel can raise 8 tons of cargo, so to lift off 16 tons you will need to burn 2 tons of fuel. There will be 14 tons of rocket with fuel after that.
* During landing on Earth, one ton of fuel can land 7 tons of cargo, so for landing 14 tons you will need to burn 2 tons of fuel. Remaining weight is 12 tons, that is, a rocket without any fuel.
In the second case, the rocket will not be able even to take off from Earth.
Tags: binary search, math
Correct Solution:
```
# your code goes here
def predicate(x, m, a):
rhs = 0
for i in range(len(a)):
cv = (m+(x-rhs))/a[i]
#print(cv)
if cv<-5e-7:
return False
rhs+= cv
#print(rhs)
if(x-rhs >= -5e-7):
return True
return False
n = int(input())
m = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = []
for i in range( n-1):
c.append(a[i])
c.append(b[i+1])
c.append(a[-1])
c.append(b[0])
#predicate(10, m, c)
lo = 0
hi = 1e10
i = 0
while i < 100:
mid = (hi+lo)/2
if predicate(mid, m, c):
hi = mid
else:
lo = mid
i+=1
print(lo) if lo <= 1e9+5e-7 else print(-1)
```
| 87,531 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on n - 2 intermediate planets. Formally: we number all the planets from 1 to n. 1 is Earth, n is Mars. Natasha will make exactly n flights: 1 → 2 → … n → 1.
Flight from x to y consists of two phases: take-off from planet x and landing to planet y. This way, the overall itinerary of the trip will be: the 1-st planet → take-off from the 1-st planet → landing to the 2-nd planet → 2-nd planet → take-off from the 2-nd planet → … → landing to the n-th planet → the n-th planet → take-off from the n-th planet → landing to the 1-st planet → the 1-st planet.
The mass of the rocket together with all the useful cargo (but without fuel) is m tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that 1 ton of fuel can lift off a_i tons of rocket from the i-th planet or to land b_i tons of rocket onto the i-th planet.
For example, if the weight of rocket is 9 tons, weight of fuel is 3 tons and take-off coefficient is 8 (a_i = 8), then 1.5 tons of fuel will be burnt (since 1.5 ⋅ 8 = 9 + 3). The new weight of fuel after take-off will be 1.5 tons.
Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.
Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
Input
The first line contains a single integer n (2 ≤ n ≤ 1000) — number of planets.
The second line contains the only integer m (1 ≤ m ≤ 1000) — weight of the payload.
The third line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 1000), where a_i is the number of tons, which can be lifted off by one ton of fuel.
The fourth line contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ 1000), where b_i is the number of tons, which can be landed by one ton of fuel.
It is guaranteed, that if Natasha can make a flight, then it takes no more than 10^9 tons of fuel.
Output
If Natasha can fly to Mars through (n - 2) planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number -1.
It is guaranteed, that if Natasha can make a flight, then it takes no more than 10^9 tons of fuel.
The answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}. Formally, let your answer be p, and the jury's answer be q. Your answer is considered correct if \frac{|p - q|}{max{(1, |q|)}} ≤ 10^{-6}.
Examples
Input
2
12
11 8
7 5
Output
10.0000000000
Input
3
1
1 4 1
2 5 3
Output
-1
Input
6
2
4 6 3 3 5 6
2 6 3 6 5 3
Output
85.4800000000
Note
Let's consider the first example.
Initially, the mass of a rocket with fuel is 22 tons.
* At take-off from Earth one ton of fuel can lift off 11 tons of cargo, so to lift off 22 tons you need to burn 2 tons of fuel. Remaining weight of the rocket with fuel is 20 tons.
* During landing on Mars, one ton of fuel can land 5 tons of cargo, so for landing 20 tons you will need to burn 4 tons of fuel. There will be 16 tons of the rocket with fuel remaining.
* While taking off from Mars, one ton of fuel can raise 8 tons of cargo, so to lift off 16 tons you will need to burn 2 tons of fuel. There will be 14 tons of rocket with fuel after that.
* During landing on Earth, one ton of fuel can land 7 tons of cargo, so for landing 14 tons you will need to burn 2 tons of fuel. Remaining weight is 12 tons, that is, a rocket without any fuel.
In the second case, the rocket will not be able even to take off from Earth.
Tags: binary search, math
Correct Solution:
```
n = int(input())
m = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
start = m
if b[0]-1 <= 0:
print(-1)
else:
m += m/(b[0]-1)
flag = True
for i in range(n-1,0,-1):
if a[i] - 1 <= 0:
flag = False
print(-1)
break
else:
m += m/(a[i]-1)
if b[i] - 1 <= 0:
flag = False
print(-1)
break
else:
m += m/(b[i]-1)
if flag:
if a[0] - 1 <= 0:
print(-1)
else:
m += m/(a[0]-1)
print(m-start)
```
| 87,532 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on n - 2 intermediate planets. Formally: we number all the planets from 1 to n. 1 is Earth, n is Mars. Natasha will make exactly n flights: 1 → 2 → … n → 1.
Flight from x to y consists of two phases: take-off from planet x and landing to planet y. This way, the overall itinerary of the trip will be: the 1-st planet → take-off from the 1-st planet → landing to the 2-nd planet → 2-nd planet → take-off from the 2-nd planet → … → landing to the n-th planet → the n-th planet → take-off from the n-th planet → landing to the 1-st planet → the 1-st planet.
The mass of the rocket together with all the useful cargo (but without fuel) is m tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that 1 ton of fuel can lift off a_i tons of rocket from the i-th planet or to land b_i tons of rocket onto the i-th planet.
For example, if the weight of rocket is 9 tons, weight of fuel is 3 tons and take-off coefficient is 8 (a_i = 8), then 1.5 tons of fuel will be burnt (since 1.5 ⋅ 8 = 9 + 3). The new weight of fuel after take-off will be 1.5 tons.
Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.
Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
Input
The first line contains a single integer n (2 ≤ n ≤ 1000) — number of planets.
The second line contains the only integer m (1 ≤ m ≤ 1000) — weight of the payload.
The third line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 1000), where a_i is the number of tons, which can be lifted off by one ton of fuel.
The fourth line contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ 1000), where b_i is the number of tons, which can be landed by one ton of fuel.
It is guaranteed, that if Natasha can make a flight, then it takes no more than 10^9 tons of fuel.
Output
If Natasha can fly to Mars through (n - 2) planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number -1.
It is guaranteed, that if Natasha can make a flight, then it takes no more than 10^9 tons of fuel.
The answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}. Formally, let your answer be p, and the jury's answer be q. Your answer is considered correct if \frac{|p - q|}{max{(1, |q|)}} ≤ 10^{-6}.
Examples
Input
2
12
11 8
7 5
Output
10.0000000000
Input
3
1
1 4 1
2 5 3
Output
-1
Input
6
2
4 6 3 3 5 6
2 6 3 6 5 3
Output
85.4800000000
Note
Let's consider the first example.
Initially, the mass of a rocket with fuel is 22 tons.
* At take-off from Earth one ton of fuel can lift off 11 tons of cargo, so to lift off 22 tons you need to burn 2 tons of fuel. Remaining weight of the rocket with fuel is 20 tons.
* During landing on Mars, one ton of fuel can land 5 tons of cargo, so for landing 20 tons you will need to burn 4 tons of fuel. There will be 16 tons of the rocket with fuel remaining.
* While taking off from Mars, one ton of fuel can raise 8 tons of cargo, so to lift off 16 tons you will need to burn 2 tons of fuel. There will be 14 tons of rocket with fuel after that.
* During landing on Earth, one ton of fuel can land 7 tons of cargo, so for landing 14 tons you will need to burn 2 tons of fuel. Remaining weight is 12 tons, that is, a rocket without any fuel.
In the second case, the rocket will not be able even to take off from Earth.
Submitted Solution:
```
n = int(input())
m = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
def f(x):
summ = x + m
#print(summ, x, "summ")
for i in range(n):
summ -= summ / a[i % n]
#print(summ, x, "summ")
summ -= summ / b[(i + 1) % n]
#print(summ, x, "summ")
if summ < m:
return False
#print(summ, x, "summ")
if summ < m:
return False
return True
left = 0
right = 10 ** 9 + 1
while (right - left) >= 10 ** (-6):
mid = (left + right) / 2
if f(mid):
right = mid
else:
left = mid
if right > 10 ** 9 + 10 ** (-5):
print(-1)
else:
print(right)
```
Yes
| 87,533 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on n - 2 intermediate planets. Formally: we number all the planets from 1 to n. 1 is Earth, n is Mars. Natasha will make exactly n flights: 1 → 2 → … n → 1.
Flight from x to y consists of two phases: take-off from planet x and landing to planet y. This way, the overall itinerary of the trip will be: the 1-st planet → take-off from the 1-st planet → landing to the 2-nd planet → 2-nd planet → take-off from the 2-nd planet → … → landing to the n-th planet → the n-th planet → take-off from the n-th planet → landing to the 1-st planet → the 1-st planet.
The mass of the rocket together with all the useful cargo (but without fuel) is m tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that 1 ton of fuel can lift off a_i tons of rocket from the i-th planet or to land b_i tons of rocket onto the i-th planet.
For example, if the weight of rocket is 9 tons, weight of fuel is 3 tons and take-off coefficient is 8 (a_i = 8), then 1.5 tons of fuel will be burnt (since 1.5 ⋅ 8 = 9 + 3). The new weight of fuel after take-off will be 1.5 tons.
Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.
Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
Input
The first line contains a single integer n (2 ≤ n ≤ 1000) — number of planets.
The second line contains the only integer m (1 ≤ m ≤ 1000) — weight of the payload.
The third line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 1000), where a_i is the number of tons, which can be lifted off by one ton of fuel.
The fourth line contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ 1000), where b_i is the number of tons, which can be landed by one ton of fuel.
It is guaranteed, that if Natasha can make a flight, then it takes no more than 10^9 tons of fuel.
Output
If Natasha can fly to Mars through (n - 2) planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number -1.
It is guaranteed, that if Natasha can make a flight, then it takes no more than 10^9 tons of fuel.
The answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}. Formally, let your answer be p, and the jury's answer be q. Your answer is considered correct if \frac{|p - q|}{max{(1, |q|)}} ≤ 10^{-6}.
Examples
Input
2
12
11 8
7 5
Output
10.0000000000
Input
3
1
1 4 1
2 5 3
Output
-1
Input
6
2
4 6 3 3 5 6
2 6 3 6 5 3
Output
85.4800000000
Note
Let's consider the first example.
Initially, the mass of a rocket with fuel is 22 tons.
* At take-off from Earth one ton of fuel can lift off 11 tons of cargo, so to lift off 22 tons you need to burn 2 tons of fuel. Remaining weight of the rocket with fuel is 20 tons.
* During landing on Mars, one ton of fuel can land 5 tons of cargo, so for landing 20 tons you will need to burn 4 tons of fuel. There will be 16 tons of the rocket with fuel remaining.
* While taking off from Mars, one ton of fuel can raise 8 tons of cargo, so to lift off 16 tons you will need to burn 2 tons of fuel. There will be 14 tons of rocket with fuel after that.
* During landing on Earth, one ton of fuel can land 7 tons of cargo, so for landing 14 tons you will need to burn 2 tons of fuel. Remaining weight is 12 tons, that is, a rocket without any fuel.
In the second case, the rocket will not be able even to take off from Earth.
Submitted Solution:
```
n=int(input())
m=int(input())
a=[int(i) for i in input().split()]
b=[int(i) for i in input().split()]
z=(a[0]-1)/a[0]
l=0
for i in range(1,n):
z=z*(b[i]-1)/b[i]
z=z*(a[i]-1)/a[i]
z=z*(b[0]-1)/b[0]
try:
print("{0:.10f}".format(m/z-m))
except:
print(-1)
```
Yes
| 87,534 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on n - 2 intermediate planets. Formally: we number all the planets from 1 to n. 1 is Earth, n is Mars. Natasha will make exactly n flights: 1 → 2 → … n → 1.
Flight from x to y consists of two phases: take-off from planet x and landing to planet y. This way, the overall itinerary of the trip will be: the 1-st planet → take-off from the 1-st planet → landing to the 2-nd planet → 2-nd planet → take-off from the 2-nd planet → … → landing to the n-th planet → the n-th planet → take-off from the n-th planet → landing to the 1-st planet → the 1-st planet.
The mass of the rocket together with all the useful cargo (but without fuel) is m tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that 1 ton of fuel can lift off a_i tons of rocket from the i-th planet or to land b_i tons of rocket onto the i-th planet.
For example, if the weight of rocket is 9 tons, weight of fuel is 3 tons and take-off coefficient is 8 (a_i = 8), then 1.5 tons of fuel will be burnt (since 1.5 ⋅ 8 = 9 + 3). The new weight of fuel after take-off will be 1.5 tons.
Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.
Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
Input
The first line contains a single integer n (2 ≤ n ≤ 1000) — number of planets.
The second line contains the only integer m (1 ≤ m ≤ 1000) — weight of the payload.
The third line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 1000), where a_i is the number of tons, which can be lifted off by one ton of fuel.
The fourth line contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ 1000), where b_i is the number of tons, which can be landed by one ton of fuel.
It is guaranteed, that if Natasha can make a flight, then it takes no more than 10^9 tons of fuel.
Output
If Natasha can fly to Mars through (n - 2) planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number -1.
It is guaranteed, that if Natasha can make a flight, then it takes no more than 10^9 tons of fuel.
The answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}. Formally, let your answer be p, and the jury's answer be q. Your answer is considered correct if \frac{|p - q|}{max{(1, |q|)}} ≤ 10^{-6}.
Examples
Input
2
12
11 8
7 5
Output
10.0000000000
Input
3
1
1 4 1
2 5 3
Output
-1
Input
6
2
4 6 3 3 5 6
2 6 3 6 5 3
Output
85.4800000000
Note
Let's consider the first example.
Initially, the mass of a rocket with fuel is 22 tons.
* At take-off from Earth one ton of fuel can lift off 11 tons of cargo, so to lift off 22 tons you need to burn 2 tons of fuel. Remaining weight of the rocket with fuel is 20 tons.
* During landing on Mars, one ton of fuel can land 5 tons of cargo, so for landing 20 tons you will need to burn 4 tons of fuel. There will be 16 tons of the rocket with fuel remaining.
* While taking off from Mars, one ton of fuel can raise 8 tons of cargo, so to lift off 16 tons you will need to burn 2 tons of fuel. There will be 14 tons of rocket with fuel after that.
* During landing on Earth, one ton of fuel can land 7 tons of cargo, so for landing 14 tons you will need to burn 2 tons of fuel. Remaining weight is 12 tons, that is, a rocket without any fuel.
In the second case, the rocket will not be able even to take off from Earth.
Submitted Solution:
```
n = int(input())
rm = m = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
if min(a+b) is 1:
print(-1)
else:
for i in range(n-1,-1,-1):
m += m / (a[(i + 1) % n] - 1)
m += m / (b[i] - 1)
print(round(m - rm,7))
```
Yes
| 87,535 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on n - 2 intermediate planets. Formally: we number all the planets from 1 to n. 1 is Earth, n is Mars. Natasha will make exactly n flights: 1 → 2 → … n → 1.
Flight from x to y consists of two phases: take-off from planet x and landing to planet y. This way, the overall itinerary of the trip will be: the 1-st planet → take-off from the 1-st planet → landing to the 2-nd planet → 2-nd planet → take-off from the 2-nd planet → … → landing to the n-th planet → the n-th planet → take-off from the n-th planet → landing to the 1-st planet → the 1-st planet.
The mass of the rocket together with all the useful cargo (but without fuel) is m tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that 1 ton of fuel can lift off a_i tons of rocket from the i-th planet or to land b_i tons of rocket onto the i-th planet.
For example, if the weight of rocket is 9 tons, weight of fuel is 3 tons and take-off coefficient is 8 (a_i = 8), then 1.5 tons of fuel will be burnt (since 1.5 ⋅ 8 = 9 + 3). The new weight of fuel after take-off will be 1.5 tons.
Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.
Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
Input
The first line contains a single integer n (2 ≤ n ≤ 1000) — number of planets.
The second line contains the only integer m (1 ≤ m ≤ 1000) — weight of the payload.
The third line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 1000), where a_i is the number of tons, which can be lifted off by one ton of fuel.
The fourth line contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ 1000), where b_i is the number of tons, which can be landed by one ton of fuel.
It is guaranteed, that if Natasha can make a flight, then it takes no more than 10^9 tons of fuel.
Output
If Natasha can fly to Mars through (n - 2) planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number -1.
It is guaranteed, that if Natasha can make a flight, then it takes no more than 10^9 tons of fuel.
The answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}. Formally, let your answer be p, and the jury's answer be q. Your answer is considered correct if \frac{|p - q|}{max{(1, |q|)}} ≤ 10^{-6}.
Examples
Input
2
12
11 8
7 5
Output
10.0000000000
Input
3
1
1 4 1
2 5 3
Output
-1
Input
6
2
4 6 3 3 5 6
2 6 3 6 5 3
Output
85.4800000000
Note
Let's consider the first example.
Initially, the mass of a rocket with fuel is 22 tons.
* At take-off from Earth one ton of fuel can lift off 11 tons of cargo, so to lift off 22 tons you need to burn 2 tons of fuel. Remaining weight of the rocket with fuel is 20 tons.
* During landing on Mars, one ton of fuel can land 5 tons of cargo, so for landing 20 tons you will need to burn 4 tons of fuel. There will be 16 tons of the rocket with fuel remaining.
* While taking off from Mars, one ton of fuel can raise 8 tons of cargo, so to lift off 16 tons you will need to burn 2 tons of fuel. There will be 14 tons of rocket with fuel after that.
* During landing on Earth, one ton of fuel can land 7 tons of cargo, so for landing 14 tons you will need to burn 2 tons of fuel. Remaining weight is 12 tons, that is, a rocket without any fuel.
In the second case, the rocket will not be able even to take off from Earth.
Submitted Solution:
```
n = int(input())
m = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
def f(x,a):
if a == 0 or a == 1:
print(-1)
import sys;sys.exit(0)
return x*(1/a)/(1-1/a)
cur_wt = m
for bi in b:
cur_wt = cur_wt + f(cur_wt, bi)
for ai in reversed(a):
cur_wt = cur_wt + f(cur_wt, ai)
print("%f"%(cur_wt - m))
```
Yes
| 87,536 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on n - 2 intermediate planets. Formally: we number all the planets from 1 to n. 1 is Earth, n is Mars. Natasha will make exactly n flights: 1 → 2 → … n → 1.
Flight from x to y consists of two phases: take-off from planet x and landing to planet y. This way, the overall itinerary of the trip will be: the 1-st planet → take-off from the 1-st planet → landing to the 2-nd planet → 2-nd planet → take-off from the 2-nd planet → … → landing to the n-th planet → the n-th planet → take-off from the n-th planet → landing to the 1-st planet → the 1-st planet.
The mass of the rocket together with all the useful cargo (but without fuel) is m tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that 1 ton of fuel can lift off a_i tons of rocket from the i-th planet or to land b_i tons of rocket onto the i-th planet.
For example, if the weight of rocket is 9 tons, weight of fuel is 3 tons and take-off coefficient is 8 (a_i = 8), then 1.5 tons of fuel will be burnt (since 1.5 ⋅ 8 = 9 + 3). The new weight of fuel after take-off will be 1.5 tons.
Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.
Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
Input
The first line contains a single integer n (2 ≤ n ≤ 1000) — number of planets.
The second line contains the only integer m (1 ≤ m ≤ 1000) — weight of the payload.
The third line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 1000), where a_i is the number of tons, which can be lifted off by one ton of fuel.
The fourth line contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ 1000), where b_i is the number of tons, which can be landed by one ton of fuel.
It is guaranteed, that if Natasha can make a flight, then it takes no more than 10^9 tons of fuel.
Output
If Natasha can fly to Mars through (n - 2) planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number -1.
It is guaranteed, that if Natasha can make a flight, then it takes no more than 10^9 tons of fuel.
The answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}. Formally, let your answer be p, and the jury's answer be q. Your answer is considered correct if \frac{|p - q|}{max{(1, |q|)}} ≤ 10^{-6}.
Examples
Input
2
12
11 8
7 5
Output
10.0000000000
Input
3
1
1 4 1
2 5 3
Output
-1
Input
6
2
4 6 3 3 5 6
2 6 3 6 5 3
Output
85.4800000000
Note
Let's consider the first example.
Initially, the mass of a rocket with fuel is 22 tons.
* At take-off from Earth one ton of fuel can lift off 11 tons of cargo, so to lift off 22 tons you need to burn 2 tons of fuel. Remaining weight of the rocket with fuel is 20 tons.
* During landing on Mars, one ton of fuel can land 5 tons of cargo, so for landing 20 tons you will need to burn 4 tons of fuel. There will be 16 tons of the rocket with fuel remaining.
* While taking off from Mars, one ton of fuel can raise 8 tons of cargo, so to lift off 16 tons you will need to burn 2 tons of fuel. There will be 14 tons of rocket with fuel after that.
* During landing on Earth, one ton of fuel can land 7 tons of cargo, so for landing 14 tons you will need to burn 2 tons of fuel. Remaining weight is 12 tons, that is, a rocket without any fuel.
In the second case, the rocket will not be able even to take off from Earth.
Submitted Solution:
```
def solve(n):
n = n - n/s[0];
for i in range(1, len(s)):
n = n - n/s1[i]
n = n - n/s[i];
if n < m :
return False
n = n - n/s1[0]
return n>=m
n = int(input())
m = int(input())
s = list( int(x) for x in input().split( ))
s1 = list(int(x)for x in input().split( ))
low = 1
high = (10**9) + 5
while(high - low > 0.000001):
mid = (high+low)/2
if solve(mid + m ):
high= mid;
else:
low = mid;
if(solve(low + m )):
print(low);
elif(solve(high+ m)):
print(high)
else:
print(-1)
```
No
| 87,537 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on n - 2 intermediate planets. Formally: we number all the planets from 1 to n. 1 is Earth, n is Mars. Natasha will make exactly n flights: 1 → 2 → … n → 1.
Flight from x to y consists of two phases: take-off from planet x and landing to planet y. This way, the overall itinerary of the trip will be: the 1-st planet → take-off from the 1-st planet → landing to the 2-nd planet → 2-nd planet → take-off from the 2-nd planet → … → landing to the n-th planet → the n-th planet → take-off from the n-th planet → landing to the 1-st planet → the 1-st planet.
The mass of the rocket together with all the useful cargo (but without fuel) is m tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that 1 ton of fuel can lift off a_i tons of rocket from the i-th planet or to land b_i tons of rocket onto the i-th planet.
For example, if the weight of rocket is 9 tons, weight of fuel is 3 tons and take-off coefficient is 8 (a_i = 8), then 1.5 tons of fuel will be burnt (since 1.5 ⋅ 8 = 9 + 3). The new weight of fuel after take-off will be 1.5 tons.
Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.
Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
Input
The first line contains a single integer n (2 ≤ n ≤ 1000) — number of planets.
The second line contains the only integer m (1 ≤ m ≤ 1000) — weight of the payload.
The third line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 1000), where a_i is the number of tons, which can be lifted off by one ton of fuel.
The fourth line contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ 1000), where b_i is the number of tons, which can be landed by one ton of fuel.
It is guaranteed, that if Natasha can make a flight, then it takes no more than 10^9 tons of fuel.
Output
If Natasha can fly to Mars through (n - 2) planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number -1.
It is guaranteed, that if Natasha can make a flight, then it takes no more than 10^9 tons of fuel.
The answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}. Formally, let your answer be p, and the jury's answer be q. Your answer is considered correct if \frac{|p - q|}{max{(1, |q|)}} ≤ 10^{-6}.
Examples
Input
2
12
11 8
7 5
Output
10.0000000000
Input
3
1
1 4 1
2 5 3
Output
-1
Input
6
2
4 6 3 3 5 6
2 6 3 6 5 3
Output
85.4800000000
Note
Let's consider the first example.
Initially, the mass of a rocket with fuel is 22 tons.
* At take-off from Earth one ton of fuel can lift off 11 tons of cargo, so to lift off 22 tons you need to burn 2 tons of fuel. Remaining weight of the rocket with fuel is 20 tons.
* During landing on Mars, one ton of fuel can land 5 tons of cargo, so for landing 20 tons you will need to burn 4 tons of fuel. There will be 16 tons of the rocket with fuel remaining.
* While taking off from Mars, one ton of fuel can raise 8 tons of cargo, so to lift off 16 tons you will need to burn 2 tons of fuel. There will be 14 tons of rocket with fuel after that.
* During landing on Earth, one ton of fuel can land 7 tons of cargo, so for landing 14 tons you will need to burn 2 tons of fuel. Remaining weight is 12 tons, that is, a rocket without any fuel.
In the second case, the rocket will not be able even to take off from Earth.
Submitted Solution:
```
n=int(input())
m=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
l=0
r=1000000001
def can(w):
z=w+m
x=w-z/a[0]
if x<0:
return 0
for i in range(1,n):
x=x-(x+m)/b[i]
if x<0:
return 0
x=x-(x+m)/a[i]
if x<0:
return 0
x=x-(x+m)/b[0]
if x<0: return 0
return 1
while r-l>=0.0000001:
w=(r+l)/2
if can(w): r=w
else: l=w
print(round(r,6))
```
No
| 87,538 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on n - 2 intermediate planets. Formally: we number all the planets from 1 to n. 1 is Earth, n is Mars. Natasha will make exactly n flights: 1 → 2 → … n → 1.
Flight from x to y consists of two phases: take-off from planet x and landing to planet y. This way, the overall itinerary of the trip will be: the 1-st planet → take-off from the 1-st planet → landing to the 2-nd planet → 2-nd planet → take-off from the 2-nd planet → … → landing to the n-th planet → the n-th planet → take-off from the n-th planet → landing to the 1-st planet → the 1-st planet.
The mass of the rocket together with all the useful cargo (but without fuel) is m tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that 1 ton of fuel can lift off a_i tons of rocket from the i-th planet or to land b_i tons of rocket onto the i-th planet.
For example, if the weight of rocket is 9 tons, weight of fuel is 3 tons and take-off coefficient is 8 (a_i = 8), then 1.5 tons of fuel will be burnt (since 1.5 ⋅ 8 = 9 + 3). The new weight of fuel after take-off will be 1.5 tons.
Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.
Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
Input
The first line contains a single integer n (2 ≤ n ≤ 1000) — number of planets.
The second line contains the only integer m (1 ≤ m ≤ 1000) — weight of the payload.
The third line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 1000), where a_i is the number of tons, which can be lifted off by one ton of fuel.
The fourth line contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ 1000), where b_i is the number of tons, which can be landed by one ton of fuel.
It is guaranteed, that if Natasha can make a flight, then it takes no more than 10^9 tons of fuel.
Output
If Natasha can fly to Mars through (n - 2) planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number -1.
It is guaranteed, that if Natasha can make a flight, then it takes no more than 10^9 tons of fuel.
The answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}. Formally, let your answer be p, and the jury's answer be q. Your answer is considered correct if \frac{|p - q|}{max{(1, |q|)}} ≤ 10^{-6}.
Examples
Input
2
12
11 8
7 5
Output
10.0000000000
Input
3
1
1 4 1
2 5 3
Output
-1
Input
6
2
4 6 3 3 5 6
2 6 3 6 5 3
Output
85.4800000000
Note
Let's consider the first example.
Initially, the mass of a rocket with fuel is 22 tons.
* At take-off from Earth one ton of fuel can lift off 11 tons of cargo, so to lift off 22 tons you need to burn 2 tons of fuel. Remaining weight of the rocket with fuel is 20 tons.
* During landing on Mars, one ton of fuel can land 5 tons of cargo, so for landing 20 tons you will need to burn 4 tons of fuel. There will be 16 tons of the rocket with fuel remaining.
* While taking off from Mars, one ton of fuel can raise 8 tons of cargo, so to lift off 16 tons you will need to burn 2 tons of fuel. There will be 14 tons of rocket with fuel after that.
* During landing on Earth, one ton of fuel can land 7 tons of cargo, so for landing 14 tons you will need to burn 2 tons of fuel. Remaining weight is 12 tons, that is, a rocket without any fuel.
In the second case, the rocket will not be able even to take off from Earth.
Submitted Solution:
```
import math
import itertools
getInputList = lambda : list(input().split())
getInputIntList = lambda : list(map(int,input().split()))
n = int(input())
m = int(input())
a = getInputIntList()
b = getInputIntList()
w = a+b
left = 0
right = 10**9
best = -1
"""
2
12
11 8
7 5
11 5 8 7
"""
while left <= right:
md = (left + right)//2
iw = md + m
for i in w:
iw -= iw/i
if iw >= m:
best = md
right = md -1
else:
left = md + 1
left = 0
right = 10**6
ans = best
while left <= right:
md = (left + right)//2
iw = (md/10**6) + m + best -1
for i in w:
iw -= iw/i
if iw >= m:
ans = (md/10**6) + best -1
right = md-1
else:
left = md+1
print(min(best,ans))
```
No
| 87,539 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on n - 2 intermediate planets. Formally: we number all the planets from 1 to n. 1 is Earth, n is Mars. Natasha will make exactly n flights: 1 → 2 → … n → 1.
Flight from x to y consists of two phases: take-off from planet x and landing to planet y. This way, the overall itinerary of the trip will be: the 1-st planet → take-off from the 1-st planet → landing to the 2-nd planet → 2-nd planet → take-off from the 2-nd planet → … → landing to the n-th planet → the n-th planet → take-off from the n-th planet → landing to the 1-st planet → the 1-st planet.
The mass of the rocket together with all the useful cargo (but without fuel) is m tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that 1 ton of fuel can lift off a_i tons of rocket from the i-th planet or to land b_i tons of rocket onto the i-th planet.
For example, if the weight of rocket is 9 tons, weight of fuel is 3 tons and take-off coefficient is 8 (a_i = 8), then 1.5 tons of fuel will be burnt (since 1.5 ⋅ 8 = 9 + 3). The new weight of fuel after take-off will be 1.5 tons.
Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.
Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
Input
The first line contains a single integer n (2 ≤ n ≤ 1000) — number of planets.
The second line contains the only integer m (1 ≤ m ≤ 1000) — weight of the payload.
The third line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 1000), where a_i is the number of tons, which can be lifted off by one ton of fuel.
The fourth line contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ 1000), where b_i is the number of tons, which can be landed by one ton of fuel.
It is guaranteed, that if Natasha can make a flight, then it takes no more than 10^9 tons of fuel.
Output
If Natasha can fly to Mars through (n - 2) planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number -1.
It is guaranteed, that if Natasha can make a flight, then it takes no more than 10^9 tons of fuel.
The answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}. Formally, let your answer be p, and the jury's answer be q. Your answer is considered correct if \frac{|p - q|}{max{(1, |q|)}} ≤ 10^{-6}.
Examples
Input
2
12
11 8
7 5
Output
10.0000000000
Input
3
1
1 4 1
2 5 3
Output
-1
Input
6
2
4 6 3 3 5 6
2 6 3 6 5 3
Output
85.4800000000
Note
Let's consider the first example.
Initially, the mass of a rocket with fuel is 22 tons.
* At take-off from Earth one ton of fuel can lift off 11 tons of cargo, so to lift off 22 tons you need to burn 2 tons of fuel. Remaining weight of the rocket with fuel is 20 tons.
* During landing on Mars, one ton of fuel can land 5 tons of cargo, so for landing 20 tons you will need to burn 4 tons of fuel. There will be 16 tons of the rocket with fuel remaining.
* While taking off from Mars, one ton of fuel can raise 8 tons of cargo, so to lift off 16 tons you will need to burn 2 tons of fuel. There will be 14 tons of rocket with fuel after that.
* During landing on Earth, one ton of fuel can land 7 tons of cargo, so for landing 14 tons you will need to burn 2 tons of fuel. Remaining weight is 12 tons, that is, a rocket without any fuel.
In the second case, the rocket will not be able even to take off from Earth.
Submitted Solution:
```
N,M=int(input()),int(input())
u,d=[*map(int,input().split())],[*map(int,input().split())]
if d[0] == 1:
print(-1)
exit(0)
need = M / (d[0] - 1)
if need <= 0 or need > 10**9:
print(-1)
exit(0)
for i in range(N - 1, 0, -1):
if u[i] == 1:
print(-1)
exit(0)
need = (M+need*u[i])/(u[i]-1)
if need <= 0 or need > 10**9:
print(-1)
exit(0)
if d[i] == 1:
print(-1)
exit(0)
need = (M+need*d[i])/(d[i]-1)
if need <= 0 or need > 10**9:
print(-1)
exit(0)
if u[0] == 1:
print(-1)
exit(0)
need = (M+need*u[0])/(u[0]-1)
if need <= 0 or need > 10**9:
print(-1)
exit(0)
print('%.15f' % need)
```
No
| 87,540 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has two arrays A and B of lengths n and m, respectively.
He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array [1, 10, 100, 1000, 10000] Vasya can obtain array [1, 1110, 10000], and from array [1, 2, 3] Vasya can obtain array [6].
Two arrays A and B are considered equal if and only if they have the same length and for each valid i A_i = B_i.
Vasya wants to perform some of these operations on array A, some on array B, in such a way that arrays A and B become equal. Moreover, the lengths of the resulting arrays should be maximal possible.
Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays A and B equal.
Input
The first line contains a single integer n~(1 ≤ n ≤ 3 ⋅ 10^5) — the length of the first array.
The second line contains n integers a_1, a_2, ⋅⋅⋅, a_n~(1 ≤ a_i ≤ 10^9) — elements of the array A.
The third line contains a single integer m~(1 ≤ m ≤ 3 ⋅ 10^5) — the length of the second array.
The fourth line contains m integers b_1, b_2, ⋅⋅⋅, b_m~(1 ≤ b_i ≤ 10^9) - elements of the array B.
Output
Print a single integer — the maximum length of the resulting arrays after some operations were performed on arrays A and B in such a way that they became equal.
If there is no way to make array equal, print "-1".
Examples
Input
5
11 2 3 5 7
4
11 7 3 7
Output
3
Input
2
1 2
1
100
Output
-1
Input
3
1 2 3
3
1 2 3
Output
3
Tags: greedy, two pointers
Correct Solution:
```
import sys
f=sys.stdin
out=sys.stdout
n=int(f.readline().rstrip('\r\n'))
a=list(map(int,f.readline().rstrip('\r\n').split()))
m=int(f.readline().rstrip('\r\n'))
b=list(map(int,f.readline().rstrip('\r\n').split()))
i=n-1
j=m-1
c=0
while i>=0 and j>=0:
if a[i]==b[j]:
c+=1
i-=1
j-=1
elif a[i]<b[j]:
a[i-1]+=a[i]
i-=1
else:
b[j-1]+=b[j]
j-=1
if i==-1 and j==-1:
out.write(str(c))
else:
out.write("-1")
```
| 87,541 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has two arrays A and B of lengths n and m, respectively.
He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array [1, 10, 100, 1000, 10000] Vasya can obtain array [1, 1110, 10000], and from array [1, 2, 3] Vasya can obtain array [6].
Two arrays A and B are considered equal if and only if they have the same length and for each valid i A_i = B_i.
Vasya wants to perform some of these operations on array A, some on array B, in such a way that arrays A and B become equal. Moreover, the lengths of the resulting arrays should be maximal possible.
Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays A and B equal.
Input
The first line contains a single integer n~(1 ≤ n ≤ 3 ⋅ 10^5) — the length of the first array.
The second line contains n integers a_1, a_2, ⋅⋅⋅, a_n~(1 ≤ a_i ≤ 10^9) — elements of the array A.
The third line contains a single integer m~(1 ≤ m ≤ 3 ⋅ 10^5) — the length of the second array.
The fourth line contains m integers b_1, b_2, ⋅⋅⋅, b_m~(1 ≤ b_i ≤ 10^9) - elements of the array B.
Output
Print a single integer — the maximum length of the resulting arrays after some operations were performed on arrays A and B in such a way that they became equal.
If there is no way to make array equal, print "-1".
Examples
Input
5
11 2 3 5 7
4
11 7 3 7
Output
3
Input
2
1 2
1
100
Output
-1
Input
3
1 2 3
3
1 2 3
Output
3
Tags: greedy, two pointers
Correct Solution:
```
n=int(input())
a=list(map(int,input().split()))
m=int(input())
b=list(map(int,input().split()))
ans=0
i=0
j=0
while(i!=n and j!=m):
if a[i]==b[j]:
ans+=1
i+=1
j+=1
elif a[i]<b[j]:
if i+1<len(a):
a[i+1]+=a[i]
i+=1
else:
if j+1<len(b):
b[j+1]+=b[j]
j+=1
if i!=n or j!=m:
print(-1)
else:
print(ans)
```
| 87,542 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has two arrays A and B of lengths n and m, respectively.
He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array [1, 10, 100, 1000, 10000] Vasya can obtain array [1, 1110, 10000], and from array [1, 2, 3] Vasya can obtain array [6].
Two arrays A and B are considered equal if and only if they have the same length and for each valid i A_i = B_i.
Vasya wants to perform some of these operations on array A, some on array B, in such a way that arrays A and B become equal. Moreover, the lengths of the resulting arrays should be maximal possible.
Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays A and B equal.
Input
The first line contains a single integer n~(1 ≤ n ≤ 3 ⋅ 10^5) — the length of the first array.
The second line contains n integers a_1, a_2, ⋅⋅⋅, a_n~(1 ≤ a_i ≤ 10^9) — elements of the array A.
The third line contains a single integer m~(1 ≤ m ≤ 3 ⋅ 10^5) — the length of the second array.
The fourth line contains m integers b_1, b_2, ⋅⋅⋅, b_m~(1 ≤ b_i ≤ 10^9) - elements of the array B.
Output
Print a single integer — the maximum length of the resulting arrays after some operations were performed on arrays A and B in such a way that they became equal.
If there is no way to make array equal, print "-1".
Examples
Input
5
11 2 3 5 7
4
11 7 3 7
Output
3
Input
2
1 2
1
100
Output
-1
Input
3
1 2 3
3
1 2 3
Output
3
Tags: greedy, two pointers
Correct Solution:
```
#------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------game starts now-----------------------------------------------------
from collections import deque
n=int(input())
l=list(map(int,input().split()))
m=int(input())
l1=list(map(int,input().split()))
t=0
p=0
d=dict()
y=0
k=1
f=0
k1=1
while(True):
if l[t]==l1[p]:
d.update({y:l[t]})
y+=1
t+=k
p+=k1
k=1
k1=1
else:
if l[t]<l1[p]:
if t+k>=len(l):
f=1
break
else:
l[t]+=l[t+k]
k+=1
elif l1[p]<l[t]:
if p+k1>=len(l1):
f=1
break
else:
l1[p]+=l1[p+k1]
k1+=1
if t>=len(l) or p>=len(l1):
break
if f==1 or t!=n or p!=m:
print(-1)
else:
print(len(d))
```
| 87,543 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has two arrays A and B of lengths n and m, respectively.
He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array [1, 10, 100, 1000, 10000] Vasya can obtain array [1, 1110, 10000], and from array [1, 2, 3] Vasya can obtain array [6].
Two arrays A and B are considered equal if and only if they have the same length and for each valid i A_i = B_i.
Vasya wants to perform some of these operations on array A, some on array B, in such a way that arrays A and B become equal. Moreover, the lengths of the resulting arrays should be maximal possible.
Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays A and B equal.
Input
The first line contains a single integer n~(1 ≤ n ≤ 3 ⋅ 10^5) — the length of the first array.
The second line contains n integers a_1, a_2, ⋅⋅⋅, a_n~(1 ≤ a_i ≤ 10^9) — elements of the array A.
The third line contains a single integer m~(1 ≤ m ≤ 3 ⋅ 10^5) — the length of the second array.
The fourth line contains m integers b_1, b_2, ⋅⋅⋅, b_m~(1 ≤ b_i ≤ 10^9) - elements of the array B.
Output
Print a single integer — the maximum length of the resulting arrays after some operations were performed on arrays A and B in such a way that they became equal.
If there is no way to make array equal, print "-1".
Examples
Input
5
11 2 3 5 7
4
11 7 3 7
Output
3
Input
2
1 2
1
100
Output
-1
Input
3
1 2 3
3
1 2 3
Output
3
Tags: greedy, two pointers
Correct Solution:
```
from fractions import gcd
import math
n = int(input())
a= [int(i) for i in input().split()]
m = int(input())
b= [int(i) for i in input().split()]
nn = []
mm = []
if sum(a)!=sum(b):
print(-1)
exit()
ptr_a = 0
ptr_b = 0
sum_a = 0
sum_b = 0
while ptr_a<n and ptr_b<m:
if sum_a==0 and sum_b==0 and a[ptr_a]==b[ptr_b]:
mm.append(a[ptr_a])
nn.append(a[ptr_a])
ptr_a+=1
ptr_b+=1
else:
if sum_a==0 and sum_b==0:
sum_a = a[ptr_a]
sum_b = b[ptr_b]
if sum_a < sum_b:
ptr_a+=1
sum_a+=a[ptr_a]
elif sum_a > sum_b:
ptr_b+=1
sum_b+=b[ptr_b]
else:
ptr_a+=1
ptr_b+=1
nn.append(sum_b)
mm.append(sum_b)
sum_a=0
sum_b = 0
# print(nn,mm,ptr_a,ptr_b,sum_a,sum_b)
print(len(nn))
```
| 87,544 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has two arrays A and B of lengths n and m, respectively.
He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array [1, 10, 100, 1000, 10000] Vasya can obtain array [1, 1110, 10000], and from array [1, 2, 3] Vasya can obtain array [6].
Two arrays A and B are considered equal if and only if they have the same length and for each valid i A_i = B_i.
Vasya wants to perform some of these operations on array A, some on array B, in such a way that arrays A and B become equal. Moreover, the lengths of the resulting arrays should be maximal possible.
Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays A and B equal.
Input
The first line contains a single integer n~(1 ≤ n ≤ 3 ⋅ 10^5) — the length of the first array.
The second line contains n integers a_1, a_2, ⋅⋅⋅, a_n~(1 ≤ a_i ≤ 10^9) — elements of the array A.
The third line contains a single integer m~(1 ≤ m ≤ 3 ⋅ 10^5) — the length of the second array.
The fourth line contains m integers b_1, b_2, ⋅⋅⋅, b_m~(1 ≤ b_i ≤ 10^9) - elements of the array B.
Output
Print a single integer — the maximum length of the resulting arrays after some operations were performed on arrays A and B in such a way that they became equal.
If there is no way to make array equal, print "-1".
Examples
Input
5
11 2 3 5 7
4
11 7 3 7
Output
3
Input
2
1 2
1
100
Output
-1
Input
3
1 2 3
3
1 2 3
Output
3
Tags: greedy, two pointers
Correct Solution:
```
ka=int(input())
a=list(map(int,input().split()))
kb=int(input())
b=list(map(int,input().split()))
def sum1(a):
k=0
for i in a:
k+=a
return k
def www(a ,b, k1, k2):
ka=k1
kb=k2
sa=a[ka]
sb=b[kb]
while sa!=sb:
if sa>sb:
kb+=1
sb+=b[kb]
else:
ka+=1
sa+=a[ka]
return ka+1,kb+1
k1=0
k2=0
if sum(a)!=sum(b):
print('-1')
else:
ans=0
while k1<len(a):
k1,k2=www(a,b,k1,k2)
ans+=1
print(ans)
```
| 87,545 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has two arrays A and B of lengths n and m, respectively.
He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array [1, 10, 100, 1000, 10000] Vasya can obtain array [1, 1110, 10000], and from array [1, 2, 3] Vasya can obtain array [6].
Two arrays A and B are considered equal if and only if they have the same length and for each valid i A_i = B_i.
Vasya wants to perform some of these operations on array A, some on array B, in such a way that arrays A and B become equal. Moreover, the lengths of the resulting arrays should be maximal possible.
Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays A and B equal.
Input
The first line contains a single integer n~(1 ≤ n ≤ 3 ⋅ 10^5) — the length of the first array.
The second line contains n integers a_1, a_2, ⋅⋅⋅, a_n~(1 ≤ a_i ≤ 10^9) — elements of the array A.
The third line contains a single integer m~(1 ≤ m ≤ 3 ⋅ 10^5) — the length of the second array.
The fourth line contains m integers b_1, b_2, ⋅⋅⋅, b_m~(1 ≤ b_i ≤ 10^9) - elements of the array B.
Output
Print a single integer — the maximum length of the resulting arrays after some operations were performed on arrays A and B in such a way that they became equal.
If there is no way to make array equal, print "-1".
Examples
Input
5
11 2 3 5 7
4
11 7 3 7
Output
3
Input
2
1 2
1
100
Output
-1
Input
3
1 2 3
3
1 2 3
Output
3
Tags: greedy, two pointers
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
m = int(input())
b = list(map(int, input().split()))
ptra = 1
ptrb = 1
sa = a[0]
sb = b[0]
ans = 0
while ptra != n and ptrb != m:
if sa == sb:
ans += 1
sa = a[ptra]
sb = b[ptrb]
ptra += 1
ptrb += 1
continue
if sa < sb:
sa += a[ptra]
ptra += 1
else:
sb += b[ptrb]
ptrb += 1
while ptra != n:
sa += a[ptra]
ptra += 1
while ptrb != m:
sb += b[ptrb]
ptrb += 1
if sa != sb:
print(-1)
exit(0)
print(ans + 1)
```
| 87,546 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has two arrays A and B of lengths n and m, respectively.
He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array [1, 10, 100, 1000, 10000] Vasya can obtain array [1, 1110, 10000], and from array [1, 2, 3] Vasya can obtain array [6].
Two arrays A and B are considered equal if and only if they have the same length and for each valid i A_i = B_i.
Vasya wants to perform some of these operations on array A, some on array B, in such a way that arrays A and B become equal. Moreover, the lengths of the resulting arrays should be maximal possible.
Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays A and B equal.
Input
The first line contains a single integer n~(1 ≤ n ≤ 3 ⋅ 10^5) — the length of the first array.
The second line contains n integers a_1, a_2, ⋅⋅⋅, a_n~(1 ≤ a_i ≤ 10^9) — elements of the array A.
The third line contains a single integer m~(1 ≤ m ≤ 3 ⋅ 10^5) — the length of the second array.
The fourth line contains m integers b_1, b_2, ⋅⋅⋅, b_m~(1 ≤ b_i ≤ 10^9) - elements of the array B.
Output
Print a single integer — the maximum length of the resulting arrays after some operations were performed on arrays A and B in such a way that they became equal.
If there is no way to make array equal, print "-1".
Examples
Input
5
11 2 3 5 7
4
11 7 3 7
Output
3
Input
2
1 2
1
100
Output
-1
Input
3
1 2 3
3
1 2 3
Output
3
Tags: greedy, two pointers
Correct Solution:
```
# import atexit
# import io
# import sys
#
# _INPUT_LINES = sys.stdin.read().splitlines()
# input = iter(_INPUT_LINES).__next__
# _OUTPUT_BUFFER = io.StringIO()
# sys.stdout = _OUTPUT_BUFFER
#
#
# @atexit.register
# def write():
# sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
from itertools import accumulate
def main():
n = int(input())
arr1 = list(accumulate(map(int, input().split())))
m = int(input())
arr2 = list(accumulate(map(int, input().split())))
if arr1[-1] != arr2[-1]:
print(-1)
exit(0)
s1 = set(arr1)
cnt = 0
for v in arr2:
if v in s1:
cnt += 1
print(cnt)
if __name__ == "__main__":
main()
```
| 87,547 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has two arrays A and B of lengths n and m, respectively.
He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array [1, 10, 100, 1000, 10000] Vasya can obtain array [1, 1110, 10000], and from array [1, 2, 3] Vasya can obtain array [6].
Two arrays A and B are considered equal if and only if they have the same length and for each valid i A_i = B_i.
Vasya wants to perform some of these operations on array A, some on array B, in such a way that arrays A and B become equal. Moreover, the lengths of the resulting arrays should be maximal possible.
Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays A and B equal.
Input
The first line contains a single integer n~(1 ≤ n ≤ 3 ⋅ 10^5) — the length of the first array.
The second line contains n integers a_1, a_2, ⋅⋅⋅, a_n~(1 ≤ a_i ≤ 10^9) — elements of the array A.
The third line contains a single integer m~(1 ≤ m ≤ 3 ⋅ 10^5) — the length of the second array.
The fourth line contains m integers b_1, b_2, ⋅⋅⋅, b_m~(1 ≤ b_i ≤ 10^9) - elements of the array B.
Output
Print a single integer — the maximum length of the resulting arrays after some operations were performed on arrays A and B in such a way that they became equal.
If there is no way to make array equal, print "-1".
Examples
Input
5
11 2 3 5 7
4
11 7 3 7
Output
3
Input
2
1 2
1
100
Output
-1
Input
3
1 2 3
3
1 2 3
Output
3
Tags: greedy, two pointers
Correct Solution:
```
n = int(input())
arr = list(map(int, input().split()))
m = int(input())
brr = list(map(int, input().split()))
if sum(arr) != sum(brr):
print(-1)
exit()
ai = 0
bi = 0
asm = 0
bsm = 0
cnt = 0
while ai < len(arr) and bi < len(brr):
if asm < bsm:
asm += arr[ai]
ai += 1
elif bsm < asm:
bsm += brr[bi]
bi += 1
else:
cnt += 1
asm = arr[ai]
bsm = brr[bi]
ai += 1
bi += 1
print(cnt)
```
| 87,548 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has two arrays A and B of lengths n and m, respectively.
He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array [1, 10, 100, 1000, 10000] Vasya can obtain array [1, 1110, 10000], and from array [1, 2, 3] Vasya can obtain array [6].
Two arrays A and B are considered equal if and only if they have the same length and for each valid i A_i = B_i.
Vasya wants to perform some of these operations on array A, some on array B, in such a way that arrays A and B become equal. Moreover, the lengths of the resulting arrays should be maximal possible.
Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays A and B equal.
Input
The first line contains a single integer n~(1 ≤ n ≤ 3 ⋅ 10^5) — the length of the first array.
The second line contains n integers a_1, a_2, ⋅⋅⋅, a_n~(1 ≤ a_i ≤ 10^9) — elements of the array A.
The third line contains a single integer m~(1 ≤ m ≤ 3 ⋅ 10^5) — the length of the second array.
The fourth line contains m integers b_1, b_2, ⋅⋅⋅, b_m~(1 ≤ b_i ≤ 10^9) - elements of the array B.
Output
Print a single integer — the maximum length of the resulting arrays after some operations were performed on arrays A and B in such a way that they became equal.
If there is no way to make array equal, print "-1".
Examples
Input
5
11 2 3 5 7
4
11 7 3 7
Output
3
Input
2
1 2
1
100
Output
-1
Input
3
1 2 3
3
1 2 3
Output
3
Submitted Solution:
```
n=int(input())
a=[int(i) for i in input().split(' ')]
m=int(input())
b=[int(i) for i in input().split(' ')]
aa=[a[0]]
bb=[b[0]]
for i in range(1,n):
aa.append(aa[-1]+a[i])
for i in range(1,m):
bb.append(bb[-1]+b[i])
a1=set(aa)
a2=set(bb)
if sum(a)!=sum(b):
print(-1)
else:
print(len((a1.intersection(a2))))
```
Yes
| 87,549 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has two arrays A and B of lengths n and m, respectively.
He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array [1, 10, 100, 1000, 10000] Vasya can obtain array [1, 1110, 10000], and from array [1, 2, 3] Vasya can obtain array [6].
Two arrays A and B are considered equal if and only if they have the same length and for each valid i A_i = B_i.
Vasya wants to perform some of these operations on array A, some on array B, in such a way that arrays A and B become equal. Moreover, the lengths of the resulting arrays should be maximal possible.
Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays A and B equal.
Input
The first line contains a single integer n~(1 ≤ n ≤ 3 ⋅ 10^5) — the length of the first array.
The second line contains n integers a_1, a_2, ⋅⋅⋅, a_n~(1 ≤ a_i ≤ 10^9) — elements of the array A.
The third line contains a single integer m~(1 ≤ m ≤ 3 ⋅ 10^5) — the length of the second array.
The fourth line contains m integers b_1, b_2, ⋅⋅⋅, b_m~(1 ≤ b_i ≤ 10^9) - elements of the array B.
Output
Print a single integer — the maximum length of the resulting arrays after some operations were performed on arrays A and B in such a way that they became equal.
If there is no way to make array equal, print "-1".
Examples
Input
5
11 2 3 5 7
4
11 7 3 7
Output
3
Input
2
1 2
1
100
Output
-1
Input
3
1 2 3
3
1 2 3
Output
3
Submitted Solution:
```
n = int(input())
a = [int(x) for x in input().split()]
m = int(input())
b = [int(x) for x in input().split()]
i = j = 0
x = a[0]
y = b[0]
length = 0
while True:
if x == y and i < (n - 1) and j < (m - 1):
length += 1
i += 1
j += 1
# if i < n and j < m:
x = a[i]
y = b[j]
elif x < y and i < (n - 1):
i += 1
x += a[i]
elif x > y and j < (m - 1):
j += 1
y += b[j]
else:
break
if i == (n - 1) and j == (m - 1) and x == y:
print(length + 1)
else:
print(-1)
```
Yes
| 87,550 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has two arrays A and B of lengths n and m, respectively.
He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array [1, 10, 100, 1000, 10000] Vasya can obtain array [1, 1110, 10000], and from array [1, 2, 3] Vasya can obtain array [6].
Two arrays A and B are considered equal if and only if they have the same length and for each valid i A_i = B_i.
Vasya wants to perform some of these operations on array A, some on array B, in such a way that arrays A and B become equal. Moreover, the lengths of the resulting arrays should be maximal possible.
Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays A and B equal.
Input
The first line contains a single integer n~(1 ≤ n ≤ 3 ⋅ 10^5) — the length of the first array.
The second line contains n integers a_1, a_2, ⋅⋅⋅, a_n~(1 ≤ a_i ≤ 10^9) — elements of the array A.
The third line contains a single integer m~(1 ≤ m ≤ 3 ⋅ 10^5) — the length of the second array.
The fourth line contains m integers b_1, b_2, ⋅⋅⋅, b_m~(1 ≤ b_i ≤ 10^9) - elements of the array B.
Output
Print a single integer — the maximum length of the resulting arrays after some operations were performed on arrays A and B in such a way that they became equal.
If there is no way to make array equal, print "-1".
Examples
Input
5
11 2 3 5 7
4
11 7 3 7
Output
3
Input
2
1 2
1
100
Output
-1
Input
3
1 2 3
3
1 2 3
Output
3
Submitted Solution:
```
# import sys
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
n = int(input())
a = list(map(int,input().split()))
m = int(input())
b = list(map(int,input().split()))
aNew = [0]*n
bNew = [0]*m
aNew[0] = a[0]
bNew[0] = b[0]
for i in range(1,n):
aNew[i] = aNew[i-1] + a[i]
for i in range(1,m):
bNew[i] = bNew[i-1] + b[i]
count = 0
i = 0
j = 0
while (i<n and j<m):
if (aNew[i] > bNew[j]):
j += 1
elif (aNew[i] < bNew[j]):
i += 1
else:
count += 1
i += 1
j += 1
if (i==n and j==m):
print(count)
else:
print(-1)
```
Yes
| 87,551 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has two arrays A and B of lengths n and m, respectively.
He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array [1, 10, 100, 1000, 10000] Vasya can obtain array [1, 1110, 10000], and from array [1, 2, 3] Vasya can obtain array [6].
Two arrays A and B are considered equal if and only if they have the same length and for each valid i A_i = B_i.
Vasya wants to perform some of these operations on array A, some on array B, in such a way that arrays A and B become equal. Moreover, the lengths of the resulting arrays should be maximal possible.
Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays A and B equal.
Input
The first line contains a single integer n~(1 ≤ n ≤ 3 ⋅ 10^5) — the length of the first array.
The second line contains n integers a_1, a_2, ⋅⋅⋅, a_n~(1 ≤ a_i ≤ 10^9) — elements of the array A.
The third line contains a single integer m~(1 ≤ m ≤ 3 ⋅ 10^5) — the length of the second array.
The fourth line contains m integers b_1, b_2, ⋅⋅⋅, b_m~(1 ≤ b_i ≤ 10^9) - elements of the array B.
Output
Print a single integer — the maximum length of the resulting arrays after some operations were performed on arrays A and B in such a way that they became equal.
If there is no way to make array equal, print "-1".
Examples
Input
5
11 2 3 5 7
4
11 7 3 7
Output
3
Input
2
1 2
1
100
Output
-1
Input
3
1 2 3
3
1 2 3
Output
3
Submitted Solution:
```
n = int(input())
arr1 = [int(element) for element in input().split()]
m = int(input())
arr2 = [int(element) for element in input().split()]
res = 0
p1 = 0
p2 = 0
sum1 = arr1[p1]
sum2 = arr2[p2]
arr1.append(0)
arr2.append(0)
while (p1 < n and p2 < m):
if (sum1 == sum2):
res += 1
sum1 = arr1[p1 + 1]
sum2 = arr2[p2 + 1]
p1 += 1
p2 += 1
elif (sum1 < sum2):
sum1 += arr1[p1 + 1]
p1 += 1
elif (sum1 > sum2):
sum2 += arr2[p2 + 1]
p2 += 1
if (p1 == n and p2 == m):
print(res)
else:
print(-1)
```
Yes
| 87,552 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has two arrays A and B of lengths n and m, respectively.
He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array [1, 10, 100, 1000, 10000] Vasya can obtain array [1, 1110, 10000], and from array [1, 2, 3] Vasya can obtain array [6].
Two arrays A and B are considered equal if and only if they have the same length and for each valid i A_i = B_i.
Vasya wants to perform some of these operations on array A, some on array B, in such a way that arrays A and B become equal. Moreover, the lengths of the resulting arrays should be maximal possible.
Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays A and B equal.
Input
The first line contains a single integer n~(1 ≤ n ≤ 3 ⋅ 10^5) — the length of the first array.
The second line contains n integers a_1, a_2, ⋅⋅⋅, a_n~(1 ≤ a_i ≤ 10^9) — elements of the array A.
The third line contains a single integer m~(1 ≤ m ≤ 3 ⋅ 10^5) — the length of the second array.
The fourth line contains m integers b_1, b_2, ⋅⋅⋅, b_m~(1 ≤ b_i ≤ 10^9) - elements of the array B.
Output
Print a single integer — the maximum length of the resulting arrays after some operations were performed on arrays A and B in such a way that they became equal.
If there is no way to make array equal, print "-1".
Examples
Input
5
11 2 3 5 7
4
11 7 3 7
Output
3
Input
2
1 2
1
100
Output
-1
Input
3
1 2 3
3
1 2 3
Output
3
Submitted Solution:
```
n = int(input())
a = [int(i) for i in input().split()]
m = int(input())
b = [int(i) for i in input().split()]
if sum(a) != sum(b):
print(-1)
else:
i = 0
j = 0
c1 = a[0]
c2 = b[0]
count = 0
while i < n and j < m:
if c1 == c2:
count += 1
i += 1
j += 1
if i < n and j < n:
c1 += a[i]
c2 += b[j]
elif c1 < c2:
i += 1
if i < n:
c1 += a[i]
elif c2 < c1:
j += 1
if j < n:
c2 += b[j]
print(count)
```
No
| 87,553 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has two arrays A and B of lengths n and m, respectively.
He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array [1, 10, 100, 1000, 10000] Vasya can obtain array [1, 1110, 10000], and from array [1, 2, 3] Vasya can obtain array [6].
Two arrays A and B are considered equal if and only if they have the same length and for each valid i A_i = B_i.
Vasya wants to perform some of these operations on array A, some on array B, in such a way that arrays A and B become equal. Moreover, the lengths of the resulting arrays should be maximal possible.
Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays A and B equal.
Input
The first line contains a single integer n~(1 ≤ n ≤ 3 ⋅ 10^5) — the length of the first array.
The second line contains n integers a_1, a_2, ⋅⋅⋅, a_n~(1 ≤ a_i ≤ 10^9) — elements of the array A.
The third line contains a single integer m~(1 ≤ m ≤ 3 ⋅ 10^5) — the length of the second array.
The fourth line contains m integers b_1, b_2, ⋅⋅⋅, b_m~(1 ≤ b_i ≤ 10^9) - elements of the array B.
Output
Print a single integer — the maximum length of the resulting arrays after some operations were performed on arrays A and B in such a way that they became equal.
If there is no way to make array equal, print "-1".
Examples
Input
5
11 2 3 5 7
4
11 7 3 7
Output
3
Input
2
1 2
1
100
Output
-1
Input
3
1 2 3
3
1 2 3
Output
3
Submitted Solution:
```
from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush,heappop
import math
from collections import *
from functools import reduce,cmp_to_key, lru_cache
import sys
input = sys.stdin.readline
M = mod = 10 ** 9 + 7
def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
def inv_mod(n):return pow(n, mod - 2, mod)
def li():return [int(i) for i in input().rstrip('\n').split()]
def st():return input().rstrip('\n')
def val():return int(input().rstrip('\n'))
def li2():return [i for i in input().rstrip('\n')]
def li3():return [int(i) for i in input().rstrip('\n')]
n = val()
l1 = li()
m = val()
l2 = li()
if sum(l1) != sum(l2):
print(-1)
exit()
curr1 = ans = i = j = curr2 = 0
i = j = 1
for itr in range(n):
if l1[itr] != l2[itr]:
ans = itr
i = itr + 1
curr1 = l1[itr]
j = itr
break
ans += 1
i = itr + 1
j = itr + 1
if i == n:
print(ans)
exit()
while i < n and j < m:
if curr1 == curr2:
curr1 = curr2 = 0
i += 1
j += 1
ans += 1
if i < n:
curr1 = l1[i]
i += 1
elif curr1 < curr2:
curr1 += l1[i]
i += 1
else:
curr2 += l2[j]
j += 1
# print(i, j, curr1, curr2, ans)
# print(ans)
ans += 1
print(ans)
```
No
| 87,554 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has two arrays A and B of lengths n and m, respectively.
He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array [1, 10, 100, 1000, 10000] Vasya can obtain array [1, 1110, 10000], and from array [1, 2, 3] Vasya can obtain array [6].
Two arrays A and B are considered equal if and only if they have the same length and for each valid i A_i = B_i.
Vasya wants to perform some of these operations on array A, some on array B, in such a way that arrays A and B become equal. Moreover, the lengths of the resulting arrays should be maximal possible.
Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays A and B equal.
Input
The first line contains a single integer n~(1 ≤ n ≤ 3 ⋅ 10^5) — the length of the first array.
The second line contains n integers a_1, a_2, ⋅⋅⋅, a_n~(1 ≤ a_i ≤ 10^9) — elements of the array A.
The third line contains a single integer m~(1 ≤ m ≤ 3 ⋅ 10^5) — the length of the second array.
The fourth line contains m integers b_1, b_2, ⋅⋅⋅, b_m~(1 ≤ b_i ≤ 10^9) - elements of the array B.
Output
Print a single integer — the maximum length of the resulting arrays after some operations were performed on arrays A and B in such a way that they became equal.
If there is no way to make array equal, print "-1".
Examples
Input
5
11 2 3 5 7
4
11 7 3 7
Output
3
Input
2
1 2
1
100
Output
-1
Input
3
1 2 3
3
1 2 3
Output
3
Submitted Solution:
```
"""import math
n,k=map(int,input().split())
#s=[int(x) for x in input().split()]
#for i in range(0,len(s)):
ans=k//n
if(k%n!=0):
ans=ans+1
print(ans)
#ans=math.ceil(k/n)
#print(ans)
"""
"""q=int(input())
for i in range(0,q):
n,m,k=map(int,input().split())
if(k<n or k<m):
print('-1')
else:
#ct=min(n,m)
x=max(n,m)-min(n,m)
y=k-min(n,m)
if(x%2==0 and (y-x)%2==0):
print(k)
elif(x%2==0 and (y-x)%2!=0):
print(k-2)
else:
print(k-1)"""
n=int(input())
s1=[int(x) for x in input().split()]
m=int(input())
s2=[int(x) for x in input().split()]
if(n==1 or m==1):
if(n==1):
r=0
for j in range(0,m):
r=r+s2[j]
if(r==s1[0]):
print('1')
else:
print('-1')
else:
r=0
for j in range(0,n):
r=r+s1[j]
if(r==s2[0]):
print('1')
else:
print('-1')
else:
pt1=1
pt2=1
sm1=s1[0]
sm2=s2[0]
L1=[]
L2=[]
c=0
for i in range(0,n+m+1):
if(sm1==sm2):
c=c+1
L1.append(sm1)
L2.append(sm2)
sm1=s1[pt1]
sm2=s2[pt2]
pt1=pt1+1
pt2=pt2+1
elif(sm1>sm2):
sm2=sm2+s2[pt2]
pt2=pt2+1
else:
sm1=sm1+s1[pt1]
pt1=pt1+1
if(pt1==n or pt2==m):
break
if(sm1==sm2):
c=c+1
L1.append(sm1)
L2.append(sm2)
#sm1=s1[pt1]
#sm2=s2[pt2]
pt1=pt1+1
pt2=pt2+1
if(len(L1)==0 or len(L2)==0):
print('-1')
else:
if(len(L1)==len(L2)):
print(len(L1))
```
No
| 87,555 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has two arrays A and B of lengths n and m, respectively.
He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array [1, 10, 100, 1000, 10000] Vasya can obtain array [1, 1110, 10000], and from array [1, 2, 3] Vasya can obtain array [6].
Two arrays A and B are considered equal if and only if they have the same length and for each valid i A_i = B_i.
Vasya wants to perform some of these operations on array A, some on array B, in such a way that arrays A and B become equal. Moreover, the lengths of the resulting arrays should be maximal possible.
Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays A and B equal.
Input
The first line contains a single integer n~(1 ≤ n ≤ 3 ⋅ 10^5) — the length of the first array.
The second line contains n integers a_1, a_2, ⋅⋅⋅, a_n~(1 ≤ a_i ≤ 10^9) — elements of the array A.
The third line contains a single integer m~(1 ≤ m ≤ 3 ⋅ 10^5) — the length of the second array.
The fourth line contains m integers b_1, b_2, ⋅⋅⋅, b_m~(1 ≤ b_i ≤ 10^9) - elements of the array B.
Output
Print a single integer — the maximum length of the resulting arrays after some operations were performed on arrays A and B in such a way that they became equal.
If there is no way to make array equal, print "-1".
Examples
Input
5
11 2 3 5 7
4
11 7 3 7
Output
3
Input
2
1 2
1
100
Output
-1
Input
3
1 2 3
3
1 2 3
Output
3
Submitted Solution:
```
from sys import stdin, stdout
import cProfile
printHeap = str()
test = False
memory_constrained = False
def display(string_to_print):
stdout.write(str(string_to_print) + "\n")
def test_print(output):
if test:
stdout.write(str(output) + "\n")
def display_list(list1, sep=" "):
stdout.write(sep.join(map(str, list1)) + "\n")
def get_int():
return int(stdin.readline())
def get_tuple():
return map(int, stdin.readline().split())
def get_list():
return list(map(int, stdin.readline().split()))
memory = dict()
def clear_cache():
global memory
memory = dict()
def cached_fn(fn, *args):
global memory
if args in memory:
return memory[args]
else:
result = fn(*args)
memory[args] = result
return result
# ----------------------------------------------------------------------------------- MAIN PROGRAM
def main():
n = get_int()
a = get_list()
m = get_int()
b = get_list()
if sum(a)!=sum(b):
print("-1")
return
i =0
j = 0
sa = 0
sb = 0
count = 0
while True:
test_print(str(j)+"=JI="+str(i))
if (i==n or j==m):
break
if a[i]==b[j]:
count +=1
i+=1
j+=1
sa,sb = 0,0
continue
elif sa>sb:
sb+=b[j]
j+=1
if sa==sb:
count+=1
sa, sb = 0, 0
elif sa<sb:
sa+=a[i]
i+=1
if sa==sb:
count+=1
sa, sb = 0, 0
else:
if a[i]>b[j]:
sb = b[j]
j+=1
else:
sa = a[i]
i+=1
display(count)
# --------------------------------------------------------------------------------------------- END
cProfile.run('main()') if test else main()
```
No
| 87,556 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call the following process a transformation of a sequence of length n.
If the sequence is empty, the process ends. Otherwise, append the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor) (GCD) of all the elements of the sequence to the result and remove one arbitrary element from the sequence. Thus, when the process ends, we have a sequence of n integers: the greatest common divisors of all the elements in the sequence before each deletion.
You are given an integer sequence 1, 2, ..., n. Find the lexicographically maximum result of its transformation.
A sequence a_1, a_2, …, a_n is lexicographically larger than a sequence b_1, b_2, …, b_n, if there is an index i such that a_j = b_j for all j < i, and a_i > b_i.
Input
The first and only line of input contains one integer n (1≤ n≤ 10^6).
Output
Output n integers — the lexicographically maximum result of the transformation.
Examples
Input
3
Output
1 1 3
Input
2
Output
1 2
Input
1
Output
1
Note
In the first sample the answer may be achieved this way:
* Append GCD(1, 2, 3) = 1, remove 2.
* Append GCD(1, 3) = 1, remove 1.
* Append GCD(3) = 3, remove 3.
We get the sequence [1, 1, 3] as the result.
Tags: constructive algorithms, math
Correct Solution:
```
from math import gcd
n = int(input())
if n==3:
print(1,1,3)
exit()
ans = []
p = 0
avail = [i+1 for i in range(n)]
vis = [False for i in range(n)]
while avail!=[]:
# print(avail)
cnt = 0
for i in range(0,len(avail),2):
p = gcd(p,avail[i])
vis[avail[i]-1] = True
cnt+=1
ans = ans+[p for i in range(cnt)]
# print(avail,p)
p = 0
avail = []
for i in range(n):
if vis[i]==False:
avail.append(i+1)
if len(avail)==1:
ans.append(avail[0])
break
elif len(avail)==2:
ans+=[gcd(avail[0],avail[1]),avail[1]]
break
elif len(avail)==3:
x,y,z = avail
a = gcd(gcd(x,y),z)
b = gcd(y,z)
ans+=[a,b,z]
break
# print(avail,p)
print(*ans)
```
| 87,557 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call the following process a transformation of a sequence of length n.
If the sequence is empty, the process ends. Otherwise, append the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor) (GCD) of all the elements of the sequence to the result and remove one arbitrary element from the sequence. Thus, when the process ends, we have a sequence of n integers: the greatest common divisors of all the elements in the sequence before each deletion.
You are given an integer sequence 1, 2, ..., n. Find the lexicographically maximum result of its transformation.
A sequence a_1, a_2, …, a_n is lexicographically larger than a sequence b_1, b_2, …, b_n, if there is an index i such that a_j = b_j for all j < i, and a_i > b_i.
Input
The first and only line of input contains one integer n (1≤ n≤ 10^6).
Output
Output n integers — the lexicographically maximum result of the transformation.
Examples
Input
3
Output
1 1 3
Input
2
Output
1 2
Input
1
Output
1
Note
In the first sample the answer may be achieved this way:
* Append GCD(1, 2, 3) = 1, remove 2.
* Append GCD(1, 3) = 1, remove 1.
* Append GCD(3) = 3, remove 3.
We get the sequence [1, 1, 3] as the result.
Tags: constructive algorithms, math
Correct Solution:
```
n = int(input())
visit = [0 for i in range(n+1)]
res = []
c = 0
s,t=0,0
def do(i):
global c,s,t
for j in range(i,n+1,2*i):
res.append(i)
c += 1
if c >= (n-1) and n>2:
if s == 0:
s = j
else:
t = j
return res
curr = 0
i = 1
while(i<=n):
# print(i)
do(i)
i = 2*i
if n>2:
res[n-1] = max(s,t)
# print(s,t)
for i in res:
print(i,end=" ")
```
| 87,558 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call the following process a transformation of a sequence of length n.
If the sequence is empty, the process ends. Otherwise, append the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor) (GCD) of all the elements of the sequence to the result and remove one arbitrary element from the sequence. Thus, when the process ends, we have a sequence of n integers: the greatest common divisors of all the elements in the sequence before each deletion.
You are given an integer sequence 1, 2, ..., n. Find the lexicographically maximum result of its transformation.
A sequence a_1, a_2, …, a_n is lexicographically larger than a sequence b_1, b_2, …, b_n, if there is an index i such that a_j = b_j for all j < i, and a_i > b_i.
Input
The first and only line of input contains one integer n (1≤ n≤ 10^6).
Output
Output n integers — the lexicographically maximum result of the transformation.
Examples
Input
3
Output
1 1 3
Input
2
Output
1 2
Input
1
Output
1
Note
In the first sample the answer may be achieved this way:
* Append GCD(1, 2, 3) = 1, remove 2.
* Append GCD(1, 3) = 1, remove 1.
* Append GCD(3) = 3, remove 3.
We get the sequence [1, 1, 3] as the result.
Tags: constructive algorithms, math
Correct Solution:
```
n = int(input())
if n == 1:
print("1")
elif n == 2:
print("1 2")
else:
base = 1
gap = 2
cur = base
next = 1
ans = ''
for i in range(n - 1):
ans += str(base) + ' '
next = cur
cur += gap
if cur > n:
base *= 2
gap *= 2
cur = base
next = max(next, cur)
ans += str(next)
print(ans)
```
| 87,559 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call the following process a transformation of a sequence of length n.
If the sequence is empty, the process ends. Otherwise, append the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor) (GCD) of all the elements of the sequence to the result and remove one arbitrary element from the sequence. Thus, when the process ends, we have a sequence of n integers: the greatest common divisors of all the elements in the sequence before each deletion.
You are given an integer sequence 1, 2, ..., n. Find the lexicographically maximum result of its transformation.
A sequence a_1, a_2, …, a_n is lexicographically larger than a sequence b_1, b_2, …, b_n, if there is an index i such that a_j = b_j for all j < i, and a_i > b_i.
Input
The first and only line of input contains one integer n (1≤ n≤ 10^6).
Output
Output n integers — the lexicographically maximum result of the transformation.
Examples
Input
3
Output
1 1 3
Input
2
Output
1 2
Input
1
Output
1
Note
In the first sample the answer may be achieved this way:
* Append GCD(1, 2, 3) = 1, remove 2.
* Append GCD(1, 3) = 1, remove 1.
* Append GCD(3) = 3, remove 3.
We get the sequence [1, 1, 3] as the result.
Tags: constructive algorithms, math
Correct Solution:
```
#Complexity - O(logn)
import math
n = int(input())
arr = []
curr = 1
while n > 0:
if n == 1:
arr.append(curr)
break
elif n == 2:
arr.append(curr)
arr.append(curr*2)
break
elif n == 3:
arr.append(curr)
arr.append(curr*1)
arr.append(curr*3)
break
else:
arr.extend([curr]*math.ceil(n/2))
n = math.floor(n/2)
curr *= 2
print(" ".join(map(str, arr)))
```
| 87,560 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call the following process a transformation of a sequence of length n.
If the sequence is empty, the process ends. Otherwise, append the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor) (GCD) of all the elements of the sequence to the result and remove one arbitrary element from the sequence. Thus, when the process ends, we have a sequence of n integers: the greatest common divisors of all the elements in the sequence before each deletion.
You are given an integer sequence 1, 2, ..., n. Find the lexicographically maximum result of its transformation.
A sequence a_1, a_2, …, a_n is lexicographically larger than a sequence b_1, b_2, …, b_n, if there is an index i such that a_j = b_j for all j < i, and a_i > b_i.
Input
The first and only line of input contains one integer n (1≤ n≤ 10^6).
Output
Output n integers — the lexicographically maximum result of the transformation.
Examples
Input
3
Output
1 1 3
Input
2
Output
1 2
Input
1
Output
1
Note
In the first sample the answer may be achieved this way:
* Append GCD(1, 2, 3) = 1, remove 2.
* Append GCD(1, 3) = 1, remove 1.
* Append GCD(3) = 3, remove 3.
We get the sequence [1, 1, 3] as the result.
Tags: constructive algorithms, math
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
import math
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
def input(): return sys.stdin.readline().rstrip("\r\n")
def getint(): return int(input())
def getints(): return list(map(int, input().split()))
def getint1(): return list(map(lambda x: int(x) - 1, input().split()))
def main():
###CODE
n = getint()
k = n
if n==1:
print(1)
elif n==2:
print(1,2)
elif n==3:
print(1,1,3)
else:
extra = 0
l = []
if n%2:
extra = 1
n-=1
while n>1:
v = math.ceil(n/2)
l.append(v)
n -= l[-1]
out = []
l[0] += extra
p = 1
for i in l:
out.extend([p]*i)
p*=2
out = out[:k-1]
p = out[-1]
out.append(p*(k//p))
print(*out)
if __name__ == "__main__":
main()
```
| 87,561 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call the following process a transformation of a sequence of length n.
If the sequence is empty, the process ends. Otherwise, append the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor) (GCD) of all the elements of the sequence to the result and remove one arbitrary element from the sequence. Thus, when the process ends, we have a sequence of n integers: the greatest common divisors of all the elements in the sequence before each deletion.
You are given an integer sequence 1, 2, ..., n. Find the lexicographically maximum result of its transformation.
A sequence a_1, a_2, …, a_n is lexicographically larger than a sequence b_1, b_2, …, b_n, if there is an index i such that a_j = b_j for all j < i, and a_i > b_i.
Input
The first and only line of input contains one integer n (1≤ n≤ 10^6).
Output
Output n integers — the lexicographically maximum result of the transformation.
Examples
Input
3
Output
1 1 3
Input
2
Output
1 2
Input
1
Output
1
Note
In the first sample the answer may be achieved this way:
* Append GCD(1, 2, 3) = 1, remove 2.
* Append GCD(1, 3) = 1, remove 1.
* Append GCD(3) = 3, remove 3.
We get the sequence [1, 1, 3] as the result.
Tags: constructive algorithms, math
Correct Solution:
```
n=int(input())
def cal(n,t):
if n==1:
print(t,end=' ')
elif n==2:
print(t,t<<1,end=' ')
elif n==3:
print(t,t,t*3, end=' ')
else:
tmp=n-(n>>1)
for i in range(tmp):
print(t,end=' ')
cal(n>>1,t<<1)
cal(n,1)
```
| 87,562 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call the following process a transformation of a sequence of length n.
If the sequence is empty, the process ends. Otherwise, append the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor) (GCD) of all the elements of the sequence to the result and remove one arbitrary element from the sequence. Thus, when the process ends, we have a sequence of n integers: the greatest common divisors of all the elements in the sequence before each deletion.
You are given an integer sequence 1, 2, ..., n. Find the lexicographically maximum result of its transformation.
A sequence a_1, a_2, …, a_n is lexicographically larger than a sequence b_1, b_2, …, b_n, if there is an index i such that a_j = b_j for all j < i, and a_i > b_i.
Input
The first and only line of input contains one integer n (1≤ n≤ 10^6).
Output
Output n integers — the lexicographically maximum result of the transformation.
Examples
Input
3
Output
1 1 3
Input
2
Output
1 2
Input
1
Output
1
Note
In the first sample the answer may be achieved this way:
* Append GCD(1, 2, 3) = 1, remove 2.
* Append GCD(1, 3) = 1, remove 1.
* Append GCD(3) = 3, remove 3.
We get the sequence [1, 1, 3] as the result.
Tags: constructive algorithms, math
Correct Solution:
```
#copying.............................................
n,t=int(input()),1
while n>0:
if n!=3:
k=n//2+n%2
print((str(t)+' ')*k,end='')
n-=k
t*=2
else:
print(t,t,t*3)
n=0
```
| 87,563 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call the following process a transformation of a sequence of length n.
If the sequence is empty, the process ends. Otherwise, append the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor) (GCD) of all the elements of the sequence to the result and remove one arbitrary element from the sequence. Thus, when the process ends, we have a sequence of n integers: the greatest common divisors of all the elements in the sequence before each deletion.
You are given an integer sequence 1, 2, ..., n. Find the lexicographically maximum result of its transformation.
A sequence a_1, a_2, …, a_n is lexicographically larger than a sequence b_1, b_2, …, b_n, if there is an index i such that a_j = b_j for all j < i, and a_i > b_i.
Input
The first and only line of input contains one integer n (1≤ n≤ 10^6).
Output
Output n integers — the lexicographically maximum result of the transformation.
Examples
Input
3
Output
1 1 3
Input
2
Output
1 2
Input
1
Output
1
Note
In the first sample the answer may be achieved this way:
* Append GCD(1, 2, 3) = 1, remove 2.
* Append GCD(1, 3) = 1, remove 1.
* Append GCD(3) = 3, remove 3.
We get the sequence [1, 1, 3] as the result.
Tags: constructive algorithms, math
Correct Solution:
```
from sys import stdin,stdout,exit,setrecursionlimit
def sin():
return stdin.readline().rstrip()
def listInput():
return list(map(int,sin().split()))
def printBS(li):
if not li: return
for i in range(len(li)-1):
stdout.write("%d "%(li[i]))
stdout.write("%d\n"%(li[-1]))
setrecursionlimit(10**5)
n = int(sin())
def res(i):
if i==1: return [1]
if i==2: return [1,2]
if i==3: return [1,1,3]
cnt = i//2
if i%2==1: cnt+=1
return [1]*cnt+[2*j for j in res(i-cnt)]
printBS(res(n))
```
| 87,564 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call the following process a transformation of a sequence of length n.
If the sequence is empty, the process ends. Otherwise, append the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor) (GCD) of all the elements of the sequence to the result and remove one arbitrary element from the sequence. Thus, when the process ends, we have a sequence of n integers: the greatest common divisors of all the elements in the sequence before each deletion.
You are given an integer sequence 1, 2, ..., n. Find the lexicographically maximum result of its transformation.
A sequence a_1, a_2, …, a_n is lexicographically larger than a sequence b_1, b_2, …, b_n, if there is an index i such that a_j = b_j for all j < i, and a_i > b_i.
Input
The first and only line of input contains one integer n (1≤ n≤ 10^6).
Output
Output n integers — the lexicographically maximum result of the transformation.
Examples
Input
3
Output
1 1 3
Input
2
Output
1 2
Input
1
Output
1
Note
In the first sample the answer may be achieved this way:
* Append GCD(1, 2, 3) = 1, remove 2.
* Append GCD(1, 3) = 1, remove 1.
* Append GCD(3) = 3, remove 3.
We get the sequence [1, 1, 3] as the result.
Submitted Solution:
```
n = int(input())
if n == 3:
print('1 1 3')
exit()
if n == 1:
print('1')
exit()
if n == 2:
print('1 2')
exit()
d = 2
ans = []
lfn = n
while d <= n:
k = n // d
for j in range(lfn - k):
ans.append(d//2)
lfn = n - len(ans)
d *=2
d //= 2
k = n/d
if k < 1.5:
ans.append(d)
else:
ans.append(d + d//2)
print(' '.join([str(i) for i in ans]))
```
Yes
| 87,565 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call the following process a transformation of a sequence of length n.
If the sequence is empty, the process ends. Otherwise, append the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor) (GCD) of all the elements of the sequence to the result and remove one arbitrary element from the sequence. Thus, when the process ends, we have a sequence of n integers: the greatest common divisors of all the elements in the sequence before each deletion.
You are given an integer sequence 1, 2, ..., n. Find the lexicographically maximum result of its transformation.
A sequence a_1, a_2, …, a_n is lexicographically larger than a sequence b_1, b_2, …, b_n, if there is an index i such that a_j = b_j for all j < i, and a_i > b_i.
Input
The first and only line of input contains one integer n (1≤ n≤ 10^6).
Output
Output n integers — the lexicographically maximum result of the transformation.
Examples
Input
3
Output
1 1 3
Input
2
Output
1 2
Input
1
Output
1
Note
In the first sample the answer may be achieved this way:
* Append GCD(1, 2, 3) = 1, remove 2.
* Append GCD(1, 3) = 1, remove 1.
* Append GCD(3) = 3, remove 3.
We get the sequence [1, 1, 3] as the result.
Submitted Solution:
```
import bisect
from itertools import accumulate
import os
import sys
import math
from decimal import *
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
def input(): return sys.stdin.readline().rstrip("\r\n")
def isPrime(n) :
if (n <= 1) : return False
if (n <= 3) : return True
if (n % 2 == 0 or n % 3 == 0) : return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
def SieveOfEratosthenes(n):
prime=[]
primes = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (primes[p] == True):
prime.append(p)
for i in range(p * p, n+1, p):
primes[i] = False
p += 1
return prime
def primefactors(n):
fac=[]
while(n%2==0):
fac.append(2)
n=n//2
for i in range(3,int(math.sqrt(n))+2):
while(n%i==0):
fac.append(i)
n=n//i
if n>1:
fac.append(n)
return fac
def factors(n):
fac=set()
fac.add(1)
fac.add(n)
for i in range(2,int(math.sqrt(n))+1):
if n%i==0:
fac.add(i)
fac.add(n//i)
return list(fac)
def NcR(n, r):
p = 1
k = 1
if (n - r < r):
r = n - r
if (r != 0):
while (r):
p *= n
k *= r
m = math.gcd(p, k)
p //= m
k //= m
n -= 1
r -= 1
else:
p = 1
return p
#--------------------------------------------------------
n = int(input())
i = 0
while n:
if n == 3:
print(2**i,2**i,3*2**i)
break
print(*([2**i]*((n+1)//2)),end = ' ')
n -= (n+1)//2
i += 1
```
Yes
| 87,566 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call the following process a transformation of a sequence of length n.
If the sequence is empty, the process ends. Otherwise, append the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor) (GCD) of all the elements of the sequence to the result and remove one arbitrary element from the sequence. Thus, when the process ends, we have a sequence of n integers: the greatest common divisors of all the elements in the sequence before each deletion.
You are given an integer sequence 1, 2, ..., n. Find the lexicographically maximum result of its transformation.
A sequence a_1, a_2, …, a_n is lexicographically larger than a sequence b_1, b_2, …, b_n, if there is an index i such that a_j = b_j for all j < i, and a_i > b_i.
Input
The first and only line of input contains one integer n (1≤ n≤ 10^6).
Output
Output n integers — the lexicographically maximum result of the transformation.
Examples
Input
3
Output
1 1 3
Input
2
Output
1 2
Input
1
Output
1
Note
In the first sample the answer may be achieved this way:
* Append GCD(1, 2, 3) = 1, remove 2.
* Append GCD(1, 3) = 1, remove 1.
* Append GCD(3) = 3, remove 3.
We get the sequence [1, 1, 3] as the result.
Submitted Solution:
```
n = int(input())
if (n == 3):
print('1 1 3')
else:
done = 0
arr = []
for i in range(30, -1, -1):
arr.extend([2**i]*(n//(2**i) - done))
done += n//(2**i) - done
if (done == 1):
k = i
arr[0] = max(arr[0], (n//2**(k-1)) * 2**(k-1))
arr.reverse()
print(' '.join(map(str, arr)))
```
Yes
| 87,567 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call the following process a transformation of a sequence of length n.
If the sequence is empty, the process ends. Otherwise, append the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor) (GCD) of all the elements of the sequence to the result and remove one arbitrary element from the sequence. Thus, when the process ends, we have a sequence of n integers: the greatest common divisors of all the elements in the sequence before each deletion.
You are given an integer sequence 1, 2, ..., n. Find the lexicographically maximum result of its transformation.
A sequence a_1, a_2, …, a_n is lexicographically larger than a sequence b_1, b_2, …, b_n, if there is an index i such that a_j = b_j for all j < i, and a_i > b_i.
Input
The first and only line of input contains one integer n (1≤ n≤ 10^6).
Output
Output n integers — the lexicographically maximum result of the transformation.
Examples
Input
3
Output
1 1 3
Input
2
Output
1 2
Input
1
Output
1
Note
In the first sample the answer may be achieved this way:
* Append GCD(1, 2, 3) = 1, remove 2.
* Append GCD(1, 3) = 1, remove 1.
* Append GCD(3) = 3, remove 3.
We get the sequence [1, 1, 3] as the result.
Submitted Solution:
```
n=int(input())
n0=n
a=[]
a1=0
b=1
while a1<n0:
if n==3:
a+=[b,b,3*b]
a1+=3
else:
a+=[b]*((n+1)//2)
a1+=(n+1)//2
n//=2
b*=2
print(*a)
```
Yes
| 87,568 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call the following process a transformation of a sequence of length n.
If the sequence is empty, the process ends. Otherwise, append the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor) (GCD) of all the elements of the sequence to the result and remove one arbitrary element from the sequence. Thus, when the process ends, we have a sequence of n integers: the greatest common divisors of all the elements in the sequence before each deletion.
You are given an integer sequence 1, 2, ..., n. Find the lexicographically maximum result of its transformation.
A sequence a_1, a_2, …, a_n is lexicographically larger than a sequence b_1, b_2, …, b_n, if there is an index i such that a_j = b_j for all j < i, and a_i > b_i.
Input
The first and only line of input contains one integer n (1≤ n≤ 10^6).
Output
Output n integers — the lexicographically maximum result of the transformation.
Examples
Input
3
Output
1 1 3
Input
2
Output
1 2
Input
1
Output
1
Note
In the first sample the answer may be achieved this way:
* Append GCD(1, 2, 3) = 1, remove 2.
* Append GCD(1, 3) = 1, remove 1.
* Append GCD(3) = 3, remove 3.
We get the sequence [1, 1, 3] as the result.
Submitted Solution:
```
from math import log2
n = int(input())
if n == 1:
print(1)
elif n == 3:
print(1, 1, 3)
exit()
l = [1] * (n // 2)
if n % 2 == 1:
l.append(1)
xn = int(log2(n))
tmp = n - len(l)
for i in range(2, xn+1):
fn = tmp // 2
if tmp % 2 == 1:
fn += 1
tmp -= fn
l += ([pow(2, i-1)] * fn)
l.append(pow(2, xn))
print(' '.join(str(i) for i in l))
```
No
| 87,569 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call the following process a transformation of a sequence of length n.
If the sequence is empty, the process ends. Otherwise, append the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor) (GCD) of all the elements of the sequence to the result and remove one arbitrary element from the sequence. Thus, when the process ends, we have a sequence of n integers: the greatest common divisors of all the elements in the sequence before each deletion.
You are given an integer sequence 1, 2, ..., n. Find the lexicographically maximum result of its transformation.
A sequence a_1, a_2, …, a_n is lexicographically larger than a sequence b_1, b_2, …, b_n, if there is an index i such that a_j = b_j for all j < i, and a_i > b_i.
Input
The first and only line of input contains one integer n (1≤ n≤ 10^6).
Output
Output n integers — the lexicographically maximum result of the transformation.
Examples
Input
3
Output
1 1 3
Input
2
Output
1 2
Input
1
Output
1
Note
In the first sample the answer may be achieved this way:
* Append GCD(1, 2, 3) = 1, remove 2.
* Append GCD(1, 3) = 1, remove 1.
* Append GCD(3) = 3, remove 3.
We get the sequence [1, 1, 3] as the result.
Submitted Solution:
```
n = int(input())
if n == 3:
print('1 1 3')
exit()
i = 1
while n:
if i > 1:
print(' ', end='')
print(*([i] * ((n + 1) // 2)), end='')
i <<= 1
n >>= 1
```
No
| 87,570 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call the following process a transformation of a sequence of length n.
If the sequence is empty, the process ends. Otherwise, append the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor) (GCD) of all the elements of the sequence to the result and remove one arbitrary element from the sequence. Thus, when the process ends, we have a sequence of n integers: the greatest common divisors of all the elements in the sequence before each deletion.
You are given an integer sequence 1, 2, ..., n. Find the lexicographically maximum result of its transformation.
A sequence a_1, a_2, …, a_n is lexicographically larger than a sequence b_1, b_2, …, b_n, if there is an index i such that a_j = b_j for all j < i, and a_i > b_i.
Input
The first and only line of input contains one integer n (1≤ n≤ 10^6).
Output
Output n integers — the lexicographically maximum result of the transformation.
Examples
Input
3
Output
1 1 3
Input
2
Output
1 2
Input
1
Output
1
Note
In the first sample the answer may be achieved this way:
* Append GCD(1, 2, 3) = 1, remove 2.
* Append GCD(1, 3) = 1, remove 1.
* Append GCD(3) = 3, remove 3.
We get the sequence [1, 1, 3] as the result.
Submitted Solution:
```
def getFactors(n):
f = []
p = 2
while n % p == 0:
f.append(p)
n /= p
p = 3
while n > 1:
while n % p == 0:
f.append(p)
n /= p
p += 2
return f
def getMagicNumbers(n, factors):
answer = [0] * len(factors)
for i, f in enumerate(factors):
answer[-i - 1] = n
n //= f
return answer
n = int(input())
answer = [1] * n
factors = getFactors(n)
if len(factors) == 1:
answer[-1] = n
else:
replacement = getMagicNumbers(n, factors)
answer[n - len(replacement):] = replacement
print (' '.join(map(str, answer)))
# 2 2 2
# 2 4 8
# 8
# 4 8
#
# 1 1 1 1 1 2 2
# 4
# 2 2 3
# 3 2 2
# 2 4 6 12
# 2,2,3->
# 12->6->3
# 24
# 2 2 2 3
# 24->12->6->3
#2 3 6
#1 1 1 2 3 6
#
#1 1 1 2 3 6
# 4
# 1 2 3 4
# 4
# 1 1 2 4
# 2 3 4 5
# 1
# 1 1 1 2 4
# 1 1 1 1 5
# 1 1 1 1 1 1 1 1 3 9
```
No
| 87,571 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call the following process a transformation of a sequence of length n.
If the sequence is empty, the process ends. Otherwise, append the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor) (GCD) of all the elements of the sequence to the result and remove one arbitrary element from the sequence. Thus, when the process ends, we have a sequence of n integers: the greatest common divisors of all the elements in the sequence before each deletion.
You are given an integer sequence 1, 2, ..., n. Find the lexicographically maximum result of its transformation.
A sequence a_1, a_2, …, a_n is lexicographically larger than a sequence b_1, b_2, …, b_n, if there is an index i such that a_j = b_j for all j < i, and a_i > b_i.
Input
The first and only line of input contains one integer n (1≤ n≤ 10^6).
Output
Output n integers — the lexicographically maximum result of the transformation.
Examples
Input
3
Output
1 1 3
Input
2
Output
1 2
Input
1
Output
1
Note
In the first sample the answer may be achieved this way:
* Append GCD(1, 2, 3) = 1, remove 2.
* Append GCD(1, 3) = 1, remove 1.
* Append GCD(3) = 3, remove 3.
We get the sequence [1, 1, 3] as the result.
Submitted Solution:
```
n = int(input())
def solve(n):
if n == 1: return '1'
if n == 2: return '1 2'
if n == 3: return '1 1 3'
if n == 6: return '1 1 1 2 2 6'
if n == 7: return '1 1 1 1 2 2 6'
res = []
num = 1
tmp = n
while len(res) < tmp:
c = (n+1) // 2
res += [num] * c
n = n - c
num *= 2
return ' '.join(map(str, res))
print(solve(n))
```
No
| 87,572 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sonya had a birthday recently. She was presented with the matrix of size n× m and consist of lowercase Latin letters. We assume that the rows are numbered by integers from 1 to n from bottom to top, and the columns are numbered from 1 to m from left to right.
Let's call a submatrix (i_1, j_1, i_2, j_2) (1≤ i_1≤ i_2≤ n; 1≤ j_1≤ j_2≤ m) elements a_{ij} of this matrix, such that i_1≤ i≤ i_2 and j_1≤ j≤ j_2. Sonya states that a submatrix is beautiful if we can independently reorder the characters in each row (not in column) so that all rows and columns of this submatrix form palidroms.
Let's recall that a string is called palindrome if it reads the same from left to right and from right to left. For example, strings abacaba, bcaacb, a are palindromes while strings abca, acbba, ab are not.
Help Sonya to find the number of beautiful submatrixes. Submatrixes are different if there is an element that belongs to only one submatrix.
Input
The first line contains two integers n and m (1≤ n, m≤ 250) — the matrix dimensions.
Each of the next n lines contains m lowercase Latin letters.
Output
Print one integer — the number of beautiful submatrixes.
Examples
Input
1 3
aba
Output
4
Input
2 3
aca
aac
Output
11
Input
3 5
accac
aaaba
cccaa
Output
43
Note
In the first example, the following submatrixes are beautiful: ((1, 1), (1, 1)); ((1, 2), (1, 2)); ((1, 3), (1, 3)); ((1, 1), (1, 3)).
In the second example, all submatrixes that consist of one element and the following are beautiful: ((1, 1), (2, 1)); ((1, 1), (1, 3)); ((2, 1), (2, 3)); ((1, 1), (2, 3)); ((2, 1), (2, 2)).
Some of the beautiful submatrixes are: ((1, 1), (1, 5)); ((1, 2), (3, 4)); ((1, 1), (3, 5)).
The submatrix ((1, 1), (3, 5)) is beautiful since it can be reordered as:
accca
aabaa
accca
In such a matrix every row and every column form palindromes.
Submitted Solution:
```
#!/usr/bin/python
# encoding:UTF-8
# Filename:Base.py
import sys
import random
import copy
from itertools import permutations, combinations
from math import sqrt, fabs, ceil
from collections import namedtuple
# ------Util Const--------
in_file_path = "input.txt"
output_file_path = "output.txt"
SUBMIT = True
def get_array(x, initial=None):
dimension = len(x)
if dimension == 1:
return [copy.deepcopy(initial) for _ in range(x[0])]
else:
return [get_array(x[1:], initial) for _ in range(x[0])]
def read_num(fin, num_type=int):
tmp_list = [num_type(x) for x in fin.readline().strip().split()]
if len(tmp_list) == 1:
return tmp_list[0]
else:
return tuple(tmp_list)
def manacher(s):
# new_s = [s[0]]
# for i in range(1, len(s)):
# new_s.append('#')
# new_s.append(s[i])
# print(new_s)
ans_list = []
max_range = 0
max_center = 0
for i in range(0, len(s)):
if max_range > i:
p = min(ans_list[2 * max_center - i], max_range - i)
else:
p = 1
while i - p >= 0 and i + p < len(s) and s[i + p] == s[i - p]:
p += 1
if i + p > max_range:
max_center = i
max_range = i + p
ans_list.append(p)
return ans_list
# A
# def solve(fin, fout):
# n, k = read_num(fin)
# print(ceil((n * 8.0) / k) + ceil((n * 2.0) / k) + ceil((n * 5.0) / k))
# B
# def solve(fin):
# n = read_num(fin)
# for _ in range(0, n):
# l, r = read_num(fin)
# if (r - l + 1) % 2 == 0:
# if l % 2 == 0:
# print(int(-(r - l + 1) / 2))
# else:
# print(int((r - l + 1) / 2))
# else:
# if l % 2 == 0:
# print(int(-(r - l) / 2 + r))
# else:
# print(int((r - l) / 2 - r))
# C
# def solve(fin):
# def count_color(x, y, xx, yy):
# # return _w(x, y, xx, yy), _b(x, y, xx, yy)
# if x > xx or y > yy:
# return 0, 0
# t = (xx - x + 1) * (yy - y + 1)
# if t % 2 == 0:
# return t // 2, t // 2
# else:
# if (x + y) % 2 == 0:
# return t - t // 2, t // 2
# else:
# return t // 2, t - t // 2
#
# T = read_num(fin)
# for _ in range(0, T):
# # print('Test: ',T)
# n, m = read_num(fin)
# x1, y1, x2, y2 = read_num(fin)
# x3, y3, x4, y4 = read_num(fin)
# w, _ = count_color(1, 1, n, m)
# if (max(x1, x3) > min(x2, x4)) or (max(y1, y3) > min(y2, y4)):
# tmp_w, tmp_b = count_color(x1, y1, x2, y2)
# w += tmp_b
# tmp_w, tmp_b = count_color(x3, y3, x4, y4)
# w -= tmp_w
# else:
# tmp_w, tmp_b = count_color(x1, y1, x2, y2)
# w += tmp_b
# tmp_w, tmp_b = count_color(x3, y3, x4, y4)
# w -= tmp_w
# tmp_x_list = sorted([x1, x2, x3, x4])
# tmp_y_list = sorted([y1, y2, y3, y4])
# x5, x6 = tmp_x_list[1], tmp_x_list[2]
# y5, y6 = tmp_y_list[1], tmp_y_list[2]
# tmp_w, tmp_b = count_color(x5, y5, x6, y6)
# w -= tmp_b
# print(w, n * m - w)
# D
# def solve(fin):
# T = read_num(fin)
# for _ in range(0, T):
# n, k = read_num(fin)
# if n > 34 or k == 1:
# print('YES', n - 1)
# else:
# f = [0]
# for _ in range(0, n):
# f.append(f[-1] * 4 + 1)
# min_step = 1
# max_step = 1 + f[n - 1]
# out_range = 3
# flag = True
# for i in range(0, n):
# if min_step <= k <= max_step:
# print('YES', n - i - 1)
# flag = False
# break
# max_step += out_range
# min_step += out_range
# out_range = out_range * 2 + 1
# if n - 2 - i >= 0:
# max_step += (out_range - 2) * f[n - 2 - i]
# if flag:
# print('NO')
# E
def solve(fin):
n, m = read_num(fin)
mx = []
for line in fin:
mx.append([ord(x) - ord('a') for x in line.strip()])
# print(mx[-1])
bit = [1]
for i in range(1, 26):
bit.append(bit[-1] * 251 % int(1e9 + 7))
ans = 0
for i in range(0, m):
set_s = [0] * n
count_s = get_array([n, 26], 0)
count_odd = [0] * n
for j in range(i, m):
for k in range(0, n):
p = mx[k][j]
set_s[k] += bit[p]
count_s[k][p] += 1
if count_s[k][p] & 1:
count_odd[k] += 1
else:
count_odd[k] -= 1
flag = False
for i in range(1, len(set_s)):
if set_s[i] != set_s[-1]:
flag = True
break
if flag:
new_s = []
for k in range(0, n):
if count_odd[k] >= 2:
new_s.append(-k-1)
else:
new_s.append(set_s[k])
if k + 1 < n:
new_s.append(0)
# print(new_s)
ans_list = manacher(new_s)
# print(i, j, new_s, ans_list)
for k in range(0, len(ans_list)):
if new_s[k] < 0:
continue
if k & 1:
ans += ans_list[k] // 2
else:
ans += int(ceil(ans_list[k] / 2.0))
else:
# print(set_s)
if count_odd[0] < 2 :
ans += len(set_s) * (len(set_s) - 1) / 2 + len(set_s)
print(ans)
if __name__ == '__main__':
if SUBMIT:
solve(sys.stdin)
else:
solve(open(in_file_path, 'r'))
```
No
| 87,573 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sonya had a birthday recently. She was presented with the matrix of size n× m and consist of lowercase Latin letters. We assume that the rows are numbered by integers from 1 to n from bottom to top, and the columns are numbered from 1 to m from left to right.
Let's call a submatrix (i_1, j_1, i_2, j_2) (1≤ i_1≤ i_2≤ n; 1≤ j_1≤ j_2≤ m) elements a_{ij} of this matrix, such that i_1≤ i≤ i_2 and j_1≤ j≤ j_2. Sonya states that a submatrix is beautiful if we can independently reorder the characters in each row (not in column) so that all rows and columns of this submatrix form palidroms.
Let's recall that a string is called palindrome if it reads the same from left to right and from right to left. For example, strings abacaba, bcaacb, a are palindromes while strings abca, acbba, ab are not.
Help Sonya to find the number of beautiful submatrixes. Submatrixes are different if there is an element that belongs to only one submatrix.
Input
The first line contains two integers n and m (1≤ n, m≤ 250) — the matrix dimensions.
Each of the next n lines contains m lowercase Latin letters.
Output
Print one integer — the number of beautiful submatrixes.
Examples
Input
1 3
aba
Output
4
Input
2 3
aca
aac
Output
11
Input
3 5
accac
aaaba
cccaa
Output
43
Note
In the first example, the following submatrixes are beautiful: ((1, 1), (1, 1)); ((1, 2), (1, 2)); ((1, 3), (1, 3)); ((1, 1), (1, 3)).
In the second example, all submatrixes that consist of one element and the following are beautiful: ((1, 1), (2, 1)); ((1, 1), (1, 3)); ((2, 1), (2, 3)); ((1, 1), (2, 3)); ((2, 1), (2, 2)).
Some of the beautiful submatrixes are: ((1, 1), (1, 5)); ((1, 2), (3, 4)); ((1, 1), (3, 5)).
The submatrix ((1, 1), (3, 5)) is beautiful since it can be reordered as:
accca
aabaa
accca
In such a matrix every row and every column form palindromes.
Submitted Solution:
```
#!/usr/bin/python
# encoding:UTF-8
# Filename:Base.py
import sys
import random
import copy
from itertools import permutations, combinations
from math import sqrt, fabs, ceil
from collections import namedtuple
# ------Util Const--------
in_file_path = "input.txt"
output_file_path = "output.txt"
SUBMIT = True
def get_array(x, initial=None):
dimension = len(x)
if dimension == 1:
return [copy.deepcopy(initial) for _ in range(x[0])]
else:
return [get_array(x[1:], initial) for _ in range(x[0])]
def read_num(fin, num_type=int):
tmp_list = [num_type(x) for x in fin.readline().strip().split()]
if len(tmp_list) == 1:
return tmp_list[0]
else:
return tuple(tmp_list)
def manacher(s):
ans_list = []
max_range = 0
max_center = 0
for i in range(0, len(s)):
p = 1
if max_range > i:
p = min(ans_list[2 * max_center - i], max_range - i)
while i - p >= 0 and i + p < len(s) and s[i + p] == s[i - p]:
p += 1
if i + p > max_range:
max_center = i
max_range = i + p
ans_list.append(p)
return ans_list
# A
# def solve(fin, fout):
# n, k = read_num(fin)
# print(ceil((n * 8.0) / k) + ceil((n * 2.0) / k) + ceil((n * 5.0) / k))
# B
# def solve(fin):
# n = read_num(fin)
# for _ in range(0, n):
# l, r = read_num(fin)
# if (r - l + 1) % 2 == 0:
# if l % 2 == 0:
# print(int(-(r - l + 1) / 2))
# else:
# print(int((r - l + 1) / 2))
# else:
# if l % 2 == 0:
# print(int(-(r - l) / 2 + r))
# else:
# print(int((r - l) / 2 - r))
# C
# def solve(fin):
# def count_color(x, y, xx, yy):
# # return _w(x, y, xx, yy), _b(x, y, xx, yy)
# if x > xx or y > yy:
# return 0, 0
# t = (xx - x + 1) * (yy - y + 1)
# if t % 2 == 0:
# return t // 2, t // 2
# else:
# if (x + y) % 2 == 0:
# return t - t // 2, t // 2
# else:
# return t // 2, t - t // 2
#
# T = read_num(fin)
# for _ in range(0, T):
# # print('Test: ',T)
# n, m = read_num(fin)
# x1, y1, x2, y2 = read_num(fin)
# x3, y3, x4, y4 = read_num(fin)
# w, _ = count_color(1, 1, n, m)
# if (max(x1, x3) > min(x2, x4)) or (max(y1, y3) > min(y2, y4)):
# tmp_w, tmp_b = count_color(x1, y1, x2, y2)
# w += tmp_b
# tmp_w, tmp_b = count_color(x3, y3, x4, y4)
# w -= tmp_w
# else:
# tmp_w, tmp_b = count_color(x1, y1, x2, y2)
# w += tmp_b
# tmp_w, tmp_b = count_color(x3, y3, x4, y4)
# w -= tmp_w
# tmp_x_list = sorted([x1, x2, x3, x4])
# tmp_y_list = sorted([y1, y2, y3, y4])
# x5, x6 = tmp_x_list[1], tmp_x_list[2]
# y5, y6 = tmp_y_list[1], tmp_y_list[2]
# tmp_w, tmp_b = count_color(x5, y5, x6, y6)
# w -= tmp_b
# print(w, n * m - w)
# D
# def solve(fin):
# T = read_num(fin)
# for _ in range(0, T):
# n, k = read_num(fin)
# if n > 34 or k == 1:
# print('YES', n - 1)
# else:
# f = [0]
# for _ in range(0, n):
# f.append(f[-1] * 4 + 1)
# min_step = 1
# max_step = 1 + f[n - 1]
# out_range = 3
# flag = True
# for i in range(0, n):
# if min_step <= k <= max_step:
# print('YES', n - i - 1)
# flag = False
# break
# max_step += out_range
# min_step += out_range
# out_range = out_range * 2 + 1
# if n - 2 - i >= 0:
# max_step += (out_range - 2) * f[n - 2 - i]
# if flag:
# print('NO')
# E
def count_col(s, is_even):
sum = 0
# print(s, is_even)
for i in range(len(s)):
min_s = s[i]
for j in range(i, -1, -1):
min_s = min(min_s, s[j])
if is_even:
sum += int(ceil(min_s / 2.0))
else:
sum += min_s // 2
# print(sum)
return sum
def solve(fin):
n, m = read_num(fin)
mx = []
for line in fin:
mx.append([ord(x) - ord('a') for x in line.strip()])
# print(mx[-1])
dead_mask = -1
base = 251
bit = [1]
for i in range(1, 26):
bit.append(bit[-1] * 251)
ans = 0
for i in range(0, m):
set_s = [0] * n
count_s = get_array([n, 26], 0)
count_odd = [0] * n
for j in range(i, m):
for k in range(0, n):
p = mx[k][j]
set_s[k] += bit[p]
count_s[k][p] += 1
if count_s[k][p] & 1:
count_odd[k] += 1
else:
count_odd[k] -= 1
new_s = []
for k in range(0, n):
if count_odd[k] >= 2:
new_s.append(-k-1)
else:
new_s.append(set_s[k])
if k + 1 != n:
new_s.append(0)
ans_list = manacher(new_s)
# print(i, j, new_s, ans_list)
for k in range(0, len(ans_list)):
if new_s[int(ceil(k/2.0))] < 0:
continue
if k % 2 == 0:
ans += int(ceil(ans_list[k] / 2.0))
else:
ans += ans_list[k] // 2
print(ans)
if __name__ == '__main__':
if SUBMIT:
solve(sys.stdin)
else:
solve(open(in_file_path, 'r'))
```
No
| 87,574 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sonya had a birthday recently. She was presented with the matrix of size n× m and consist of lowercase Latin letters. We assume that the rows are numbered by integers from 1 to n from bottom to top, and the columns are numbered from 1 to m from left to right.
Let's call a submatrix (i_1, j_1, i_2, j_2) (1≤ i_1≤ i_2≤ n; 1≤ j_1≤ j_2≤ m) elements a_{ij} of this matrix, such that i_1≤ i≤ i_2 and j_1≤ j≤ j_2. Sonya states that a submatrix is beautiful if we can independently reorder the characters in each row (not in column) so that all rows and columns of this submatrix form palidroms.
Let's recall that a string is called palindrome if it reads the same from left to right and from right to left. For example, strings abacaba, bcaacb, a are palindromes while strings abca, acbba, ab are not.
Help Sonya to find the number of beautiful submatrixes. Submatrixes are different if there is an element that belongs to only one submatrix.
Input
The first line contains two integers n and m (1≤ n, m≤ 250) — the matrix dimensions.
Each of the next n lines contains m lowercase Latin letters.
Output
Print one integer — the number of beautiful submatrixes.
Examples
Input
1 3
aba
Output
4
Input
2 3
aca
aac
Output
11
Input
3 5
accac
aaaba
cccaa
Output
43
Note
In the first example, the following submatrixes are beautiful: ((1, 1), (1, 1)); ((1, 2), (1, 2)); ((1, 3), (1, 3)); ((1, 1), (1, 3)).
In the second example, all submatrixes that consist of one element and the following are beautiful: ((1, 1), (2, 1)); ((1, 1), (1, 3)); ((2, 1), (2, 3)); ((1, 1), (2, 3)); ((2, 1), (2, 2)).
Some of the beautiful submatrixes are: ((1, 1), (1, 5)); ((1, 2), (3, 4)); ((1, 1), (3, 5)).
The submatrix ((1, 1), (3, 5)) is beautiful since it can be reordered as:
accca
aabaa
accca
In such a matrix every row and every column form palindromes.
Submitted Solution:
```
# -*- coding:utf-8 -*-
"""
created by shuangquan.huang at 11/27/18
"""
import collections
N, M = map(int, input().split())
A = []
for i in range(N):
A.append(list(input()))
ans = 0
B = [[None for _ in range(M+1)] for _ in range(N)]
for r in range(N):
wc = collections.Counter()
B[r][0] = wc.copy()
for c in range(M):
wc[A[r][c]] += 1
B[r][c+1] = wc.copy()
for r in range(N):
for c in range(M):
for l in range(1, M-c+1):
wc = B[r][c+l] - B[r][c]
if sum([1 if x % 2 == 1 else 0 for x in wc.values()]) <= 1:
print(r, c, l)
ans += 1
for h in range(r+1, N):
a = r
b = h
p = True
while a < b:
if B[a][c + l] - B[a][c] != B[b][c+l] - B[b][c]:
p = False
break
a += 1
b -= 1
if p:
ans += 1
print(ans)
```
No
| 87,575 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sonya had a birthday recently. She was presented with the matrix of size n× m and consist of lowercase Latin letters. We assume that the rows are numbered by integers from 1 to n from bottom to top, and the columns are numbered from 1 to m from left to right.
Let's call a submatrix (i_1, j_1, i_2, j_2) (1≤ i_1≤ i_2≤ n; 1≤ j_1≤ j_2≤ m) elements a_{ij} of this matrix, such that i_1≤ i≤ i_2 and j_1≤ j≤ j_2. Sonya states that a submatrix is beautiful if we can independently reorder the characters in each row (not in column) so that all rows and columns of this submatrix form palidroms.
Let's recall that a string is called palindrome if it reads the same from left to right and from right to left. For example, strings abacaba, bcaacb, a are palindromes while strings abca, acbba, ab are not.
Help Sonya to find the number of beautiful submatrixes. Submatrixes are different if there is an element that belongs to only one submatrix.
Input
The first line contains two integers n and m (1≤ n, m≤ 250) — the matrix dimensions.
Each of the next n lines contains m lowercase Latin letters.
Output
Print one integer — the number of beautiful submatrixes.
Examples
Input
1 3
aba
Output
4
Input
2 3
aca
aac
Output
11
Input
3 5
accac
aaaba
cccaa
Output
43
Note
In the first example, the following submatrixes are beautiful: ((1, 1), (1, 1)); ((1, 2), (1, 2)); ((1, 3), (1, 3)); ((1, 1), (1, 3)).
In the second example, all submatrixes that consist of one element and the following are beautiful: ((1, 1), (2, 1)); ((1, 1), (1, 3)); ((2, 1), (2, 3)); ((1, 1), (2, 3)); ((2, 1), (2, 2)).
Some of the beautiful submatrixes are: ((1, 1), (1, 5)); ((1, 2), (3, 4)); ((1, 1), (3, 5)).
The submatrix ((1, 1), (3, 5)) is beautiful since it can be reordered as:
accca
aabaa
accca
In such a matrix every row and every column form palindromes.
Submitted Solution:
```
#!/usr/bin/python
# encoding:UTF-8
# Filename:Base.py
import sys
import random
import copy
from itertools import permutations, combinations
from math import sqrt, fabs, ceil
from collections import namedtuple
# ------Util Const--------
in_file_path = "input.txt"
output_file_path = "output.txt"
SUBMIT = True
def get_array(x, initial=None):
dimension = len(x)
if dimension == 1:
return [copy.deepcopy(initial) for _ in range(x[0])]
else:
return [get_array(x[1:], initial) for _ in range(x[0])]
def read_num(fin, num_type=int):
tmp_list = [num_type(x) for x in fin.readline().strip().split()]
if len(tmp_list) == 1:
return tmp_list[0]
else:
return tuple(tmp_list)
def manacher(s):
# new_s = [s[0]]
# for i in range(1, len(s)):
# new_s.append('#')
# new_s.append(s[i])
# print(new_s)
ans_list = []
max_range = 0
max_center = 0
for i in range(0, len(s)):
if max_range > i:
p = min(ans_list[2 * max_center - i], max_range - i)
else:
p = 1
while i - p >= 0 and i + p < len(s) and s[i + p] == s[i - p]:
p += 1
if i + p > max_range:
max_center = i
max_range = i + p
ans_list.append(p)
return ans_list
# A
# def solve(fin, fout):
# n, k = read_num(fin)
# print(ceil((n * 8.0) / k) + ceil((n * 2.0) / k) + ceil((n * 5.0) / k))
# B
# def solve(fin):
# n = read_num(fin)
# for _ in range(0, n):
# l, r = read_num(fin)
# if (r - l + 1) % 2 == 0:
# if l % 2 == 0:
# print(int(-(r - l + 1) / 2))
# else:
# print(int((r - l + 1) / 2))
# else:
# if l % 2 == 0:
# print(int(-(r - l) / 2 + r))
# else:
# print(int((r - l) / 2 - r))
# C
# def solve(fin):
# def count_color(x, y, xx, yy):
# # return _w(x, y, xx, yy), _b(x, y, xx, yy)
# if x > xx or y > yy:
# return 0, 0
# t = (xx - x + 1) * (yy - y + 1)
# if t % 2 == 0:
# return t // 2, t // 2
# else:
# if (x + y) % 2 == 0:
# return t - t // 2, t // 2
# else:
# return t // 2, t - t // 2
#
# T = read_num(fin)
# for _ in range(0, T):
# # print('Test: ',T)
# n, m = read_num(fin)
# x1, y1, x2, y2 = read_num(fin)
# x3, y3, x4, y4 = read_num(fin)
# w, _ = count_color(1, 1, n, m)
# if (max(x1, x3) > min(x2, x4)) or (max(y1, y3) > min(y2, y4)):
# tmp_w, tmp_b = count_color(x1, y1, x2, y2)
# w += tmp_b
# tmp_w, tmp_b = count_color(x3, y3, x4, y4)
# w -= tmp_w
# else:
# tmp_w, tmp_b = count_color(x1, y1, x2, y2)
# w += tmp_b
# tmp_w, tmp_b = count_color(x3, y3, x4, y4)
# w -= tmp_w
# tmp_x_list = sorted([x1, x2, x3, x4])
# tmp_y_list = sorted([y1, y2, y3, y4])
# x5, x6 = tmp_x_list[1], tmp_x_list[2]
# y5, y6 = tmp_y_list[1], tmp_y_list[2]
# tmp_w, tmp_b = count_color(x5, y5, x6, y6)
# w -= tmp_b
# print(w, n * m - w)
# D
# def solve(fin):
# T = read_num(fin)
# for _ in range(0, T):
# n, k = read_num(fin)
# if n > 34 or k == 1:
# print('YES', n - 1)
# else:
# f = [0]
# for _ in range(0, n):
# f.append(f[-1] * 4 + 1)
# min_step = 1
# max_step = 1 + f[n - 1]
# out_range = 3
# flag = True
# for i in range(0, n):
# if min_step <= k <= max_step:
# print('YES', n - i - 1)
# flag = False
# break
# max_step += out_range
# min_step += out_range
# out_range = out_range * 2 + 1
# if n - 2 - i >= 0:
# max_step += (out_range - 2) * f[n - 2 - i]
# if flag:
# print('NO')
# E
def solve(fin):
n, m = read_num(fin)
mx = []
for line in fin:
mx.append([ord(x) - ord('a') for x in line.strip()])
# print(mx[-1])
bit = [1]
for i in range(1, 26):
bit.append(bit[-1] * 251 % int(1e9 + 7))
ans = 0
for i in range(0, m):
set_s = [0] * n
count_s = get_array([n, 26], 0)
count_odd = [0] * n
for j in range(i, m):
for k in range(0, n):
p = mx[k][j]
set_s[k] += bit[p]
count_s[k][p] += 1
if count_s[k][p] & 1:
count_odd[k] += 1
else:
count_odd[k] -= 1
flag = False
for i in range(1, len(set_s)):
if set_s[i] != set_s[-1]:
flag = True
break
if flag:
new_s = []
for k in range(0, n):
if count_odd[k] >= 2:
new_s.append(-k-1)
else:
new_s.append(set_s[k])
if k + 1 < n:
new_s.append(0)
# print(new_s)
ans_list = manacher(new_s)
# print(i, j, new_s, ans_list)
for k in range(0, len(ans_list)):
if new_s[k] < 0:
continue
if k & 1:
ans += ans_list[k] // 2
else:
ans += int(ceil(ans_list[k] / 2.0))
else:
ans += len(set_s) * (len(set_s) - 1) / 2
print(ans)
if __name__ == '__main__':
if SUBMIT:
solve(sys.stdin)
else:
solve(open(in_file_path, 'r'))
```
No
| 87,576 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This problem differs from one which was on the online contest.
The sequence a1, a2, ..., an is called increasing, if ai < ai + 1 for i < n.
The sequence s1, s2, ..., sk is called the subsequence of the sequence a1, a2, ..., an, if there exist such a set of indexes 1 ≤ i1 < i2 < ... < ik ≤ n that aij = sj. In other words, the sequence s can be derived from the sequence a by crossing out some elements.
You are given two sequences of integer numbers. You are to find their longest common increasing subsequence, i.e. an increasing sequence of maximum length that is the subsequence of both sequences.
Input
The first line contains an integer n (1 ≤ n ≤ 500) — the length of the first sequence. The second line contains n space-separated integers from the range [0, 109] — elements of the first sequence. The third line contains an integer m (1 ≤ m ≤ 500) — the length of the second sequence. The fourth line contains m space-separated integers from the range [0, 109] — elements of the second sequence.
Output
In the first line output k — the length of the longest common increasing subsequence. In the second line output the subsequence itself. Separate the elements with a space. If there are several solutions, output any.
Examples
Input
7
2 3 1 6 5 4 6
4
1 3 5 6
Output
3
3 5 6
Input
5
1 2 0 2 1
3
1 0 1
Output
2
0 1
Tags: dp
Correct Solution:
```
def get_lcis_length(X, Y):
len_Y = len(Y)
# maintain current lcis length
# curr_lcis_len: len lcis(X, Y[0..i])
curr_lcis_len = [0] * len_Y
for u in X:
lcis_prefix_max = []
curr_max = 0
# copy current lcis length table and create prefix max from it
# to make access in next step be O(1)
for i, v in enumerate(Y):
if v < u:
curr_max = max(curr_max, curr_lcis_len[i])
lcis_prefix_max.append(curr_max)
# loop through all elements in Y
# update current lcis length if the element matches with current element in X
for i, v in enumerate(Y):
if u == v:
curr_lcis_len[i] = max(curr_lcis_len[i], (0 if i == 0 else lcis_prefix_max[i - 1]) + 1)
# find maximum lcis length
max_lcis_length = curr_lcis_len[0]
for i, u in enumerate(curr_lcis_len):
max_lcis_length = max(max_lcis_length, u)
# Backtrack to get the LCIS
# Redo all previous step, but break when we found lcis that has the same length
# with max_lcis_length
# Need to break the loop to stop backtracking table (bt) being updated
# No need to backtrack if there is no LCIS
if max_lcis_length == 0:
print(0)
return max_lcis_length
curr_lcis_len = [0] * len_Y
bt = [-1] * len_Y # backtracking table
for u in X:
lcis_prefix_max = []
bt_id = []
curr_max = 0
curr_id_max = -1;
# copy current lcis length table and create prefix max from it
# to make access in next step be O(1)
# but, we also keep where should we backtrack if we use the lcis_pref_max
for i, v in enumerate(Y):
if v < u:
if curr_max < curr_lcis_len[i]:
curr_max = curr_lcis_len[i]
curr_id_max = i
lcis_prefix_max.append(curr_max)
bt_id.append(curr_id_max)
# print("bt_id", bt_id)
# print("lcis pref max", lcis_prefix_max)
# print("curr lcis len", curr_lcis_len)
# loop through all elements in Y
# update current lcis length if the element matches with current element in X
for i, v in enumerate(Y):
if u == v:
# print(u, v)
if curr_lcis_len[i] < (0 if i == 0 else lcis_prefix_max[i - 1]) + 1:
curr_lcis_len[i] = (0 if i == 0 else lcis_prefix_max[i - 1]) + 1
bt[i] = (-1 if i == 0 else bt_id[i - 1]) # also update where should we backtrack if using this index
# if this is one of the lcis, use the backtrack table to track the values
if curr_lcis_len[i] == max_lcis_length:
lcis_list = []
now = i
while now != -1:
lcis_list.append(Y[now]);
now = bt[now]
lcis_list.reverse()
print(max_lcis_length)
for i, u in enumerate(lcis_list):
print(u, end=('\n' if i == max_lcis_length - 1 else ' '))
return max_lcis_length, lcis_list
return max_lcis_length
x = []
try:
while True:
y = input()
x.append(y)
except EOFError:
pass
x = ' '.join(x)
x = x.split()
x = [int(i) for i in x]
X = []
Y = []
num_x = x[0]
for i in range(1, num_x + 1):
X.append(x[i])
for i in range(x[num_x + 1]):
Y.append(x[num_x + 2 + i])
get_lcis_length(X, Y)
```
| 87,577 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This problem differs from one which was on the online contest.
The sequence a1, a2, ..., an is called increasing, if ai < ai + 1 for i < n.
The sequence s1, s2, ..., sk is called the subsequence of the sequence a1, a2, ..., an, if there exist such a set of indexes 1 ≤ i1 < i2 < ... < ik ≤ n that aij = sj. In other words, the sequence s can be derived from the sequence a by crossing out some elements.
You are given two sequences of integer numbers. You are to find their longest common increasing subsequence, i.e. an increasing sequence of maximum length that is the subsequence of both sequences.
Input
The first line contains an integer n (1 ≤ n ≤ 500) — the length of the first sequence. The second line contains n space-separated integers from the range [0, 109] — elements of the first sequence. The third line contains an integer m (1 ≤ m ≤ 500) — the length of the second sequence. The fourth line contains m space-separated integers from the range [0, 109] — elements of the second sequence.
Output
In the first line output k — the length of the longest common increasing subsequence. In the second line output the subsequence itself. Separate the elements with a space. If there are several solutions, output any.
Examples
Input
7
2 3 1 6 5 4 6
4
1 3 5 6
Output
3
3 5 6
Input
5
1 2 0 2 1
3
1 0 1
Output
2
0 1
Tags: dp
Correct Solution:
```
n = int(input())
a = [0] + list(map(int, input().split()))
m = int(input())
b = [0] + list(map(int, input().split()))
d = [[0 for j in range(m+1)] for i in range(n+1)]
prev = [0] * (n+1)
for i in range(1, n+1):
for j in range(1, m+1):
if a[i] == b[j]:
d[i][j] = 1
for k in range(1, i):
if a[k] < a[i] and d[i][j] < d[k][j] + 1:
d[i][j] = d[k][j] + 1
prev[i] = k
else:
d[i][j] = d[i][j - 1]
pos = 0
for i in range(1, n+1):
if d[pos][m] < d[i][m]:
pos = i
ans = []
while pos != 0:
ans.append(a[pos])
pos = prev[pos]
print(len(ans))
print(*ans[::-1])
# Fri Oct 09 2020 18:06:27 GMT+0300 (Москва, стандартное время)
```
| 87,578 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This problem differs from one which was on the online contest.
The sequence a1, a2, ..., an is called increasing, if ai < ai + 1 for i < n.
The sequence s1, s2, ..., sk is called the subsequence of the sequence a1, a2, ..., an, if there exist such a set of indexes 1 ≤ i1 < i2 < ... < ik ≤ n that aij = sj. In other words, the sequence s can be derived from the sequence a by crossing out some elements.
You are given two sequences of integer numbers. You are to find their longest common increasing subsequence, i.e. an increasing sequence of maximum length that is the subsequence of both sequences.
Input
The first line contains an integer n (1 ≤ n ≤ 500) — the length of the first sequence. The second line contains n space-separated integers from the range [0, 109] — elements of the first sequence. The third line contains an integer m (1 ≤ m ≤ 500) — the length of the second sequence. The fourth line contains m space-separated integers from the range [0, 109] — elements of the second sequence.
Output
In the first line output k — the length of the longest common increasing subsequence. In the second line output the subsequence itself. Separate the elements with a space. If there are several solutions, output any.
Examples
Input
7
2 3 1 6 5 4 6
4
1 3 5 6
Output
3
3 5 6
Input
5
1 2 0 2 1
3
1 0 1
Output
2
0 1
Tags: dp
Correct Solution:
```
__author__ = 'Darren'
# dp(i,j): length of the LCIS between f[0:i+1] and s[0:j+1] that ends at s[j]
# if f[i] == s[j]: dp(i,j) = max_len + 1
# else: dp(i,j) = dp(i-1,j)
def solve():
n = int(input())
first = list(map(int, input().split()))
m = int(input())
second = list(map(int, input().split()))
if m > n:
n, m = m, n
first, second = second, first
# dp[j]: LCIS ending at second[j]
# prev[j]: index of the second-to-last number for the LCIS ending at second[j]
dp, prev = [0] * m, [-1] * m
for i in range(n):
# max_len: length of the LCIS whose largest number is smaller than first[i]
max_len, last_index = 0, -1
for j in range(m):
if first[i] == second[j] and dp[j] < max_len + 1:
dp[j] = max_len + 1
prev[j] = last_index
elif first[i] > second[j] and max_len < dp[j]:
max_len = dp[j]
last_index = j
# Find the length of LCIS between the first and second sequences, and
# the index of the last common number in the second sequence
max_value, index_max = 0, -1
for index, value in enumerate(dp):
if value > max_value:
max_value = value
index_max = index
print(max_value)
if max_value > 0:
seq = []
index = index_max
while index >= 0:
seq.append(str(second[index]))
index = prev[index]
seq.reverse()
print(' '.join(seq))
if __name__ == '__main__':
solve()
```
| 87,579 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This problem differs from one which was on the online contest.
The sequence a1, a2, ..., an is called increasing, if ai < ai + 1 for i < n.
The sequence s1, s2, ..., sk is called the subsequence of the sequence a1, a2, ..., an, if there exist such a set of indexes 1 ≤ i1 < i2 < ... < ik ≤ n that aij = sj. In other words, the sequence s can be derived from the sequence a by crossing out some elements.
You are given two sequences of integer numbers. You are to find their longest common increasing subsequence, i.e. an increasing sequence of maximum length that is the subsequence of both sequences.
Input
The first line contains an integer n (1 ≤ n ≤ 500) — the length of the first sequence. The second line contains n space-separated integers from the range [0, 109] — elements of the first sequence. The third line contains an integer m (1 ≤ m ≤ 500) — the length of the second sequence. The fourth line contains m space-separated integers from the range [0, 109] — elements of the second sequence.
Output
In the first line output k — the length of the longest common increasing subsequence. In the second line output the subsequence itself. Separate the elements with a space. If there are several solutions, output any.
Examples
Input
7
2 3 1 6 5 4 6
4
1 3 5 6
Output
3
3 5 6
Input
5
1 2 0 2 1
3
1 0 1
Output
2
0 1
Tags: dp
Correct Solution:
```
n = int(input())
a = [0] + list(map(int, input().split()))
m = int(input())
b = [0] + list(map(int, input().split()))
d = [[0 for j in range(m+1)] for i in range(n+1)]
prev = [0] * (n+1)
for i in range(1, n+1):
for j in range(1, m+1):
if a[i] == b[j]:
d[i][j] = 1
for k in range(1, i):
if a[k] < a[i] and d[i][j] < d[k][j] + 1:
d[i][j] = d[k][j] + 1
prev[i] = k
else:
d[i][j] = d[i][j - 1]
pos = 0
for i in range(1, n+1):
if d[pos][m] < d[i][m]:
pos = i
ans = []
while pos != 0:
ans.append(a[pos])
pos = prev[pos]
print(len(ans))
print(*ans[::-1])
# Tue Oct 15 2019 10:46:29 GMT+0300 (MSK)
```
| 87,580 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This problem differs from one which was on the online contest.
The sequence a1, a2, ..., an is called increasing, if ai < ai + 1 for i < n.
The sequence s1, s2, ..., sk is called the subsequence of the sequence a1, a2, ..., an, if there exist such a set of indexes 1 ≤ i1 < i2 < ... < ik ≤ n that aij = sj. In other words, the sequence s can be derived from the sequence a by crossing out some elements.
You are given two sequences of integer numbers. You are to find their longest common increasing subsequence, i.e. an increasing sequence of maximum length that is the subsequence of both sequences.
Input
The first line contains an integer n (1 ≤ n ≤ 500) — the length of the first sequence. The second line contains n space-separated integers from the range [0, 109] — elements of the first sequence. The third line contains an integer m (1 ≤ m ≤ 500) — the length of the second sequence. The fourth line contains m space-separated integers from the range [0, 109] — elements of the second sequence.
Output
In the first line output k — the length of the longest common increasing subsequence. In the second line output the subsequence itself. Separate the elements with a space. If there are several solutions, output any.
Examples
Input
7
2 3 1 6 5 4 6
4
1 3 5 6
Output
3
3 5 6
Input
5
1 2 0 2 1
3
1 0 1
Output
2
0 1
Tags: dp
Correct Solution:
```
n=int(input())
a=list(map(int,input().split()))
m=int(input())
b=list(map(int,input().split()))
dp=[[0]*(m + 1) for i in range(n + 1)]
p=[[0]*(m + 1) for i in range(n + 1)]
v1=0
mx=0
for i in range(1,n+1):
bst=0
v=0
for j in range(1,m+1):
dp[i][j]=dp[i-1][j]
p[i][j]=p[i-1][j]
if(a[i-1]==b[j-1] and bst+1>dp[i][j]):
dp[i][j]=bst+1
p[i][j]=v
if(a[i - 1]>b[j - 1] and dp[i-1][j]>bst):
v=b[j-1]
bst=dp[i-1][j]
if(dp[i][j]>mx):
mx=dp[i][j]
v1 = b[j - 1]
print(mx)
i=n-1
j=m-1
arr=[0]*mx
for k in range(mx):
while(a[i]!=v1):
i=i-1
while(b[j]!=v1):
j=j-1
arr[mx-1-k]=a[i]
v1=p[i+1][j+1]
for k in range(mx):
print(arr[k],end=' ')
# Tue Aug 04 2020 01:02:44 GMT+0300 (Москва, стандартное время)
```
| 87,581 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This problem differs from one which was on the online contest.
The sequence a1, a2, ..., an is called increasing, if ai < ai + 1 for i < n.
The sequence s1, s2, ..., sk is called the subsequence of the sequence a1, a2, ..., an, if there exist such a set of indexes 1 ≤ i1 < i2 < ... < ik ≤ n that aij = sj. In other words, the sequence s can be derived from the sequence a by crossing out some elements.
You are given two sequences of integer numbers. You are to find their longest common increasing subsequence, i.e. an increasing sequence of maximum length that is the subsequence of both sequences.
Input
The first line contains an integer n (1 ≤ n ≤ 500) — the length of the first sequence. The second line contains n space-separated integers from the range [0, 109] — elements of the first sequence. The third line contains an integer m (1 ≤ m ≤ 500) — the length of the second sequence. The fourth line contains m space-separated integers from the range [0, 109] — elements of the second sequence.
Output
In the first line output k — the length of the longest common increasing subsequence. In the second line output the subsequence itself. Separate the elements with a space. If there are several solutions, output any.
Examples
Input
7
2 3 1 6 5 4 6
4
1 3 5 6
Output
3
3 5 6
Input
5
1 2 0 2 1
3
1 0 1
Output
2
0 1
Tags: dp
Correct Solution:
```
n1=int(input())
arr1=list(map(int,input().split()))
n2=int(input())
arr2=list(map(int,input().split()))
if(n1>n2):
temp=n1
n1=n2
n2=temp
temp1=arr1.copy()
arr1=arr2.copy()
arr2=temp1
table=[]
count=[0]*n2
table1=[]
for i in range(n2):
table.append([])
for i in range(n1):
table1.append([])
for i in range(n1):
ct=0
for j in range(n2):
if(arr1[i]==arr2[j]):
if(ct+1>count[j]):
count[j]=ct+1
table[j]=table1[i].copy()
table[j].append(arr1[i])
if(arr1[i]>arr2[j]):
if(count[j]>ct):
ct=count[j]
table1[i]=table[j].copy()
mx=0
res=[]
for i in range(n2):
if(count[i]>mx):
mx=count[i]
res=table[i]
print(mx)
if(mx!=0):
for i in res:
print(i,end=" ")
else:
print()
```
| 87,582 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This problem differs from one which was on the online contest.
The sequence a1, a2, ..., an is called increasing, if ai < ai + 1 for i < n.
The sequence s1, s2, ..., sk is called the subsequence of the sequence a1, a2, ..., an, if there exist such a set of indexes 1 ≤ i1 < i2 < ... < ik ≤ n that aij = sj. In other words, the sequence s can be derived from the sequence a by crossing out some elements.
You are given two sequences of integer numbers. You are to find their longest common increasing subsequence, i.e. an increasing sequence of maximum length that is the subsequence of both sequences.
Input
The first line contains an integer n (1 ≤ n ≤ 500) — the length of the first sequence. The second line contains n space-separated integers from the range [0, 109] — elements of the first sequence. The third line contains an integer m (1 ≤ m ≤ 500) — the length of the second sequence. The fourth line contains m space-separated integers from the range [0, 109] — elements of the second sequence.
Output
In the first line output k — the length of the longest common increasing subsequence. In the second line output the subsequence itself. Separate the elements with a space. If there are several solutions, output any.
Examples
Input
7
2 3 1 6 5 4 6
4
1 3 5 6
Output
3
3 5 6
Input
5
1 2 0 2 1
3
1 0 1
Output
2
0 1
Tags: dp
Correct Solution:
```
def sub_seq(initial,lis1,lis2,sus):
total=[]
inc_initial=initial
c_lis2=lis2
if sus==[]:
subs=[initial]
else:
subs=sus
recur_sub=[initial]
ind=0
for i in lis1:
if int(i)>int(inc_initial):
if i in c_lis2:
subs.append(i)
inc_initial=i
c_lis2=c_lis2[c_lis2.index(i)+1:]
ind+=1
else:
if int(i)>int(initial):
if i in lis2:
temp_subs=subs.copy()
for h in range (len(subs)-1,-1,-1):
if int(subs[h]) < int(i):
temp_subs.append(int(i))
break
else:
temp_subs.pop()
recur_sub=sub_seq(i,lis1[ind+1:],lis2[lis2.index(i):],temp_subs)
total.append(recur_sub)
ind+=1
else:
ind+=1
min=0
su=[]
for z in total:
if len(z)>min:
min=len(z)
su=z
if min > len(subs):
return su
else:
return subs
is1=[]
ns1=int(input())
s1=input()
s1=s1.split()
ns2=int(input())
s2=input()
s2=s2.split()
if ns1>ns2:
indexi=0
for i in s2:
if i in s1:
if indexi+1<len(s2):
is1.append(sub_seq(i,s2[indexi+1:],s1[s1.index(i):],[]))
else:
is1.append([i])
indexi+=1
else:
indexi=0
for i in s1:
if i in s2:
if indexi+1<len(s1):
is1.append(sub_seq(i,s1[indexi+1:],s2[s2.index(i):],[]))
else:
is1.append([i])
indexi+=1
min=0
su=[]
for i in is1:
if len(i)>min:
min=len(i)
su=i
print(min)
print(*su)
```
| 87,583 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This problem differs from one which was on the online contest.
The sequence a1, a2, ..., an is called increasing, if ai < ai + 1 for i < n.
The sequence s1, s2, ..., sk is called the subsequence of the sequence a1, a2, ..., an, if there exist such a set of indexes 1 ≤ i1 < i2 < ... < ik ≤ n that aij = sj. In other words, the sequence s can be derived from the sequence a by crossing out some elements.
You are given two sequences of integer numbers. You are to find their longest common increasing subsequence, i.e. an increasing sequence of maximum length that is the subsequence of both sequences.
Input
The first line contains an integer n (1 ≤ n ≤ 500) — the length of the first sequence. The second line contains n space-separated integers from the range [0, 109] — elements of the first sequence. The third line contains an integer m (1 ≤ m ≤ 500) — the length of the second sequence. The fourth line contains m space-separated integers from the range [0, 109] — elements of the second sequence.
Output
In the first line output k — the length of the longest common increasing subsequence. In the second line output the subsequence itself. Separate the elements with a space. If there are several solutions, output any.
Examples
Input
7
2 3 1 6 5 4 6
4
1 3 5 6
Output
3
3 5 6
Input
5
1 2 0 2 1
3
1 0 1
Output
2
0 1
Tags: dp
Correct Solution:
```
n = int(input())
a = [0] + list(map(int, input().split()))
m = int(input())
b = [0] + list(map(int, input().split()))
n += 1
m += 1
dp = [[0] * max(m,n) for i in range(max(m,n))]
pr = [0] * (max(n, m) + 1)
ans = []
for i in range(1, n):
for j in range(1, m):
if a[i] == b[j]:
dp[i][j] = 1 #max(1, dp[i][j])
for k in range(1, i): #for k in range(1, i + 1):
if (a[k] < a[i]):
if dp[i][j] < dp[k][j] + 1:
pr[i] = k
dp[i][j] = dp[k][j] + 1
else:
dp[i][j] = dp[i][j - 1]
mi = 1
mj = 1
for i in range(1, n):
if dp[i][m-1] > dp[mi][m-1]:
mi = i
print(dp[mi][m-1])
k = dp[mi][m-1]
s = 0
while (mi != 0 and k > s):
ans.append(a[mi])
s += 1
mi = pr[mi]
if ans:
ans.reverse()
print(*ans)
'''
5
-12 0 2 5 10
8
0 2 5 10 -12 -15 0 2
6
-12 0 2 5 10 -12
8
0 2 5 10 -12 -15 0 2
'''
```
| 87,584 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This problem differs from one which was on the online contest.
The sequence a1, a2, ..., an is called increasing, if ai < ai + 1 for i < n.
The sequence s1, s2, ..., sk is called the subsequence of the sequence a1, a2, ..., an, if there exist such a set of indexes 1 ≤ i1 < i2 < ... < ik ≤ n that aij = sj. In other words, the sequence s can be derived from the sequence a by crossing out some elements.
You are given two sequences of integer numbers. You are to find their longest common increasing subsequence, i.e. an increasing sequence of maximum length that is the subsequence of both sequences.
Input
The first line contains an integer n (1 ≤ n ≤ 500) — the length of the first sequence. The second line contains n space-separated integers from the range [0, 109] — elements of the first sequence. The third line contains an integer m (1 ≤ m ≤ 500) — the length of the second sequence. The fourth line contains m space-separated integers from the range [0, 109] — elements of the second sequence.
Output
In the first line output k — the length of the longest common increasing subsequence. In the second line output the subsequence itself. Separate the elements with a space. If there are several solutions, output any.
Examples
Input
7
2 3 1 6 5 4 6
4
1 3 5 6
Output
3
3 5 6
Input
5
1 2 0 2 1
3
1 0 1
Output
2
0 1
Submitted Solution:
```
def get_lcis_length(X, Y):
len_Y = len(Y)
# maintain current lcis length
# curr_lcis_len: len lcis(X, Y[0..i])
curr_lcis_len = [0] * len_Y
for u in X:
lcis_prefix_max = []
curr_max = 0
# copy current lcis length table and create prefix max from it
# to make access in next step be O(1)
for i, v in enumerate(Y):
if v < u:
curr_max = max(curr_max, curr_lcis_len[i])
lcis_prefix_max.append(curr_max)
# loop through all elements in Y
# update current lcis length if the element matches with current element in X
for i, v in enumerate(Y):
if u == v:
curr_lcis_len[i] = max(curr_lcis_len[i], (0 if i == 0 else lcis_prefix_max[i - 1]) + 1)
# find maximum lcis length
max_lcis_length = curr_lcis_len[0]
for i, u in enumerate(curr_lcis_len):
max_lcis_length = max(max_lcis_length, u)
# Backtrack to get the LCIS
# Redo all previous step, but break when we found lcis that has the same length
# with max_lcis_length
# Need to break the loop to stop backtracking table (bt) being updated
# No need to backtrack if there is no LCIS
if max_lcis_length == 0:
print(0)
return max_lcis_length
curr_lcis_len = [0] * len_Y
bt = [-1] * len_Y # backtracking table
for u in X:
lcis_prefix_max = []
bt_id = []
curr_max = 0
curr_id_max = -1;
# copy current lcis length table and create prefix max from it
# to make access in next step be O(1)
# but, we also keep where should we backtrack if we use the lcis_pref_max
for i, v in enumerate(Y):
if v < u:
if curr_max < curr_lcis_len[i]:
curr_max = curr_lcis_len[i]
curr_id_max = i
lcis_prefix_max.append(curr_max)
bt_id.append(curr_id_max)
# loop through all elements in Y
# update current lcis length if the element matches with current element in X
for i, v in enumerate(Y):
if u == v:
if curr_lcis_len[i] < (0 if i == 0 else lcis_prefix_max[i - 1]) + 1:
curr_lcis_len[i] = (0 if i == 0 else lcis_prefix_max[i - 1]) + 1
bt[i] = (-1 if i == 0 else bt_id[i - 1]) # also update where should we backtrack if using this index
# if this is one of the lcis, use the backtrack table to track the values
if curr_lcis_len[i] == max_lcis_length:
lcis_list = []
now = i
while now != -1:
lcis_list.append(Y[now]);
now = bt[now]
lcis_list.reverse()
print(max_lcis_length)
for i, u in enumerate(lcis_list):
print(u, end=('\n' if i == max_lcis_length - 1 else ' '))
return max_lcis_length, lcis_list
return max_lcis_length
x = []
try:
while True:
y = input()
x.append(y)
except EOFError:
pass
x = ' '.join(x)
x = x.split()
x = [int(i) for i in x]
X = []
Y = []
num_x = x[0]
for i in range(1, num_x + 1):
X.append(x[i])
for i in range(x[num_x + 1]):
Y.append(x[num_x + 2 + i])
get_lcis_length(X, Y)
```
Yes
| 87,585 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This problem differs from one which was on the online contest.
The sequence a1, a2, ..., an is called increasing, if ai < ai + 1 for i < n.
The sequence s1, s2, ..., sk is called the subsequence of the sequence a1, a2, ..., an, if there exist such a set of indexes 1 ≤ i1 < i2 < ... < ik ≤ n that aij = sj. In other words, the sequence s can be derived from the sequence a by crossing out some elements.
You are given two sequences of integer numbers. You are to find their longest common increasing subsequence, i.e. an increasing sequence of maximum length that is the subsequence of both sequences.
Input
The first line contains an integer n (1 ≤ n ≤ 500) — the length of the first sequence. The second line contains n space-separated integers from the range [0, 109] — elements of the first sequence. The third line contains an integer m (1 ≤ m ≤ 500) — the length of the second sequence. The fourth line contains m space-separated integers from the range [0, 109] — elements of the second sequence.
Output
In the first line output k — the length of the longest common increasing subsequence. In the second line output the subsequence itself. Separate the elements with a space. If there are several solutions, output any.
Examples
Input
7
2 3 1 6 5 4 6
4
1 3 5 6
Output
3
3 5 6
Input
5
1 2 0 2 1
3
1 0 1
Output
2
0 1
Submitted Solution:
```
"""
s1=input()
s2=input()
n=len(s1)
m=len(s2)
dp=[]
for i in range(n+1):
h=[]
for j in range(m+1):
h.append(0)
dp.append(h)
for i in range(1,n+1):
for j in range(1,m+1):
if(s1[i-1]==s2[j-1]):
dp[i][j]=dp[i-1][j-1]+1
else:
dp[i][j]=max(dp[i-1][j],dp[i][j-1])
print(dp[n][m])"""
"""
n=int(input())
s1=[int(x) for x in input().split()]
m=int(input())
s2=[int(x) for x in input().split()]
table=[0]*m
for i in range(n):
curr=0
for j in range(m):
if(s1[i]==s2[j]):
table[j]=max(table[j],curr+1)
if(s1[i]>s2[j]):
curr=max(curr,table[j])
print(max(table))
"""
n=int(input())
s1=[0]+[int(x) for x in input().split()]
m=int(input())
s2=[0]+[int(x) for x in input().split()]
table=[0]*(m+1)
pos=[0]*(m+1)
for i in range(1,n+1):
curr=0
for j in range(1,m+1):
if(s1[i]==s2[j]):
table[j]=table[curr]+1
pos[j]=curr
if(s1[i]>s2[j] and table[curr]<table[j]):
curr=j
p=0
for i in range(1,m+1):
if(table[i]>table[p]):
p=i
print(table[p])
def out(p):
if(not p):
return
out(pos[p])
print(s2[p],end=" ")
out(p)
print(" ")
```
Yes
| 87,586 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This problem differs from one which was on the online contest.
The sequence a1, a2, ..., an is called increasing, if ai < ai + 1 for i < n.
The sequence s1, s2, ..., sk is called the subsequence of the sequence a1, a2, ..., an, if there exist such a set of indexes 1 ≤ i1 < i2 < ... < ik ≤ n that aij = sj. In other words, the sequence s can be derived from the sequence a by crossing out some elements.
You are given two sequences of integer numbers. You are to find their longest common increasing subsequence, i.e. an increasing sequence of maximum length that is the subsequence of both sequences.
Input
The first line contains an integer n (1 ≤ n ≤ 500) — the length of the first sequence. The second line contains n space-separated integers from the range [0, 109] — elements of the first sequence. The third line contains an integer m (1 ≤ m ≤ 500) — the length of the second sequence. The fourth line contains m space-separated integers from the range [0, 109] — elements of the second sequence.
Output
In the first line output k — the length of the longest common increasing subsequence. In the second line output the subsequence itself. Separate the elements with a space. If there are several solutions, output any.
Examples
Input
7
2 3 1 6 5 4 6
4
1 3 5 6
Output
3
3 5 6
Input
5
1 2 0 2 1
3
1 0 1
Output
2
0 1
Submitted Solution:
```
__author__ = 'Darren'
def solve():
n = int(input())
first = list(map(int, input().split()))
m = int(input())
second = list(map(int, input().split()))
if m > n:
n, m = m, n
first, second = second, first
dp, prev = [0] * m, [-1] * m
for i in range(n):
max_len, last_index = 0, -1
for j in range(m):
if first[i] == second[j] and dp[j] < max_len + 1:
dp[j] = max_len + 1
prev[j] = last_index
elif first[i] > second[j] and max_len < dp[j]:
max_len = dp[j]
last_index = j
max_value, index_max = 0, -1
for index, value in enumerate(dp):
if value > max_value:
max_value = value
index_max = index
print(max_value)
if max_value > 0:
seq = []
index = index_max
while index >= 0:
seq.append(str(second[index]))
index = prev[index]
seq.reverse()
print(' '.join(seq))
if __name__ == '__main__':
solve()
```
Yes
| 87,587 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This problem differs from one which was on the online contest.
The sequence a1, a2, ..., an is called increasing, if ai < ai + 1 for i < n.
The sequence s1, s2, ..., sk is called the subsequence of the sequence a1, a2, ..., an, if there exist such a set of indexes 1 ≤ i1 < i2 < ... < ik ≤ n that aij = sj. In other words, the sequence s can be derived from the sequence a by crossing out some elements.
You are given two sequences of integer numbers. You are to find their longest common increasing subsequence, i.e. an increasing sequence of maximum length that is the subsequence of both sequences.
Input
The first line contains an integer n (1 ≤ n ≤ 500) — the length of the first sequence. The second line contains n space-separated integers from the range [0, 109] — elements of the first sequence. The third line contains an integer m (1 ≤ m ≤ 500) — the length of the second sequence. The fourth line contains m space-separated integers from the range [0, 109] — elements of the second sequence.
Output
In the first line output k — the length of the longest common increasing subsequence. In the second line output the subsequence itself. Separate the elements with a space. If there are several solutions, output any.
Examples
Input
7
2 3 1 6 5 4 6
4
1 3 5 6
Output
3
3 5 6
Input
5
1 2 0 2 1
3
1 0 1
Output
2
0 1
Submitted Solution:
```
def lcis(a, b):
n, m = len(a), len(b)
dp = [0]*m
best_seq, max_len = [], 0
for i in range(n):
current = 0
seq = []
for j in range(m):
if a[i] == b[j]:
f = seq + [a[i]]
if len(f) > max_len:
max_len = len(f)
best_seq = f
dp[j] = max(current+1, dp[j])
if a[i] > b[j]:
if dp[j] > current:
current = dp[j]
seq.append(b[j])
return max_len, best_seq
n = int(input())
a = input().split(' ')
a = [int(x) for x in a]
m = int(input())
b = input().split(' ')
b = [int(x) for x in b]
x, y = lcis(a, b)
print(x)
y = [str(x) for x in y]
print(' '.join(y))
```
Yes
| 87,588 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This problem differs from one which was on the online contest.
The sequence a1, a2, ..., an is called increasing, if ai < ai + 1 for i < n.
The sequence s1, s2, ..., sk is called the subsequence of the sequence a1, a2, ..., an, if there exist such a set of indexes 1 ≤ i1 < i2 < ... < ik ≤ n that aij = sj. In other words, the sequence s can be derived from the sequence a by crossing out some elements.
You are given two sequences of integer numbers. You are to find their longest common increasing subsequence, i.e. an increasing sequence of maximum length that is the subsequence of both sequences.
Input
The first line contains an integer n (1 ≤ n ≤ 500) — the length of the first sequence. The second line contains n space-separated integers from the range [0, 109] — elements of the first sequence. The third line contains an integer m (1 ≤ m ≤ 500) — the length of the second sequence. The fourth line contains m space-separated integers from the range [0, 109] — elements of the second sequence.
Output
In the first line output k — the length of the longest common increasing subsequence. In the second line output the subsequence itself. Separate the elements with a space. If there are several solutions, output any.
Examples
Input
7
2 3 1 6 5 4 6
4
1 3 5 6
Output
3
3 5 6
Input
5
1 2 0 2 1
3
1 0 1
Output
2
0 1
Submitted Solution:
```
is1=[]
is2=[]
ns1=int(input())
s1=input()
s1=s1.split()
ns2=int(input())
s2=input()
s2=s2.split()
if ns1>ns2:
seq=[]
for i in s2:
subs=[]
inde=0
if i in s1:
position=s1.index(i)
subs.append(i)
if position+1<len(s1):
temp_s1=s1[position+1:]
if (s2.index(i)+1)<len(s2):
for j in s2[s2.index(i)+1:]:
if int(j)>int(subs[inde]):
if j in temp_s1:
subs.append(j)
inde+=1
if temp_s1.index(j)+1<len(temp_s1):
temp_s1=temp_s1[temp_s1.index(j)+1:]
else:
break
seq.append(subs)
else:
seq=[]
for i in s1:
subs=[]
inde=0
if i in s2:
position=s2.index(i)
subs.append(i)
if position+1<len(s2):
temp_s2=s2[position+1:]
if (s1.index(i)+1)<len(s1):
for j in s1[s1.index(i)+1:]:
if int(j)>int(subs[inde]):
if j in temp_s2:
subs.append(j)
inde+=1
if temp_s2.index(j)+1<len(temp_s2):
temp_s2=temp_s2[temp_s2.index(j)+1:]
else:
break
seq.append(subs)
min=0
su=[]
for i in seq:
if len(i)>min:
min=len(i)
su=i
print(min)
print(*su)
```
No
| 87,589 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This problem differs from one which was on the online contest.
The sequence a1, a2, ..., an is called increasing, if ai < ai + 1 for i < n.
The sequence s1, s2, ..., sk is called the subsequence of the sequence a1, a2, ..., an, if there exist such a set of indexes 1 ≤ i1 < i2 < ... < ik ≤ n that aij = sj. In other words, the sequence s can be derived from the sequence a by crossing out some elements.
You are given two sequences of integer numbers. You are to find their longest common increasing subsequence, i.e. an increasing sequence of maximum length that is the subsequence of both sequences.
Input
The first line contains an integer n (1 ≤ n ≤ 500) — the length of the first sequence. The second line contains n space-separated integers from the range [0, 109] — elements of the first sequence. The third line contains an integer m (1 ≤ m ≤ 500) — the length of the second sequence. The fourth line contains m space-separated integers from the range [0, 109] — elements of the second sequence.
Output
In the first line output k — the length of the longest common increasing subsequence. In the second line output the subsequence itself. Separate the elements with a space. If there are several solutions, output any.
Examples
Input
7
2 3 1 6 5 4 6
4
1 3 5 6
Output
3
3 5 6
Input
5
1 2 0 2 1
3
1 0 1
Output
2
0 1
Submitted Solution:
```
n1=int(input())
arr1=list(map(int,input().split()))
n2=int(input())
arr2=list(map(int,input().split()))
arr3=[]
for i in range(n1+1):
c=[]
for j in range(n2+1):
c.append([])
arr3.append(c.copy())
for i in range(1,n1+1):
for j in range(1,n2+1):
if(arr1[i-1]==arr2[j-1]):
arr3[i][j].extend(arr3[i-1][j-1].copy())
arr3[i][j].append(arr1[i-1])
else:
x=arr3[i-1][j]
y=arr3[i][j-1]
if(len(x)>=len(y)):
arr3[i][j].extend(x.copy())
else:
arr3[i][j].extend(y.copy())
# print(arr3[n1][n2])
arr4=arr3[n1][n2].copy()
l=len(arr4)
arr1=[]
arr2=[1]*l
for i in range(l):
arr1.append([arr4[i]])
for i in range(1,l):
for j in range(i):
if(arr4[i]>arr4[j]):
if(arr2[i]<arr2[j]+1):
arr2[i]=arr2[j]+1
arr1[i]=arr1[j].copy()
arr1[i].append(arr4[i])
mx=-1
res=[]
for i in range(l):
if(mx<arr2[i]):
mx=arr2[i]
res=arr1[i]
print(mx)
for i in res:
print(i,end=" ")
```
No
| 87,590 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This problem differs from one which was on the online contest.
The sequence a1, a2, ..., an is called increasing, if ai < ai + 1 for i < n.
The sequence s1, s2, ..., sk is called the subsequence of the sequence a1, a2, ..., an, if there exist such a set of indexes 1 ≤ i1 < i2 < ... < ik ≤ n that aij = sj. In other words, the sequence s can be derived from the sequence a by crossing out some elements.
You are given two sequences of integer numbers. You are to find their longest common increasing subsequence, i.e. an increasing sequence of maximum length that is the subsequence of both sequences.
Input
The first line contains an integer n (1 ≤ n ≤ 500) — the length of the first sequence. The second line contains n space-separated integers from the range [0, 109] — elements of the first sequence. The third line contains an integer m (1 ≤ m ≤ 500) — the length of the second sequence. The fourth line contains m space-separated integers from the range [0, 109] — elements of the second sequence.
Output
In the first line output k — the length of the longest common increasing subsequence. In the second line output the subsequence itself. Separate the elements with a space. If there are several solutions, output any.
Examples
Input
7
2 3 1 6 5 4 6
4
1 3 5 6
Output
3
3 5 6
Input
5
1 2 0 2 1
3
1 0 1
Output
2
0 1
Submitted Solution:
```
n1=int(input())
arr1=list(map(int,input().split()))
n2=int(input())
arr2=list(map(int,input().split()))
arr3=[]
for i in range(n1+1):
c=[]
for j in range(n2+1):
c.append([])
arr3.append(c.copy())
for i in range(1,n1+1):
for j in range(1,n2+1):
if(arr1[i-1]==arr2[j-1]):
arr3[i][j].extend(arr3[i-1][j-1].copy())
arr3[i][j].append(arr1[i-1])
else:
x=arr3[i-1][j]
y=arr3[i][j-1]
if(len(x)>=len(y)):
arr3[i][j].extend(x.copy())
else:
arr3[i][j].extend(y.copy())
# print(arr3[n1][n2])
arr4=arr3[n1][n2].copy()
l=len(arr4)
arr1=[]
arr2=[1]*l
for i in range(l):
arr1.append([arr4[i]])
for i in range(1,l):
for j in range(i):
if(arr4[i]>arr4[j]):
if(arr2[i]<arr2[j]+1):
arr2[i]=arr2[j]+1
arr1[i]=arr1[j].copy()
arr1[i].append(arr4[i])
mx=0
res=[]
for i in range(l):
if(mx<arr2[i]):
mx=arr2[i]
res=arr1[i]
print(mx)
if(mx!=0):
for i in res:
print(i,end=" ")
else:
print()
```
No
| 87,591 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This problem differs from one which was on the online contest.
The sequence a1, a2, ..., an is called increasing, if ai < ai + 1 for i < n.
The sequence s1, s2, ..., sk is called the subsequence of the sequence a1, a2, ..., an, if there exist such a set of indexes 1 ≤ i1 < i2 < ... < ik ≤ n that aij = sj. In other words, the sequence s can be derived from the sequence a by crossing out some elements.
You are given two sequences of integer numbers. You are to find their longest common increasing subsequence, i.e. an increasing sequence of maximum length that is the subsequence of both sequences.
Input
The first line contains an integer n (1 ≤ n ≤ 500) — the length of the first sequence. The second line contains n space-separated integers from the range [0, 109] — elements of the first sequence. The third line contains an integer m (1 ≤ m ≤ 500) — the length of the second sequence. The fourth line contains m space-separated integers from the range [0, 109] — elements of the second sequence.
Output
In the first line output k — the length of the longest common increasing subsequence. In the second line output the subsequence itself. Separate the elements with a space. If there are several solutions, output any.
Examples
Input
7
2 3 1 6 5 4 6
4
1 3 5 6
Output
3
3 5 6
Input
5
1 2 0 2 1
3
1 0 1
Output
2
0 1
Submitted Solution:
```
n = int(input())
S = input().split()
m = int(input())
T = input().split()
x = len(S);y = len(T)
d = [[ 0 for i in range(y+1)] for r in range(x+1) ]
prev = [0]*(max(x+1,y+1))
for i in range(1,x+1):
for j in range(1,y+1):
if S[i-1] == T[j-1] :
d[i][j] = 1
for k in range(1,i):
if S[k-1] < S[i-1] and d[i][j] < 1 + d[k][j]:
d[i][j] = 1 + d[k][j]
prev[i]=k
else:
d[i][j] = d[i][j-1]
p = 0
for i in range(1,n+1):
if d[p][m] < d[i][m]:
p = i
ans = []
while p !=0:
ans.append(S[p-1])
p = prev[p]
print(len(ans))
print(*ans[::-1])
```
No
| 87,592 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya likes taking part in Codeforces contests. When a round is over, Vasya follows all submissions in the system testing tab.
There are n solutions, the i-th of them should be tested on a_i tests, testing one solution on one test takes 1 second. The solutions are judged in the order from 1 to n. There are k testing processes which test solutions simultaneously. Each of them can test at most one solution at a time.
At any time moment t when some testing process is not judging any solution, it takes the first solution from the queue and tests it on each test in increasing order of the test ids. Let this solution have id i, then it is being tested on the first test from time moment t till time moment t + 1, then on the second test till time moment t + 2 and so on. This solution is fully tested at time moment t + a_i, and after that the testing process immediately starts testing another solution.
Consider some time moment, let there be exactly m fully tested solutions by this moment. There is a caption "System testing: d%" on the page with solutions, where d is calculated as
$$$d = round\left(100⋅m/n\right),$$$
where round(x) = ⌊{x + 0.5}⌋ is a function which maps every real to the nearest integer.
Vasya calls a submission interesting if there is a time moment (possibly, non-integer) when the solution is being tested on some test q, and the caption says "System testing: q%". Find the number of interesting solutions.
Please note that in case when multiple processes attempt to take the first submission from the queue at the same moment (for instance, at the initial moment), the order they take the solutions does not matter.
Input
The first line contains two positive integers n and k (1 ≤ n ≤ 1000, 1 ≤ k ≤ 100) standing for the number of submissions and the number of testing processes respectively.
The second line contains n positive integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 150), where a_i is equal to the number of tests the i-th submission is to be run on.
Output
Output the only integer — the number of interesting submissions.
Examples
Input
2 2
49 100
Output
1
Input
4 2
32 100 33 1
Output
2
Input
14 5
48 19 6 9 50 20 3 42 38 43 36 21 44 6
Output
5
Note
Consider the first example. At time moment 0 both solutions start testing. At time moment 49 the first solution is fully tested, so at time moment 49.5 the second solution is being tested on the test 50, and the caption says "System testing: 50%" (because there is one fully tested solution out of two). So, the second solution is interesting.
Consider the second example. At time moment 0 the first and the second solutions start testing. At time moment 32 the first solution is fully tested, the third solution starts testing, the caption says "System testing: 25%". At time moment 32 + 24.5 = 56.5 the third solutions is being tested on test 25, the caption is still the same, thus this solution is interesting. After that the third solution is fully tested at time moment 32 + 33 = 65, the fourth solution is fully tested at time moment 65 + 1 = 66. The captions becomes "System testing: 75%", and at time moment 74.5 the second solution is being tested on test 75. So, this solution is also interesting. Overall, there are two interesting solutions.
Tags: implementation
Correct Solution:
```
n, k = map(int, input().split())
a = list(map(int, input().split()))
s, ans = [-2]*k, [0]*n
q1 = q2 = naw = 0
while q1 < n or any(q != -1 for q in s):
for q in range(k):
naw += (s[q] != -1 and s[q] != -2 and s[q][1] == q2)/n
if q2 == 74:
q3 = 0
for q in range(k):
if s[q] != -1:
if s[q] == -2 and q1 < n:
s[q] = [0, a[q1], q1]
q1 += 1
elif s[q] == -2 or q1 == n and q2 == s[q][1]:
s[q] = -1
elif q2 == s[q][1]:
s[q] = [s[q][1], s[q][1]+a[q1], q1]
ans[s[q][2]] |= (naw * 100+0.5)//1 == q2 - s[q][0] + 1
q1 += 1
else:
ans[s[q][2]] |= (naw * 100+0.5)//1 == q2-s[q][0]+1
q2 += 1
print(ans.count(1))
```
| 87,593 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya likes taking part in Codeforces contests. When a round is over, Vasya follows all submissions in the system testing tab.
There are n solutions, the i-th of them should be tested on a_i tests, testing one solution on one test takes 1 second. The solutions are judged in the order from 1 to n. There are k testing processes which test solutions simultaneously. Each of them can test at most one solution at a time.
At any time moment t when some testing process is not judging any solution, it takes the first solution from the queue and tests it on each test in increasing order of the test ids. Let this solution have id i, then it is being tested on the first test from time moment t till time moment t + 1, then on the second test till time moment t + 2 and so on. This solution is fully tested at time moment t + a_i, and after that the testing process immediately starts testing another solution.
Consider some time moment, let there be exactly m fully tested solutions by this moment. There is a caption "System testing: d%" on the page with solutions, where d is calculated as
$$$d = round\left(100⋅m/n\right),$$$
where round(x) = ⌊{x + 0.5}⌋ is a function which maps every real to the nearest integer.
Vasya calls a submission interesting if there is a time moment (possibly, non-integer) when the solution is being tested on some test q, and the caption says "System testing: q%". Find the number of interesting solutions.
Please note that in case when multiple processes attempt to take the first submission from the queue at the same moment (for instance, at the initial moment), the order they take the solutions does not matter.
Input
The first line contains two positive integers n and k (1 ≤ n ≤ 1000, 1 ≤ k ≤ 100) standing for the number of submissions and the number of testing processes respectively.
The second line contains n positive integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 150), where a_i is equal to the number of tests the i-th submission is to be run on.
Output
Output the only integer — the number of interesting submissions.
Examples
Input
2 2
49 100
Output
1
Input
4 2
32 100 33 1
Output
2
Input
14 5
48 19 6 9 50 20 3 42 38 43 36 21 44 6
Output
5
Note
Consider the first example. At time moment 0 both solutions start testing. At time moment 49 the first solution is fully tested, so at time moment 49.5 the second solution is being tested on the test 50, and the caption says "System testing: 50%" (because there is one fully tested solution out of two). So, the second solution is interesting.
Consider the second example. At time moment 0 the first and the second solutions start testing. At time moment 32 the first solution is fully tested, the third solution starts testing, the caption says "System testing: 25%". At time moment 32 + 24.5 = 56.5 the third solutions is being tested on test 25, the caption is still the same, thus this solution is interesting. After that the third solution is fully tested at time moment 32 + 33 = 65, the fourth solution is fully tested at time moment 65 + 1 = 66. The captions becomes "System testing: 75%", and at time moment 74.5 the second solution is being tested on test 75. So, this solution is also interesting. Overall, there are two interesting solutions.
Tags: implementation
Correct Solution:
```
from collections import defaultdict as dd
import math
import heapq
def nn():
return int(input())
def li():
return list(input())
def mi():
return map(int, input().split())
def lm():
return list(map(int, input().split()))
n, p=mi()
l=lm()
pq=[]
done=0
intints=[]
for i in range(min(p,n)):
heapq.heappush(pq, l[i])
intints.append((0,l[i]))
currtask=min(p,n)
interesting=0
donetimes=[]
while done<n:
nextdone=heapq.heappop(pq)
done+=1
currtime=nextdone
donetimes.append(currtime)
if currtask<len(l):
heapq.heappush(pq,l[currtask]+currtime)
intints.append((currtime,l[currtask]+currtime))
currtask+=1
percenttimes=[]
for i in range(n):
percenttimes.append((math.floor(100*(i+1)/n+1/2),donetimes[i]))
#print(percenttimes)
for lower, upper in intints:
for j in range(1,len(percenttimes)):
lowertime=percenttimes[j-1][1]
uppertime=percenttimes[j][1]
percent=percenttimes[j-1][0]
values=upper-lower
#print(values,percent)
if percent in range(1,values+1):
time=lower+percent-1/2
if time>lowertime and time<uppertime:
interesting+=1
break
print(interesting)
#print(donetimes, intints)
```
| 87,594 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya likes taking part in Codeforces contests. When a round is over, Vasya follows all submissions in the system testing tab.
There are n solutions, the i-th of them should be tested on a_i tests, testing one solution on one test takes 1 second. The solutions are judged in the order from 1 to n. There are k testing processes which test solutions simultaneously. Each of them can test at most one solution at a time.
At any time moment t when some testing process is not judging any solution, it takes the first solution from the queue and tests it on each test in increasing order of the test ids. Let this solution have id i, then it is being tested on the first test from time moment t till time moment t + 1, then on the second test till time moment t + 2 and so on. This solution is fully tested at time moment t + a_i, and after that the testing process immediately starts testing another solution.
Consider some time moment, let there be exactly m fully tested solutions by this moment. There is a caption "System testing: d%" on the page with solutions, where d is calculated as
$$$d = round\left(100⋅m/n\right),$$$
where round(x) = ⌊{x + 0.5}⌋ is a function which maps every real to the nearest integer.
Vasya calls a submission interesting if there is a time moment (possibly, non-integer) when the solution is being tested on some test q, and the caption says "System testing: q%". Find the number of interesting solutions.
Please note that in case when multiple processes attempt to take the first submission from the queue at the same moment (for instance, at the initial moment), the order they take the solutions does not matter.
Input
The first line contains two positive integers n and k (1 ≤ n ≤ 1000, 1 ≤ k ≤ 100) standing for the number of submissions and the number of testing processes respectively.
The second line contains n positive integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 150), where a_i is equal to the number of tests the i-th submission is to be run on.
Output
Output the only integer — the number of interesting submissions.
Examples
Input
2 2
49 100
Output
1
Input
4 2
32 100 33 1
Output
2
Input
14 5
48 19 6 9 50 20 3 42 38 43 36 21 44 6
Output
5
Note
Consider the first example. At time moment 0 both solutions start testing. At time moment 49 the first solution is fully tested, so at time moment 49.5 the second solution is being tested on the test 50, and the caption says "System testing: 50%" (because there is one fully tested solution out of two). So, the second solution is interesting.
Consider the second example. At time moment 0 the first and the second solutions start testing. At time moment 32 the first solution is fully tested, the third solution starts testing, the caption says "System testing: 25%". At time moment 32 + 24.5 = 56.5 the third solutions is being tested on test 25, the caption is still the same, thus this solution is interesting. After that the third solution is fully tested at time moment 32 + 33 = 65, the fourth solution is fully tested at time moment 65 + 1 = 66. The captions becomes "System testing: 75%", and at time moment 74.5 the second solution is being tested on test 75. So, this solution is also interesting. Overall, there are two interesting solutions.
Tags: implementation
Correct Solution:
```
n,k=map(int,input().split())
li=list(map(int,input().split()))
k=min(n,k)
res=li[:k]
pro=li[:k]
for i in range(k-1,-1,-1):
li.pop(i)
don=[]
for i in range(k):
don.append(0)
t=0
d=0
m=0
c=0
used=[False]*n
p=list(range(k))
while li or res:
t1=t
pd=[]
for i in don:
pd.append(i)
t=min(res)+t1
for i in range(len(don)):
don[i]=don[i]+t-t1
for i in range(len(res)):
res[i]=pro[i]-don[i]
for i in range(len(don)):
if pd[i]<d<=don[i] and not used[p[i]]:
c+=1
used[p[i]]='True'
z=0
for i in range(len(res)-1,-1,-1):
if res[i]==0:
z+=1
pro.pop(i)
res.pop(i)
don.pop(i)
for j in range(i,k-1):
p[j]=p[j+1]
m+=z
d=int(100*(m/n)+0.5)
while(z):
z-=1
if li:
pro.append(li[0])
res.append(li[0])
don.append(0)
p[k-1-z]=n-len(li)
li.pop(0)
print(c)
```
| 87,595 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya likes taking part in Codeforces contests. When a round is over, Vasya follows all submissions in the system testing tab.
There are n solutions, the i-th of them should be tested on a_i tests, testing one solution on one test takes 1 second. The solutions are judged in the order from 1 to n. There are k testing processes which test solutions simultaneously. Each of them can test at most one solution at a time.
At any time moment t when some testing process is not judging any solution, it takes the first solution from the queue and tests it on each test in increasing order of the test ids. Let this solution have id i, then it is being tested on the first test from time moment t till time moment t + 1, then on the second test till time moment t + 2 and so on. This solution is fully tested at time moment t + a_i, and after that the testing process immediately starts testing another solution.
Consider some time moment, let there be exactly m fully tested solutions by this moment. There is a caption "System testing: d%" on the page with solutions, where d is calculated as
$$$d = round\left(100⋅m/n\right),$$$
where round(x) = ⌊{x + 0.5}⌋ is a function which maps every real to the nearest integer.
Vasya calls a submission interesting if there is a time moment (possibly, non-integer) when the solution is being tested on some test q, and the caption says "System testing: q%". Find the number of interesting solutions.
Please note that in case when multiple processes attempt to take the first submission from the queue at the same moment (for instance, at the initial moment), the order they take the solutions does not matter.
Input
The first line contains two positive integers n and k (1 ≤ n ≤ 1000, 1 ≤ k ≤ 100) standing for the number of submissions and the number of testing processes respectively.
The second line contains n positive integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 150), where a_i is equal to the number of tests the i-th submission is to be run on.
Output
Output the only integer — the number of interesting submissions.
Examples
Input
2 2
49 100
Output
1
Input
4 2
32 100 33 1
Output
2
Input
14 5
48 19 6 9 50 20 3 42 38 43 36 21 44 6
Output
5
Note
Consider the first example. At time moment 0 both solutions start testing. At time moment 49 the first solution is fully tested, so at time moment 49.5 the second solution is being tested on the test 50, and the caption says "System testing: 50%" (because there is one fully tested solution out of two). So, the second solution is interesting.
Consider the second example. At time moment 0 the first and the second solutions start testing. At time moment 32 the first solution is fully tested, the third solution starts testing, the caption says "System testing: 25%". At time moment 32 + 24.5 = 56.5 the third solutions is being tested on test 25, the caption is still the same, thus this solution is interesting. After that the third solution is fully tested at time moment 32 + 33 = 65, the fourth solution is fully tested at time moment 65 + 1 = 66. The captions becomes "System testing: 75%", and at time moment 74.5 the second solution is being tested on test 75. So, this solution is also interesting. Overall, there are two interesting solutions.
Tags: implementation
Correct Solution:
```
n,k = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
k = min(k, n)
p = a[:k];q = a[:k];r = list(range(k))
m = 0;j = k
ans = 0
used = [False]*n
while True:
d = int(100 * m / n + 0.5)
for i in range(k):
if p[i]==0:
continue
p[i]-=1
if q[i]-p[i]==d and not used[r[i]]:
ans += 1
used[r[i]] = True
if p[i] == 0:
m += 1
if j == n:
continue
p[i] = a[j];q[i] = a[j];r[i] = j
j += 1
if p.count(0) == k:
break
print(ans)
```
| 87,596 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya likes taking part in Codeforces contests. When a round is over, Vasya follows all submissions in the system testing tab.
There are n solutions, the i-th of them should be tested on a_i tests, testing one solution on one test takes 1 second. The solutions are judged in the order from 1 to n. There are k testing processes which test solutions simultaneously. Each of them can test at most one solution at a time.
At any time moment t when some testing process is not judging any solution, it takes the first solution from the queue and tests it on each test in increasing order of the test ids. Let this solution have id i, then it is being tested on the first test from time moment t till time moment t + 1, then on the second test till time moment t + 2 and so on. This solution is fully tested at time moment t + a_i, and after that the testing process immediately starts testing another solution.
Consider some time moment, let there be exactly m fully tested solutions by this moment. There is a caption "System testing: d%" on the page with solutions, where d is calculated as
$$$d = round\left(100⋅m/n\right),$$$
where round(x) = ⌊{x + 0.5}⌋ is a function which maps every real to the nearest integer.
Vasya calls a submission interesting if there is a time moment (possibly, non-integer) when the solution is being tested on some test q, and the caption says "System testing: q%". Find the number of interesting solutions.
Please note that in case when multiple processes attempt to take the first submission from the queue at the same moment (for instance, at the initial moment), the order they take the solutions does not matter.
Input
The first line contains two positive integers n and k (1 ≤ n ≤ 1000, 1 ≤ k ≤ 100) standing for the number of submissions and the number of testing processes respectively.
The second line contains n positive integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 150), where a_i is equal to the number of tests the i-th submission is to be run on.
Output
Output the only integer — the number of interesting submissions.
Examples
Input
2 2
49 100
Output
1
Input
4 2
32 100 33 1
Output
2
Input
14 5
48 19 6 9 50 20 3 42 38 43 36 21 44 6
Output
5
Note
Consider the first example. At time moment 0 both solutions start testing. At time moment 49 the first solution is fully tested, so at time moment 49.5 the second solution is being tested on the test 50, and the caption says "System testing: 50%" (because there is one fully tested solution out of two). So, the second solution is interesting.
Consider the second example. At time moment 0 the first and the second solutions start testing. At time moment 32 the first solution is fully tested, the third solution starts testing, the caption says "System testing: 25%". At time moment 32 + 24.5 = 56.5 the third solutions is being tested on test 25, the caption is still the same, thus this solution is interesting. After that the third solution is fully tested at time moment 32 + 33 = 65, the fourth solution is fully tested at time moment 65 + 1 = 66. The captions becomes "System testing: 75%", and at time moment 74.5 the second solution is being tested on test 75. So, this solution is also interesting. Overall, there are two interesting solutions.
Tags: implementation
Correct Solution:
```
#!/usr/bin/env python3
import math
from collections import deque
n, k = map(int, input().split())
q = deque(list(map(int, input().split())))
progress = 0
d = 0
interesting = 0
jobs = []
def minpass(jobs):
return list(map(lambda x: [x[0], x[1]+1, x[2]], jobs))
def rmdone(jobs):
cur_jobs = list(filter(lambda x: x[0]>x[1], jobs))
done = len(jobs) - len(cur_jobs)
return (cur_jobs, done)
while len(jobs) > 0 or len(q) > 0:
for j in range(len(jobs)):
if jobs[j][1] == d and not jobs[j][2]:
interesting += 1
jobs[j][2] = True
jobs, done = rmdone(jobs)
progress += done
d = max(math.floor(100*progress/n + 0.5), 0.00001)
while len(q) and len(jobs) < k:
jobs.append([q.popleft(),0,False])
jobs = minpass(jobs)
print(interesting)
```
| 87,597 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya likes taking part in Codeforces contests. When a round is over, Vasya follows all submissions in the system testing tab.
There are n solutions, the i-th of them should be tested on a_i tests, testing one solution on one test takes 1 second. The solutions are judged in the order from 1 to n. There are k testing processes which test solutions simultaneously. Each of them can test at most one solution at a time.
At any time moment t when some testing process is not judging any solution, it takes the first solution from the queue and tests it on each test in increasing order of the test ids. Let this solution have id i, then it is being tested on the first test from time moment t till time moment t + 1, then on the second test till time moment t + 2 and so on. This solution is fully tested at time moment t + a_i, and after that the testing process immediately starts testing another solution.
Consider some time moment, let there be exactly m fully tested solutions by this moment. There is a caption "System testing: d%" on the page with solutions, where d is calculated as
$$$d = round\left(100⋅m/n\right),$$$
where round(x) = ⌊{x + 0.5}⌋ is a function which maps every real to the nearest integer.
Vasya calls a submission interesting if there is a time moment (possibly, non-integer) when the solution is being tested on some test q, and the caption says "System testing: q%". Find the number of interesting solutions.
Please note that in case when multiple processes attempt to take the first submission from the queue at the same moment (for instance, at the initial moment), the order they take the solutions does not matter.
Input
The first line contains two positive integers n and k (1 ≤ n ≤ 1000, 1 ≤ k ≤ 100) standing for the number of submissions and the number of testing processes respectively.
The second line contains n positive integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 150), where a_i is equal to the number of tests the i-th submission is to be run on.
Output
Output the only integer — the number of interesting submissions.
Examples
Input
2 2
49 100
Output
1
Input
4 2
32 100 33 1
Output
2
Input
14 5
48 19 6 9 50 20 3 42 38 43 36 21 44 6
Output
5
Note
Consider the first example. At time moment 0 both solutions start testing. At time moment 49 the first solution is fully tested, so at time moment 49.5 the second solution is being tested on the test 50, and the caption says "System testing: 50%" (because there is one fully tested solution out of two). So, the second solution is interesting.
Consider the second example. At time moment 0 the first and the second solutions start testing. At time moment 32 the first solution is fully tested, the third solution starts testing, the caption says "System testing: 25%". At time moment 32 + 24.5 = 56.5 the third solutions is being tested on test 25, the caption is still the same, thus this solution is interesting. After that the third solution is fully tested at time moment 32 + 33 = 65, the fourth solution is fully tested at time moment 65 + 1 = 66. The captions becomes "System testing: 75%", and at time moment 74.5 the second solution is being tested on test 75. So, this solution is also interesting. Overall, there are two interesting solutions.
Tags: implementation
Correct Solution:
```
n, k = map(int, input().split())
a = list(map(int, input().split()))
processes = [0] * k
start = [None] * n
finish = [None] * n
for i in range(n):
first_free = min(enumerate(processes), key=lambda x: x[1])[0]
start[i] = processes[first_free]
finish[i] = processes[first_free] + a[i]
processes[first_free] = finish[i]
finish.sort()
finished = [0] * n * 151
j = 0
for i in range(n * 151):
finished[i] = finished[i - 1]
while finish[j] <= i and j < n - 1:
if finish[j] == i:
finished[i] += 1
j += 1
res = 0
for i in range(n):
is_good = False
for j in range(a[i]):
time = start[i] + j
m = finished[time]
if j + 1 == int(100 * m / n + 0.5):
res += 1
break
print(res)
```
| 87,598 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya likes taking part in Codeforces contests. When a round is over, Vasya follows all submissions in the system testing tab.
There are n solutions, the i-th of them should be tested on a_i tests, testing one solution on one test takes 1 second. The solutions are judged in the order from 1 to n. There are k testing processes which test solutions simultaneously. Each of them can test at most one solution at a time.
At any time moment t when some testing process is not judging any solution, it takes the first solution from the queue and tests it on each test in increasing order of the test ids. Let this solution have id i, then it is being tested on the first test from time moment t till time moment t + 1, then on the second test till time moment t + 2 and so on. This solution is fully tested at time moment t + a_i, and after that the testing process immediately starts testing another solution.
Consider some time moment, let there be exactly m fully tested solutions by this moment. There is a caption "System testing: d%" on the page with solutions, where d is calculated as
$$$d = round\left(100⋅m/n\right),$$$
where round(x) = ⌊{x + 0.5}⌋ is a function which maps every real to the nearest integer.
Vasya calls a submission interesting if there is a time moment (possibly, non-integer) when the solution is being tested on some test q, and the caption says "System testing: q%". Find the number of interesting solutions.
Please note that in case when multiple processes attempt to take the first submission from the queue at the same moment (for instance, at the initial moment), the order they take the solutions does not matter.
Input
The first line contains two positive integers n and k (1 ≤ n ≤ 1000, 1 ≤ k ≤ 100) standing for the number of submissions and the number of testing processes respectively.
The second line contains n positive integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 150), where a_i is equal to the number of tests the i-th submission is to be run on.
Output
Output the only integer — the number of interesting submissions.
Examples
Input
2 2
49 100
Output
1
Input
4 2
32 100 33 1
Output
2
Input
14 5
48 19 6 9 50 20 3 42 38 43 36 21 44 6
Output
5
Note
Consider the first example. At time moment 0 both solutions start testing. At time moment 49 the first solution is fully tested, so at time moment 49.5 the second solution is being tested on the test 50, and the caption says "System testing: 50%" (because there is one fully tested solution out of two). So, the second solution is interesting.
Consider the second example. At time moment 0 the first and the second solutions start testing. At time moment 32 the first solution is fully tested, the third solution starts testing, the caption says "System testing: 25%". At time moment 32 + 24.5 = 56.5 the third solutions is being tested on test 25, the caption is still the same, thus this solution is interesting. After that the third solution is fully tested at time moment 32 + 33 = 65, the fourth solution is fully tested at time moment 65 + 1 = 66. The captions becomes "System testing: 75%", and at time moment 74.5 the second solution is being tested on test 75. So, this solution is also interesting. Overall, there are two interesting solutions.
Tags: implementation
Correct Solution:
```
nums = list(map(int, input().split()))
n, k = nums[0], nums[1]
solved = 0
tests = list(map(int, input().split()))
res = 0
machines_remain = []
machines_now = []
machines_interes = []
for foo in range(k):
machines_remain.append(0)
machines_now.append(0)
machines_interes.append(0)
d = 0
while True:
if solved < n:
m = 0
while m < len(machines_remain):
if machines_remain[m] == 0 and len(tests) > 0:
machines_remain[m] = tests[0]
machines_now[m] = 0
machines_interes[m] = 0
tests.pop(0)
if machines_remain[m] > 0:
machines_now[m] += 1
if (machines_now[m] == d) and (machines_interes[m]==0):
machines_interes[m] = 1
res += 1
machines_remain[m] -= 1
if machines_remain[m] == 0:
machines_now[m] = 0
solved += 1
m += 1
d = int(100 * solved / n + 0.5)
else:
print(res)
break
```
| 87,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.