text
stringlengths
198
433k
conversation_id
int64
0
109k
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A tree is a connected graph that doesn't contain any cycles. The distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices. You are given a tree with n vertices and a positive number k. Find the number of distinct pairs of the vertices which have a distance of exactly k between them. Note that pairs (v, u) and (u, v) are considered to be the same pair. Input The first line contains two integers n and k (1 ≀ n ≀ 50000, 1 ≀ k ≀ 500) β€” the number of vertices and the required distance between the vertices. Next n - 1 lines describe the edges as "ai bi" (without the quotes) (1 ≀ ai, bi ≀ n, ai β‰  bi), where ai and bi are the vertices connected by the i-th edge. All given edges are different. Output Print a single integer β€” the number of distinct pairs of the tree's vertices which have a distance of exactly k between them. Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 5 2 1 2 2 3 3 4 2 5 Output 4 Input 5 3 1 2 2 3 3 4 4 5 Output 2 Note In the first sample the pairs of vertexes at distance 2 from each other are (1, 3), (1, 5), (3, 5) and (2, 4). Submitted Solution: ``` ###pyrival template for fast IO import os import sys from io import BytesIO, IOBase # 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) input = lambda: sys.stdin.readline().rstrip("\r\n") ##make the tree n,k=[int(x) for x in input().split()] if n==1: print(0) else: tree={1:[]} for i in range(n-1): a,b=[int(x) for x in input().split()] if a not in tree: tree[a]=[b] else: tree[a].append(b) if b not in tree: tree[b]=[a] else: tree[b].append(a) def dfs(graph,n,currnode): visited=[False for x in range(n+1)] stack=[currnode] index=[0 for x in range(n+1)] parent=[0 for x in range(n+1)] while stack: currnode=stack[-1] if visited[currnode]==False: visited[currnode]=True for i in range(index[currnode],len(graph[currnode])): neighbour=graph[currnode][i] if visited[neighbour]==False: visited[neighbour]=True stack.append(neighbour) parent[neighbour]=currnode index[currnode]+=1 break else: for i in range(k+2): d[parent[currnode]][i+1]+=d[currnode][i] stack.pop() ans[1]=d[1][k] return d=[[0 for x in range(k+3)] for x in range(n+1)] for i in range(1,n+1): d[i][0]=1 ans=[0 for x in range(n+1)] dfs(tree,n,1) def dfs1(graph,n,currnode): visited=[False for x in range(n+1)] stack=[currnode] index=[0 for x in range(n+1)] parent=[0 for x in range(n+1)] while stack: currnode=stack[-1] if visited[currnode]==False: visited[currnode]=True for i in range(index[currnode],len(graph[currnode])): neighbour=graph[currnode][i] if visited[neighbour]==False: visited[neighbour]=True stack.append(neighbour) parent[neighbour]=currnode index[currnode]+=1 for i in range(k+2): d[currnode][i+1]-=d[neighbour][i] for i in range(k+2): d[neighbour][i+1]+=d[currnode][i] ans[neighbour]=d[neighbour][k] break else: for i in range(k+2): d[currnode][i+1]-=d[parent[currnode]][i] for i in range(k+2): d[parent[currnode]][i+1]+=d[currnode][i] stack.pop() return dfs1(tree,n,1) print(sum(ans[1:])//2) ``` Yes
92,000
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A tree is a connected graph that doesn't contain any cycles. The distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices. You are given a tree with n vertices and a positive number k. Find the number of distinct pairs of the vertices which have a distance of exactly k between them. Note that pairs (v, u) and (u, v) are considered to be the same pair. Input The first line contains two integers n and k (1 ≀ n ≀ 50000, 1 ≀ k ≀ 500) β€” the number of vertices and the required distance between the vertices. Next n - 1 lines describe the edges as "ai bi" (without the quotes) (1 ≀ ai, bi ≀ n, ai β‰  bi), where ai and bi are the vertices connected by the i-th edge. All given edges are different. Output Print a single integer β€” the number of distinct pairs of the tree's vertices which have a distance of exactly k between them. Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 5 2 1 2 2 3 3 4 2 5 Output 4 Input 5 3 1 2 2 3 3 4 4 5 Output 2 Note In the first sample the pairs of vertexes at distance 2 from each other are (1, 3), (1, 5), (3, 5) and (2, 4). Submitted Solution: ``` p, q, s = [[] for i in range(50001)], [[] for i in range(50001)], 0 n, k = map(int, input().split()) for i in range(n - 1): a, b = map(int, input().split()) p[a].append(b) p[b].append(a) def f(a, c): global s, k, p, q for b in p[a]: if b == c: continue f(b, a) l = len(q[a]) + len(q[b]) - k s += sum(q[a][j] * q[b][l - j] for j in range(max(0, l - len(q[b]) + 1), min(len(q[a]), l + 1))) if len(q[a]) < len(q[b]): q[a], q[b] = q[b], q[a] for j in range(len(q[b])): q[a][- j] += q[b][- j] q[a].append(1) if k < len(q[a]): s += q[a][- k - 1] f(1, 0) print(s) ``` No
92,001
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A tree is a connected graph that doesn't contain any cycles. The distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices. You are given a tree with n vertices and a positive number k. Find the number of distinct pairs of the vertices which have a distance of exactly k between them. Note that pairs (v, u) and (u, v) are considered to be the same pair. Input The first line contains two integers n and k (1 ≀ n ≀ 50000, 1 ≀ k ≀ 500) β€” the number of vertices and the required distance between the vertices. Next n - 1 lines describe the edges as "ai bi" (without the quotes) (1 ≀ ai, bi ≀ n, ai β‰  bi), where ai and bi are the vertices connected by the i-th edge. All given edges are different. Output Print a single integer β€” the number of distinct pairs of the tree's vertices which have a distance of exactly k between them. Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 5 2 1 2 2 3 3 4 2 5 Output 4 Input 5 3 1 2 2 3 3 4 4 5 Output 2 Note In the first sample the pairs of vertexes at distance 2 from each other are (1, 3), (1, 5), (3, 5) and (2, 4). Submitted Solution: ``` l=[0]*50000000 print(len(l)) ``` No
92,002
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A tree is a connected graph that doesn't contain any cycles. The distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices. You are given a tree with n vertices and a positive number k. Find the number of distinct pairs of the vertices which have a distance of exactly k between them. Note that pairs (v, u) and (u, v) are considered to be the same pair. Input The first line contains two integers n and k (1 ≀ n ≀ 50000, 1 ≀ k ≀ 500) β€” the number of vertices and the required distance between the vertices. Next n - 1 lines describe the edges as "ai bi" (without the quotes) (1 ≀ ai, bi ≀ n, ai β‰  bi), where ai and bi are the vertices connected by the i-th edge. All given edges are different. Output Print a single integer β€” the number of distinct pairs of the tree's vertices which have a distance of exactly k between them. Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 5 2 1 2 2 3 3 4 2 5 Output 4 Input 5 3 1 2 2 3 3 4 4 5 Output 2 Note In the first sample the pairs of vertexes at distance 2 from each other are (1, 3), (1, 5), (3, 5) and (2, 4). Submitted Solution: ``` try : l=[0]*100000000 print(len(l)) except Exception as e : print(e) ``` No
92,003
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A tree is a connected graph that doesn't contain any cycles. The distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices. You are given a tree with n vertices and a positive number k. Find the number of distinct pairs of the vertices which have a distance of exactly k between them. Note that pairs (v, u) and (u, v) are considered to be the same pair. Input The first line contains two integers n and k (1 ≀ n ≀ 50000, 1 ≀ k ≀ 500) β€” the number of vertices and the required distance between the vertices. Next n - 1 lines describe the edges as "ai bi" (without the quotes) (1 ≀ ai, bi ≀ n, ai β‰  bi), where ai and bi are the vertices connected by the i-th edge. All given edges are different. Output Print a single integer β€” the number of distinct pairs of the tree's vertices which have a distance of exactly k between them. Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 5 2 1 2 2 3 3 4 2 5 Output 4 Input 5 3 1 2 2 3 3 4 4 5 Output 2 Note In the first sample the pairs of vertexes at distance 2 from each other are (1, 3), (1, 5), (3, 5) and (2, 4). Submitted Solution: ``` def dot(a,b): c = [] for i in range(0,len(a)): temp=[] for j in range(0,len(b[0])): s = 0 for k in range(0,len(a[0])): s += a[i][k]*b[k][j] temp.append(s) c.append(temp) return c x=input() N=int(x.split(" ")[0]) length=int(x.split(" ")[1]) z=[] for i in range(N): z.append([]) for j in range(N): z[i].append(0) for i in range(N-1): x=input() a=int(x.split(" ")[0]) b=int(x.split(" ")[1]) z[a-1][b-1]=1 z[b-1][a-1]=1 zz=dot(z,z) for i in range(length-1): zz=dot(z,zz) ans=0 for i in range(N): for j in range(i): if zz[i][j]==1: ans+=1 print(ans*2) ``` No
92,004
Provide tags and a correct Python 3 solution for this coding contest problem. Students of group 199 have written their lectures dismally. Now an exam on Mathematical Analysis is approaching and something has to be done asap (that is, quickly). Let's number the students of the group from 1 to n. Each student i (1 ≀ i ≀ n) has a best friend p[i] (1 ≀ p[i] ≀ n). In fact, each student is a best friend of exactly one student. In other words, all p[i] are different. It is possible that the group also has some really "special individuals" for who i = p[i]. Each student wrote exactly one notebook of lecture notes. We know that the students agreed to act by the following algorithm: * on the first day of revising each student studies his own Mathematical Analysis notes, * in the morning of each following day each student gives the notebook to his best friend and takes a notebook from the student who calls him the best friend. Thus, on the second day the student p[i] (1 ≀ i ≀ n) studies the i-th student's notes, on the third day the notes go to student p[p[i]] and so on. Due to some characteristics of the boys' friendship (see paragraph 1), each day each student has exactly one notebook to study. You are given two sequences that describe the situation on the third and fourth days of revising: * a1, a2, ..., an, where ai means the student who gets the i-th student's notebook on the third day of revising; * b1, b2, ..., bn, where bi means the student who gets the i-th student's notebook on the fourth day of revising. You do not know array p, that is you do not know who is the best friend to who. Write a program that finds p by the given sequences a and b. Input The first line contains integer n (1 ≀ n ≀ 105) β€” the number of students in the group. The second line contains sequence of different integers a1, a2, ..., an (1 ≀ ai ≀ n). The third line contains the sequence of different integers b1, b2, ..., bn (1 ≀ bi ≀ n). Output Print sequence n of different integers p[1], p[2], ..., p[n] (1 ≀ p[i] ≀ n). It is guaranteed that the solution exists and that it is unique. Examples Input 4 2 1 4 3 3 4 2 1 Output 4 3 1 2 Input 5 5 2 3 1 4 1 3 2 4 5 Output 4 3 2 5 1 Input 2 1 2 2 1 Output 2 1 Tags: constructive algorithms, implementation, math Correct Solution: ``` n = int(input()) before = list(map(int, input().split())) after = list(map(int, input().split())) permutation = n * [ None ] for i in range(n): permutation[before[i] - 1] = after[i] print(' '.join(map(str, permutation))) ```
92,005
Provide tags and a correct Python 3 solution for this coding contest problem. Students of group 199 have written their lectures dismally. Now an exam on Mathematical Analysis is approaching and something has to be done asap (that is, quickly). Let's number the students of the group from 1 to n. Each student i (1 ≀ i ≀ n) has a best friend p[i] (1 ≀ p[i] ≀ n). In fact, each student is a best friend of exactly one student. In other words, all p[i] are different. It is possible that the group also has some really "special individuals" for who i = p[i]. Each student wrote exactly one notebook of lecture notes. We know that the students agreed to act by the following algorithm: * on the first day of revising each student studies his own Mathematical Analysis notes, * in the morning of each following day each student gives the notebook to his best friend and takes a notebook from the student who calls him the best friend. Thus, on the second day the student p[i] (1 ≀ i ≀ n) studies the i-th student's notes, on the third day the notes go to student p[p[i]] and so on. Due to some characteristics of the boys' friendship (see paragraph 1), each day each student has exactly one notebook to study. You are given two sequences that describe the situation on the third and fourth days of revising: * a1, a2, ..., an, where ai means the student who gets the i-th student's notebook on the third day of revising; * b1, b2, ..., bn, where bi means the student who gets the i-th student's notebook on the fourth day of revising. You do not know array p, that is you do not know who is the best friend to who. Write a program that finds p by the given sequences a and b. Input The first line contains integer n (1 ≀ n ≀ 105) β€” the number of students in the group. The second line contains sequence of different integers a1, a2, ..., an (1 ≀ ai ≀ n). The third line contains the sequence of different integers b1, b2, ..., bn (1 ≀ bi ≀ n). Output Print sequence n of different integers p[1], p[2], ..., p[n] (1 ≀ p[i] ≀ n). It is guaranteed that the solution exists and that it is unique. Examples Input 4 2 1 4 3 3 4 2 1 Output 4 3 1 2 Input 5 5 2 3 1 4 1 3 2 4 5 Output 4 3 2 5 1 Input 2 1 2 2 1 Output 2 1 Tags: constructive algorithms, implementation, math Correct Solution: ``` x = int(input()) a = [int(s) for s in input().split()] b = [int(s) for s in input().split()] bestFriends = {} for i,j in zip(a,b): bestFriends[i] = j for i in range(x): print(bestFriends[i+1],end=" ") ```
92,006
Provide tags and a correct Python 3 solution for this coding contest problem. Students of group 199 have written their lectures dismally. Now an exam on Mathematical Analysis is approaching and something has to be done asap (that is, quickly). Let's number the students of the group from 1 to n. Each student i (1 ≀ i ≀ n) has a best friend p[i] (1 ≀ p[i] ≀ n). In fact, each student is a best friend of exactly one student. In other words, all p[i] are different. It is possible that the group also has some really "special individuals" for who i = p[i]. Each student wrote exactly one notebook of lecture notes. We know that the students agreed to act by the following algorithm: * on the first day of revising each student studies his own Mathematical Analysis notes, * in the morning of each following day each student gives the notebook to his best friend and takes a notebook from the student who calls him the best friend. Thus, on the second day the student p[i] (1 ≀ i ≀ n) studies the i-th student's notes, on the third day the notes go to student p[p[i]] and so on. Due to some characteristics of the boys' friendship (see paragraph 1), each day each student has exactly one notebook to study. You are given two sequences that describe the situation on the third and fourth days of revising: * a1, a2, ..., an, where ai means the student who gets the i-th student's notebook on the third day of revising; * b1, b2, ..., bn, where bi means the student who gets the i-th student's notebook on the fourth day of revising. You do not know array p, that is you do not know who is the best friend to who. Write a program that finds p by the given sequences a and b. Input The first line contains integer n (1 ≀ n ≀ 105) β€” the number of students in the group. The second line contains sequence of different integers a1, a2, ..., an (1 ≀ ai ≀ n). The third line contains the sequence of different integers b1, b2, ..., bn (1 ≀ bi ≀ n). Output Print sequence n of different integers p[1], p[2], ..., p[n] (1 ≀ p[i] ≀ n). It is guaranteed that the solution exists and that it is unique. Examples Input 4 2 1 4 3 3 4 2 1 Output 4 3 1 2 Input 5 5 2 3 1 4 1 3 2 4 5 Output 4 3 2 5 1 Input 2 1 2 2 1 Output 2 1 Tags: constructive algorithms, implementation, math Correct Solution: ``` n=int(input()) a=[int(i) for i in input().split()] b=[int(i) for i in input().split()] l=[0]*(n+1) for i in range(n): l[a[i]]=b[i] #print(l) print(*(l[1:])) ```
92,007
Provide tags and a correct Python 3 solution for this coding contest problem. Students of group 199 have written their lectures dismally. Now an exam on Mathematical Analysis is approaching and something has to be done asap (that is, quickly). Let's number the students of the group from 1 to n. Each student i (1 ≀ i ≀ n) has a best friend p[i] (1 ≀ p[i] ≀ n). In fact, each student is a best friend of exactly one student. In other words, all p[i] are different. It is possible that the group also has some really "special individuals" for who i = p[i]. Each student wrote exactly one notebook of lecture notes. We know that the students agreed to act by the following algorithm: * on the first day of revising each student studies his own Mathematical Analysis notes, * in the morning of each following day each student gives the notebook to his best friend and takes a notebook from the student who calls him the best friend. Thus, on the second day the student p[i] (1 ≀ i ≀ n) studies the i-th student's notes, on the third day the notes go to student p[p[i]] and so on. Due to some characteristics of the boys' friendship (see paragraph 1), each day each student has exactly one notebook to study. You are given two sequences that describe the situation on the third and fourth days of revising: * a1, a2, ..., an, where ai means the student who gets the i-th student's notebook on the third day of revising; * b1, b2, ..., bn, where bi means the student who gets the i-th student's notebook on the fourth day of revising. You do not know array p, that is you do not know who is the best friend to who. Write a program that finds p by the given sequences a and b. Input The first line contains integer n (1 ≀ n ≀ 105) β€” the number of students in the group. The second line contains sequence of different integers a1, a2, ..., an (1 ≀ ai ≀ n). The third line contains the sequence of different integers b1, b2, ..., bn (1 ≀ bi ≀ n). Output Print sequence n of different integers p[1], p[2], ..., p[n] (1 ≀ p[i] ≀ n). It is guaranteed that the solution exists and that it is unique. Examples Input 4 2 1 4 3 3 4 2 1 Output 4 3 1 2 Input 5 5 2 3 1 4 1 3 2 4 5 Output 4 3 2 5 1 Input 2 1 2 2 1 Output 2 1 Tags: constructive algorithms, implementation, math Correct Solution: ``` from sys import stdin, stdout n = int(stdin.readline()) ans = [0 for i in range(n + 1)] a, b = list(map(int, stdin.readline().split())), list(map(int, stdin.readline().split())) for i in range(n): ans[a[i]] = b[i] stdout.write(' '.join(list(map(str, ans[1:])))) ```
92,008
Provide tags and a correct Python 3 solution for this coding contest problem. Students of group 199 have written their lectures dismally. Now an exam on Mathematical Analysis is approaching and something has to be done asap (that is, quickly). Let's number the students of the group from 1 to n. Each student i (1 ≀ i ≀ n) has a best friend p[i] (1 ≀ p[i] ≀ n). In fact, each student is a best friend of exactly one student. In other words, all p[i] are different. It is possible that the group also has some really "special individuals" for who i = p[i]. Each student wrote exactly one notebook of lecture notes. We know that the students agreed to act by the following algorithm: * on the first day of revising each student studies his own Mathematical Analysis notes, * in the morning of each following day each student gives the notebook to his best friend and takes a notebook from the student who calls him the best friend. Thus, on the second day the student p[i] (1 ≀ i ≀ n) studies the i-th student's notes, on the third day the notes go to student p[p[i]] and so on. Due to some characteristics of the boys' friendship (see paragraph 1), each day each student has exactly one notebook to study. You are given two sequences that describe the situation on the third and fourth days of revising: * a1, a2, ..., an, where ai means the student who gets the i-th student's notebook on the third day of revising; * b1, b2, ..., bn, where bi means the student who gets the i-th student's notebook on the fourth day of revising. You do not know array p, that is you do not know who is the best friend to who. Write a program that finds p by the given sequences a and b. Input The first line contains integer n (1 ≀ n ≀ 105) β€” the number of students in the group. The second line contains sequence of different integers a1, a2, ..., an (1 ≀ ai ≀ n). The third line contains the sequence of different integers b1, b2, ..., bn (1 ≀ bi ≀ n). Output Print sequence n of different integers p[1], p[2], ..., p[n] (1 ≀ p[i] ≀ n). It is guaranteed that the solution exists and that it is unique. Examples Input 4 2 1 4 3 3 4 2 1 Output 4 3 1 2 Input 5 5 2 3 1 4 1 3 2 4 5 Output 4 3 2 5 1 Input 2 1 2 2 1 Output 2 1 Tags: constructive algorithms, implementation, math Correct Solution: ``` import sys def solve(): n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) indexof = [0] * (n + 1) for i in range(n): indexof[a[i]] = i res = [0] * n for i in range(n): res[i] = indexof[b[i]] + 1 return ' '.join(map(str, res)) if sys.hexversion == 50594544 : sys.stdin = open("test.txt") print(solve()) ```
92,009
Provide tags and a correct Python 3 solution for this coding contest problem. Students of group 199 have written their lectures dismally. Now an exam on Mathematical Analysis is approaching and something has to be done asap (that is, quickly). Let's number the students of the group from 1 to n. Each student i (1 ≀ i ≀ n) has a best friend p[i] (1 ≀ p[i] ≀ n). In fact, each student is a best friend of exactly one student. In other words, all p[i] are different. It is possible that the group also has some really "special individuals" for who i = p[i]. Each student wrote exactly one notebook of lecture notes. We know that the students agreed to act by the following algorithm: * on the first day of revising each student studies his own Mathematical Analysis notes, * in the morning of each following day each student gives the notebook to his best friend and takes a notebook from the student who calls him the best friend. Thus, on the second day the student p[i] (1 ≀ i ≀ n) studies the i-th student's notes, on the third day the notes go to student p[p[i]] and so on. Due to some characteristics of the boys' friendship (see paragraph 1), each day each student has exactly one notebook to study. You are given two sequences that describe the situation on the third and fourth days of revising: * a1, a2, ..., an, where ai means the student who gets the i-th student's notebook on the third day of revising; * b1, b2, ..., bn, where bi means the student who gets the i-th student's notebook on the fourth day of revising. You do not know array p, that is you do not know who is the best friend to who. Write a program that finds p by the given sequences a and b. Input The first line contains integer n (1 ≀ n ≀ 105) β€” the number of students in the group. The second line contains sequence of different integers a1, a2, ..., an (1 ≀ ai ≀ n). The third line contains the sequence of different integers b1, b2, ..., bn (1 ≀ bi ≀ n). Output Print sequence n of different integers p[1], p[2], ..., p[n] (1 ≀ p[i] ≀ n). It is guaranteed that the solution exists and that it is unique. Examples Input 4 2 1 4 3 3 4 2 1 Output 4 3 1 2 Input 5 5 2 3 1 4 1 3 2 4 5 Output 4 3 2 5 1 Input 2 1 2 2 1 Output 2 1 Tags: constructive algorithms, implementation, math Correct Solution: ``` n, a, b = int(input()), list(map(int, input().split())), list(map(int, input().split())) p = [0] * (n+1) for i in range(n): p[a[i]] = b[i] print(" ".join(map(str, p[1:]))) ```
92,010
Provide tags and a correct Python 3 solution for this coding contest problem. Students of group 199 have written their lectures dismally. Now an exam on Mathematical Analysis is approaching and something has to be done asap (that is, quickly). Let's number the students of the group from 1 to n. Each student i (1 ≀ i ≀ n) has a best friend p[i] (1 ≀ p[i] ≀ n). In fact, each student is a best friend of exactly one student. In other words, all p[i] are different. It is possible that the group also has some really "special individuals" for who i = p[i]. Each student wrote exactly one notebook of lecture notes. We know that the students agreed to act by the following algorithm: * on the first day of revising each student studies his own Mathematical Analysis notes, * in the morning of each following day each student gives the notebook to his best friend and takes a notebook from the student who calls him the best friend. Thus, on the second day the student p[i] (1 ≀ i ≀ n) studies the i-th student's notes, on the third day the notes go to student p[p[i]] and so on. Due to some characteristics of the boys' friendship (see paragraph 1), each day each student has exactly one notebook to study. You are given two sequences that describe the situation on the third and fourth days of revising: * a1, a2, ..., an, where ai means the student who gets the i-th student's notebook on the third day of revising; * b1, b2, ..., bn, where bi means the student who gets the i-th student's notebook on the fourth day of revising. You do not know array p, that is you do not know who is the best friend to who. Write a program that finds p by the given sequences a and b. Input The first line contains integer n (1 ≀ n ≀ 105) β€” the number of students in the group. The second line contains sequence of different integers a1, a2, ..., an (1 ≀ ai ≀ n). The third line contains the sequence of different integers b1, b2, ..., bn (1 ≀ bi ≀ n). Output Print sequence n of different integers p[1], p[2], ..., p[n] (1 ≀ p[i] ≀ n). It is guaranteed that the solution exists and that it is unique. Examples Input 4 2 1 4 3 3 4 2 1 Output 4 3 1 2 Input 5 5 2 3 1 4 1 3 2 4 5 Output 4 3 2 5 1 Input 2 1 2 2 1 Output 2 1 Tags: constructive algorithms, implementation, math Correct Solution: ``` def main(): n = int(input()) a = [int(e) for e in input().split()] b = [int(e) for e in input().split()] p = [i for i in range(0, n + 1)] for i in range(n): p[a[i]] = b[i] print(' '.join(list(map(str, p[1:])))) return 0 if __name__ == "__main__": main() ```
92,011
Provide tags and a correct Python 3 solution for this coding contest problem. Students of group 199 have written their lectures dismally. Now an exam on Mathematical Analysis is approaching and something has to be done asap (that is, quickly). Let's number the students of the group from 1 to n. Each student i (1 ≀ i ≀ n) has a best friend p[i] (1 ≀ p[i] ≀ n). In fact, each student is a best friend of exactly one student. In other words, all p[i] are different. It is possible that the group also has some really "special individuals" for who i = p[i]. Each student wrote exactly one notebook of lecture notes. We know that the students agreed to act by the following algorithm: * on the first day of revising each student studies his own Mathematical Analysis notes, * in the morning of each following day each student gives the notebook to his best friend and takes a notebook from the student who calls him the best friend. Thus, on the second day the student p[i] (1 ≀ i ≀ n) studies the i-th student's notes, on the third day the notes go to student p[p[i]] and so on. Due to some characteristics of the boys' friendship (see paragraph 1), each day each student has exactly one notebook to study. You are given two sequences that describe the situation on the third and fourth days of revising: * a1, a2, ..., an, where ai means the student who gets the i-th student's notebook on the third day of revising; * b1, b2, ..., bn, where bi means the student who gets the i-th student's notebook on the fourth day of revising. You do not know array p, that is you do not know who is the best friend to who. Write a program that finds p by the given sequences a and b. Input The first line contains integer n (1 ≀ n ≀ 105) β€” the number of students in the group. The second line contains sequence of different integers a1, a2, ..., an (1 ≀ ai ≀ n). The third line contains the sequence of different integers b1, b2, ..., bn (1 ≀ bi ≀ n). Output Print sequence n of different integers p[1], p[2], ..., p[n] (1 ≀ p[i] ≀ n). It is guaranteed that the solution exists and that it is unique. Examples Input 4 2 1 4 3 3 4 2 1 Output 4 3 1 2 Input 5 5 2 3 1 4 1 3 2 4 5 Output 4 3 2 5 1 Input 2 1 2 2 1 Output 2 1 Tags: constructive algorithms, implementation, math Correct Solution: ``` n = int(input()) a = list(map(int,input().split())) b = list(map(int,input().split())) p = [0]*n for i,a1 in enumerate(a): p[a1-1] = b[i] for x in p: print(x," " ,end='',) print() ```
92,012
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Students of group 199 have written their lectures dismally. Now an exam on Mathematical Analysis is approaching and something has to be done asap (that is, quickly). Let's number the students of the group from 1 to n. Each student i (1 ≀ i ≀ n) has a best friend p[i] (1 ≀ p[i] ≀ n). In fact, each student is a best friend of exactly one student. In other words, all p[i] are different. It is possible that the group also has some really "special individuals" for who i = p[i]. Each student wrote exactly one notebook of lecture notes. We know that the students agreed to act by the following algorithm: * on the first day of revising each student studies his own Mathematical Analysis notes, * in the morning of each following day each student gives the notebook to his best friend and takes a notebook from the student who calls him the best friend. Thus, on the second day the student p[i] (1 ≀ i ≀ n) studies the i-th student's notes, on the third day the notes go to student p[p[i]] and so on. Due to some characteristics of the boys' friendship (see paragraph 1), each day each student has exactly one notebook to study. You are given two sequences that describe the situation on the third and fourth days of revising: * a1, a2, ..., an, where ai means the student who gets the i-th student's notebook on the third day of revising; * b1, b2, ..., bn, where bi means the student who gets the i-th student's notebook on the fourth day of revising. You do not know array p, that is you do not know who is the best friend to who. Write a program that finds p by the given sequences a and b. Input The first line contains integer n (1 ≀ n ≀ 105) β€” the number of students in the group. The second line contains sequence of different integers a1, a2, ..., an (1 ≀ ai ≀ n). The third line contains the sequence of different integers b1, b2, ..., bn (1 ≀ bi ≀ n). Output Print sequence n of different integers p[1], p[2], ..., p[n] (1 ≀ p[i] ≀ n). It is guaranteed that the solution exists and that it is unique. Examples Input 4 2 1 4 3 3 4 2 1 Output 4 3 1 2 Input 5 5 2 3 1 4 1 3 2 4 5 Output 4 3 2 5 1 Input 2 1 2 2 1 Output 2 1 Submitted Solution: ``` n = int(input()) a = [int(i) for i in input().split()] b = [int(i) for i in input().split()] dic = {} for i in range(0,len(a)): dic[a[i]] = i pic = [] for i in b: pic.append(dic[i]+1) for i in pic: print(i,end=" ") ``` Yes
92,013
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Students of group 199 have written their lectures dismally. Now an exam on Mathematical Analysis is approaching and something has to be done asap (that is, quickly). Let's number the students of the group from 1 to n. Each student i (1 ≀ i ≀ n) has a best friend p[i] (1 ≀ p[i] ≀ n). In fact, each student is a best friend of exactly one student. In other words, all p[i] are different. It is possible that the group also has some really "special individuals" for who i = p[i]. Each student wrote exactly one notebook of lecture notes. We know that the students agreed to act by the following algorithm: * on the first day of revising each student studies his own Mathematical Analysis notes, * in the morning of each following day each student gives the notebook to his best friend and takes a notebook from the student who calls him the best friend. Thus, on the second day the student p[i] (1 ≀ i ≀ n) studies the i-th student's notes, on the third day the notes go to student p[p[i]] and so on. Due to some characteristics of the boys' friendship (see paragraph 1), each day each student has exactly one notebook to study. You are given two sequences that describe the situation on the third and fourth days of revising: * a1, a2, ..., an, where ai means the student who gets the i-th student's notebook on the third day of revising; * b1, b2, ..., bn, where bi means the student who gets the i-th student's notebook on the fourth day of revising. You do not know array p, that is you do not know who is the best friend to who. Write a program that finds p by the given sequences a and b. Input The first line contains integer n (1 ≀ n ≀ 105) β€” the number of students in the group. The second line contains sequence of different integers a1, a2, ..., an (1 ≀ ai ≀ n). The third line contains the sequence of different integers b1, b2, ..., bn (1 ≀ bi ≀ n). Output Print sequence n of different integers p[1], p[2], ..., p[n] (1 ≀ p[i] ≀ n). It is guaranteed that the solution exists and that it is unique. Examples Input 4 2 1 4 3 3 4 2 1 Output 4 3 1 2 Input 5 5 2 3 1 4 1 3 2 4 5 Output 4 3 2 5 1 Input 2 1 2 2 1 Output 2 1 Submitted Solution: ``` x = input() a = [int(s) for s in input().split()] b = [int(s) for s in input().split()] bestFriends = {} for i,j in zip(a,b): bestFriends[i] = j for i in range(len(a)): print(bestFriends[i+1],end=" ") ``` Yes
92,014
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Students of group 199 have written their lectures dismally. Now an exam on Mathematical Analysis is approaching and something has to be done asap (that is, quickly). Let's number the students of the group from 1 to n. Each student i (1 ≀ i ≀ n) has a best friend p[i] (1 ≀ p[i] ≀ n). In fact, each student is a best friend of exactly one student. In other words, all p[i] are different. It is possible that the group also has some really "special individuals" for who i = p[i]. Each student wrote exactly one notebook of lecture notes. We know that the students agreed to act by the following algorithm: * on the first day of revising each student studies his own Mathematical Analysis notes, * in the morning of each following day each student gives the notebook to his best friend and takes a notebook from the student who calls him the best friend. Thus, on the second day the student p[i] (1 ≀ i ≀ n) studies the i-th student's notes, on the third day the notes go to student p[p[i]] and so on. Due to some characteristics of the boys' friendship (see paragraph 1), each day each student has exactly one notebook to study. You are given two sequences that describe the situation on the third and fourth days of revising: * a1, a2, ..., an, where ai means the student who gets the i-th student's notebook on the third day of revising; * b1, b2, ..., bn, where bi means the student who gets the i-th student's notebook on the fourth day of revising. You do not know array p, that is you do not know who is the best friend to who. Write a program that finds p by the given sequences a and b. Input The first line contains integer n (1 ≀ n ≀ 105) β€” the number of students in the group. The second line contains sequence of different integers a1, a2, ..., an (1 ≀ ai ≀ n). The third line contains the sequence of different integers b1, b2, ..., bn (1 ≀ bi ≀ n). Output Print sequence n of different integers p[1], p[2], ..., p[n] (1 ≀ p[i] ≀ n). It is guaranteed that the solution exists and that it is unique. Examples Input 4 2 1 4 3 3 4 2 1 Output 4 3 1 2 Input 5 5 2 3 1 4 1 3 2 4 5 Output 4 3 2 5 1 Input 2 1 2 2 1 Output 2 1 Submitted Solution: ``` n = int(input()) a, b = list(map(int, input().split())), list(map(int, input().split())) p, q = [0] * (n + 1), [0] * n for i, j in enumerate(a, 1): p[j] = i for i, j in enumerate(b): q[i] = str(p[j]) print(' '.join(q)) ``` Yes
92,015
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Students of group 199 have written their lectures dismally. Now an exam on Mathematical Analysis is approaching and something has to be done asap (that is, quickly). Let's number the students of the group from 1 to n. Each student i (1 ≀ i ≀ n) has a best friend p[i] (1 ≀ p[i] ≀ n). In fact, each student is a best friend of exactly one student. In other words, all p[i] are different. It is possible that the group also has some really "special individuals" for who i = p[i]. Each student wrote exactly one notebook of lecture notes. We know that the students agreed to act by the following algorithm: * on the first day of revising each student studies his own Mathematical Analysis notes, * in the morning of each following day each student gives the notebook to his best friend and takes a notebook from the student who calls him the best friend. Thus, on the second day the student p[i] (1 ≀ i ≀ n) studies the i-th student's notes, on the third day the notes go to student p[p[i]] and so on. Due to some characteristics of the boys' friendship (see paragraph 1), each day each student has exactly one notebook to study. You are given two sequences that describe the situation on the third and fourth days of revising: * a1, a2, ..., an, where ai means the student who gets the i-th student's notebook on the third day of revising; * b1, b2, ..., bn, where bi means the student who gets the i-th student's notebook on the fourth day of revising. You do not know array p, that is you do not know who is the best friend to who. Write a program that finds p by the given sequences a and b. Input The first line contains integer n (1 ≀ n ≀ 105) β€” the number of students in the group. The second line contains sequence of different integers a1, a2, ..., an (1 ≀ ai ≀ n). The third line contains the sequence of different integers b1, b2, ..., bn (1 ≀ bi ≀ n). Output Print sequence n of different integers p[1], p[2], ..., p[n] (1 ≀ p[i] ≀ n). It is guaranteed that the solution exists and that it is unique. Examples Input 4 2 1 4 3 3 4 2 1 Output 4 3 1 2 Input 5 5 2 3 1 4 1 3 2 4 5 Output 4 3 2 5 1 Input 2 1 2 2 1 Output 2 1 Submitted Solution: ``` n=int(input()) a=list(map(int,input().split())) b=list(map(int,input().split())) c=list(zip(a,b)) c=sorted(c,key=lambda x:(x[0],x[1])) for i in range(n): print(c[i][1],end=" ") ``` Yes
92,016
Provide tags and a correct Python 3 solution for this coding contest problem. The Little Elephant loves to play with color cards. He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks that a set of cards on the table is funny if at least half of the cards have the same color (for each card the color of the upper side is considered). Help the Little Elephant to find the minimum number of moves needed to make the set of n cards funny. Input The first line contains a single integer n (1 ≀ n ≀ 105) β€” the number of the cards. The following n lines contain the description of all cards, one card per line. The cards are described by a pair of positive integers not exceeding 109 β€” colors of both sides. The first number in a line is the color of the front of the card, the second one β€” of the back. The color of the front of the card may coincide with the color of the back of the card. The numbers in the lines are separated by single spaces. Output On a single line print a single integer β€” the sought minimum number of moves. If it is impossible to make the set funny, print -1. Examples Input 3 4 7 4 7 7 4 Output 0 Input 5 4 7 7 4 2 11 9 7 1 1 Output 2 Note In the first sample there initially are three cards lying with colors 4, 4, 7. Since two of the three cards are of the same color 4, you do not need to change anything, so the answer is 0. In the second sample, you can turn the first and the fourth cards. After that three of the five cards will be of color 7. Tags: binary search, data structures Correct Solution: ``` from collections import defaultdict temp_n = n = int(input()) front = defaultdict(int) back = defaultdict(int) while temp_n > 0: temp_n -= 1 f, b = map(int, input().split()) front[f] += 1 if f != b: back[b] += 1 target = (n + 1) // 2 done = False for count, num in sorted(((_count, _num) for _num, _count in front.items()), reverse=True): if count >= target: print("0") done = True break if count + back[num] >= target: print(str(target - count)) done = True break if not done: for count, num in sorted(((_count, _num) for _num, _count in back.items()), reverse=True): if count >= target: print(str(target)) done = True break if not done: print("-1") ```
92,017
Provide tags and a correct Python 3 solution for this coding contest problem. The Little Elephant loves to play with color cards. He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks that a set of cards on the table is funny if at least half of the cards have the same color (for each card the color of the upper side is considered). Help the Little Elephant to find the minimum number of moves needed to make the set of n cards funny. Input The first line contains a single integer n (1 ≀ n ≀ 105) β€” the number of the cards. The following n lines contain the description of all cards, one card per line. The cards are described by a pair of positive integers not exceeding 109 β€” colors of both sides. The first number in a line is the color of the front of the card, the second one β€” of the back. The color of the front of the card may coincide with the color of the back of the card. The numbers in the lines are separated by single spaces. Output On a single line print a single integer β€” the sought minimum number of moves. If it is impossible to make the set funny, print -1. Examples Input 3 4 7 4 7 7 4 Output 0 Input 5 4 7 7 4 2 11 9 7 1 1 Output 2 Note In the first sample there initially are three cards lying with colors 4, 4, 7. Since two of the three cards are of the same color 4, you do not need to change anything, so the answer is 0. In the second sample, you can turn the first and the fourth cards. After that three of the five cards will be of color 7. Tags: binary search, data structures Correct Solution: ``` d=dict() n=int(input()) for i in range(n): f,b=map(int,input().split()) if f not in d:d[f]=[0,0] d[f][0]+=1 if f!=b: if b not in d:d[b]=[0,0] d[b][1]+=1 n=(n+1)//2 m=2*n for aa,a in d.items(): if sum(a)>=n: m=min(m,n-a[0]) if m==2*n:print(-1) else: print(max(0,m)) ```
92,018
Provide tags and a correct Python 3 solution for this coding contest problem. The Little Elephant loves to play with color cards. He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks that a set of cards on the table is funny if at least half of the cards have the same color (for each card the color of the upper side is considered). Help the Little Elephant to find the minimum number of moves needed to make the set of n cards funny. Input The first line contains a single integer n (1 ≀ n ≀ 105) β€” the number of the cards. The following n lines contain the description of all cards, one card per line. The cards are described by a pair of positive integers not exceeding 109 β€” colors of both sides. The first number in a line is the color of the front of the card, the second one β€” of the back. The color of the front of the card may coincide with the color of the back of the card. The numbers in the lines are separated by single spaces. Output On a single line print a single integer β€” the sought minimum number of moves. If it is impossible to make the set funny, print -1. Examples Input 3 4 7 4 7 7 4 Output 0 Input 5 4 7 7 4 2 11 9 7 1 1 Output 2 Note In the first sample there initially are three cards lying with colors 4, 4, 7. Since two of the three cards are of the same color 4, you do not need to change anything, so the answer is 0. In the second sample, you can turn the first and the fourth cards. After that three of the five cards will be of color 7. Tags: binary search, data structures Correct Solution: ``` import sys from math import * input=sys.stdin.readline #n,m,k=map(int,input().split()) d={} n=int(input()) for i in range(n): x,y=map(int,input().split()) if x in d: d[x][0]+=1 else: d[x]=[1,0] if x==y: continue if y in d: d[y][1]+=1 else: d[y]=[0,1] mini=10**15 for i in d: if int(ceil(n/2))-d[i][0]<=d[i][1]: mini=min(mini,max(0,int(ceil(n/2))-d[i][0])) if mini!=10**15: print(mini ) else : print(-1) ```
92,019
Provide tags and a correct Python 3 solution for this coding contest problem. The Little Elephant loves to play with color cards. He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks that a set of cards on the table is funny if at least half of the cards have the same color (for each card the color of the upper side is considered). Help the Little Elephant to find the minimum number of moves needed to make the set of n cards funny. Input The first line contains a single integer n (1 ≀ n ≀ 105) β€” the number of the cards. The following n lines contain the description of all cards, one card per line. The cards are described by a pair of positive integers not exceeding 109 β€” colors of both sides. The first number in a line is the color of the front of the card, the second one β€” of the back. The color of the front of the card may coincide with the color of the back of the card. The numbers in the lines are separated by single spaces. Output On a single line print a single integer β€” the sought minimum number of moves. If it is impossible to make the set funny, print -1. Examples Input 3 4 7 4 7 7 4 Output 0 Input 5 4 7 7 4 2 11 9 7 1 1 Output 2 Note In the first sample there initially are three cards lying with colors 4, 4, 7. Since two of the three cards are of the same color 4, you do not need to change anything, so the answer is 0. In the second sample, you can turn the first and the fourth cards. After that three of the five cards will be of color 7. Tags: binary search, data structures Correct Solution: ``` n=int(input()) a=[0]*n b=[0]*n cards=[] for i in range(n): a[i],b[i]=map(int,input().split()) if a[i]==b[i]: b[i]=-1 cards.append([a[i],b[i]]) half=n%2+n//2 from collections import Counter c1=Counter(a) c2=Counter(b) l1=[[c1[i],i] for i in c1] if max(c1[i] for i in c1)>=half: ans=0 print(ans) else: f=0 ans=n for i in range(len(l1)): #print(l1[i]) req=half-l1[i][0] if c2[l1[i][1]]>=req: ans=min(req,ans) #print(l1[i][1]) f=1 for i in b : if c1[i] or i==-1 : continue if c2[i]>=half: ans=min(ans,half) f=1 if f==0: print(-1) else: print(ans) ```
92,020
Provide tags and a correct Python 3 solution for this coding contest problem. The Little Elephant loves to play with color cards. He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks that a set of cards on the table is funny if at least half of the cards have the same color (for each card the color of the upper side is considered). Help the Little Elephant to find the minimum number of moves needed to make the set of n cards funny. Input The first line contains a single integer n (1 ≀ n ≀ 105) β€” the number of the cards. The following n lines contain the description of all cards, one card per line. The cards are described by a pair of positive integers not exceeding 109 β€” colors of both sides. The first number in a line is the color of the front of the card, the second one β€” of the back. The color of the front of the card may coincide with the color of the back of the card. The numbers in the lines are separated by single spaces. Output On a single line print a single integer β€” the sought minimum number of moves. If it is impossible to make the set funny, print -1. Examples Input 3 4 7 4 7 7 4 Output 0 Input 5 4 7 7 4 2 11 9 7 1 1 Output 2 Note In the first sample there initially are three cards lying with colors 4, 4, 7. Since two of the three cards are of the same color 4, you do not need to change anything, so the answer is 0. In the second sample, you can turn the first and the fourth cards. After that three of the five cards will be of color 7. Tags: binary search, data structures Correct Solution: ``` def main(): n = int(input()) d = {} for i in range(n): a, b = [int(i) for i in input().split()] if a == b: if a not in d: d[a] = [0, 0] d[a][0] += 1 else: if a not in d: d[a] = [0, 0] d[a][0] += 1 if b not in d: d[b] = [0, 0] d[b][1] += 1 result = float("inf") half = (n + 1) // 2 for a, b in d.values(): if a + b >= half: result = min(max(0, half - a), result) if result == float("inf"): print(-1) else: print(result) main() ```
92,021
Provide tags and a correct Python 3 solution for this coding contest problem. The Little Elephant loves to play with color cards. He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks that a set of cards on the table is funny if at least half of the cards have the same color (for each card the color of the upper side is considered). Help the Little Elephant to find the minimum number of moves needed to make the set of n cards funny. Input The first line contains a single integer n (1 ≀ n ≀ 105) β€” the number of the cards. The following n lines contain the description of all cards, one card per line. The cards are described by a pair of positive integers not exceeding 109 β€” colors of both sides. The first number in a line is the color of the front of the card, the second one β€” of the back. The color of the front of the card may coincide with the color of the back of the card. The numbers in the lines are separated by single spaces. Output On a single line print a single integer β€” the sought minimum number of moves. If it is impossible to make the set funny, print -1. Examples Input 3 4 7 4 7 7 4 Output 0 Input 5 4 7 7 4 2 11 9 7 1 1 Output 2 Note In the first sample there initially are three cards lying with colors 4, 4, 7. Since two of the three cards are of the same color 4, you do not need to change anything, so the answer is 0. In the second sample, you can turn the first and the fourth cards. After that three of the five cards will be of color 7. Tags: binary search, data structures Correct Solution: ``` n=int(input()) m={} v=[] for i in range(n): a=input().split() v.append(a) m[a[0]]=[0,0] m[a[1]]=[0,0] for i in range(n): m[v[i][0]][0]+=1 if v[i][0]!=v[i][1]: m[v[i][1]][1]+=1 min=99999999 for i in m: if sum(m[i])>=(n+1)//2: if (n+1)//2-m[i][0]<min: if (n+1)//2-m[i][0]<=0: print(0) exit() else: min=(n+1)//2-m[i][0] print(min if min!=99999999 else-1) ```
92,022
Provide tags and a correct Python 3 solution for this coding contest problem. The Little Elephant loves to play with color cards. He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks that a set of cards on the table is funny if at least half of the cards have the same color (for each card the color of the upper side is considered). Help the Little Elephant to find the minimum number of moves needed to make the set of n cards funny. Input The first line contains a single integer n (1 ≀ n ≀ 105) β€” the number of the cards. The following n lines contain the description of all cards, one card per line. The cards are described by a pair of positive integers not exceeding 109 β€” colors of both sides. The first number in a line is the color of the front of the card, the second one β€” of the back. The color of the front of the card may coincide with the color of the back of the card. The numbers in the lines are separated by single spaces. Output On a single line print a single integer β€” the sought minimum number of moves. If it is impossible to make the set funny, print -1. Examples Input 3 4 7 4 7 7 4 Output 0 Input 5 4 7 7 4 2 11 9 7 1 1 Output 2 Note In the first sample there initially are three cards lying with colors 4, 4, 7. Since two of the three cards are of the same color 4, you do not need to change anything, so the answer is 0. In the second sample, you can turn the first and the fourth cards. After that three of the five cards will be of color 7. Tags: binary search, data structures Correct Solution: ``` from collections import defaultdict from math import ceil d= defaultdict(list) n = int(input()) for i in range(n): a,b =map(int,input().split()) if a==b: if a in d: d[a][0]+=1 else: d[a]=[1,0] else: if a in d: d[a][0]+=1 else: d[a] =[1,0] if b in d: d[b][1]+=1 else: d[b] = [0,1] m= ceil(n/2) #print(d) mini = 1e6 for i in d: a =d[i][0] b= d[i][1] if a+b>=m: if a>=m: mini= min(0,mini) else: mini = min(m-a,mini) if mini ==1e6: print(-1) else: print(mini) ```
92,023
Provide tags and a correct Python 3 solution for this coding contest problem. The Little Elephant loves to play with color cards. He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks that a set of cards on the table is funny if at least half of the cards have the same color (for each card the color of the upper side is considered). Help the Little Elephant to find the minimum number of moves needed to make the set of n cards funny. Input The first line contains a single integer n (1 ≀ n ≀ 105) β€” the number of the cards. The following n lines contain the description of all cards, one card per line. The cards are described by a pair of positive integers not exceeding 109 β€” colors of both sides. The first number in a line is the color of the front of the card, the second one β€” of the back. The color of the front of the card may coincide with the color of the back of the card. The numbers in the lines are separated by single spaces. Output On a single line print a single integer β€” the sought minimum number of moves. If it is impossible to make the set funny, print -1. Examples Input 3 4 7 4 7 7 4 Output 0 Input 5 4 7 7 4 2 11 9 7 1 1 Output 2 Note In the first sample there initially are three cards lying with colors 4, 4, 7. Since two of the three cards are of the same color 4, you do not need to change anything, so the answer is 0. In the second sample, you can turn the first and the fourth cards. After that three of the five cards will be of color 7. Tags: binary search, data structures Correct Solution: ``` from collections import Counter import sys n=int(input()) ans=10**20 fr={} ba={} for _ in range(n): x,y=map(int,input().split()) if x in fr: fr[x]+=1 else: fr[x]=1 if x!=y: if y in ba: ba[y]+=1 else: ba[y]=1 for i in fr: if i in ba: x=fr[i]+ba[i] if x*2>=n: ans=min(ans,max(0,(n+1)//2-fr[i])) else: x=fr[i] if x*2>=n: ans=min(ans,max(0,(n+1)//2-fr[i])) for j in ba: y=ba[j] if y*2>=n: ans=min(ans,max(0,(n+1)//2)) if ans==10**20: ans=-1 print(ans) ```
92,024
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Little Elephant loves to play with color cards. He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks that a set of cards on the table is funny if at least half of the cards have the same color (for each card the color of the upper side is considered). Help the Little Elephant to find the minimum number of moves needed to make the set of n cards funny. Input The first line contains a single integer n (1 ≀ n ≀ 105) β€” the number of the cards. The following n lines contain the description of all cards, one card per line. The cards are described by a pair of positive integers not exceeding 109 β€” colors of both sides. The first number in a line is the color of the front of the card, the second one β€” of the back. The color of the front of the card may coincide with the color of the back of the card. The numbers in the lines are separated by single spaces. Output On a single line print a single integer β€” the sought minimum number of moves. If it is impossible to make the set funny, print -1. Examples Input 3 4 7 4 7 7 4 Output 0 Input 5 4 7 7 4 2 11 9 7 1 1 Output 2 Note In the first sample there initially are three cards lying with colors 4, 4, 7. Since two of the three cards are of the same color 4, you do not need to change anything, so the answer is 0. In the second sample, you can turn the first and the fourth cards. After that three of the five cards will be of color 7. Submitted Solution: ``` from collections import defaultdict import sys n = int(sys.stdin.readline()) # n: nro de cartas de dos colores sol = -1 # sol: nro minimo de movimientos mitad = (n + 1) // 2 f = defaultdict(int) a = defaultdict(int) # f,a: contador de las cartas que estan de frente y atras for i in range(n): frente, atras = map(int, input().split()) # frente, atras: son los colores de las cartas en su respectiva cara - pueden ser el mismo f[frente] += 1 if (frente != atras): a[atras] += 1 f = sorted(f.items(), key=lambda item: item[1], reverse=True) # Ordenar por el color que mas se repite al que menos # No hay que hacer nada, ya hay un color predominante if (f[0][1] >= mitad): sol = 0 if (sol == -1): for color, cant in f: if (a[color] + cant >= mitad): sol = mitad - cant break if (sol == -1): a = sorted(a.items(), key=lambda item: item[1], reverse=True) for color, cant in a: if (cant >= mitad): sol = mitad break sys.stdout.write(str(sol)) # En cualquier mov el elefante puede dar vuelta una carta # Un conjunto de cartas sera chistoso si al menos la mitad # de las cartas tiene el mismo color ``` Yes
92,025
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Little Elephant loves to play with color cards. He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks that a set of cards on the table is funny if at least half of the cards have the same color (for each card the color of the upper side is considered). Help the Little Elephant to find the minimum number of moves needed to make the set of n cards funny. Input The first line contains a single integer n (1 ≀ n ≀ 105) β€” the number of the cards. The following n lines contain the description of all cards, one card per line. The cards are described by a pair of positive integers not exceeding 109 β€” colors of both sides. The first number in a line is the color of the front of the card, the second one β€” of the back. The color of the front of the card may coincide with the color of the back of the card. The numbers in the lines are separated by single spaces. Output On a single line print a single integer β€” the sought minimum number of moves. If it is impossible to make the set funny, print -1. Examples Input 3 4 7 4 7 7 4 Output 0 Input 5 4 7 7 4 2 11 9 7 1 1 Output 2 Note In the first sample there initially are three cards lying with colors 4, 4, 7. Since two of the three cards are of the same color 4, you do not need to change anything, so the answer is 0. In the second sample, you can turn the first and the fourth cards. After that three of the five cards will be of color 7. Submitted Solution: ``` n = int(input()) m = int((n+1)/2) colors = [[ ]]*n colors_d = {} for i in range(n): a , b = list(map(int,input().split(' '))) colors[i]=[a,b] if a in colors_d.keys(): colors_d[a][0] += 1 else: colors_d[a] = [1,0] if a != b: if b in colors_d.keys(): colors_d[b][1] += 1 else: colors_d[b] = [0,1] minimo = 50001 for i,el in colors_d.items(): if sum(el) < m: continue if el[0] > m: minimo = 0 break if m - el[0] < minimo: minimo = m-el[0] if minimo == 50001: minimo = -1 print(minimo) ``` Yes
92,026
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Little Elephant loves to play with color cards. He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks that a set of cards on the table is funny if at least half of the cards have the same color (for each card the color of the upper side is considered). Help the Little Elephant to find the minimum number of moves needed to make the set of n cards funny. Input The first line contains a single integer n (1 ≀ n ≀ 105) β€” the number of the cards. The following n lines contain the description of all cards, one card per line. The cards are described by a pair of positive integers not exceeding 109 β€” colors of both sides. The first number in a line is the color of the front of the card, the second one β€” of the back. The color of the front of the card may coincide with the color of the back of the card. The numbers in the lines are separated by single spaces. Output On a single line print a single integer β€” the sought minimum number of moves. If it is impossible to make the set funny, print -1. Examples Input 3 4 7 4 7 7 4 Output 0 Input 5 4 7 7 4 2 11 9 7 1 1 Output 2 Note In the first sample there initially are three cards lying with colors 4, 4, 7. Since two of the three cards are of the same color 4, you do not need to change anything, so the answer is 0. In the second sample, you can turn the first and the fourth cards. After that three of the five cards will be of color 7. Submitted Solution: ``` from collections import Counter 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") ########################################################## #it=iter(t) #if all(c in it for c in s): #ls.sort(key=lambda x: (x[0], x[1])) #n,k= map(int, input().split()) # ls=list(map(int,input().split())) # for i in range(m): import math #n,k= map(int, input().split()) #ls=list(map(int,input().split())) x=int(input()) d={} ls={} same={} for i in range(x): n,k= map(int, input().split()) if n==k: if n in same: same[n]+=1 else: same[n]=1 if n not in ls: ls[n]=1 else: ls[n]+=1 if k not in d: d[k]=1 else: d[k]+=1 var=x//2 if x%2!=0: var+=1 ans=var f=0 for i in ls: if i in d: value=ls[i]+d[i] if i in same: value-=same[i] if value>=var: ans=min(ans,max(0,var-ls[i])) f=1 else: if ls[i]>=var: ans=0 f=1 break if f==1: print(ans) else: for i in d: if d[i]>=var: print(var) exit() print(-1) #arr=list(map(int,input().split())) ``` Yes
92,027
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Little Elephant loves to play with color cards. He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks that a set of cards on the table is funny if at least half of the cards have the same color (for each card the color of the upper side is considered). Help the Little Elephant to find the minimum number of moves needed to make the set of n cards funny. Input The first line contains a single integer n (1 ≀ n ≀ 105) β€” the number of the cards. The following n lines contain the description of all cards, one card per line. The cards are described by a pair of positive integers not exceeding 109 β€” colors of both sides. The first number in a line is the color of the front of the card, the second one β€” of the back. The color of the front of the card may coincide with the color of the back of the card. The numbers in the lines are separated by single spaces. Output On a single line print a single integer β€” the sought minimum number of moves. If it is impossible to make the set funny, print -1. Examples Input 3 4 7 4 7 7 4 Output 0 Input 5 4 7 7 4 2 11 9 7 1 1 Output 2 Note In the first sample there initially are three cards lying with colors 4, 4, 7. Since two of the three cards are of the same color 4, you do not need to change anything, so the answer is 0. In the second sample, you can turn the first and the fourth cards. After that three of the five cards will be of color 7. Submitted Solution: ``` """ Author - Satwik Tiwari . 24th NOV , 2020 - Tuesday """ #=============================================================================================== #importing some useful libraries. from __future__ import division, print_function from fractions import Fraction import sys import os from io import BytesIO, IOBase from functools import cmp_to_key # from itertools import * from heapq import * from math import gcd, factorial,floor,ceil,sqrt from copy import deepcopy from collections import deque from bisect import bisect_left as bl from bisect import bisect_right as br from bisect import bisect #============================================================================================== #fast I/O region 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") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) # inp = lambda: sys.stdin.readline().rstrip("\r\n") #=============================================================================================== ### START ITERATE RECURSION ### from types import GeneratorType def iterative(f, stack=[]): def wrapped_func(*args, **kwargs): if stack: return f(*args, **kwargs) to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) continue stack.pop() if not stack: break to = stack[-1].send(to) return to return wrapped_func #### END ITERATE RECURSION #### #=============================================================================================== #some shortcuts def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input def out(var): sys.stdout.write(str(var)) #for fast output, always take string def lis(): return list(map(int, inp().split())) def stringlis(): return list(map(str, inp().split())) def sep(): return map(int, inp().split()) def strsep(): return map(str, inp().split()) # def graph(vertex): return [[] for i in range(0,vertex+1)] def testcase(t): for pp in range(t): solve(pp) def google(p): print('Case #'+str(p)+': ',end='') def lcm(a,b): return (a*b)//gcd(a,b) def power(x, y, p) : y%=(p-1) #not so sure about this. used when y>p-1. if p is prime. res = 1 # Initialize result x = x % p # Update x if it is more , than or equal to p if (x == 0) : return 0 while (y > 0) : if ((y & 1) == 1) : # If y is odd, multiply, x with result res = (res * x) % p y = y >> 1 # y = y/2 x = (x * x) % p return res def ncr(n,r): return factorial(n) // (factorial(r) * factorial(max(n - r, 1))) 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 inf = pow(10,20) mod = 10**9+7 #=============================================================================================== # code here ;)) def solve(case): n = int(inp()) front = {} back = {} have = {} same = {} a = [] for i in range(n): l,r = sep() if(l == r): if(l not in same): same[l] = 1 else: same[l] +=1 a.append((l,r)) have[l] = 1 have[r] = 1 if(l in front): front[l]+=1 else: front[l] = 1 if(r in back): back[r]+=1 else: back[r] = 1 ans = inf for i in have: # print(i) f = (0 if i not in front else front[i]) b = (0 if i not in back else back[i]) - (0 if i not in same else same[i]) # print(f,b,ceil(n/2)) if(f>=ceil(n/2)): ans = min(ans,0) elif(f+b >= ceil(n/2)): ans = min(ans,ceil(n/2) - f) print(-1 if ans == inf else ans) testcase(1) # testcase(int(inp())) ``` Yes
92,028
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Little Elephant loves to play with color cards. He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks that a set of cards on the table is funny if at least half of the cards have the same color (for each card the color of the upper side is considered). Help the Little Elephant to find the minimum number of moves needed to make the set of n cards funny. Input The first line contains a single integer n (1 ≀ n ≀ 105) β€” the number of the cards. The following n lines contain the description of all cards, one card per line. The cards are described by a pair of positive integers not exceeding 109 β€” colors of both sides. The first number in a line is the color of the front of the card, the second one β€” of the back. The color of the front of the card may coincide with the color of the back of the card. The numbers in the lines are separated by single spaces. Output On a single line print a single integer β€” the sought minimum number of moves. If it is impossible to make the set funny, print -1. Examples Input 3 4 7 4 7 7 4 Output 0 Input 5 4 7 7 4 2 11 9 7 1 1 Output 2 Note In the first sample there initially are three cards lying with colors 4, 4, 7. Since two of the three cards are of the same color 4, you do not need to change anything, so the answer is 0. In the second sample, you can turn the first and the fourth cards. After that three of the five cards will be of color 7. Submitted Solution: ``` n=int(input()) a=[0]*n b=[0]*n cards=[] for i in range(n): a[i],b[i]=map(int,input().split()) if a[i]==b[i]: b[i]=-1 cards.append([a[i],b[i]]) half=n%2+n//2 from collections import Counter c1=Counter(a) c2=Counter(b) l1=[[c1[i],i] for i in c1] l2=[[c2[i],i] for i in c2] l1.sort(reverse=True) #l2.sort() if l1[0][0]>=half: ans=0 print(ans) else: f=0 ans=100000000000000000000000 for i in range(len(l1)): #print(l1[i]) req=half-l1[i][0] if c2[l1[i][1]]>=req: ans=min(req,ans) #print(l1[i][1]) f=1 break if f==0: print(-1) else: print(ans) ``` No
92,029
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Little Elephant loves to play with color cards. He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks that a set of cards on the table is funny if at least half of the cards have the same color (for each card the color of the upper side is considered). Help the Little Elephant to find the minimum number of moves needed to make the set of n cards funny. Input The first line contains a single integer n (1 ≀ n ≀ 105) β€” the number of the cards. The following n lines contain the description of all cards, one card per line. The cards are described by a pair of positive integers not exceeding 109 β€” colors of both sides. The first number in a line is the color of the front of the card, the second one β€” of the back. The color of the front of the card may coincide with the color of the back of the card. The numbers in the lines are separated by single spaces. Output On a single line print a single integer β€” the sought minimum number of moves. If it is impossible to make the set funny, print -1. Examples Input 3 4 7 4 7 7 4 Output 0 Input 5 4 7 7 4 2 11 9 7 1 1 Output 2 Note In the first sample there initially are three cards lying with colors 4, 4, 7. Since two of the three cards are of the same color 4, you do not need to change anything, so the answer is 0. In the second sample, you can turn the first and the fourth cards. After that three of the five cards will be of color 7. Submitted Solution: ``` n=int(input()) a=[0]*n b=[0]*n cards=[] for i in range(n): a[i],b[i]=map(int,input().split()) if a[i]==b[i]: b[i]=-1 cards.append([a[i],b[i]]) half=n%2+n//2 from collections import Counter c1=Counter(a) c2=Counter(b) l1=[[c1[i],i] for i in c1] l2=[[c2[i],i] for i in c2] l1.sort(reverse=True) #l2.sort() if l1[0][0]>=half: ans=0 print(ans) else: f=0 ans=100000000000000000000000 for i in range(len(l1)): #print(l1[i]) req=half-l1[i][0] if c2[l1[i][1]]>=req: ans=min(req,ans) #print(l1[i][1]) f=1 break for i in b : if c1[i]: continue if c2[i]>=half: ans=min(ans,half) f=1 if f==0: print(-1) else: print(ans) ``` No
92,030
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Little Elephant loves to play with color cards. He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks that a set of cards on the table is funny if at least half of the cards have the same color (for each card the color of the upper side is considered). Help the Little Elephant to find the minimum number of moves needed to make the set of n cards funny. Input The first line contains a single integer n (1 ≀ n ≀ 105) β€” the number of the cards. The following n lines contain the description of all cards, one card per line. The cards are described by a pair of positive integers not exceeding 109 β€” colors of both sides. The first number in a line is the color of the front of the card, the second one β€” of the back. The color of the front of the card may coincide with the color of the back of the card. The numbers in the lines are separated by single spaces. Output On a single line print a single integer β€” the sought minimum number of moves. If it is impossible to make the set funny, print -1. Examples Input 3 4 7 4 7 7 4 Output 0 Input 5 4 7 7 4 2 11 9 7 1 1 Output 2 Note In the first sample there initially are three cards lying with colors 4, 4, 7. Since two of the three cards are of the same color 4, you do not need to change anything, so the answer is 0. In the second sample, you can turn the first and the fourth cards. After that three of the five cards will be of color 7. Submitted Solution: ``` n=int(input()) a=[0]*n b=[0]*n cards=[] for i in range(n): a[i],b[i]=map(int,input().split()) if a[i]==b[i]: b[i]=-1 cards.append([a[i],b[i]]) half=n%2+n//2 from collections import Counter c1=Counter(a) c2=Counter(b) l1=[[c1[i],i] for i in c1] if l1[0][0]>=half: ans=0 print(ans) else: f=0 ans=n for i in range(len(l1)): #print(l1[i]) req=half-l1[i][0] if c2[l1[i][1]]>=req: ans=min(req,ans) #print(l1[i][1]) f=1 for i in b : if c1[i]: continue if c2[i]>=half: ans=min(ans,half) f=1 if f==0: print(-1) else: print(ans) ``` No
92,031
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Little Elephant loves to play with color cards. He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks that a set of cards on the table is funny if at least half of the cards have the same color (for each card the color of the upper side is considered). Help the Little Elephant to find the minimum number of moves needed to make the set of n cards funny. Input The first line contains a single integer n (1 ≀ n ≀ 105) β€” the number of the cards. The following n lines contain the description of all cards, one card per line. The cards are described by a pair of positive integers not exceeding 109 β€” colors of both sides. The first number in a line is the color of the front of the card, the second one β€” of the back. The color of the front of the card may coincide with the color of the back of the card. The numbers in the lines are separated by single spaces. Output On a single line print a single integer β€” the sought minimum number of moves. If it is impossible to make the set funny, print -1. Examples Input 3 4 7 4 7 7 4 Output 0 Input 5 4 7 7 4 2 11 9 7 1 1 Output 2 Note In the first sample there initially are three cards lying with colors 4, 4, 7. Since two of the three cards are of the same color 4, you do not need to change anything, so the answer is 0. In the second sample, you can turn the first and the fourth cards. After that three of the five cards will be of color 7. Submitted Solution: ``` n = int(input()) m = int((n+1)/2) colors = [[ ]]*n colors_d = {} for i in range(n): a , b = list(map(int,input().split(' '))) colors[i]=[a,b] if a in colors_d.keys(): colors_d[a][0] += 1 else: colors_d[a] = [1,0] if b in colors_d.keys(): colors_d[b][1] += 1 else: colors_d[b] = [0,1] minimo = 50001 for i,el in colors_d.items(): if sum(el) < m: continue if el[0] > m: minimo = 0 break if m - el[0] < minimo: minimo = m-el[0] if minimo == 50001: minimo = -1 print(minimo) ``` No
92,032
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a table consisting of n rows and m columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right. To cyclically shift a table row one cell to the right means to move the value of each cell, except for the last one, to the right neighboring cell, and to move the value of the last cell to the first cell. A cyclical shift of a row to the left is performed similarly, but in the other direction. For example, if we cyclically shift a row "00110" one cell to the right, we get a row "00011", but if we shift a row "00110" one cell to the left, we get a row "01100". Determine the minimum number of moves needed to make some table column consist only of numbers 1. Input The first line contains two space-separated integers: n (1 ≀ n ≀ 100) β€” the number of rows in the table and m (1 ≀ m ≀ 104) β€” the number of columns in the table. Then n lines follow, each of them contains m characters "0" or "1": the j-th character of the i-th line describes the contents of the cell in the i-th row and in the j-th column of the table. It is guaranteed that the description of the table contains no other characters besides "0" and "1". Output Print a single number: the minimum number of moves needed to get only numbers 1 in some column of the table. If this is impossible, print -1. Examples Input 3 6 101010 000100 100000 Output 3 Input 2 3 111 000 Output -1 Note In the first sample one way to achieve the goal with the least number of moves is as follows: cyclically shift the second row to the right once, then shift the third row to the left twice. Then the table column before the last one will contain only 1s. In the second sample one can't shift the rows to get a column containing only 1s. Tags: brute force, two pointers Correct Solution: ``` n, m = map(int, input().split()) memo = [[int(2e9) for j in range(m)] for i in range(n)] for i in range(n): s = input() if s.find('1') == -1: print(-1) exit() memo[i][0] = s[::-1].find('1') + 1 memo[i][m-1] = s.find('1') + 1 for j in range(m): if s[j] == '1': memo[i][j] = 0 else: memo[i][j] = min(memo[i][j], memo[i][j-1] + 1) for j in range(m-2, -1, -1): memo[i][j] = min(memo[i][j], memo[i][j+1] + 1) print(min([sum([memo[i][j] for i in range(n)]) for j in range(m)])) ```
92,033
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a table consisting of n rows and m columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right. To cyclically shift a table row one cell to the right means to move the value of each cell, except for the last one, to the right neighboring cell, and to move the value of the last cell to the first cell. A cyclical shift of a row to the left is performed similarly, but in the other direction. For example, if we cyclically shift a row "00110" one cell to the right, we get a row "00011", but if we shift a row "00110" one cell to the left, we get a row "01100". Determine the minimum number of moves needed to make some table column consist only of numbers 1. Input The first line contains two space-separated integers: n (1 ≀ n ≀ 100) β€” the number of rows in the table and m (1 ≀ m ≀ 104) β€” the number of columns in the table. Then n lines follow, each of them contains m characters "0" or "1": the j-th character of the i-th line describes the contents of the cell in the i-th row and in the j-th column of the table. It is guaranteed that the description of the table contains no other characters besides "0" and "1". Output Print a single number: the minimum number of moves needed to get only numbers 1 in some column of the table. If this is impossible, print -1. Examples Input 3 6 101010 000100 100000 Output 3 Input 2 3 111 000 Output -1 Note In the first sample one way to achieve the goal with the least number of moves is as follows: cyclically shift the second row to the right once, then shift the third row to the left twice. Then the table column before the last one will contain only 1s. In the second sample one can't shift the rows to get a column containing only 1s. Tags: brute force, two pointers Correct Solution: ``` n, m = map(int, input().split()) f = [[int(1e9) for j in range(m)] for i in range(n)] for i in range(n): s = input() if s.find('1') == -1: print(-1) exit() f[i][0] = s[::-1].find('1') + 1 f[i][m - 1] = s.find('1') + 1 for j in range(m): f[i][j] = 0 if s[j] == '1' else f[i][j] for j in range(m): f[i][j] = min(f[i][j], f[i][j - 1] + 1) for j in range(m - 2, -1, -1): f[i][j] = min(f[i][j], f[i][j + 1] + 1) print(min([sum([f[i][j] for i in range(n)]) for j in range(m)])); ```
92,034
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a table consisting of n rows and m columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right. To cyclically shift a table row one cell to the right means to move the value of each cell, except for the last one, to the right neighboring cell, and to move the value of the last cell to the first cell. A cyclical shift of a row to the left is performed similarly, but in the other direction. For example, if we cyclically shift a row "00110" one cell to the right, we get a row "00011", but if we shift a row "00110" one cell to the left, we get a row "01100". Determine the minimum number of moves needed to make some table column consist only of numbers 1. Input The first line contains two space-separated integers: n (1 ≀ n ≀ 100) β€” the number of rows in the table and m (1 ≀ m ≀ 104) β€” the number of columns in the table. Then n lines follow, each of them contains m characters "0" or "1": the j-th character of the i-th line describes the contents of the cell in the i-th row and in the j-th column of the table. It is guaranteed that the description of the table contains no other characters besides "0" and "1". Output Print a single number: the minimum number of moves needed to get only numbers 1 in some column of the table. If this is impossible, print -1. Examples Input 3 6 101010 000100 100000 Output 3 Input 2 3 111 000 Output -1 Note In the first sample one way to achieve the goal with the least number of moves is as follows: cyclically shift the second row to the right once, then shift the third row to the left twice. Then the table column before the last one will contain only 1s. In the second sample one can't shift the rows to get a column containing only 1s. Tags: brute force, two pointers Correct Solution: ``` def binS(a, x, n): l, r = -1, n while(l + 1 < r): m = (l + r)//2 if(a[m] >= x): r = m else: l = m return min(abs(a[r] - x), abs(a[r - 1] - x)) def main(): n, m = [int(i) for i in input().split()] q = [0]*m for i in range(n): s = input()*3 a = [] ln = 0 for j in range(m*3): if s[j] == '1': a += [j] ln += 1 if ln == 0: q = [-1] break for x in range(m, m*2): q[x - m] += binS(a, x, ln) print(min(q)) main() ```
92,035
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a table consisting of n rows and m columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right. To cyclically shift a table row one cell to the right means to move the value of each cell, except for the last one, to the right neighboring cell, and to move the value of the last cell to the first cell. A cyclical shift of a row to the left is performed similarly, but in the other direction. For example, if we cyclically shift a row "00110" one cell to the right, we get a row "00011", but if we shift a row "00110" one cell to the left, we get a row "01100". Determine the minimum number of moves needed to make some table column consist only of numbers 1. Input The first line contains two space-separated integers: n (1 ≀ n ≀ 100) β€” the number of rows in the table and m (1 ≀ m ≀ 104) β€” the number of columns in the table. Then n lines follow, each of them contains m characters "0" or "1": the j-th character of the i-th line describes the contents of the cell in the i-th row and in the j-th column of the table. It is guaranteed that the description of the table contains no other characters besides "0" and "1". Output Print a single number: the minimum number of moves needed to get only numbers 1 in some column of the table. If this is impossible, print -1. Examples Input 3 6 101010 000100 100000 Output 3 Input 2 3 111 000 Output -1 Note In the first sample one way to achieve the goal with the least number of moves is as follows: cyclically shift the second row to the right once, then shift the third row to the left twice. Then the table column before the last one will contain only 1s. In the second sample one can't shift the rows to get a column containing only 1s. Tags: brute force, two pointers Correct Solution: ``` ''' Auther: ghoshashis545 Ashis Ghosh College: jalpaiguri Govt Enggineering College ''' from os import path import sys from heapq import heappush,heappop from functools import cmp_to_key as ctk from collections import deque,defaultdict as dd from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right from itertools import permutations from datetime import datetime from math import ceil,sqrt,log,gcd def ii():return int(input()) def si():return input() def mi():return map(int,input().split()) def li():return list(mi()) abc='abcdefghijklmnopqrstuvwxyz' # mod=1000000007 mod=998244353 inf = float("inf") vow=['a','e','i','o','u'] dx,dy=[-1,1,0,0],[0,0,1,-1] def bo(i): return ord(i)-ord('a') file=1 def solve(): # for _ in range(ii()): n,m=mi() a=[] f=0 for i in range(n): s=list(si()) if '1' not in s: f=1 continue # s1=s+""+s # print(s1) pre=[m]*(2*m) if s[0]=='1': pre[0]=0 for j in range(1,2*m): if s[j%m]=='1': pre[j]=0 else: pre[j]=pre[j-1]+1 suff=[m]*(2*m) if s[-1]=='1': suff[-1]=0 for j in range(2*m-2,-1,-1): if s[j%m]=='1': suff[j]=0 else: suff[j]=suff[j+1]+1 # print(pre,suff) b=[m]*m for j in range(2*m): b[j%m]=min({b[j%m],pre[j],suff[j]}) a.append(b) # for i in a: # print(*i) if(f): print("-1") exit(0) # print(a) ans=inf for i in range(m): s=0 for j in range(n): s+=a[j][i] ans=min(ans,s) print(ans) if __name__ =="__main__": if(file): if path.exists('input1.txt'): sys.stdin=open('input1.txt', 'r') sys.stdout=open('output1.txt','w') else: input=sys.stdin.readline solve() ```
92,036
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a table consisting of n rows and m columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right. To cyclically shift a table row one cell to the right means to move the value of each cell, except for the last one, to the right neighboring cell, and to move the value of the last cell to the first cell. A cyclical shift of a row to the left is performed similarly, but in the other direction. For example, if we cyclically shift a row "00110" one cell to the right, we get a row "00011", but if we shift a row "00110" one cell to the left, we get a row "01100". Determine the minimum number of moves needed to make some table column consist only of numbers 1. Input The first line contains two space-separated integers: n (1 ≀ n ≀ 100) β€” the number of rows in the table and m (1 ≀ m ≀ 104) β€” the number of columns in the table. Then n lines follow, each of them contains m characters "0" or "1": the j-th character of the i-th line describes the contents of the cell in the i-th row and in the j-th column of the table. It is guaranteed that the description of the table contains no other characters besides "0" and "1". Output Print a single number: the minimum number of moves needed to get only numbers 1 in some column of the table. If this is impossible, print -1. Examples Input 3 6 101010 000100 100000 Output 3 Input 2 3 111 000 Output -1 Note In the first sample one way to achieve the goal with the least number of moves is as follows: cyclically shift the second row to the right once, then shift the third row to the left twice. Then the table column before the last one will contain only 1s. In the second sample one can't shift the rows to get a column containing only 1s. Tags: brute force, two pointers Correct Solution: ``` def calc_shift_cost(row): starts = [i for i, x in enumerate(row) if x] for start in starts: d = 2 pos = start + 1 if pos == len(row): pos = 0 while row[pos] != 1: if row[pos]: row[pos] = min(row[pos], d) else: row[pos] = d d += 1 pos += 1 if pos == len(row): pos = 0 d = 2 pos = start - 1 if pos == -1: pos = len(row) - 1 while row[pos] != 1: if row[pos]: row[pos] = min(row[pos], d) else: row[pos] = d d += 1 pos -= 1 if pos == -1: pos = len(row) - 1 for x in range(len(row)): row[x] -= 1 class CodeforcesTask229ASolution: def __init__(self): self.result = '' self.n_m = [] self.board = [] def read_input(self): self.n_m = [int(x) for x in input().split(" ")] for x in range(self.n_m[0]): self.board.append([int(x) for x in input()]) def process_task(self): for row in self.board: if sum(row): calc_shift_cost(row) else: self.result = "-1" break if not self.result: costs = [] for x in range(self.n_m[1]): ss = 0 for y in range(self.n_m[0]): ss += self.board[y][x] costs.append(ss) self.result = str(min(costs)) def get_result(self): return self.result if __name__ == "__main__": Solution = CodeforcesTask229ASolution() Solution.read_input() Solution.process_task() print(Solution.get_result()) ```
92,037
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a table consisting of n rows and m columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right. To cyclically shift a table row one cell to the right means to move the value of each cell, except for the last one, to the right neighboring cell, and to move the value of the last cell to the first cell. A cyclical shift of a row to the left is performed similarly, but in the other direction. For example, if we cyclically shift a row "00110" one cell to the right, we get a row "00011", but if we shift a row "00110" one cell to the left, we get a row "01100". Determine the minimum number of moves needed to make some table column consist only of numbers 1. Input The first line contains two space-separated integers: n (1 ≀ n ≀ 100) β€” the number of rows in the table and m (1 ≀ m ≀ 104) β€” the number of columns in the table. Then n lines follow, each of them contains m characters "0" or "1": the j-th character of the i-th line describes the contents of the cell in the i-th row and in the j-th column of the table. It is guaranteed that the description of the table contains no other characters besides "0" and "1". Output Print a single number: the minimum number of moves needed to get only numbers 1 in some column of the table. If this is impossible, print -1. Examples Input 3 6 101010 000100 100000 Output 3 Input 2 3 111 000 Output -1 Note In the first sample one way to achieve the goal with the least number of moves is as follows: cyclically shift the second row to the right once, then shift the third row to the left twice. Then the table column before the last one will contain only 1s. In the second sample one can't shift the rows to get a column containing only 1s. Tags: brute force, two pointers Correct Solution: ``` x=int(input().split(' ')[0]) y=[] for i in range(x): y.append(input()) for x in y: if '1' not in x: print("-1") exit() # y=['101010','000100','100000'] # y=['1011','1100','0010','0001'] # yy=[ (s.index('1'),s.rindex('1')) for s in y ] # l=len(y[0]) ########################## #00010000 -3/8 s="00010100" s="000100110" # 8+3,7 4 # 8+3,6 5 # 5,4 1 def row_cost_cal(string): arrL=['']*len(string) initPosL=0 if string[0]!='1': initPosL = - ( len(string) - string.rindex('1') ) for i in range(len(string)): if string[i]=='1': arrL[i]=0 initPosL=i else: arrL[i]=i-initPosL arrR=['']*len(string) initPosR=0 if string[-1]!='1': initPosR = len(string) + string.index('1') for i in range(len(string)-1,-1,-1): if string[i]=='1': arrR[i]=0 initPosR=i else: arrR[i]=initPosR-i arrMin=[ min(arrL[i],arrR[i]) for i in range(len(string)) ] # print(arrL) # print(arrR) return arrMin # row_cost_cal(s) # row_cost_cal("1001000") arrCost = [ row_cost_cal(string) for string in y] # print(arrCost) colCost = [sum(x) for x in zip(*arrCost)] print(min(colCost)) ```
92,038
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a table consisting of n rows and m columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right. To cyclically shift a table row one cell to the right means to move the value of each cell, except for the last one, to the right neighboring cell, and to move the value of the last cell to the first cell. A cyclical shift of a row to the left is performed similarly, but in the other direction. For example, if we cyclically shift a row "00110" one cell to the right, we get a row "00011", but if we shift a row "00110" one cell to the left, we get a row "01100". Determine the minimum number of moves needed to make some table column consist only of numbers 1. Input The first line contains two space-separated integers: n (1 ≀ n ≀ 100) β€” the number of rows in the table and m (1 ≀ m ≀ 104) β€” the number of columns in the table. Then n lines follow, each of them contains m characters "0" or "1": the j-th character of the i-th line describes the contents of the cell in the i-th row and in the j-th column of the table. It is guaranteed that the description of the table contains no other characters besides "0" and "1". Output Print a single number: the minimum number of moves needed to get only numbers 1 in some column of the table. If this is impossible, print -1. Examples Input 3 6 101010 000100 100000 Output 3 Input 2 3 111 000 Output -1 Note In the first sample one way to achieve the goal with the least number of moves is as follows: cyclically shift the second row to the right once, then shift the third row to the left twice. Then the table column before the last one will contain only 1s. In the second sample one can't shift the rows to get a column containing only 1s. Tags: brute force, two pointers Correct Solution: ``` import sys n, m = map(int, input().split()) mp = ['' for i in range(n)] f = [[0 for j in range(m)] for i in range(n)] for i in range(n): mp[i] = input() if mp[i].find('1') == -1: print(-1) sys.exit() tmp = mp[i][::-1].find('1') + 1 for j in range(m): if mp[i][j] == '1': f[i][j] = 0 else: f[i][j] = f[i][j - 1] + 1 if j > 0 else tmp tmp = mp[i].find('1') + 1 for j in range(m - 1, -1, -1): f[i][j] = min(f[i][j], f[i][j + 1] + 1 if j + 1 < m else tmp) ans = int(1e9) for j in range(m): sm = 0 for i in range(n): sm += f[i][j] ans = min(ans, sm) print(ans); ```
92,039
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a table consisting of n rows and m columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right. To cyclically shift a table row one cell to the right means to move the value of each cell, except for the last one, to the right neighboring cell, and to move the value of the last cell to the first cell. A cyclical shift of a row to the left is performed similarly, but in the other direction. For example, if we cyclically shift a row "00110" one cell to the right, we get a row "00011", but if we shift a row "00110" one cell to the left, we get a row "01100". Determine the minimum number of moves needed to make some table column consist only of numbers 1. Input The first line contains two space-separated integers: n (1 ≀ n ≀ 100) β€” the number of rows in the table and m (1 ≀ m ≀ 104) β€” the number of columns in the table. Then n lines follow, each of them contains m characters "0" or "1": the j-th character of the i-th line describes the contents of the cell in the i-th row and in the j-th column of the table. It is guaranteed that the description of the table contains no other characters besides "0" and "1". Output Print a single number: the minimum number of moves needed to get only numbers 1 in some column of the table. If this is impossible, print -1. Examples Input 3 6 101010 000100 100000 Output 3 Input 2 3 111 000 Output -1 Note In the first sample one way to achieve the goal with the least number of moves is as follows: cyclically shift the second row to the right once, then shift the third row to the left twice. Then the table column before the last one will contain only 1s. In the second sample one can't shift the rows to get a column containing only 1s. Tags: brute force, two pointers Correct Solution: ``` """ Author - Satwik Tiwari . 20th Oct , 2020 - Tuesday """ #=============================================================================================== #importing some useful libraries. from __future__ import division, print_function from fractions import Fraction import sys import os from io import BytesIO, IOBase from functools import cmp_to_key # from itertools import * from heapq import * from math import gcd, factorial,floor,ceil from copy import deepcopy from collections import deque from bisect import bisect_left as bl from bisect import bisect_right as br from bisect import bisect #============================================================================================== #fast I/O region 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") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) # inp = lambda: sys.stdin.readline().rstrip("\r\n") #=============================================================================================== ### START ITERATE RECURSION ### from types import GeneratorType def iterative(f, stack=[]): def wrapped_func(*args, **kwargs): if stack: return f(*args, **kwargs) to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) continue stack.pop() if not stack: break to = stack[-1].send(to) return to return wrapped_func #### END ITERATE RECURSION #### #=============================================================================================== #some shortcuts def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input def out(var): sys.stdout.write(str(var)) #for fast output, always take string def lis(): return list(map(int, inp().split())) def stringlis(): return list(map(str, inp().split())) def sep(): return map(int, inp().split()) def strsep(): return map(str, inp().split()) # def graph(vertex): return [[] for i in range(0,vertex+1)] def zerolist(n): return [0]*n def nextline(): out("\n") #as stdout.write always print sring. def testcase(t): for pp in range(t): solve(pp) def printlist(a) : for p in range(0,len(a)): out(str(a[p]) + ' ') def google(p): print('Case #'+str(p)+': ',end='') def lcm(a,b): return (a*b)//gcd(a,b) def power(x, y, p) : res = 1 # Initialize result x = x % p # Update x if it is more , than or equal to p if (x == 0) : return 0 while (y > 0) : if ((y & 1) == 1) : # If y is odd, multiply, x with result res = (res * x) % p y = y >> 1 # y = y/2 x = (x * x) % p return res def ncr(n,r): return factorial(n) // (factorial(r) * factorial(max(n - r, 1))) 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 inf = pow(10,20) mod = 998244353 #=============================================================================================== # code here ;)) def solve(case): n,m = sep() g = [] for i in range(n): temp = list(inp()) for i in range(m): temp[i] = int(temp[i]) temp*=2 g.append(temp) for i in range(n): if(g[i].count(0) == 2*m): print(-1) return left = [] right = [] for i in range(n): temp = [0]*(2*m+1) temp[2*m] = inf for j in range(2*m-1,-1,-1): if(g[i][j] == 1): temp[j] = j else: temp[j] = temp[j+1] right.append(temp) temp = [0]*(2*m+1) temp[2*m] = inf for j in range(2*m): if(g[i][j] == 1): temp[j] = j else: temp[j] = temp[j-1] left.append(temp) # for i in range(n): # print(left[i]) # print(right[i]) # print('===') ans = inf for j in range(m): curr = 0 for i in range(n): t1 = left[i][j+m] t2 = right[i][j] # print(j-t1,t2-j,j+m-t2,m-j+t1) # print(t1,t2,j) # print(j,add,i) curr+=min(j-t1+m,t2-j) ans = min(ans,curr) print(ans) testcase(1) # testcase(int(inp())) ```
92,040
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a table consisting of n rows and m columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right. To cyclically shift a table row one cell to the right means to move the value of each cell, except for the last one, to the right neighboring cell, and to move the value of the last cell to the first cell. A cyclical shift of a row to the left is performed similarly, but in the other direction. For example, if we cyclically shift a row "00110" one cell to the right, we get a row "00011", but if we shift a row "00110" one cell to the left, we get a row "01100". Determine the minimum number of moves needed to make some table column consist only of numbers 1. Input The first line contains two space-separated integers: n (1 ≀ n ≀ 100) β€” the number of rows in the table and m (1 ≀ m ≀ 104) β€” the number of columns in the table. Then n lines follow, each of them contains m characters "0" or "1": the j-th character of the i-th line describes the contents of the cell in the i-th row and in the j-th column of the table. It is guaranteed that the description of the table contains no other characters besides "0" and "1". Output Print a single number: the minimum number of moves needed to get only numbers 1 in some column of the table. If this is impossible, print -1. Examples Input 3 6 101010 000100 100000 Output 3 Input 2 3 111 000 Output -1 Note In the first sample one way to achieve the goal with the least number of moves is as follows: cyclically shift the second row to the right once, then shift the third row to the left twice. Then the table column before the last one will contain only 1s. In the second sample one can't shift the rows to get a column containing only 1s. Submitted Solution: ``` n, m = map(int, input().split()) f = [[int(1e9) for j in range(m)] for i in range(n)] for i in range(n): s = input() if s.find('1') == -1: print(-1) exit() f[i][0] = s[::-1].find('1') + 1 f[i][m - 1] = s.find('1') + 1 for j in range(m): f[i][j] = 0 if s[j] == '1' else min(f[i][j], f[i][j - 1] + 1) for j in range(m - 2, -1, -1): f[i][j] = min(f[i][j], f[i][j + 1] + 1) print(min([sum([f[i][j] for i in range(n)]) for j in range(m)])); ``` Yes
92,041
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a table consisting of n rows and m columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right. To cyclically shift a table row one cell to the right means to move the value of each cell, except for the last one, to the right neighboring cell, and to move the value of the last cell to the first cell. A cyclical shift of a row to the left is performed similarly, but in the other direction. For example, if we cyclically shift a row "00110" one cell to the right, we get a row "00011", but if we shift a row "00110" one cell to the left, we get a row "01100". Determine the minimum number of moves needed to make some table column consist only of numbers 1. Input The first line contains two space-separated integers: n (1 ≀ n ≀ 100) β€” the number of rows in the table and m (1 ≀ m ≀ 104) β€” the number of columns in the table. Then n lines follow, each of them contains m characters "0" or "1": the j-th character of the i-th line describes the contents of the cell in the i-th row and in the j-th column of the table. It is guaranteed that the description of the table contains no other characters besides "0" and "1". Output Print a single number: the minimum number of moves needed to get only numbers 1 in some column of the table. If this is impossible, print -1. Examples Input 3 6 101010 000100 100000 Output 3 Input 2 3 111 000 Output -1 Note In the first sample one way to achieve the goal with the least number of moves is as follows: cyclically shift the second row to the right once, then shift the third row to the left twice. Then the table column before the last one will contain only 1s. In the second sample one can't shift the rows to get a column containing only 1s. Submitted Solution: ``` G = [[], [1], [1, 1], [1, 2, 1], [1, 2, 2, 1], [1, 2, 3, 2, 1]] def g(k): global G if k < 6: return G[k] return list(range(1, (k + 1) // 2 + 1)) + list(range(k // 2, 0, -1)) def f(): n, m = map(int, input().split()) s, p = [0] * m, [0] * m for i in range(n): q = [j for j, x in enumerate(input()) if x == '1'] if not q: return -1 c = q.pop(0) p[c], a = 0, c + 1 for b in q: p[b] = 0 if b > a: p[a: b] = g(b - a) a = b + 1 if c + m > a: t = g(c + m - a) p[a: ], p[: c] = t[: m - a], t[m - a: ] for j, x in enumerate(p): s[j] += x return min(s) print(f()) ``` Yes
92,042
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a table consisting of n rows and m columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right. To cyclically shift a table row one cell to the right means to move the value of each cell, except for the last one, to the right neighboring cell, and to move the value of the last cell to the first cell. A cyclical shift of a row to the left is performed similarly, but in the other direction. For example, if we cyclically shift a row "00110" one cell to the right, we get a row "00011", but if we shift a row "00110" one cell to the left, we get a row "01100". Determine the minimum number of moves needed to make some table column consist only of numbers 1. Input The first line contains two space-separated integers: n (1 ≀ n ≀ 100) β€” the number of rows in the table and m (1 ≀ m ≀ 104) β€” the number of columns in the table. Then n lines follow, each of them contains m characters "0" or "1": the j-th character of the i-th line describes the contents of the cell in the i-th row and in the j-th column of the table. It is guaranteed that the description of the table contains no other characters besides "0" and "1". Output Print a single number: the minimum number of moves needed to get only numbers 1 in some column of the table. If this is impossible, print -1. Examples Input 3 6 101010 000100 100000 Output 3 Input 2 3 111 000 Output -1 Note In the first sample one way to achieve the goal with the least number of moves is as follows: cyclically shift the second row to the right once, then shift the third row to the left twice. Then the table column before the last one will contain only 1s. In the second sample one can't shift the rows to get a column containing only 1s. Submitted Solution: ``` # https://vjudge.net/contest/339915#problem/J def calculate_row_distance(row, rows_len): init_i = row.index(1) dist = 0 dists = [-1 for i in range(rows_len)] i = init_i for x in range(rows_len): if i == rows_len: i = 0 if row[i] == 1: dist = 0 dists[i] = 0 elif dists[i] == -1 or dists[i] > dist: dists[i] = dist elif dists[i] < dist: dist = dists[i] dist += 1 i += 1 dist = 0 i = init_i for x in range(rows_len): if i == -1: i = rows_len-1 if row[i] == 1: dist = 0 dists[i] = 0 elif dists[i] == -1 or dists[i] > dist: dists[i] = dist elif dists[i] < dist: dist = dists[i] dist += 1 i -= 1 return dists def init(): cols_len, rows_len = map(lambda x: int(x), input().split(' ')) cols_distance = [0 for i in range(rows_len)] for r in range(cols_len): row = [int(i) for i in input()] if 1 not in row: print('-1') return dists = calculate_row_distance(row, rows_len) for c in range(rows_len): cols_distance[c] += dists[c] cols_distance.sort() print(cols_distance[0]) init() ``` Yes
92,043
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a table consisting of n rows and m columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right. To cyclically shift a table row one cell to the right means to move the value of each cell, except for the last one, to the right neighboring cell, and to move the value of the last cell to the first cell. A cyclical shift of a row to the left is performed similarly, but in the other direction. For example, if we cyclically shift a row "00110" one cell to the right, we get a row "00011", but if we shift a row "00110" one cell to the left, we get a row "01100". Determine the minimum number of moves needed to make some table column consist only of numbers 1. Input The first line contains two space-separated integers: n (1 ≀ n ≀ 100) β€” the number of rows in the table and m (1 ≀ m ≀ 104) β€” the number of columns in the table. Then n lines follow, each of them contains m characters "0" or "1": the j-th character of the i-th line describes the contents of the cell in the i-th row and in the j-th column of the table. It is guaranteed that the description of the table contains no other characters besides "0" and "1". Output Print a single number: the minimum number of moves needed to get only numbers 1 in some column of the table. If this is impossible, print -1. Examples Input 3 6 101010 000100 100000 Output 3 Input 2 3 111 000 Output -1 Note In the first sample one way to achieve the goal with the least number of moves is as follows: cyclically shift the second row to the right once, then shift the third row to the left twice. Then the table column before the last one will contain only 1s. In the second sample one can't shift the rows to get a column containing only 1s. Submitted Solution: ``` n, m = input().split(' ') n = int(n) m = int(m) flag=True ls = list() min_one = 10**4 + 1 lines= [] for i in range(n): line = input() lines.append(line) c = len(line) for j in range(len(line)): if(line[j] == '1'): ls.append(j) break else: c-=1 if(c == 0): flag = False break ls.sort() min_one = ls[len(ls)//2] if(flag == False): print(-1) else: step = 0 for i in range(len(ls)): if(lines[i][min_one] != '1'): step += abs(ls[i] - min_one) print(step) ``` No
92,044
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a table consisting of n rows and m columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right. To cyclically shift a table row one cell to the right means to move the value of each cell, except for the last one, to the right neighboring cell, and to move the value of the last cell to the first cell. A cyclical shift of a row to the left is performed similarly, but in the other direction. For example, if we cyclically shift a row "00110" one cell to the right, we get a row "00011", but if we shift a row "00110" one cell to the left, we get a row "01100". Determine the minimum number of moves needed to make some table column consist only of numbers 1. Input The first line contains two space-separated integers: n (1 ≀ n ≀ 100) β€” the number of rows in the table and m (1 ≀ m ≀ 104) β€” the number of columns in the table. Then n lines follow, each of them contains m characters "0" or "1": the j-th character of the i-th line describes the contents of the cell in the i-th row and in the j-th column of the table. It is guaranteed that the description of the table contains no other characters besides "0" and "1". Output Print a single number: the minimum number of moves needed to get only numbers 1 in some column of the table. If this is impossible, print -1. Examples Input 3 6 101010 000100 100000 Output 3 Input 2 3 111 000 Output -1 Note In the first sample one way to achieve the goal with the least number of moves is as follows: cyclically shift the second row to the right once, then shift the third row to the left twice. Then the table column before the last one will contain only 1s. In the second sample one can't shift the rows to get a column containing only 1s. Submitted Solution: ``` n, m = map(int, input().split()) A = [input() for _ in range(n)] if '0' * m in A: print(-1) exit(0) ans = 10 ** 20 for j in range(m): cnt = 0 for i in range(n): lol = 0 for bb in range(m+228): if (j - bb >= 0 and A[i][j-bb] == '1') or (j+bb < m and A[i][j+bb] == '1'): lol = bb break cnt += lol ans = min(ans, cnt) print(ans) ``` No
92,045
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a table consisting of n rows and m columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right. To cyclically shift a table row one cell to the right means to move the value of each cell, except for the last one, to the right neighboring cell, and to move the value of the last cell to the first cell. A cyclical shift of a row to the left is performed similarly, but in the other direction. For example, if we cyclically shift a row "00110" one cell to the right, we get a row "00011", but if we shift a row "00110" one cell to the left, we get a row "01100". Determine the minimum number of moves needed to make some table column consist only of numbers 1. Input The first line contains two space-separated integers: n (1 ≀ n ≀ 100) β€” the number of rows in the table and m (1 ≀ m ≀ 104) β€” the number of columns in the table. Then n lines follow, each of them contains m characters "0" or "1": the j-th character of the i-th line describes the contents of the cell in the i-th row and in the j-th column of the table. It is guaranteed that the description of the table contains no other characters besides "0" and "1". Output Print a single number: the minimum number of moves needed to get only numbers 1 in some column of the table. If this is impossible, print -1. Examples Input 3 6 101010 000100 100000 Output 3 Input 2 3 111 000 Output -1 Note In the first sample one way to achieve the goal with the least number of moves is as follows: cyclically shift the second row to the right once, then shift the third row to the left twice. Then the table column before the last one will contain only 1s. In the second sample one can't shift the rows to get a column containing only 1s. Submitted Solution: ``` import sys n, m = map(int, input().split()) mp = ['' for i in range(n)] f = [[0 for j in range(m)] for i in range(n)] for i in range(n): mp[i] = input() if mp[i].find('1') == -1: print(-1) sys.exit() tmp = mp[i][::-1].find('1') for j in range(m): if mp[i][j] == '1': f[i][j] = 0 else: f[i][j] = f[i][j - 1] + 1 if j > 0 else tmp ans = int(1e9) for i in range(n): sm = 0 for j in range(m): sm += f[i][j]; ans = min(ans, sm) print(ans); ``` No
92,046
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a table consisting of n rows and m columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right. To cyclically shift a table row one cell to the right means to move the value of each cell, except for the last one, to the right neighboring cell, and to move the value of the last cell to the first cell. A cyclical shift of a row to the left is performed similarly, but in the other direction. For example, if we cyclically shift a row "00110" one cell to the right, we get a row "00011", but if we shift a row "00110" one cell to the left, we get a row "01100". Determine the minimum number of moves needed to make some table column consist only of numbers 1. Input The first line contains two space-separated integers: n (1 ≀ n ≀ 100) β€” the number of rows in the table and m (1 ≀ m ≀ 104) β€” the number of columns in the table. Then n lines follow, each of them contains m characters "0" or "1": the j-th character of the i-th line describes the contents of the cell in the i-th row and in the j-th column of the table. It is guaranteed that the description of the table contains no other characters besides "0" and "1". Output Print a single number: the minimum number of moves needed to get only numbers 1 in some column of the table. If this is impossible, print -1. Examples Input 3 6 101010 000100 100000 Output 3 Input 2 3 111 000 Output -1 Note In the first sample one way to achieve the goal with the least number of moves is as follows: cyclically shift the second row to the right once, then shift the third row to the left twice. Then the table column before the last one will contain only 1s. In the second sample one can't shift the rows to get a column containing only 1s. Submitted Solution: ``` n, m = map(int, input().split()) A = [input() for _ in range(n)] if '0' * m in A: print(-1) exit(0) ans = 10 ** 20 for j in range(m): cnt = 0 for i in range(n): lol = 0 for bb in range(m): if (j - bb >= 0 and A[i][j-bb] == '1') or (j+bb < m and A[i][j+bb] == '1'): lol = bb break cnt += lol ans = min(ans, cnt) print(ans) ``` No
92,047
Provide tags and a correct Python 3 solution for this coding contest problem. Little Petya likes permutations a lot. Recently his mom has presented him permutation q1, q2, ..., qn of length n. A permutation a of length n is a sequence of integers a1, a2, ..., an (1 ≀ ai ≀ n), all integers there are distinct. There is only one thing Petya likes more than permutations: playing with little Masha. As it turns out, Masha also has a permutation of length n. Petya decided to get the same permutation, whatever the cost may be. For that, he devised a game with the following rules: * Before the beginning of the game Petya writes permutation 1, 2, ..., n on the blackboard. After that Petya makes exactly k moves, which are described below. * During a move Petya tosses a coin. If the coin shows heads, he performs point 1, if the coin shows tails, he performs point 2. 1. Let's assume that the board contains permutation p1, p2, ..., pn at the given moment. Then Petya removes the written permutation p from the board and writes another one instead: pq1, pq2, ..., pqn. In other words, Petya applies permutation q (which he has got from his mother) to permutation p. 2. All actions are similar to point 1, except that Petya writes permutation t on the board, such that: tqi = pi for all i from 1 to n. In other words, Petya applies a permutation that is inverse to q to permutation p. We know that after the k-th move the board contained Masha's permutation s1, s2, ..., sn. Besides, we know that throughout the game process Masha's permutation never occurred on the board before the k-th move. Note that the game has exactly k moves, that is, throughout the game the coin was tossed exactly k times. Your task is to determine whether the described situation is possible or else state that Petya was mistaken somewhere. See samples and notes to them for a better understanding. Input The first line contains two integers n and k (1 ≀ n, k ≀ 100). The second line contains n space-separated integers q1, q2, ..., qn (1 ≀ qi ≀ n) β€” the permutation that Petya's got as a present. The third line contains Masha's permutation s, in the similar format. It is guaranteed that the given sequences q and s are correct permutations. Output If the situation that is described in the statement is possible, print "YES" (without the quotes), otherwise print "NO" (without the quotes). Examples Input 4 1 2 3 4 1 1 2 3 4 Output NO Input 4 1 4 3 1 2 3 4 2 1 Output YES Input 4 3 4 3 1 2 3 4 2 1 Output YES Input 4 2 4 3 1 2 2 1 4 3 Output YES Input 4 1 4 3 1 2 2 1 4 3 Output NO Note In the first sample Masha's permutation coincides with the permutation that was written on the board before the beginning of the game. Consequently, that violates the condition that Masha's permutation never occurred on the board before k moves were performed. In the second sample the described situation is possible, in case if after we toss a coin, we get tails. In the third sample the possible coin tossing sequence is: heads-tails-tails. In the fourth sample the possible coin tossing sequence is: heads-heads. Tags: implementation, math Correct Solution: ``` def Solve(x,L): if(x==k[0]): return L==S if((x,tuple(L)) in Mem): return False if(L==S): return False E=[] for i in range(len(L)): E.append(L[Q[i]-1]) if(Solve(x+1,E)): return True E=[0]*len(L) for i in range(len(L)): E[Q[i]-1]=L[i] if(Solve(x+1,E)): return True Mem[(x,tuple(L))]=1 return False Mem={} k=[0] n,k[0]=map(int,input().split()) P=list(range(1,n+1)) Q=list(map(int,input().split())) S=list(map(int,input().split())) if(Solve(0,P)): print("YES") else: print("NO") ```
92,048
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Little Petya likes permutations a lot. Recently his mom has presented him permutation q1, q2, ..., qn of length n. A permutation a of length n is a sequence of integers a1, a2, ..., an (1 ≀ ai ≀ n), all integers there are distinct. There is only one thing Petya likes more than permutations: playing with little Masha. As it turns out, Masha also has a permutation of length n. Petya decided to get the same permutation, whatever the cost may be. For that, he devised a game with the following rules: * Before the beginning of the game Petya writes permutation 1, 2, ..., n on the blackboard. After that Petya makes exactly k moves, which are described below. * During a move Petya tosses a coin. If the coin shows heads, he performs point 1, if the coin shows tails, he performs point 2. 1. Let's assume that the board contains permutation p1, p2, ..., pn at the given moment. Then Petya removes the written permutation p from the board and writes another one instead: pq1, pq2, ..., pqn. In other words, Petya applies permutation q (which he has got from his mother) to permutation p. 2. All actions are similar to point 1, except that Petya writes permutation t on the board, such that: tqi = pi for all i from 1 to n. In other words, Petya applies a permutation that is inverse to q to permutation p. We know that after the k-th move the board contained Masha's permutation s1, s2, ..., sn. Besides, we know that throughout the game process Masha's permutation never occurred on the board before the k-th move. Note that the game has exactly k moves, that is, throughout the game the coin was tossed exactly k times. Your task is to determine whether the described situation is possible or else state that Petya was mistaken somewhere. See samples and notes to them for a better understanding. Input The first line contains two integers n and k (1 ≀ n, k ≀ 100). The second line contains n space-separated integers q1, q2, ..., qn (1 ≀ qi ≀ n) β€” the permutation that Petya's got as a present. The third line contains Masha's permutation s, in the similar format. It is guaranteed that the given sequences q and s are correct permutations. Output If the situation that is described in the statement is possible, print "YES" (without the quotes), otherwise print "NO" (without the quotes). Examples Input 4 1 2 3 4 1 1 2 3 4 Output NO Input 4 1 4 3 1 2 3 4 2 1 Output YES Input 4 3 4 3 1 2 3 4 2 1 Output YES Input 4 2 4 3 1 2 2 1 4 3 Output YES Input 4 1 4 3 1 2 2 1 4 3 Output NO Note In the first sample Masha's permutation coincides with the permutation that was written on the board before the beginning of the game. Consequently, that violates the condition that Masha's permutation never occurred on the board before k moves were performed. In the second sample the described situation is possible, in case if after we toss a coin, we get tails. In the third sample the possible coin tossing sequence is: heads-tails-tails. In the fourth sample the possible coin tossing sequence is: heads-heads. Submitted Solution: ``` def Solve(x,L): if(x==k[0]): return L==S if((x,tuple(L)) in Mem): return False if(L==S): return False E=[] for i in range(len(L)): E.append(L[Q[i]-1]) if(Solve(x+1,E)): return True E=[0]*len(L) for i in range(len(L)): E[Q[i]-1]=L[i] if(Solve(x+1,E)): return True Mem[(x,tuple(L))]=1 return False Mem={} k=[0] n,k[0]=map(int,input().split()) P=list(range(1,n+1)) Q=list(map(int,input().split())) S=list(map(int,input().split())) print(Solve(0,P)) ``` No
92,049
Provide tags and a correct Python 3 solution for this coding contest problem. There is a square matrix n Γ— n, consisting of non-negative integer numbers. You should find such a way on it that * starts in the upper left cell of the matrix; * each following cell is to the right or down from the current cell; * the way ends in the bottom right cell. Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros. Input The first line contains an integer number n (2 ≀ n ≀ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109). Output In the first line print the least number of trailing zeros. In the second line print the correspondent way itself. Examples Input 3 1 2 3 4 5 6 7 8 9 Output 0 DDRR Tags: dp, math Correct Solution: ``` n = int(input()) xr = range(n) a5 = [list(map(int, input().split())) for _ in xr] a2 = [[0 for _ in xr] for _ in xr] y = 0 x0 = -1 for y in xr: for x in xr: i = a5[y][x] m5 = 0 m2 = 0 if i == 0: x0 = x while i and i%2 == 0: i/=2 m2+=1 while i and i%5 == 0: i/=5 m5+=1 if y == 0 and x == 0: a5[y][x] = m5 a2[y][x] = m2 continue left5 = a5[y][x-1] left2 = a2[y][x-1] up5 = a5[y-1][x] up2 = a2[y-1][x] if y == 0: a5[y][x] = left5 + m5 a2[y][x] = left2 + m2 continue if x == 0: a5[y][x] = up5 + m5 a2[y][x] = up2 + m2 continue a5[y][x] = min(up5, left5) + m5 a2[y][x] = min(up2, left2) + m2 def getpath(k): p = '' y = x = n-1 while not (y == 0 and x == 0): if y and x: if k == 5: if a5[y-1][x] < a5[y][x-1]: p+='D' y-=1 else: p+='R' x-=1 else: if a2[y-1][x] < a2[y][x-1]: p+='D' y-=1 else: p+='R' x-=1 elif y == 0: p+='R' x-=1 elif x == 0: p+='D' y-=1 return p[::-1] ten = 0 path = '' if a5[n-1][n-1] < a2[n-1][n-1]: ten = a5[n-1][n-1] path = getpath(5) else: ten = a2[n-1][n-1] path = getpath(2) if ten > 1 and x0 > -1: ten = 1 path = 'R'*x0 + 'D'*(n-1) + 'R'*(n-1-x0) print(ten) print(path) ```
92,050
Provide tags and a correct Python 3 solution for this coding contest problem. There is a square matrix n Γ— n, consisting of non-negative integer numbers. You should find such a way on it that * starts in the upper left cell of the matrix; * each following cell is to the right or down from the current cell; * the way ends in the bottom right cell. Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros. Input The first line contains an integer number n (2 ≀ n ≀ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109). Output In the first line print the least number of trailing zeros. In the second line print the correspondent way itself. Examples Input 3 1 2 3 4 5 6 7 8 9 Output 0 DDRR Tags: dp, math Correct Solution: ``` n = int(input()) field = [] field_two = [] field_five = [] fields = [field_two, field_five] max_zero = 20000 zero_i = None def make_mult(number, div, i): global zero_i if number == 0: zero_i = i return max_zero count = 0 while number % div == 0: count += 1 number //= div return count def get_path(): for i in range(1, n): field_two[i][0] += field_two[i - 1][0] field_five[i][0] += field_five[i - 1][0] for j in range(1, n): field_two[0][j] += field_two[0][j - 1] field_five[0][j] += field_five[0][j - 1] for i in range(1, n): for j in range(1, n): field_two[i][j] += min(field_two[i - 1][j], field_two[i][j - 1]) field_five[i][j] += min(field_five[i - 1][j], field_five[i][j - 1]) if field_two[-1][-1] < field_five[-1][-1]: return field_two[-1][-1], build_path(field_two) else: return field_five[-1][-1], build_path(field_five) def build_path(mult_field): path = [] i = j = n - 1 while i + j: if i == 0 or not j == 0 and mult_field[i][j - 1] < mult_field[i - 1][j]: path.append("R") j -= 1 else: path.append("D") i -= 1 path.reverse() return "".join(path) def solver(): zeros, path = get_path() if zeros < 2: return zeros, path if zero_i is None: return zeros, path else: return 1, "D" * zero_i + "R" * (n - 1) + "D" * (n - 1 - zero_i) def main(): for i in range(n): field.append([int(e) for e in input().split()]) field_two.append([make_mult(e, 2, i) for e in field[i]]) field_five.append([make_mult(e, 5, i) for e in field[i]]) zeros, path = solver() print(zeros, path, sep="\n") if __name__ == '__main__': main() ```
92,051
Provide tags and a correct Python 3 solution for this coding contest problem. There is a square matrix n Γ— n, consisting of non-negative integer numbers. You should find such a way on it that * starts in the upper left cell of the matrix; * each following cell is to the right or down from the current cell; * the way ends in the bottom right cell. Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros. Input The first line contains an integer number n (2 ≀ n ≀ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109). Output In the first line print the least number of trailing zeros. In the second line print the correspondent way itself. Examples Input 3 1 2 3 4 5 6 7 8 9 Output 0 DDRR Tags: dp, math Correct Solution: ``` def solve(): n = int(input()) A = [] for _ in range(n): A.append([int(x) for x in input().split()]) A2 = [[0 for _ in range(n)] for __ in range(n)] A5 = [[0 for _ in range(n)] for __ in range(n)] ans = 0; act_path = "" for i in range(n): for j in range(n): if(A[i][j]==0): ans = 1 act_path = "R"*j+"D"*i+"R"*(n-1-j)+"D"*(n-1-i) A[i][j]=10 for i in range(n): for j in range(n): x = A[i][j] while(x%2==0 and x>0): A2[i][j]+=1 x//=2 while(x%5==0 and x>0): A5[i][j]+=1 x//=5 dp2 = A2 dp5 = A5 for i in range(1,n): dp2[i][0]+=dp2[i-1][0] dp2[0][i]+=dp2[0][i-1] for i in range(1,n): dp5[i][0]+=dp5[i-1][0] dp5[0][i]+=dp5[0][i-1] for i in range(1,n): for j in range(1,n): dp2[i][j]+= min(dp2[i-1][j],dp2[i][j-1]) dp5[i][j]+= min(dp5[i-1][j],dp5[i][j-1]) dp = dp2 if dp2[-1][-1]<dp5[-1][-1] else dp5 if ans==1 and dp[-1][-1]: print(ans) print(act_path) return ans = dp[-1][-1] pi,pj = n-1,n-1 act_path = "" while(pi and pj): up = dp[pi-1][pj]<dp[pi][pj-1] act_path+= "D" if up else "R" pi-= int(up) pj-= int(not up) if(not pi): act_path+= "R"*pj else: act_path+= "D"*pi print(ans) print(act_path[::-1]) solve() ```
92,052
Provide tags and a correct Python 3 solution for this coding contest problem. There is a square matrix n Γ— n, consisting of non-negative integer numbers. You should find such a way on it that * starts in the upper left cell of the matrix; * each following cell is to the right or down from the current cell; * the way ends in the bottom right cell. Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros. Input The first line contains an integer number n (2 ≀ n ≀ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109). Output In the first line print the least number of trailing zeros. In the second line print the correspondent way itself. Examples Input 3 1 2 3 4 5 6 7 8 9 Output 0 DDRR Tags: dp, math Correct Solution: ``` def solve(x,y): z=0 while not x%y and x!=0: z+=1 x=x//y return z def main(): n=int(input()) m_2=[list(map(int,input().split())) for _ in range(n)] m_5=[[0 for _ in range(n)] for _ in range(n)] x=(-1,-1) for i in range(n): for j in range(n): if m_2[i][j]==0: x=(i,j) break if x[0]!=-1: break m_2[0][0],m_5[0][0]=solve(m_2[0][0],2),solve(m_2[0][0],5) for i in range(1,n): m_5[0][i],m_2[0][i]=m_5[0][i-1]+solve(m_2[0][i],5),m_2[0][i-1]+solve(m_2[0][i],2) m_5[i][0],m_2[i][0]=m_5[i-1][0]+solve(m_2[i][0],5),m_2[i-1][0]+solve(m_2[i][0],2) for i in range(1,n): for j in range(1,n): m_5[i][j]=min(m_5[i-1][j],m_5[i][j-1])+solve(m_2[i][j],5) m_2[i][j]=min(m_2[i-1][j],m_2[i][j-1])+solve(m_2[i][j],2) if min(m_5[-1][-1],m_2[-1][-1])>1 and x[0]!=-1: print(1) print("R"*(x[1])+"D"*(n-1)+"R"*(n-x[1]-1)) else: global c if m_5[-1][-1]<m_2[-1][-1]: c=m_5 else: c=m_2 b,i,j=[],n-1,n-1 while i or j: if i-1>=0 and j-1>=0: if c[i-1][j]<c[i][j-1]: b.append("D") i-=1 else: b.append("R") j-=1 elif i==0: b.append("R") j-=1 else: b.append("D") i-=1 print(c[-1][-1]) b.reverse() print("".join(b)) main() ```
92,053
Provide tags and a correct Python 3 solution for this coding contest problem. There is a square matrix n Γ— n, consisting of non-negative integer numbers. You should find such a way on it that * starts in the upper left cell of the matrix; * each following cell is to the right or down from the current cell; * the way ends in the bottom right cell. Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros. Input The first line contains an integer number n (2 ≀ n ≀ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109). Output In the first line print the least number of trailing zeros. In the second line print the correspondent way itself. Examples Input 3 1 2 3 4 5 6 7 8 9 Output 0 DDRR Tags: dp, math Correct Solution: ``` """ #If FastIO not needed, use this and don't forget to strip #import sys, math #input = sys.stdin.readline """ import os import sys from io import BytesIO, IOBase import heapq as h from bisect import bisect_left, bisect_right import time from types import GeneratorType BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): import os self.os = os 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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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: self.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") from collections import defaultdict as dd, deque as dq, Counter as dc import math, string start_time = time.time() def getInts(): return [int(s) for s in input().split()] def getInt(): return int(input()) def getStrs(): return [s for s in input().split()] def getStr(): return input() def listStr(): return list(input()) def getMat(n): return [getInts() for _ in range(n)] def isInt(s): return '0' <= s[0] <= '9' MOD = 998244353 """ For any given path we only need to know its factors of 2 and 5 """ def calc(x,f): if not x: return -1 ans = 0 while x % f == 0: x //= f ans += 1 return ans def solve(): N = getInt() M = getMat(N) M2 = [[calc(M[i][j],2) for j in range(N)] for i in range(N)] M5 = [[calc(M[i][j],5) for j in range(N)] for i in range(N)] dp2 = [[0 for j in range(N)] for i in range(N)] dp5 = [[0 for j in range(N)] for i in range(N)] dp2[0][0] = M2[0][0] dp5[0][0] = M5[0][0] zero = [10**18,10**18] if M[0][0] == 0: zero = [0,0] for i in range(1,N): if M[0][i] == 0: zero = [0,i] if M[i][0] == 0: zero = [i,0] if -1 in [dp2[i-1][0],M2[i][0]]: dp2[i][0] = -1 else: dp2[i][0] = dp2[i-1][0] + M2[i][0] if -1 in [dp2[0][i-1],M2[0][i]]: dp2[0][i] = -1 else: dp2[0][i] = dp2[0][i-1] + M2[0][i] if -1 in [dp5[i-1][0],M5[i][0]]: dp5[i][0] = -1 else: dp5[i][0] = dp5[i-1][0] + M5[i][0] if -1 in [dp5[0][i-1],M5[0][i]]: dp5[0][i] = -1 else: dp5[0][i] = dp5[0][i-1] + M5[0][i] for i in range(1,N): for j in range(1,N): if M[i][j] == 0: zero = [i,j] if dp2[i-1][j]*dp2[i][j-1]+M2[i][j] == 0: dp2[i][j] = 0 elif -1 in [dp2[i-1][j],dp2[i][j-1],M2[i][j]]: dp2[i][j] = -1 else: dp2[i][j] = min(dp2[i-1][j],dp2[i][j-1]) + M2[i][j] if dp5[i-1][j]*dp5[i][j-1]+M5[i][j] == 0: dp5[i][j] = 0 elif -1 in [dp5[i-1][j],dp5[i][j-1],M5[i][j]]: dp5[i][j] = -1 else: dp5[i][j] = min(dp5[i-1][j],dp5[i][j-1]) + M5[i][j] i, j = N-1, N-1 ans1 = dp2[i][j] ans2 = dp5[i][j] ans = [] if not ans1: print(0) while i+j: if not i: ans.append('R') j -= 1 elif not j: ans.append('D') i -= 1 elif dp2[i-1][j] + M2[i][j] == dp2[i][j]: ans.append('D') i -= 1 else: ans.append('R') j -= 1 print(''.join(ans[::-1])) return elif not ans2: print(0) while i+j: if not i: ans.append('R') j -= 1 elif not j: ans.append('D') i -= 1 elif dp5[i-1][j] + M5[i][j] == dp5[i][j]: ans.append('D') i -= 1 else: ans.append('R') j -= 1 print(''.join(ans[::-1])) return elif -1 in [ans1,ans2]: print(1) i, j = zero ans = ['R']*j + ['D']*i + ['R']*(N-j-1) + ['D']*(N-i-1) print(''.join(ans)) return print(min(ans1,ans2)) if ans1 <= ans2: while i+j: if not i: ans.append('R') j -= 1 elif not j: ans.append('D') i -= 1 elif dp2[i-1][j] + M2[i][j] == dp2[i][j]: ans.append('D') i -= 1 else: ans.append('R') j -= 1 else: while i+j: if not i: ans.append('R') j -= 1 elif not j: ans.append('D') i -= 1 elif dp5[i-1][j] + M5[i][j] == dp5[i][j]: ans.append('D') i -= 1 else: ans.append('R') j -= 1 print(''.join(ans[::-1])) return #for _ in range(getInt()): #print(solve()) solve() #print(time.time()-start_time) ```
92,054
Provide tags and a correct Python 3 solution for this coding contest problem. There is a square matrix n Γ— n, consisting of non-negative integer numbers. You should find such a way on it that * starts in the upper left cell of the matrix; * each following cell is to the right or down from the current cell; * the way ends in the bottom right cell. Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros. Input The first line contains an integer number n (2 ≀ n ≀ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109). Output In the first line print the least number of trailing zeros. In the second line print the correspondent way itself. Examples Input 3 1 2 3 4 5 6 7 8 9 Output 0 DDRR Tags: dp, math Correct Solution: ``` #2B - The least round way n = int(input()) m = [] for i in range(n): m.append(list(map(int, input().split()))) #Empty nxn matrix for the divisors of 2 div2 = [[0 for i in range(n)] for ii in range(n)] #Empty nxn matrix for the divisors of 5 div5 = [[0 for i in range(n)] for ii in range(n)] ans = 0 #Loop for cases where we have 0 in input for i in range(n): for ii in range(n): if m[i][ii] == 0: ans = 1 #The following variable will store the final path path = 'R' * ii + 'D' * i + 'R' * (n - 1 - ii) + 'D' * (n - 1 - i) m[i][ii] = 10 #Loop for rest of the cases #We try to find cells that decompose in factors of 2 and 5 for i in range(n): for ii in range(n): x = m[i][ii] while x % 2 == 0 and x > 0: div2[i][ii] += 1 x //= 2 while x % 5 == 0 and x > 0: div5[i][ii] += 1 x //= 5 #Now, we start the actual movement #We add each number we pass to the previous one as we go for i in range(1, n): div2[i][0] += div2[i - 1][0] div2[0][i] += div2[0][i - 1] div5[i][0] += div5[i - 1][0] div5[0][i] += div5[0][i - 1] #We apply the previous loop procedure to the entire list for i in range(1, n): for ii in range(1, n): div2[i][ii] += min(div2[i - 1][ii], div2[i][ii - 1]) div5[i][ii] += min(div5[i - 1][ii], div5[i][ii - 1]) #We record the number of zeros resulted from our movement if div2[-1][-1] < div5[-1][-1]: dp = div2 else: dp = div5 if ans == 1 and dp[-1][-1]: print(ans) print(path) #We start from the top left corner, recording our moves on our #way to the bottom right corner else: i, ii = n - 1, n - 1 path = '' #Now, we determine the direction we moved into by comparing our #current position to the previous one and include the record in path while i or ii: if not i: path += 'R' ii -= 1 elif not ii: path += 'D' i -= 1 else: if dp[i - 1][ii] < dp[i][ii - 1]: path += 'D' i -= 1 else: path += 'R' ii -= 1 path = path[::-1] #Now, we print the least number of trailing zeros, then the record of the moves print(dp[-1][-1]) print(path) ```
92,055
Provide tags and a correct Python 3 solution for this coding contest problem. There is a square matrix n Γ— n, consisting of non-negative integer numbers. You should find such a way on it that * starts in the upper left cell of the matrix; * each following cell is to the right or down from the current cell; * the way ends in the bottom right cell. Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros. Input The first line contains an integer number n (2 ≀ n ≀ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109). Output In the first line print the least number of trailing zeros. In the second line print the correspondent way itself. Examples Input 3 1 2 3 4 5 6 7 8 9 Output 0 DDRR Tags: dp, math Correct Solution: ``` n = int(input()) m = [] for i in range(n): m.append(list(map(int, input().split()))) # n x n matrices with zeroes div2 = [[0 for i in range(n)] for ii in range(n)] div5 = [[0 for i in range(n)] for ii in range(n)] # check for zero input ans = 0 for i in range(n): for ii in range(n): if m[i][ii] == 0: ans = 1 # make the path path = 'R' * ii + 'D' * i + 'R' * (n - 1 - ii) + 'D' * (n - 1 - i) m[i][ii] = 10 # find cells that decompose in factors of 2 and 5 for i in range(n): for ii in range(n): x = m[i][ii] while x % 2 == 0 and x > 0: div2[i][ii] += 1 x //= 2 while x % 5 == 0 and x > 0: div5[i][ii] += 1 x //= 5 # add each number passed to the previous one for i in range(1, n): div2[i][0] += div2[i - 1][0] div2[0][i] += div2[0][i - 1] div5[i][0] += div5[i - 1][0] div5[0][i] += div5[0][i - 1] for i in range(1, n): for ii in range(1, n): div2[i][ii] += min(div2[i - 1][ii], div2[i][ii - 1]) div5[i][ii] += min(div5[i - 1][ii], div5[i][ii - 1]) # number of zeros resulted from our movement if div2[-1][-1] < div5[-1][-1]: dp = div2 else: dp = div5 if ans == 1 and dp[-1][-1]: print(ans) print(path) # move from the top left to the bottom right corner else: i, ii = n - 1, n - 1 path = '' # determine the direction by comparing current position to the previous while i or ii: if not i: path += 'R' ii -= 1 elif not ii: path += 'D' i -= 1 else: if dp[i - 1][ii] < dp[i][ii - 1]: path += 'D' i -= 1 else: path += 'R' ii -= 1 path = path[::-1] print(dp[-1][-1]) print(path) ```
92,056
Provide tags and a correct Python 3 solution for this coding contest problem. There is a square matrix n Γ— n, consisting of non-negative integer numbers. You should find such a way on it that * starts in the upper left cell of the matrix; * each following cell is to the right or down from the current cell; * the way ends in the bottom right cell. Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros. Input The first line contains an integer number n (2 ≀ n ≀ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109). Output In the first line print the least number of trailing zeros. In the second line print the correspondent way itself. Examples Input 3 1 2 3 4 5 6 7 8 9 Output 0 DDRR Tags: dp, math Correct Solution: ``` def trail_find(i, val, m): global zero_trail if val == 0: zero_trail = i return 20000 r = 0 while val % m == 0: r += 1 val //= m return r def find_path(): for i in range(1, n): list_mod_2[i][0] += list_mod_2[i - 1][0] list_mod_5[i][0] += list_mod_5[i - 1][0] for j in range(1, n): list_mod_2[0][j] += list_mod_2[0][j - 1] list_mod_5[0][j] += list_mod_5[0][j - 1] for i in range(1, n): for j in range(1, n): list_mod_2[i][j] += min(list_mod_2[i - 1][j], list_mod_2[i][j - 1]) list_mod_5[i][j] += min(list_mod_5[i - 1][j], list_mod_5[i][j - 1]) if list_mod_2[-1][-1] < list_mod_5[-1][-1]: return list_mod_2[-1][-1], build_path(list_mod_2) else: return list_mod_5[-1][-1], build_path(list_mod_5) def build_path(lis): path = [] i = j = n - 1 while i + j: if i == 0 or not j == 0 and lis[i][j - 1] < lis[i - 1][j]: path.append('R') j -= 1 else: path.append('D') i -= 1 path.reverse() return ''.join(path) def solve(): zero, path = find_path() if zero < 2: return zero, path if zero_trail is None: return zero, path else: return 1, 'D' * zero_trail + 'R' * (n - 1) + 'D' * (n - 1 - zero_trail) n = int(input()) list_mod_2 = [] list_mod_5 = [] list_combined = [list_mod_2, list_mod_5] zero_trail = None for i in range(n): l = [int(x) for x in input().split()] list_mod_2.append([trail_find(i, e, 2) for e in l]) list_mod_5.append([trail_find(i, e, 5) for e in l]) zero, path = solve() print(zero) print(path) ```
92,057
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a square matrix n Γ— n, consisting of non-negative integer numbers. You should find such a way on it that * starts in the upper left cell of the matrix; * each following cell is to the right or down from the current cell; * the way ends in the bottom right cell. Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros. Input The first line contains an integer number n (2 ≀ n ≀ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109). Output In the first line print the least number of trailing zeros. In the second line print the correspondent way itself. Examples Input 3 1 2 3 4 5 6 7 8 9 Output 0 DDRR Submitted Solution: ``` #2B - The least round way n = int(input()) m = [] for i in range(n): m.append(list(map(int, input().split()))) #Empty nxn matrix for the divisors of 2 div2 = [[0 for i in range(n)] for ii in range(n)] #Empty nxn matrix for the divisors of 5 div5 = [[0 for i in range(n)] for ii in range(n)] ans = 0 #Loop for cases where we have 0 in input for i in range(n): for ii in range(n): if m[i][ii] == 0: ans = 1 #The following variable will store the final path path = 'R' * ii + 'D' * i + 'R' * (n - 1 - ii) + 'D' * (n - 1 - i) m[i][ii] = 10 #Loop for rest of the cases #We try to find cells that decompose in factors of 2 and 5 for i in range(n): for ii in range(n): x = m[i][ii] while x % 2 == 0 and x > 0: div2[i][ii] += 1 x //= 2 while x % 5 == 0 and x > 0: div5[i][ii] += 1 x //= 5 #Now, we start the actual movement #We add each number we pass to the previous one as we go for i in range(1, n): div2[i][0] += div2[i - 1][0] div2[0][i] += div2[0][i - 1] div5[i][0] += div5[i - 1][0] div5[0][i] += div5[0][i - 1] #We apply the previous loop procedure to the entire list for i in range(1, n): for ii in range(1, n): div2[i][ii] += min(div2[i - 1][ii], div2[i][ii - 1]) div5[i][ii] += min(div5[i - 1][ii], div5[i][ii - 1]) #We record the number of zeros resulted from our movement if div2[-1][-1] < div5[-1][-1]: dp = div2 else: dp = div5 if ans == 1 and dp[-1][-1]: print(ans) print(path) #We start from the top left corner, recording our moves on our #way to the bottom right corner else: i, ii = n - 1, n - 1 path = '' #Now, we determine the direction we moved into by comparing our #current position to the previous one and include the record in path while i or ii: if not i: path += 'R' ii -= 1 elif not ii: path += 'D' i -= 1 else: if dp[i - 1][ii] < dp[i][ii - 1]: path += 'D' i -= 1 else: path += 'R' ii -= 1 path = path[::-1] #Now, we print the least number of trailing zeros, then the full record of the moves print(dp[-1][-1]) print(path) ``` Yes
92,058
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a square matrix n Γ— n, consisting of non-negative integer numbers. You should find such a way on it that * starts in the upper left cell of the matrix; * each following cell is to the right or down from the current cell; * the way ends in the bottom right cell. Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros. Input The first line contains an integer number n (2 ≀ n ≀ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109). Output In the first line print the least number of trailing zeros. In the second line print the correspondent way itself. Examples Input 3 1 2 3 4 5 6 7 8 9 Output 0 DDRR Submitted Solution: ``` import sys,math # Initialize grid n = int(sys.stdin.readline()) grid = [] for i in range(0,n): grid.append(list(map(int,sys.stdin.readline().split()))) # Check for 0 (which will make the answer at most 1, does not play well) zero_exists = False zero_row = 0 zero_col = 0 for i in range(0,n): for j in range(0,n): if grid[i][j] == 0: zero_exists = True zero_row = i zero_col = j # Purely minimize 2s (ignoring 2s) def v_p(n, p): if n == 0: return math.inf elif n%p != 0: return 0 else: return 1+v_p(n//p,p) twos = list(map(lambda row: list(map(lambda i: v_p(i,2),row)), grid)) twos_dp = [] twos_path = [] for i in range(0,n): twos_dp.append([]) twos_path.append([]) for j in range(0,n): twos_dp[i].append(0) twos_path[i].append('') for index_sum in range(0,2*n-1): for i in range(max(0,index_sum-n+1),min(n,index_sum+1)): j = index_sum - i if i == 0 and j == 0: twos_dp[0][0] = twos[0][0] elif i == 0: twos_dp[0][j] = twos_dp[0][j-1] + twos[0][j] twos_path[0][j] = 'R' elif j == 0: twos_dp[i][0] = twos_dp[i-1][0] + twos[i][0] twos_path[i][0] = 'D' else: if twos_dp[i-1][j] < twos_dp[i][j-1]: twos_dp[i][j] = twos_dp[i-1][j] + twos[i][j] twos_path[i][j] = 'D' else: twos_dp[i][j] = twos_dp[i][j-1] + twos[i][j] twos_path[i][j] = 'R' # Purely minimize 5s (ignoring 5s) fives = list(map(lambda row: list(map(lambda i: v_p(i,5),row)), grid)) fives_dp = [] fives_path = [] for i in range(0,n): fives_dp.append([]) fives_path.append([]) for j in range(0,n): fives_dp[i].append(0) fives_path[i].append(0) for index_sum in range(0,2*n-1): for i in range(max(0,index_sum-n+1),min(n,index_sum+1)): j = index_sum - i if i == 0 and j == 0: fives_dp[0][0] = fives[0][0] elif i == 0: fives_dp[0][j] = fives_dp[0][j-1] + fives[0][j] fives_path[0][j] = 'R' elif j == 0: fives_dp[i][0] = fives_dp[i-1][0] + fives[i][0] fives_path[i][0] = 'D' else: if fives_dp[i-1][j] < fives_dp[i][j-1]: fives_dp[i][j] = fives_dp[i-1][j] + fives[i][j] fives_path[i][j] = 'D' else: fives_dp[i][j] = fives_dp[i][j-1] + fives[i][j] fives_path[i][j] ='R' def recover_path(grid): i = n-1 j = n-1 string = '' while i != 0 or j != 0: string = grid[i][j] + string if grid[i][j] == 'R': j -= 1 elif grid[i][j] == 'D': i -= 1 else: print("This should not be reached") return string # The answer is as least as good and cannot be better than either one if zero_exists and twos_dp[n-1][n-1] >= 1 and fives_dp[n-1][n-1] > 1: print(1) path = '' for i in range(0,zero_row): path += 'D' for j in range(0,zero_col): path += 'R' for i in range(zero_row+1,n): path += 'D' for j in range(zero_col+1,n): path += 'R' print(path) elif twos_dp[n-1][n-1] <= fives_dp[n-1][n-1]: print(twos_dp[n-1][n-1]) print(recover_path(twos_path)) else: print(fives_dp[n-1][n-1]) print(recover_path(fives_path)) ``` Yes
92,059
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a square matrix n Γ— n, consisting of non-negative integer numbers. You should find such a way on it that * starts in the upper left cell of the matrix; * each following cell is to the right or down from the current cell; * the way ends in the bottom right cell. Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros. Input The first line contains an integer number n (2 ≀ n ≀ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109). Output In the first line print the least number of trailing zeros. In the second line print the correspondent way itself. Examples Input 3 1 2 3 4 5 6 7 8 9 Output 0 DDRR Submitted Solution: ``` def sqr_5_converter(i): global num_called num_called += 1 if i != 0: b = (i%2 == 0) or (i%5 == 0); num_2s = 0; num_5s = 0 while b: if i%2 == 0: num_2s += 1; i = i//2; if i%5 == 0: num_5s += 1; i = i//5; b = (i%2 == 0) or (i%5 == 0) return (num_2s, num_5s) else: global zero if not zero: zero = True global zero_spot rem = num_called%n quot = num_called//n if num_called%n == 0: zero_spot = (quot - 1, n - 1) else: zero_spot = (quot, rem - 1) return (1, 1) #needs to choose the one with less 0's. def grim_reaper(r, d, add): if r[0] < d[0]: if r[1] < d[1]: return (r[0] + add[0], r[1] + add[1]) else: return (r[0] + add[0], d[1] + add[1]) else: if r[1] < d[1]: return (d[0] + add[0], r[1] + add[1]) else: return (d[0] + add[0], d[1] + add[1]) def backtracker(mode, path, m, n): # backtracker now needs to follow the zero in case of zero if mode == 2: global zero_spot x = zero_spot[1]; y = zero_spot[0] print('R'*x + 'D'*y + 'R'*(n-x) + 'D'*(m-y)); return; else: if m == 0 or n == 0: if m == 0 and n == 0: print(path); return; elif m == 0: print('R'*n + path); return; else: print('D'*m + path); return; else: # 0 for 2 and 1 for 5 if arr[m-1][n][mode] < arr[m][n-1][mode]: backtracker(mode, 'D' + path, m-1,n); elif arr[m-1][n][mode] == arr[m][n-1][mode]: if arr[m-1][n][(mode + 1)%2] <= arr[m][n-1][(mode + 1)%2]: backtracker(mode, 'D' + path, m-1,n) else: backtracker(mode, 'R' + path, m,n-1); else: backtracker(mode, 'R' + path, m,n-1); #first route is for the 2s and second is for the 5s n = int(input()) arr = [[1]]*n zero = False zero_spot = (0, 0) num_called = 0 for i in range(n): a = list(map(sqr_5_converter, (map(int, input().split())))) arr[i] = a for j in range(n): for k in range(n): if j == 0 or k == 0: if j == 0 and k == 0: continue elif j == 0: arr[j][k] = (arr[j][k-1][0] + arr[j][k][0], arr[j][k-1][1] + arr[j][k][1]) else: arr[j][k] = (arr[j-1][k][0] + arr[j][k][0], arr[j-1][k][1] + arr[j][k][1]) else: arr[j][k] = grim_reaper(arr[j][k-1], arr[j-1][k], arr[j][k]) val = min(arr[n-1][n-1][0], arr[n-1][n-1][1]) if zero and val >= 1: print(1) backtracker(2,'',n-1,n-1) else: print(val) if arr[n-1][n-1][0] < arr[n-1][n-1][1]: backtracker(0,'',n-1,n-1) else: backtracker(1,'',n-1,n-1) ``` Yes
92,060
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a square matrix n Γ— n, consisting of non-negative integer numbers. You should find such a way on it that * starts in the upper left cell of the matrix; * each following cell is to the right or down from the current cell; * the way ends in the bottom right cell. Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros. Input The first line contains an integer number n (2 ≀ n ≀ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109). Output In the first line print the least number of trailing zeros. In the second line print the correspondent way itself. Examples Input 3 1 2 3 4 5 6 7 8 9 Output 0 DDRR Submitted Solution: ``` # def zero(num): # ret = 0 # for char in str(num)[::-1]: # if char != '0': # break # ret += 1 # return ret # def count(num, m): # ret = 0 # while num % m == 0: # ret += 1 # num //= m # return ret # def compare(a, b): # a2 = count(a, 2) # a5 = count(a, 5) # b2 = count(b, 2) # b5 = count(b, 5) # if a2 < b2 or a5 < b5: # return 1 # else: # return 0 n = int(input()) m = [] for i in range(n): m.append(list(map(int, input().split()))) dp2 = [[0 for _ in range(n)] for __ in range(n)] dp5 = [[0 for _ in range(n)] for __ in range(n)] ans = 0 for i in range(n): for j in range(n): if (m[i][j] == 0): ans = 1 path = 'R' * j + 'D' * i + 'R' * (n - 1 - j) + 'D' * (n - 1 - i) m[i][j] = 10 for i in range(n): for j in range(n): x = m[i][j] while x % 2 == 0 and x > 0: dp2[i][j] += 1 x //= 2 while x % 5 == 0 and x > 0: dp5[i][j] += 1 x //= 5 for i in range(1, n): dp2[i][0] += dp2[i-1][0] dp2[0][i] += dp2[0][i-1] dp5[i][0] += dp5[i-1][0] dp5[0][i] += dp5[0][i-1] for i in range(1, n): for j in range(1, n): dp2[i][j] += min(dp2[i-1][j], dp2[i][j-1]) dp5[i][j] += min(dp5[i-1][j], dp5[i][j-1]) if dp2[-1][-1] < dp5[-1][-1]: dp = dp2 else: dp = dp5 if ans == 1 and dp[-1][-1]: print(ans) print(path) else: i, j = n - 1, n - 1 path = '' while i or j: if not i: path += 'R' j -= 1 elif not j: path += 'D' i -= 1 else: if dp[i-1][j] < dp[i][j-1]: path += 'D' i -= 1 else: path += 'R' j -= 1 path = path[::-1] print(dp[-1][-1]) print(path) # dp = [] # for i in range(n): # dp.append([]) # for j in range(n): # dp[i].append(['', 1]) # for i in range(n): # for j in range(n): # if j == 0 and i == 0: # dp[i][j][1] = m[i][j] # elif j == 0: # dp[i][j][1] = dp[i-1][j][1] * m[i][j] # dp[i][j][0] = dp[i-1][j][0] + 'D' # elif i == 0: # dp[i][j][1] = dp[i][j-1][1] * m[i][j] # dp[i][j][0] = dp[i][j-1][0] + 'R' # else: # down = dp[i-1][j][1] * m[i][j] # right = dp[i][j-1][1] * m[i][j] # # print(right, down, count(right, 2), count( # # right, 5), count(down, 2), count(down, 5)) # if compare(right, down) and zero(right) <= zero(down): # dp[i][j][1] = right # dp[i][j][0] = dp[i][j-1][0] + 'R' # else: # dp[i][j][1] = down # dp[i][j][0] = dp[i-1][j][0] + 'D' # for i in range(n): # print(dp[i]) # print(zero(dp[-1][-1][1])) # print(dp[-1][-1][0]) ``` Yes
92,061
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a square matrix n Γ— n, consisting of non-negative integer numbers. You should find such a way on it that * starts in the upper left cell of the matrix; * each following cell is to the right or down from the current cell; * the way ends in the bottom right cell. Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros. Input The first line contains an integer number n (2 ≀ n ≀ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109). Output In the first line print the least number of trailing zeros. In the second line print the correspondent way itself. Examples Input 3 1 2 3 4 5 6 7 8 9 Output 0 DDRR Submitted Solution: ``` # by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO, IOBase from math import inf def occ(x, a): ans = 0 if x == 0: return 0 while not x % a: x //= a ans += 1 return ans def main(): n = int(input()) min_2 = [[inf for _ in range(n + 1)] for _ in range(n + 1)] min_5 = [[inf for _ in range(n + 1)] for _ in range(n + 1)] arr = [list(map(int, input().split())) for _ in range(n)] min_2[0][1] = 0 min_5[0][1] = 0 fl = 0 mini = inf for i in range(1, n + 1): for j in range(1, n + 1): min_2[i][j] = min(min_2[i - 1][j], min_2[i][j - 1]) + occ(arr[i - 1][j - 1], 2) min_5[i][j] = min(min_5[i - 1][j], min_5[i][j - 1]) + occ(arr[i - 1][j - 1], 5) mini = min(mini,min(min_2[i][j],min_5[i][j])) if not arr[i-1][j-1] and mini: fl,ind = 1,j-1 if fl: print(1) sys.stdout.write('R' * ind + 'D' * (n - 1) + 'R' * (n - ind - 1)) exit() if min_2[-1][-1] < min_5[-1][-1]: print(min_2[-1][-1]) flg = min_2 else: print(min_5[-1][-1]) flg = min_5 ans = [] x, y = n, n for _ in range(2 * n - 2): if flg[x - 1][y] < flg[x][y - 1]: ans.append('D') x -= 1 else: ans.append('R') y -= 1 sys.stdout.write(''.join(ans[::-1])) #Fast IO Region 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") if __name__ == '__main__': main() ``` No
92,062
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a square matrix n Γ— n, consisting of non-negative integer numbers. You should find such a way on it that * starts in the upper left cell of the matrix; * each following cell is to the right or down from the current cell; * the way ends in the bottom right cell. Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros. Input The first line contains an integer number n (2 ≀ n ≀ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109). Output In the first line print the least number of trailing zeros. In the second line print the correspondent way itself. Examples Input 3 1 2 3 4 5 6 7 8 9 Output 0 DDRR Submitted Solution: ``` from pprint import pprint def countzero(num): if num==0: return 1 i = 0 while num > 0: if num%10: break num = num // 10 i += 1 return i def solve(block, n): # create a copy dp = [] for i in range(n): dp.append([0]*n) for i in range(n): for j in range(n): if i==0 and j==0: dp[i][j] = (0, 0, block[0][0]) elif i==0 and not j==0: __, __, c = dp[i][j-1] dp[i][j] = (i, j-1, c*block[i][j]) elif not i==0 and j==0: __, __, c = dp[i-1][j] dp[i][j] = (i-1, j, c*block[i][j]) else: __, __, c1 = dp[i][j-1] __, __, c2 = dp[i-1][j] if countzero(c1) < countzero(c2): dp[i][j] = (i, j-1, c1*block[i][j]) else: dp[i][j] = (i-1, j, c2*block[i][j]) print(countzero(dp[n-1][n-1][2])) #get path path="" start = (0, 0) cur = (n-1, n-1) while not cur == start: a, b = cur c, d, __ = dp[a][b] if c == a-1: path = "D" + path if d == b-1: path = "R" + path cur = (c, d) print(path) return dp n = int(input()) block = [] for i in range(n): row = input().split() row = list(map(int, row)) block.append(row) ans = solve(block, n) #pprint(ans) ``` No
92,063
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a square matrix n Γ— n, consisting of non-negative integer numbers. You should find such a way on it that * starts in the upper left cell of the matrix; * each following cell is to the right or down from the current cell; * the way ends in the bottom right cell. Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros. Input The first line contains an integer number n (2 ≀ n ≀ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109). Output In the first line print the least number of trailing zeros. In the second line print the correspondent way itself. Examples Input 3 1 2 3 4 5 6 7 8 9 Output 0 DDRR Submitted Solution: ``` import sys line_num = int(sys.stdin.readline()) lines = [] for i in range(0, line_num): lines.append(sys.stdin.readline().strip()) elements = [] zero_row = -1 for row_index, line in enumerate(lines): row = [int(i) for i in line.split()] if 0 in row: zero_row = row_index elements.append(row) scores = [] for n in range(line_num): temp = [] for m in range(line_num): temp.append([0, 'N']) scores.append(temp) scores[0][0] = [elements[0][0], 'N'] for temp_i in range(1, line_num): scores[0][temp_i] = [scores[0][temp_i-1][0] * elements[0][temp_i], 'R'] scores[temp_i][0] = [scores[temp_i-1][0][0] * elements[temp_i][0], 'D'] for i in range(1, line_num): for j in range(1, line_num): score_R = scores[i][j-1][0] * elements[i][j] score_D = scores[i-1][j][0] * elements[i][j] chars_R = list(str(score_R))[::-1] chars_D = list(str(score_D))[::-1] min_length = 0 if len(chars_R) < len(chars_D): min_length = len(chars_R) else: min_length = len(chars_D) choice = [0, 'N'] if min_length > 20: score_R = score_R % (10 ** 20) score_D = score_D % (10 ** 20) for index in range(0, min_length): if chars_R[index] == '0' and chars_D[index] != '0': choice = [score_D, 'D'] break elif chars_D[index] == '0' and chars_R[index] != '0': choice = [score_R, 'R'] break elif chars_D[index] == '0' and chars_R[index] == '0': continue elif chars_R[index] in ['1', '3', '7', '9']: choice = [score_R, 'R'] break elif chars_D[index] in ['1', '3', '7', '9']: choice = [score_D, 'D'] break elif chars_R[index] in ['2', '4', '6', '8'] and chars_D[index] in ['2', '4', '6', '8']: if chars_R[index] in ['2', '6']: choice = [score_R, 'R'] elif chars_D[index] in ['2', '6']: choice = [score_D, 'D'] elif chars_R[index] == '4': choice = [score_R, 'R'] elif chars_D[index] == '4': choice = [score_D, 'D'] else: choice = [score_R, 'R'] break elif chars_R[index] in ['2', '4', '6', '8'] and chars_D[index] == '5': if i < line_num-1 and j < line_num-1 and str(elements[i+1][j])[-1] == '5' and str(elements[i][j+1])[-1] == '5': choice = [score_D, 'D'] elif i < line_num-1 and j == line_num-1 and str(elements[i+1][j])[-1] == '5': choice = [score_D, 'D'] elif i == line_num - 1 and j < line_num - 1 and str(elements[i][j+1])[-1] == '5': choice = [score_D, 'D'] else: choice = [score_R, 'R'] break elif chars_D[index] in ['2', '4', '6', '8'] and chars_R[index] == '5': if i < line_num-1 and j < line_num-1 and str(elements[i+1][j])[-1] == '5' and str(elements[i][j+1])[-1] == '5': choice = [score_R, 'R'] elif i < line_num-1 and j == line_num-1 and str(elements[i+1][j])[-1] == '5': choice = [score_R, 'R'] elif i == line_num - 1 and j < line_num - 1 and str(elements[i][j+1])[-1] == '5': choice = [score_R, 'R'] else: choice = [score_D, 'D'] break elif chars_D[index] == '5' and chars_R[index] == '5': choice = [score_R, 'R'] break if choice[1] == 'N': choice = [0, 'R'] scores[i][j] = choice final_score = scores[line_num-1][line_num-1][0] if zero_row > -1 and final_score % 100 == 0: print("1") if zero_row == 0: print('R'*(line_num-1) + 'D'*(line_num-1)) else: print('D'*zero_row + 'R'*(line_num-1) + 'D'*(line_num-zero_row-1)) else: count = 0 reversed_score = list(str(final_score)[::-1]) while reversed_score and reversed_score[0] == '0': del reversed_score[0] count += 1 x = line_num - 1 y = line_num - 1 path = scores[x][y][1] while x + y > 0: if path[-1] == 'R': y = y - 1 else: x = x - 1 path += scores[x][y][1] path = path[:-1] if elements[0][0] == 795 and elements[0][1] == 244 and elements[1][0] == 273: print("1") print("DDDDDDDDDDDDRRRDRRRRDDDDDDDDDDDDDDDDRRRRRDRRRRDRRDRRRRRRRRRRDRRDDDRRRRRRDDDRRR") else: print(count) print(path[::-1]) if len(elements) == 100: print(scores) ``` No
92,064
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a square matrix n Γ— n, consisting of non-negative integer numbers. You should find such a way on it that * starts in the upper left cell of the matrix; * each following cell is to the right or down from the current cell; * the way ends in the bottom right cell. Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros. Input The first line contains an integer number n (2 ≀ n ≀ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109). Output In the first line print the least number of trailing zeros. In the second line print the correspondent way itself. Examples Input 3 1 2 3 4 5 6 7 8 9 Output 0 DDRR Submitted Solution: ``` import sys input = sys.stdin.readline from math import * from bisect import * from functools import reduce, lru_cache from collections import Counter, defaultdict n = int(input()) D = [list(map(int, input().split())) for _ in range(n)] F = lambda x, p: 0 if x % p else 1 + F(x // p, p) L = [((inf, ""), (inf, ""))] * (n + 1) for x in range(n): for y in range(n): l2 = min(y, y + 1, key = lambda i: L[i][0][0]) l5 = min(y, y + 1, key = lambda i: L[i][1][0]) c2 = L[y][0][1] + "R" if l2 == y else L[y + 1][0][1] + "D" c5 = L[y][1][1] + "R" if l5 == y else L[y + 1][1][1] + "D" L[y + 1] = ((F(D[x][y], 2) +l2, c2), (F(D[x][y], 5) + l5, c5)) R = min(L[n]) print(R[0]) print(R[1][1:]) ``` No
92,065
Provide tags and a correct Python 3 solution for this coding contest problem. Daniel is organizing a football tournament. He has come up with the following tournament format: 1. In the first several (possibly zero) stages, while the number of teams is even, they split in pairs and play one game for each pair. At each stage the loser of each pair is eliminated (there are no draws). Such stages are held while the number of teams is even. 2. Eventually there will be an odd number of teams remaining. If there is one team remaining, it will be declared the winner, and the tournament ends. Otherwise each of the remaining teams will play with each other remaining team once in round robin tournament (if there are x teams, there will be <image> games), and the tournament ends. For example, if there were 20 teams initially, they would begin by playing 10 games. So, 10 teams would be eliminated, and the remaining 10 would play 5 games. Then the remaining 5 teams would play 10 games in a round robin tournament. In total there would be 10+5+10=25 games. Daniel has already booked the stadium for n games. Help him to determine how many teams he should invite so that the tournament needs exactly n games. You should print all possible numbers of teams that will yield exactly n games in ascending order, or -1 if there are no such numbers. Input The first line contains a single integer n (1 ≀ n ≀ 1018), the number of games that should be played. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. Output Print all possible numbers of invited teams in ascending order, one per line. If exactly n games cannot be played, output one number: -1. Examples Input 3 Output 3 4 Input 25 Output 20 Input 2 Output -1 Tags: binary search, math Correct Solution: ``` n = int(input()) + 1 b, p = 1, [] while b < n + 1: d = (2 * b - 1) ** 2 + 8 * (n - b) s = int(d ** 0.5) s += int((d // s - s) // 2) if s * s == d: a = s - (2 * b - 1) if a % 4 == 0: p.append(b * (a // 2 + 1)) b *= 2 print('\n'.join(map(str, p)) if p else '-1') ```
92,066
Provide tags and a correct Python 3 solution for this coding contest problem. Daniel is organizing a football tournament. He has come up with the following tournament format: 1. In the first several (possibly zero) stages, while the number of teams is even, they split in pairs and play one game for each pair. At each stage the loser of each pair is eliminated (there are no draws). Such stages are held while the number of teams is even. 2. Eventually there will be an odd number of teams remaining. If there is one team remaining, it will be declared the winner, and the tournament ends. Otherwise each of the remaining teams will play with each other remaining team once in round robin tournament (if there are x teams, there will be <image> games), and the tournament ends. For example, if there were 20 teams initially, they would begin by playing 10 games. So, 10 teams would be eliminated, and the remaining 10 would play 5 games. Then the remaining 5 teams would play 10 games in a round robin tournament. In total there would be 10+5+10=25 games. Daniel has already booked the stadium for n games. Help him to determine how many teams he should invite so that the tournament needs exactly n games. You should print all possible numbers of teams that will yield exactly n games in ascending order, or -1 if there are no such numbers. Input The first line contains a single integer n (1 ≀ n ≀ 1018), the number of games that should be played. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. Output Print all possible numbers of invited teams in ascending order, one per line. If exactly n games cannot be played, output one number: -1. Examples Input 3 Output 3 4 Input 25 Output 20 Input 2 Output -1 Tags: binary search, math Correct Solution: ``` f=n=int(input()) N=1 while N<=n*2: l,h=0,n while h>=l: m=(l+h)//2 r=(m*2+1)*(m+N-1) if r>n:h=m-1 elif r<n:l=m+1 else: print(m*2*N+N) f=0 break N*=2 if f:print(-1) # Made By Mostafa_Khaled ```
92,067
Provide tags and a correct Python 3 solution for this coding contest problem. Daniel is organizing a football tournament. He has come up with the following tournament format: 1. In the first several (possibly zero) stages, while the number of teams is even, they split in pairs and play one game for each pair. At each stage the loser of each pair is eliminated (there are no draws). Such stages are held while the number of teams is even. 2. Eventually there will be an odd number of teams remaining. If there is one team remaining, it will be declared the winner, and the tournament ends. Otherwise each of the remaining teams will play with each other remaining team once in round robin tournament (if there are x teams, there will be <image> games), and the tournament ends. For example, if there were 20 teams initially, they would begin by playing 10 games. So, 10 teams would be eliminated, and the remaining 10 would play 5 games. Then the remaining 5 teams would play 10 games in a round robin tournament. In total there would be 10+5+10=25 games. Daniel has already booked the stadium for n games. Help him to determine how many teams he should invite so that the tournament needs exactly n games. You should print all possible numbers of teams that will yield exactly n games in ascending order, or -1 if there are no such numbers. Input The first line contains a single integer n (1 ≀ n ≀ 1018), the number of games that should be played. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. Output Print all possible numbers of invited teams in ascending order, one per line. If exactly n games cannot be played, output one number: -1. Examples Input 3 Output 3 4 Input 25 Output 20 Input 2 Output -1 Tags: binary search, math Correct Solution: ``` from decimal import * def is_int(d): return d == int(d) getcontext().prec=40 n=Decimal(input()) l=[] p2=Decimal(1) for i in range(70): d=9+8*n+4*(p2**2)-12*p2 x=(3-2*p2+d.sqrt())/2 if(is_int(x)): if(x%2==1): l.append(p2*x)#l.append((p2+(x+1)/2)*x) p2=p2*2 l.sort() if len(l)==0: print(-1) else: for i in l: print(int(i)) ```
92,068
Provide tags and a correct Python 3 solution for this coding contest problem. Daniel is organizing a football tournament. He has come up with the following tournament format: 1. In the first several (possibly zero) stages, while the number of teams is even, they split in pairs and play one game for each pair. At each stage the loser of each pair is eliminated (there are no draws). Such stages are held while the number of teams is even. 2. Eventually there will be an odd number of teams remaining. If there is one team remaining, it will be declared the winner, and the tournament ends. Otherwise each of the remaining teams will play with each other remaining team once in round robin tournament (if there are x teams, there will be <image> games), and the tournament ends. For example, if there were 20 teams initially, they would begin by playing 10 games. So, 10 teams would be eliminated, and the remaining 10 would play 5 games. Then the remaining 5 teams would play 10 games in a round robin tournament. In total there would be 10+5+10=25 games. Daniel has already booked the stadium for n games. Help him to determine how many teams he should invite so that the tournament needs exactly n games. You should print all possible numbers of teams that will yield exactly n games in ascending order, or -1 if there are no such numbers. Input The first line contains a single integer n (1 ≀ n ≀ 1018), the number of games that should be played. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. Output Print all possible numbers of invited teams in ascending order, one per line. If exactly n games cannot be played, output one number: -1. Examples Input 3 Output 3 4 Input 25 Output 20 Input 2 Output -1 Tags: binary search, math Correct Solution: ``` from math import sqrt n = int(input()) resp = set() for y in range(1, 65): delta = 2**(2*y) - (2**(y+1))*3 + 9 + 8*n raiz = -1 l, r = 0, int(sqrt(delta))+10 while l <= r : m = (l+r)//2 if m*m == delta: raiz = m break elif m*m < delta: l = m+1 else: r = m-1 if raiz == -1: continue x1 = (3-2**y+raiz)//2 x2 = (3-2**y-raiz)//2 if x1 % 2 == 1: x1 = x1 * (2**(y-1)) if x1 >= 1: resp.add(x1) if x2 % 2 == 1: x2 = x2 * (2**(y-1)) if x2 >= 1: resp.add(x2) if len(resp) == 0: print("-1") else: for e in sorted(resp): print(e) ```
92,069
Provide tags and a correct Python 3 solution for this coding contest problem. Daniel is organizing a football tournament. He has come up with the following tournament format: 1. In the first several (possibly zero) stages, while the number of teams is even, they split in pairs and play one game for each pair. At each stage the loser of each pair is eliminated (there are no draws). Such stages are held while the number of teams is even. 2. Eventually there will be an odd number of teams remaining. If there is one team remaining, it will be declared the winner, and the tournament ends. Otherwise each of the remaining teams will play with each other remaining team once in round robin tournament (if there are x teams, there will be <image> games), and the tournament ends. For example, if there were 20 teams initially, they would begin by playing 10 games. So, 10 teams would be eliminated, and the remaining 10 would play 5 games. Then the remaining 5 teams would play 10 games in a round robin tournament. In total there would be 10+5+10=25 games. Daniel has already booked the stadium for n games. Help him to determine how many teams he should invite so that the tournament needs exactly n games. You should print all possible numbers of teams that will yield exactly n games in ascending order, or -1 if there are no such numbers. Input The first line contains a single integer n (1 ≀ n ≀ 1018), the number of games that should be played. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. Output Print all possible numbers of invited teams in ascending order, one per line. If exactly n games cannot be played, output one number: -1. Examples Input 3 Output 3 4 Input 25 Output 20 Input 2 Output -1 Tags: binary search, math Correct Solution: ``` #!/usr/bin/python3 y=int(input()) s=set() e=1 for k in range(0,70): b=2*e-3 c=-2*y d=b*b-4*c if d>=0: L=0 R=d while True: M=(L+R+1)//2 if L==R: break MM=M*M if MM>d: R=M-1 else: L=M if M*M==d: x=-b+M if x>0 and x%2==0: x//=2 if x%2==1: s.add(x*e) x=-b-M if x>0 and x%2==0: x//=2 if x%2==1: s.add(x*e) e<<=1 y=True for x in sorted(s): print(x) y=False if y: print(-1) ```
92,070
Provide tags and a correct Python 3 solution for this coding contest problem. Daniel is organizing a football tournament. He has come up with the following tournament format: 1. In the first several (possibly zero) stages, while the number of teams is even, they split in pairs and play one game for each pair. At each stage the loser of each pair is eliminated (there are no draws). Such stages are held while the number of teams is even. 2. Eventually there will be an odd number of teams remaining. If there is one team remaining, it will be declared the winner, and the tournament ends. Otherwise each of the remaining teams will play with each other remaining team once in round robin tournament (if there are x teams, there will be <image> games), and the tournament ends. For example, if there were 20 teams initially, they would begin by playing 10 games. So, 10 teams would be eliminated, and the remaining 10 would play 5 games. Then the remaining 5 teams would play 10 games in a round robin tournament. In total there would be 10+5+10=25 games. Daniel has already booked the stadium for n games. Help him to determine how many teams he should invite so that the tournament needs exactly n games. You should print all possible numbers of teams that will yield exactly n games in ascending order, or -1 if there are no such numbers. Input The first line contains a single integer n (1 ≀ n ≀ 1018), the number of games that should be played. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. Output Print all possible numbers of invited teams in ascending order, one per line. If exactly n games cannot be played, output one number: -1. Examples Input 3 Output 3 4 Input 25 Output 20 Input 2 Output -1 Tags: binary search, math Correct Solution: ``` n = int(input()) f = 0 for p in range(63): N = 1 << (p+1) l = 0 h = n while h >= l: m = (l+h)//2 x = m*2+1 res = x*(x+N-3) if res == n*2: print(x*(1 << p)) f = 1 break elif res > n*2: h = m-1 else: l = m+1 if f==0: print(-1) ```
92,071
Provide tags and a correct Python 3 solution for this coding contest problem. Daniel is organizing a football tournament. He has come up with the following tournament format: 1. In the first several (possibly zero) stages, while the number of teams is even, they split in pairs and play one game for each pair. At each stage the loser of each pair is eliminated (there are no draws). Such stages are held while the number of teams is even. 2. Eventually there will be an odd number of teams remaining. If there is one team remaining, it will be declared the winner, and the tournament ends. Otherwise each of the remaining teams will play with each other remaining team once in round robin tournament (if there are x teams, there will be <image> games), and the tournament ends. For example, if there were 20 teams initially, they would begin by playing 10 games. So, 10 teams would be eliminated, and the remaining 10 would play 5 games. Then the remaining 5 teams would play 10 games in a round robin tournament. In total there would be 10+5+10=25 games. Daniel has already booked the stadium for n games. Help him to determine how many teams he should invite so that the tournament needs exactly n games. You should print all possible numbers of teams that will yield exactly n games in ascending order, or -1 if there are no such numbers. Input The first line contains a single integer n (1 ≀ n ≀ 1018), the number of games that should be played. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. Output Print all possible numbers of invited teams in ascending order, one per line. If exactly n games cannot be played, output one number: -1. Examples Input 3 Output 3 4 Input 25 Output 20 Input 2 Output -1 Tags: binary search, math Correct Solution: ``` n = int(input()) succ = False; for ii in range(0, 100): i = 2 ** ii l = 1 r = 2 ** 100 while l < r: mid = (l+r)//2 x = 2 * mid - 1 v = x*((x-1)//2+i-1) if v == n: succ = True print(x*i) break elif v < n: l = mid + 1 else: r = mid if not succ: print("-1") ```
92,072
Provide tags and a correct Python 3 solution for this coding contest problem. Daniel is organizing a football tournament. He has come up with the following tournament format: 1. In the first several (possibly zero) stages, while the number of teams is even, they split in pairs and play one game for each pair. At each stage the loser of each pair is eliminated (there are no draws). Such stages are held while the number of teams is even. 2. Eventually there will be an odd number of teams remaining. If there is one team remaining, it will be declared the winner, and the tournament ends. Otherwise each of the remaining teams will play with each other remaining team once in round robin tournament (if there are x teams, there will be <image> games), and the tournament ends. For example, if there were 20 teams initially, they would begin by playing 10 games. So, 10 teams would be eliminated, and the remaining 10 would play 5 games. Then the remaining 5 teams would play 10 games in a round robin tournament. In total there would be 10+5+10=25 games. Daniel has already booked the stadium for n games. Help him to determine how many teams he should invite so that the tournament needs exactly n games. You should print all possible numbers of teams that will yield exactly n games in ascending order, or -1 if there are no such numbers. Input The first line contains a single integer n (1 ≀ n ≀ 1018), the number of games that should be played. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. Output Print all possible numbers of invited teams in ascending order, one per line. If exactly n games cannot be played, output one number: -1. Examples Input 3 Output 3 4 Input 25 Output 20 Input 2 Output -1 Tags: binary search, math Correct Solution: ``` n = int(input()) x=1 res=[] for i in range(64): lo, hi =0, int(1e15) f=0 ans=0 while lo+1<hi: mid=(lo+hi)//2 v = (x-1)*mid+ (mid*mid-mid)//2 if(v==n): f=1; ans=mid break; if(v>n): hi=mid else: lo=mid if(f and ans%2==1): res.append(ans*x) x=x*2 if(len(res)==0): print(-1); exit(0) for x in res: print(int(x)) ```
92,073
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Daniel is organizing a football tournament. He has come up with the following tournament format: 1. In the first several (possibly zero) stages, while the number of teams is even, they split in pairs and play one game for each pair. At each stage the loser of each pair is eliminated (there are no draws). Such stages are held while the number of teams is even. 2. Eventually there will be an odd number of teams remaining. If there is one team remaining, it will be declared the winner, and the tournament ends. Otherwise each of the remaining teams will play with each other remaining team once in round robin tournament (if there are x teams, there will be <image> games), and the tournament ends. For example, if there were 20 teams initially, they would begin by playing 10 games. So, 10 teams would be eliminated, and the remaining 10 would play 5 games. Then the remaining 5 teams would play 10 games in a round robin tournament. In total there would be 10+5+10=25 games. Daniel has already booked the stadium for n games. Help him to determine how many teams he should invite so that the tournament needs exactly n games. You should print all possible numbers of teams that will yield exactly n games in ascending order, or -1 if there are no such numbers. Input The first line contains a single integer n (1 ≀ n ≀ 1018), the number of games that should be played. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. Output Print all possible numbers of invited teams in ascending order, one per line. If exactly n games cannot be played, output one number: -1. Examples Input 3 Output 3 4 Input 25 Output 20 Input 2 Output -1 Submitted Solution: ``` import sys def isqrt(n): l = -1 h = n while l + 1 < h: m = (l + h) // 2 if m * m <= n: l = m else: h = m return l with sys.stdin as fin, sys.stdout as fout: n = int(next(fin)) ans = [] for i in range(64 + 1): a = 2 ** i - 1 q = 1 - 4 * a + 4 * a ** 2 + 8 * n rt = isqrt(q) if rt ** 2 != q: continue res = 1 - 2 * a + rt if res % 2 != 0 or res % 4 == 0: continue ans.append(res // 2 * 2 ** i) if not ans: print(-1, file=fout) else: for i in ans: print(i, file=fout) ``` Yes
92,074
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Daniel is organizing a football tournament. He has come up with the following tournament format: 1. In the first several (possibly zero) stages, while the number of teams is even, they split in pairs and play one game for each pair. At each stage the loser of each pair is eliminated (there are no draws). Such stages are held while the number of teams is even. 2. Eventually there will be an odd number of teams remaining. If there is one team remaining, it will be declared the winner, and the tournament ends. Otherwise each of the remaining teams will play with each other remaining team once in round robin tournament (if there are x teams, there will be <image> games), and the tournament ends. For example, if there were 20 teams initially, they would begin by playing 10 games. So, 10 teams would be eliminated, and the remaining 10 would play 5 games. Then the remaining 5 teams would play 10 games in a round robin tournament. In total there would be 10+5+10=25 games. Daniel has already booked the stadium for n games. Help him to determine how many teams he should invite so that the tournament needs exactly n games. You should print all possible numbers of teams that will yield exactly n games in ascending order, or -1 if there are no such numbers. Input The first line contains a single integer n (1 ≀ n ≀ 1018), the number of games that should be played. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. Output Print all possible numbers of invited teams in ascending order, one per line. If exactly n games cannot be played, output one number: -1. Examples Input 3 Output 3 4 Input 25 Output 20 Input 2 Output -1 Submitted Solution: ``` ans=[] n=1 def f(r,k): a=2**k a-=1 a*=r b=r*(r-1)//2 return a+b def ff(r,k): a=2**k return a*r def tr(k): if(f(1,k)>n): return l=1 r=2**60 while(r-l>1): mid=(l+r)//2 if(f(mid,k)<n):l=mid+1 else:r=mid while(f(l,k)<n):l+=1 if(f(l,k)==n and l&1):ans.append(ff(l,k)) n=eval(input()) for i in range(60,-1,-1): tr(i) ans.sort() if len(ans)==0: print(-1) import sys sys.exit(0) for i in ans: print(i,end=' ') ``` Yes
92,075
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Daniel is organizing a football tournament. He has come up with the following tournament format: 1. In the first several (possibly zero) stages, while the number of teams is even, they split in pairs and play one game for each pair. At each stage the loser of each pair is eliminated (there are no draws). Such stages are held while the number of teams is even. 2. Eventually there will be an odd number of teams remaining. If there is one team remaining, it will be declared the winner, and the tournament ends. Otherwise each of the remaining teams will play with each other remaining team once in round robin tournament (if there are x teams, there will be <image> games), and the tournament ends. For example, if there were 20 teams initially, they would begin by playing 10 games. So, 10 teams would be eliminated, and the remaining 10 would play 5 games. Then the remaining 5 teams would play 10 games in a round robin tournament. In total there would be 10+5+10=25 games. Daniel has already booked the stadium for n games. Help him to determine how many teams he should invite so that the tournament needs exactly n games. You should print all possible numbers of teams that will yield exactly n games in ascending order, or -1 if there are no such numbers. Input The first line contains a single integer n (1 ≀ n ≀ 1018), the number of games that should be played. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. Output Print all possible numbers of invited teams in ascending order, one per line. If exactly n games cannot be played, output one number: -1. Examples Input 3 Output 3 4 Input 25 Output 20 Input 2 Output -1 Submitted Solution: ``` import sys fin = sys.stdin n = int(fin.readline()) def f(a, k): return (a * (a - 1)) // 2 + a * (2 ** k - 1) def ff(k): result = 0 while k % 2 == 0: k //= 2 result += k result += (k * (k - 1)) // 2 return result def find_a(k): i, j = 1, n while i <= j: m = (i + j) // 2 value = f(m, k) if value == n: return m if value < n: i = m + 1 else: j = m - 1 return -1 result = set() for k in range(100): a = find_a(k) if a != -1: t = a * 2 ** k if ff(t) == n: result.add(t) #result.add((a, k)) #for i in result: # print((i, ff(i))) # if ff(i) != n: # print(i) if len(result) > 0: print(" ".join(map(str, sorted(result)))) else: print(-1) ``` Yes
92,076
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Daniel is organizing a football tournament. He has come up with the following tournament format: 1. In the first several (possibly zero) stages, while the number of teams is even, they split in pairs and play one game for each pair. At each stage the loser of each pair is eliminated (there are no draws). Such stages are held while the number of teams is even. 2. Eventually there will be an odd number of teams remaining. If there is one team remaining, it will be declared the winner, and the tournament ends. Otherwise each of the remaining teams will play with each other remaining team once in round robin tournament (if there are x teams, there will be <image> games), and the tournament ends. For example, if there were 20 teams initially, they would begin by playing 10 games. So, 10 teams would be eliminated, and the remaining 10 would play 5 games. Then the remaining 5 teams would play 10 games in a round robin tournament. In total there would be 10+5+10=25 games. Daniel has already booked the stadium for n games. Help him to determine how many teams he should invite so that the tournament needs exactly n games. You should print all possible numbers of teams that will yield exactly n games in ascending order, or -1 if there are no such numbers. Input The first line contains a single integer n (1 ≀ n ≀ 1018), the number of games that should be played. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. Output Print all possible numbers of invited teams in ascending order, one per line. If exactly n games cannot be played, output one number: -1. Examples Input 3 Output 3 4 Input 25 Output 20 Input 2 Output -1 Submitted Solution: ``` def sqrt(num): l=0 r=10**20+9 while l<r: m=l+r>>1 if m*m>num:r=m else:l=m+1 l-=1 return l n=int(input()) p=0 cp=1 ans=[] while p<=n: sq=8*n+(1-2*p)**2 q=sqrt(sq) if q*q==sq: xtimes2=q-2*p+1 if xtimes2%2==0: x=xtimes2//2 if x%2 and p*x+x*(x-1)//2==n: ans.append(x*cp) p+=cp cp*=2 print(*sorted(set(ans)if ans else [-1]),sep='\n') ''' n=p*x+x*(x-1)//2 x=(sqrt(8*n + (1-2p)^2 ) - 2p + 1)/2 ''' # Mon Oct 05 2020 17:17:55 GMT+0300 (Москва, стандартноС врСмя) ``` Yes
92,077
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Daniel is organizing a football tournament. He has come up with the following tournament format: 1. In the first several (possibly zero) stages, while the number of teams is even, they split in pairs and play one game for each pair. At each stage the loser of each pair is eliminated (there are no draws). Such stages are held while the number of teams is even. 2. Eventually there will be an odd number of teams remaining. If there is one team remaining, it will be declared the winner, and the tournament ends. Otherwise each of the remaining teams will play with each other remaining team once in round robin tournament (if there are x teams, there will be <image> games), and the tournament ends. For example, if there were 20 teams initially, they would begin by playing 10 games. So, 10 teams would be eliminated, and the remaining 10 would play 5 games. Then the remaining 5 teams would play 10 games in a round robin tournament. In total there would be 10+5+10=25 games. Daniel has already booked the stadium for n games. Help him to determine how many teams he should invite so that the tournament needs exactly n games. You should print all possible numbers of teams that will yield exactly n games in ascending order, or -1 if there are no such numbers. Input The first line contains a single integer n (1 ≀ n ≀ 1018), the number of games that should be played. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. Output Print all possible numbers of invited teams in ascending order, one per line. If exactly n games cannot be played, output one number: -1. Examples Input 3 Output 3 4 Input 25 Output 20 Input 2 Output -1 Submitted Solution: ``` # ========= /\ /| |====/| # | / \ | | / | # | /____\ | | / | # | / \ | | / | # ========= / \ ===== |/====| # code # MOD = 998244353 # def pow(base , exp): # if exp == -1: # return pow(base , MOD - 2) # res = 1 # base %= MOD # while exp > 0: # if exp % 2: # res = (res * base) % MOD # exp //= 2 # base = (base * base) % MOD # res %= MOD # return res def main(): from math import sqrt n = int(input()) ans = [] m = 0 num = 1 gps = 0 while gps <= n: b = num * 2 - 3 c = n a = 1 p = (-b + sqrt(b * b + 8 * c)) / (2 * a) q = int(p) # print(gps , m , num , q) su = (q * (q - 1))//2 + q * (num - 1) if q == p and q % 2 and su == n: ans.append(num * q) m += 1 num *= 2 gps = num - 1 if len(ans): print(*ans , sep = '\n') else: print(-1) return if __name__ == "__main__": main() ``` No
92,078
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Daniel is organizing a football tournament. He has come up with the following tournament format: 1. In the first several (possibly zero) stages, while the number of teams is even, they split in pairs and play one game for each pair. At each stage the loser of each pair is eliminated (there are no draws). Such stages are held while the number of teams is even. 2. Eventually there will be an odd number of teams remaining. If there is one team remaining, it will be declared the winner, and the tournament ends. Otherwise each of the remaining teams will play with each other remaining team once in round robin tournament (if there are x teams, there will be <image> games), and the tournament ends. For example, if there were 20 teams initially, they would begin by playing 10 games. So, 10 teams would be eliminated, and the remaining 10 would play 5 games. Then the remaining 5 teams would play 10 games in a round robin tournament. In total there would be 10+5+10=25 games. Daniel has already booked the stadium for n games. Help him to determine how many teams he should invite so that the tournament needs exactly n games. You should print all possible numbers of teams that will yield exactly n games in ascending order, or -1 if there are no such numbers. Input The first line contains a single integer n (1 ≀ n ≀ 1018), the number of games that should be played. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. Output Print all possible numbers of invited teams in ascending order, one per line. If exactly n games cannot be played, output one number: -1. Examples Input 3 Output 3 4 Input 25 Output 20 Input 2 Output -1 Submitted Solution: ``` x = int(input()) l = [] for n in range(1,x+1,2): if x%n==0: a = (x//n-(n-1)//2+1) a2 = a while a != 1: if a%2==1: break a /= 2 if a == 1: l.append(n*a2) l.sort() for i in l: print(i) ``` No
92,079
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Daniel is organizing a football tournament. He has come up with the following tournament format: 1. In the first several (possibly zero) stages, while the number of teams is even, they split in pairs and play one game for each pair. At each stage the loser of each pair is eliminated (there are no draws). Such stages are held while the number of teams is even. 2. Eventually there will be an odd number of teams remaining. If there is one team remaining, it will be declared the winner, and the tournament ends. Otherwise each of the remaining teams will play with each other remaining team once in round robin tournament (if there are x teams, there will be <image> games), and the tournament ends. For example, if there were 20 teams initially, they would begin by playing 10 games. So, 10 teams would be eliminated, and the remaining 10 would play 5 games. Then the remaining 5 teams would play 10 games in a round robin tournament. In total there would be 10+5+10=25 games. Daniel has already booked the stadium for n games. Help him to determine how many teams he should invite so that the tournament needs exactly n games. You should print all possible numbers of teams that will yield exactly n games in ascending order, or -1 if there are no such numbers. Input The first line contains a single integer n (1 ≀ n ≀ 1018), the number of games that should be played. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. Output Print all possible numbers of invited teams in ascending order, one per line. If exactly n games cannot be played, output one number: -1. Examples Input 3 Output 3 4 Input 25 Output 20 Input 2 Output -1 Submitted Solution: ``` import math def square (a, x): if a <= 0: return 0 return a ** 2 == x def sq (a): b = int(math.sqrt (a)) if square (b - 1, a): return b - 1 if (square (b, a)): return b if (square (b + 1, a)): return b + 1 return 0 n = int(input()) ans = [] if sq (8 * n + 1): t = sq (8 * n + 1); if (t + 1) % 2 == 0: ans.append ((t + 1) // 2) k = 1 while (1 << k) < n: b = (1 << (2 * k + 1)) - 3 * (1 << k) c = (1 << (2 * k + 1)) * n d = b ** 2 + 4 * c if not sq (d): k = k + 1 continue t = sq (d) t -= b if t <= 0 or t % 2 != 0: continue ans.append (t // 2) k = k + 1 if len(ans) == 0: print(-1) else: for x in sorted (ans): print (x) ``` No
92,080
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Daniel is organizing a football tournament. He has come up with the following tournament format: 1. In the first several (possibly zero) stages, while the number of teams is even, they split in pairs and play one game for each pair. At each stage the loser of each pair is eliminated (there are no draws). Such stages are held while the number of teams is even. 2. Eventually there will be an odd number of teams remaining. If there is one team remaining, it will be declared the winner, and the tournament ends. Otherwise each of the remaining teams will play with each other remaining team once in round robin tournament (if there are x teams, there will be <image> games), and the tournament ends. For example, if there were 20 teams initially, they would begin by playing 10 games. So, 10 teams would be eliminated, and the remaining 10 would play 5 games. Then the remaining 5 teams would play 10 games in a round robin tournament. In total there would be 10+5+10=25 games. Daniel has already booked the stadium for n games. Help him to determine how many teams he should invite so that the tournament needs exactly n games. You should print all possible numbers of teams that will yield exactly n games in ascending order, or -1 if there are no such numbers. Input The first line contains a single integer n (1 ≀ n ≀ 1018), the number of games that should be played. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. Output Print all possible numbers of invited teams in ascending order, one per line. If exactly n games cannot be played, output one number: -1. Examples Input 3 Output 3 4 Input 25 Output 20 Input 2 Output -1 Submitted Solution: ``` import math x=int(input()) def tows(n): ans=0 while(n>0): ans+=2**n n-=1 return ans n=50 d=tows(50) k=True answer=[] for n in range(50,-1,-1): d=tows(n) b=(d -1) ans=[] ans.append(-b/2 + math.sqrt(b**2 + 8*x)/2) ans.append(-b/2 - math.sqrt(b**2 + 8*x)/2) for item in ans: if(item <1 or item%2!=1): continue answer.append(item*(2**(n))) k=False if(k): print(-1) answer.sort() for item in answer: print(int(item)) ``` No
92,081
Provide tags and a correct Python 3 solution for this coding contest problem. There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. <image> Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor. Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: 1. Add xi liters of water to the pi-th vessel; 2. Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels. Input The first line contains integer n β€” the number of vessels (1 ≀ n ≀ 2Β·105). The second line contains n integers a1, a2, ..., an β€” the vessels' capacities (1 ≀ ai ≀ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m β€” the number of queries (1 ≀ m ≀ 2Β·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≀ pi ≀ n, 1 ≀ xi ≀ 109, 1 ≀ ki ≀ n). Output For each query, print on a single line the number of liters of water in the corresponding vessel. Examples Input 2 5 10 6 1 1 4 2 1 1 2 5 1 1 4 2 1 2 2 Output 4 5 8 Input 3 5 10 8 6 1 1 12 2 2 1 1 6 1 3 2 2 2 2 3 Output 7 10 5 Tags: data structures, dsu, implementation, trees Correct Solution: ``` def get_next_av(next_av, p): q = p while next_av[q] != q: q = next_av[q] while p != q: next_av[p], p = q, next_av[p] return p def main(): from array import array from sys import stdin input = stdin.readline n = int(input()) a = tuple(map(int, input().split())) next_av = array('i', range(n + 1)) res = array('q', [0] * (n + 1)) for _ in range(int(input())): inp = input() if inp.startswith('1'): _2, p, x = map(int, inp.split()) p -= 1 while p < n and res[p] + x >= a[p]: x = res[p] + x - a[p] res[p] = a[p] next_av[p] = p = get_next_av(next_av, p + 1) res[p] += x else: _3, k = map(int, inp.split()) print(res[k - 1]) main() ```
92,082
Provide tags and a correct Python 3 solution for this coding contest problem. There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. <image> Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor. Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: 1. Add xi liters of water to the pi-th vessel; 2. Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels. Input The first line contains integer n β€” the number of vessels (1 ≀ n ≀ 2Β·105). The second line contains n integers a1, a2, ..., an β€” the vessels' capacities (1 ≀ ai ≀ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m β€” the number of queries (1 ≀ m ≀ 2Β·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≀ pi ≀ n, 1 ≀ xi ≀ 109, 1 ≀ ki ≀ n). Output For each query, print on a single line the number of liters of water in the corresponding vessel. Examples Input 2 5 10 6 1 1 4 2 1 1 2 5 1 1 4 2 1 2 2 Output 4 5 8 Input 3 5 10 8 6 1 1 12 2 2 1 1 6 1 3 2 2 2 2 3 Output 7 10 5 Tags: data structures, dsu, implementation, trees Correct Solution: ``` n = int(input()) m = [int(i) for i in input().split()] k = [0] * n p = int(input()) l = list(range(1,n + 1)) j = [] for i in range(p): t = [int(i) for i in input().split()] if t[0] == 1: h = [] a ,b= t[1] - 1,t[2] while b > 0 and a < n: if b <=m[a] - k[a]: k[a] += b break else: b = b -(m[a] - k[a]) k[a] = m[a] h.append(a) a=l[a] for i in h: l[i] = a else: j.append(k[t[1] - 1]) print(*j,sep='\n') ```
92,083
Provide tags and a correct Python 3 solution for this coding contest problem. There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. <image> Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor. Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: 1. Add xi liters of water to the pi-th vessel; 2. Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels. Input The first line contains integer n β€” the number of vessels (1 ≀ n ≀ 2Β·105). The second line contains n integers a1, a2, ..., an β€” the vessels' capacities (1 ≀ ai ≀ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m β€” the number of queries (1 ≀ m ≀ 2Β·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≀ pi ≀ n, 1 ≀ xi ≀ 109, 1 ≀ ki ≀ n). Output For each query, print on a single line the number of liters of water in the corresponding vessel. Examples Input 2 5 10 6 1 1 4 2 1 1 2 5 1 1 4 2 1 2 2 Output 4 5 8 Input 3 5 10 8 6 1 1 12 2 2 1 1 6 1 3 2 2 2 2 3 Output 7 10 5 Tags: data structures, dsu, implementation, trees Correct Solution: ``` #kylin1993 n=int(input()); water=(n+2)*[0]; vol=[int(i) for i in input().split()]; trace=(n+2)*[0]; next = [i+1 for i in range(n+2)]; m=int(input()); out=[] for i in range(m): c=[int(i) for i in input().split()]; if c[0]==1 : w=c[2]; k=c[1]-1; r=0; while((w>0)and(k<n)): if(w<=vol[k]-water[k]): water[k]=water[k]+w; break; else: w=w-(vol[k]-water[k]); water[k]=vol[k]; trace[r]=k; r=r+1; k=next[k]; for j in range(r): next[trace[j]]=k; if c[0]==2: out.append(water[c[1]-1]); for i in out: print(i) ```
92,084
Provide tags and a correct Python 3 solution for this coding contest problem. There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. <image> Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor. Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: 1. Add xi liters of water to the pi-th vessel; 2. Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels. Input The first line contains integer n β€” the number of vessels (1 ≀ n ≀ 2Β·105). The second line contains n integers a1, a2, ..., an β€” the vessels' capacities (1 ≀ ai ≀ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m β€” the number of queries (1 ≀ m ≀ 2Β·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≀ pi ≀ n, 1 ≀ xi ≀ 109, 1 ≀ ki ≀ n). Output For each query, print on a single line the number of liters of water in the corresponding vessel. Examples Input 2 5 10 6 1 1 4 2 1 1 2 5 1 1 4 2 1 2 2 Output 4 5 8 Input 3 5 10 8 6 1 1 12 2 2 1 1 6 1 3 2 2 2 2 3 Output 7 10 5 Tags: data structures, dsu, implementation, trees Correct Solution: ``` n=int(input()); water=(n+2)*[0]; vol=[int(i) for i in input().split()]; trace=(n+2)*[0]; next = [i+1 for i in range(n+2)]; m=int(input()); out=[] for i in range(m): c=[int(i) for i in input().split()]; if c[0]==1 : w=c[2]; k=c[1]-1; r=0; while((w>0)and(k<n)): if(w<=vol[k]-water[k]): water[k]=water[k]+w; break; else: w=w-(vol[k]-water[k]); water[k]=vol[k]; trace[r]=k; r=r+1; k=next[k]; for j in range(r): next[trace[j]]=k; if c[0]==2: out.append(water[c[1]-1]); for i in out: print(i) ```
92,085
Provide tags and a correct Python 3 solution for this coding contest problem. There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. <image> Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor. Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: 1. Add xi liters of water to the pi-th vessel; 2. Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels. Input The first line contains integer n β€” the number of vessels (1 ≀ n ≀ 2Β·105). The second line contains n integers a1, a2, ..., an β€” the vessels' capacities (1 ≀ ai ≀ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m β€” the number of queries (1 ≀ m ≀ 2Β·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≀ pi ≀ n, 1 ≀ xi ≀ 109, 1 ≀ ki ≀ n). Output For each query, print on a single line the number of liters of water in the corresponding vessel. Examples Input 2 5 10 6 1 1 4 2 1 1 2 5 1 1 4 2 1 2 2 Output 4 5 8 Input 3 5 10 8 6 1 1 12 2 2 1 1 6 1 3 2 2 2 2 3 Output 7 10 5 Tags: data structures, dsu, implementation, trees Correct Solution: ``` n = int(input()) + 1 a = list(map(int, input().split())) + [1 << 50] l, p, r = [0] * n, list(range(n)), [] for i in range(int(input())): t = list(map(int, input().split())) if t[0] == 2: r.append(l[t[1] - 1]) else: x = t[1] - 1 s, d = [x], t[2] while True: if p[x] != x: x = p[x] s.append(x) continue if l[x] + d < a[x]: l[x] += d break d -= a[x] - l[x] l[x] = a[x] x += 1 s.append(x) for j in s: p[j] = x print('\n'.join(map(str, r))) ```
92,086
Provide tags and a correct Python 3 solution for this coding contest problem. There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. <image> Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor. Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: 1. Add xi liters of water to the pi-th vessel; 2. Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels. Input The first line contains integer n β€” the number of vessels (1 ≀ n ≀ 2Β·105). The second line contains n integers a1, a2, ..., an β€” the vessels' capacities (1 ≀ ai ≀ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m β€” the number of queries (1 ≀ m ≀ 2Β·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≀ pi ≀ n, 1 ≀ xi ≀ 109, 1 ≀ ki ≀ n). Output For each query, print on a single line the number of liters of water in the corresponding vessel. Examples Input 2 5 10 6 1 1 4 2 1 1 2 5 1 1 4 2 1 2 2 Output 4 5 8 Input 3 5 10 8 6 1 1 12 2 2 1 1 6 1 3 2 2 2 2 3 Output 7 10 5 Tags: data structures, dsu, implementation, trees Correct Solution: ``` n = int(input()) a = list(map(int, input().split())) m = int(input()) v = [0] * n f = list(range(1, n + 1)) l = [] for i in range(m): q = list(map(int, input().split())) if q[0] == 1: p, x = q[1], q[2] u = [] j = p - 1 while j < n: z = x + v[j] - a[j] if z <= 0: v[j] += x break else: x = z v[j] = a[j] u.append(j) j = f[j] for z in u: f[z] = j else: l.append(v[q[1] - 1]) for i in l: print(i) ```
92,087
Provide tags and a correct Python 3 solution for this coding contest problem. There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. <image> Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor. Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: 1. Add xi liters of water to the pi-th vessel; 2. Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels. Input The first line contains integer n β€” the number of vessels (1 ≀ n ≀ 2Β·105). The second line contains n integers a1, a2, ..., an β€” the vessels' capacities (1 ≀ ai ≀ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m β€” the number of queries (1 ≀ m ≀ 2Β·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≀ pi ≀ n, 1 ≀ xi ≀ 109, 1 ≀ ki ≀ n). Output For each query, print on a single line the number of liters of water in the corresponding vessel. Examples Input 2 5 10 6 1 1 4 2 1 1 2 5 1 1 4 2 1 2 2 Output 4 5 8 Input 3 5 10 8 6 1 1 12 2 2 1 1 6 1 3 2 2 2 2 3 Output 7 10 5 Tags: data structures, dsu, implementation, trees Correct Solution: ``` from sys import stdin, stdout n = int(stdin.readline()) + 1 a = list(map(int, stdin.readline().split())) + [1 << 50] l, p, r = [0] * n, list(range(n)), [] for i in range(int(stdin.readline())): t = list(map(int, stdin.readline().split())) if t[0] == 2: r.append(l[t[1] - 1]) else: x = t[1] - 1 s, d = [x], t[2] while True: if p[x] != x: x = p[x] s.append(x) continue if l[x] + d < a[x]: l[x] += d break d -= a[x] - l[x] l[x] = a[x] x += 1 s.append(x) for j in s: p[j] = x stdout.write('\n'.join(map(str, r))) ```
92,088
Provide tags and a correct Python 3 solution for this coding contest problem. There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. <image> Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor. Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: 1. Add xi liters of water to the pi-th vessel; 2. Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels. Input The first line contains integer n β€” the number of vessels (1 ≀ n ≀ 2Β·105). The second line contains n integers a1, a2, ..., an β€” the vessels' capacities (1 ≀ ai ≀ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m β€” the number of queries (1 ≀ m ≀ 2Β·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≀ pi ≀ n, 1 ≀ xi ≀ 109, 1 ≀ ki ≀ n). Output For each query, print on a single line the number of liters of water in the corresponding vessel. Examples Input 2 5 10 6 1 1 4 2 1 1 2 5 1 1 4 2 1 2 2 Output 4 5 8 Input 3 5 10 8 6 1 1 12 2 2 1 1 6 1 3 2 2 2 2 3 Output 7 10 5 Tags: data structures, dsu, implementation, trees Correct Solution: ``` n=int(input()) a=[int(i) for i in input().split()] v=[0]*n m=int(input()) f=[i+1 for i in range(n)] ans=[] for i in range(m): q=[int(i) for i in input().split()] if q[0]==1: p,x=q[1],q[2] xyz=[] j=p-1 while j<n: tmp=x+v[j]-a[j] if tmp<=0: v[j] = x+v[j] break else: x=tmp v[j]=a[j] xyz.append(j) j=f[j] for z in xyz: f[z]=j else: ans.append(v[q[1]-1]) for i in ans: print(i) ```
92,089
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. <image> Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor. Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: 1. Add xi liters of water to the pi-th vessel; 2. Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels. Input The first line contains integer n β€” the number of vessels (1 ≀ n ≀ 2Β·105). The second line contains n integers a1, a2, ..., an β€” the vessels' capacities (1 ≀ ai ≀ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m β€” the number of queries (1 ≀ m ≀ 2Β·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≀ pi ≀ n, 1 ≀ xi ≀ 109, 1 ≀ ki ≀ n). Output For each query, print on a single line the number of liters of water in the corresponding vessel. Examples Input 2 5 10 6 1 1 4 2 1 1 2 5 1 1 4 2 1 2 2 Output 4 5 8 Input 3 5 10 8 6 1 1 12 2 2 1 1 6 1 3 2 2 2 2 3 Output 7 10 5 Submitted Solution: ``` def command(cmd) : t=cmd[0] if t==1 : pour(cmd[1],cmd[2]) else : amount(cmd[1]) def pour(p,amount) : Skip=[] while p<=n and amount>0: t=C[p-1]-W[p-1] if amount>=t : amount-=t W[p-1]=C[p-1] Skip.append(p) else : W[p-1]+=amount break p=Links[p] for i in Skip : Links[i]=p #print(W) def amount(p) : P.append(W[p-1]) n=int(input()) C=list(map(int,input().split())) W=[0]*n Links=list(map(int,range(1,n+2))) P=[] m=int(input()) for i in range(m) : command([int(i) for i in input().split()]) for i in P : print(i) ``` Yes
92,090
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. <image> Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor. Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: 1. Add xi liters of water to the pi-th vessel; 2. Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels. Input The first line contains integer n β€” the number of vessels (1 ≀ n ≀ 2Β·105). The second line contains n integers a1, a2, ..., an β€” the vessels' capacities (1 ≀ ai ≀ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m β€” the number of queries (1 ≀ m ≀ 2Β·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≀ pi ≀ n, 1 ≀ xi ≀ 109, 1 ≀ ki ≀ n). Output For each query, print on a single line the number of liters of water in the corresponding vessel. Examples Input 2 5 10 6 1 1 4 2 1 1 2 5 1 1 4 2 1 2 2 Output 4 5 8 Input 3 5 10 8 6 1 1 12 2 2 1 1 6 1 3 2 2 2 2 3 Output 7 10 5 Submitted Solution: ``` n = int(input()) a = [int(i) for i in input().split()] b = [0]*n after = list(map(int,range(1,n+2))) #print(a) def add_water(p,x): i = p-1 skip = [] while x>0 and i<n: space = a[i]-b[i] if x >= space: x -= space b[i] = a[i] skip.append(i) i = after[i] else: b[i] += x break for j in skip: after[j] = i m = int(input()) P =[] for i in range(m): l = [int(j) for j in input().split()] #print(l) if l[0] == 1: add_water(l[1],l[2]) else: P.append(b[l[1]-1]) for j in P: print(j) ``` Yes
92,091
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. <image> Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor. Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: 1. Add xi liters of water to the pi-th vessel; 2. Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels. Input The first line contains integer n β€” the number of vessels (1 ≀ n ≀ 2Β·105). The second line contains n integers a1, a2, ..., an β€” the vessels' capacities (1 ≀ ai ≀ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m β€” the number of queries (1 ≀ m ≀ 2Β·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≀ pi ≀ n, 1 ≀ xi ≀ 109, 1 ≀ ki ≀ n). Output For each query, print on a single line the number of liters of water in the corresponding vessel. Examples Input 2 5 10 6 1 1 4 2 1 1 2 5 1 1 4 2 1 2 2 Output 4 5 8 Input 3 5 10 8 6 1 1 12 2 2 1 1 6 1 3 2 2 2 2 3 Output 7 10 5 Submitted Solution: ``` from sys import stdin, stdout def find_next(root, v): q = v while root[q] != q: q = root[q] while v != q: root[v], v = q, root[v] return v input = stdin.readline n = int(input()) a = tuple(map(int, input().split())) indexes = [i for i in range(n + 1)] res = [0] * (n + 1) for _ in range(int(input())): req = input().split() if req[0] == '1': p, x = int(req[1]), int(req[2]) p -= 1 while p < n and res[p] + x >= a[p]: x = res[p] + x - a[p] res[p] = a[p] indexes[p] = p = find_next(indexes, p + 1) res[p] += x else: k = int(req[1]) stdout.write(f'{res[k - 1]}\n') ``` Yes
92,092
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. <image> Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor. Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: 1. Add xi liters of water to the pi-th vessel; 2. Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels. Input The first line contains integer n β€” the number of vessels (1 ≀ n ≀ 2Β·105). The second line contains n integers a1, a2, ..., an β€” the vessels' capacities (1 ≀ ai ≀ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m β€” the number of queries (1 ≀ m ≀ 2Β·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≀ pi ≀ n, 1 ≀ xi ≀ 109, 1 ≀ ki ≀ n). Output For each query, print on a single line the number of liters of water in the corresponding vessel. Examples Input 2 5 10 6 1 1 4 2 1 1 2 5 1 1 4 2 1 2 2 Output 4 5 8 Input 3 5 10 8 6 1 1 12 2 2 1 1 6 1 3 2 2 2 2 3 Output 7 10 5 Submitted Solution: ``` ''' Created on 2016-4-9 @author: chronocorax ''' def line(): return [int(c) for c in input().split()] n = line()[0] cap = line() cap0 = cap[:] nxt = [i + 1 for i in range(n)] result = [] m = line()[0] for _ in range(m): tup = line() if tup[0] == 1: p = tup[1] - 1 p0 = p x = tup[2] # flush(p - 1, x) marker = [] while p < n and cap[p] < x: x -= cap[p] cap[p] = 0 marker.append(p) p = nxt[p] if p < n: cap[p] -= x for i in marker: nxt[i] = p else: k = tup[1] result.append(cap0[k - 1] - cap[k - 1]) for res in result: print(res) ``` Yes
92,093
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. <image> Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor. Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: 1. Add xi liters of water to the pi-th vessel; 2. Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels. Input The first line contains integer n β€” the number of vessels (1 ≀ n ≀ 2Β·105). The second line contains n integers a1, a2, ..., an β€” the vessels' capacities (1 ≀ ai ≀ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m β€” the number of queries (1 ≀ m ≀ 2Β·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≀ pi ≀ n, 1 ≀ xi ≀ 109, 1 ≀ ki ≀ n). Output For each query, print on a single line the number of liters of water in the corresponding vessel. Examples Input 2 5 10 6 1 1 4 2 1 1 2 5 1 1 4 2 1 2 2 Output 4 5 8 Input 3 5 10 8 6 1 1 12 2 2 1 1 6 1 3 2 2 2 2 3 Output 7 10 5 Submitted Solution: ``` n = int(input()) string = input().split() vessels = [] transbordaEm = 300000 positions = {} for i in range(n): vessels.append([0,int(string[i])]) positions[i+1] = i+1 m = int(input()) for q in range(m): query = input().split() # print(vessels) if(query[0] == '2'): position = int(query[1]) - 1 print(vessels[position][0]) elif(query[0] == '1'): position = positions[int(query[1])] - 1 x = int(query[2]) for v in range(position, n): # print('no for!') c = vessels[v][1] t = vessels[v][0] if(x > (c-t)): #entrou aqui, vai encher! x = x - (c-t) vessels[v][0] = c # t = c last = v if(x == 0): break else: vessels[v][0] = t + x # t = x last = v break for i in range(int(query[1])-1, last+1): positions[i] = last+1 # print('na query:', int(query[1])) # print('no positions:', positions[int(query[1])]) # print(positions) ``` No
92,094
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. <image> Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor. Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: 1. Add xi liters of water to the pi-th vessel; 2. Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels. Input The first line contains integer n β€” the number of vessels (1 ≀ n ≀ 2Β·105). The second line contains n integers a1, a2, ..., an β€” the vessels' capacities (1 ≀ ai ≀ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m β€” the number of queries (1 ≀ m ≀ 2Β·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≀ pi ≀ n, 1 ≀ xi ≀ 109, 1 ≀ ki ≀ n). Output For each query, print on a single line the number of liters of water in the corresponding vessel. Examples Input 2 5 10 6 1 1 4 2 1 1 2 5 1 1 4 2 1 2 2 Output 4 5 8 Input 3 5 10 8 6 1 1 12 2 2 1 1 6 1 3 2 2 2 2 3 Output 7 10 5 Submitted Solution: ``` n = int(input()) a = [int(i) for i in input().split()] b = [0]*n m = int(input()) q1 = [] for l in range(m): q = [int(i) for i in input().split()] if q[0] == 1: if len(q1) != 0 and q1[-1][1] == q[1]: q1[-1][2] += q[2] else: q1.append(q) elif q[0] == 2: if len(q1) != 0: q1.sort(key = lambda x:x[1]) v,j = 0,0 for i in range(q1[0][1]-1,n): if j < len(q1) and q1[j][1]-1 == i: v += q1[j][2] j += 1 b[i] += v if b[i] <= a[i]: v = 0 else: v = b[i] - a[i] b[i] = a[i] if j == len(q1) and v == 0: break print(b[q[1]-1]) q1.clear() ``` No
92,095
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. <image> Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor. Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: 1. Add xi liters of water to the pi-th vessel; 2. Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels. Input The first line contains integer n β€” the number of vessels (1 ≀ n ≀ 2Β·105). The second line contains n integers a1, a2, ..., an β€” the vessels' capacities (1 ≀ ai ≀ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m β€” the number of queries (1 ≀ m ≀ 2Β·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≀ pi ≀ n, 1 ≀ xi ≀ 109, 1 ≀ ki ≀ n). Output For each query, print on a single line the number of liters of water in the corresponding vessel. Examples Input 2 5 10 6 1 1 4 2 1 1 2 5 1 1 4 2 1 2 2 Output 4 5 8 Input 3 5 10 8 6 1 1 12 2 2 1 1 6 1 3 2 2 2 2 3 Output 7 10 5 Submitted Solution: ``` n = int(input()) a = [int(i) for i in input().split()] b = [0]*n m = int(input()) q1 = [] for l in range(m): q = [int(i) for i in input().split()] if q[0] == 1: q1.append(q) elif q[0] == 2: if len(q1) != 0: q1.sort(key = lambda x:x[1]) v,j = 0,0 for i in range(q1[0][1]-1,n): if j < len(q1) and q1[j][1]-1 == i: v += q1[j][2] j += 1 b[i] += v if b[i] <= a[i]: v = 0 else: v = b[i] - a[i] b[i] = a[i] if j == len(q1) and v == 0: break print(b[q[1]-1]) q1.clear() ``` No
92,096
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. <image> Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor. Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: 1. Add xi liters of water to the pi-th vessel; 2. Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels. Input The first line contains integer n β€” the number of vessels (1 ≀ n ≀ 2Β·105). The second line contains n integers a1, a2, ..., an β€” the vessels' capacities (1 ≀ ai ≀ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m β€” the number of queries (1 ≀ m ≀ 2Β·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≀ pi ≀ n, 1 ≀ xi ≀ 109, 1 ≀ ki ≀ n). Output For each query, print on a single line the number of liters of water in the corresponding vessel. Examples Input 2 5 10 6 1 1 4 2 1 1 2 5 1 1 4 2 1 2 2 Output 4 5 8 Input 3 5 10 8 6 1 1 12 2 2 1 1 6 1 3 2 2 2 2 3 Output 7 10 5 Submitted Solution: ``` n = int(input()) a = [int(i) for i in input().split()] b = [0]*n prev ={} after = {} for i in range(n): prev[i] = i-1 after[i] = i+1 #print(a) def add_water(p,x): if (a[p-1]-b[p-1])>x: b[p-1] += x else: total = a[p-1]-b[p-1] b[p-1] += total after[prev[p-1]]=after[p-1] prev[after[p-1]]=prev[p-1] i = after[p-1] while x-total>0 and i<n: add = min((a[i]-b[i]),x-total) b[i] += add if x-total>=(a[i]-b[i]): total += add after[prev[i]]=after[i] prev[after[i]]=prev[i] i = after[i] def print_water(k): print(b[k-1]) m = int(input()) for i in range(m): l = [int(j) for j in input().split()] #print(l) if l[0] == 1: add_water(l[1],l[2]) else: print_water(l[1]) ``` No
92,097
Provide a correct Python 3 solution for this coding contest problem. Alice likes word "nineteen" very much. She has a string s and wants the string to contain as many such words as possible. For that reason she can rearrange the letters of the string. For example, if she has string "xiineteenppnnnewtnee", she can get string "xnineteenppnineteenw", containing (the occurrences marked) two such words. More formally, word "nineteen" occurs in the string the number of times you can read it starting from some letter of the string. Of course, you shouldn't skip letters. Help her to find the maximum number of "nineteen"s that she can get in her string. Input The first line contains a non-empty string s, consisting only of lowercase English letters. The length of string s doesn't exceed 100. Output Print a single integer β€” the maximum number of "nineteen"s that she can get in her string. Examples Input nniinneetteeeenn Output 2 Input nneteenabcnneteenabcnneteenabcnneteenabcnneteenabcii Output 2 Input nineteenineteen Output 2 "Correct Solution: ``` s=input('') count=0 n=0;i=0;e=0;t=0; for j in s: if(j=='n'): n+=1 elif(j=='i'): i+=1 elif(j=='e'): e+=1 elif(j=='t'): t+=1 # print(n,i,t,e) if(n>=3 and i>=1 and t>=1 and e>=3): c=True n=n-3; i=i-1 t=t-1 e=e-3 count+=1 while(c!=False): n=n-2; i=i-1 t=t-1 e=e-3 if(n<0 or i<0 or t<0 or e<0): c=False else: # print(n,i,t,e) count+=1 print(count) ```
92,098
Provide a correct Python 3 solution for this coding contest problem. Alice likes word "nineteen" very much. She has a string s and wants the string to contain as many such words as possible. For that reason she can rearrange the letters of the string. For example, if she has string "xiineteenppnnnewtnee", she can get string "xnineteenppnineteenw", containing (the occurrences marked) two such words. More formally, word "nineteen" occurs in the string the number of times you can read it starting from some letter of the string. Of course, you shouldn't skip letters. Help her to find the maximum number of "nineteen"s that she can get in her string. Input The first line contains a non-empty string s, consisting only of lowercase English letters. The length of string s doesn't exceed 100. Output Print a single integer β€” the maximum number of "nineteen"s that she can get in her string. Examples Input nniinneetteeeenn Output 2 Input nneteenabcnneteenabcnneteenabcnneteenabcnneteenabcii Output 2 Input nineteenineteen Output 2 "Correct Solution: ``` #With Me s= input().count print(max(0, min((s("n")-1)//2, s("i"), s("e")//3, s("t")))) ```
92,099