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. You are given an array a of n integers. Find the number of pairs (i, j) (1 ≀ i < j ≀ n) where the sum of a_i + a_j is greater than or equal to l and less than or equal to r (that is, l ≀ a_i + a_j ≀ r). For example, if n = 3, a = [5, 1, 2], l = 4 and r = 7, then two pairs are suitable: * i=1 and j=2 (4 ≀ 5 + 1 ≀ 7); * i=1 and j=3 (4 ≀ 5 + 2 ≀ 7). Input The first line contains an integer t (1 ≀ t ≀ 10^4). Then t test cases follow. The first line of each test case contains three integers n, l, r (1 ≀ n ≀ 2 β‹… 10^5, 1 ≀ l ≀ r ≀ 10^9) β€” the length of the array and the limits on the sum in the pair. The second line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 10^9). It is guaranteed that the sum of n overall test cases does not exceed 2 β‹… 10^5. Output For each test case, output a single integer β€” the number of index pairs (i, j) (i < j), such that l ≀ a_i + a_j ≀ r. Example Input 4 3 4 7 5 1 2 5 5 8 5 1 2 4 3 4 100 1000 1 1 1 1 5 9 13 2 5 5 1 1 Output 2 7 0 1 Submitted Solution: ``` def solve(x, a, b): x.sort() output = [0] * len(x) output2 = [0] * len(x) i, j = 0, len(x)-1 while i - j <= 0: if x[i] + x[j] >= a: output[j] = i j -= 1 else: output[i] = j + 1 i += 1 i, j = 0, len(x) - 1 while i-j <= 0: if x[i] + x[j] <= b: output2[i] = j i += 1 else: output2[j] = i-1 j -=1 answer = [o2 - o + 1 - (o <= i <= o2) for i, (o, o2) in enumerate(zip(output, output2))] return sum(answer)//2 for _ in range(int(input())): n,l,r=map(int,input().split()) a=list(map(int,input().split())) ans=solve(a,l,r) print(ans) ``` Yes
8,600
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a of n integers. Find the number of pairs (i, j) (1 ≀ i < j ≀ n) where the sum of a_i + a_j is greater than or equal to l and less than or equal to r (that is, l ≀ a_i + a_j ≀ r). For example, if n = 3, a = [5, 1, 2], l = 4 and r = 7, then two pairs are suitable: * i=1 and j=2 (4 ≀ 5 + 1 ≀ 7); * i=1 and j=3 (4 ≀ 5 + 2 ≀ 7). Input The first line contains an integer t (1 ≀ t ≀ 10^4). Then t test cases follow. The first line of each test case contains three integers n, l, r (1 ≀ n ≀ 2 β‹… 10^5, 1 ≀ l ≀ r ≀ 10^9) β€” the length of the array and the limits on the sum in the pair. The second line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 10^9). It is guaranteed that the sum of n overall test cases does not exceed 2 β‹… 10^5. Output For each test case, output a single integer β€” the number of index pairs (i, j) (i < j), such that l ≀ a_i + a_j ≀ r. Example Input 4 3 4 7 5 1 2 5 5 8 5 1 2 4 3 4 100 1000 1 1 1 1 5 9 13 2 5 5 1 1 Output 2 7 0 1 Submitted Solution: ``` from collections import defaultdict, Counter from bisect import bisect, bisect_left from math import sqrt, gcd, ceil, factorial from heapq import heapify, heappush, heappop MOD = 10**9 + 7 inf = float("inf") ans_ = [] def nin():return int(input()) def ninf():return int(file.readline()) def st():return (input().strip()) def stf():return (file.readline().strip()) def read(): return list(map(int, input().strip().split())) def readf():return list(map(int, file.readline().strip().split())) # ans_ = "" def f(arr, x): n = len(arr) i, j = 0, n-1 ans = 0 while i < j: if arr[i]+arr[j] < x: i += 1 ans += j-i+1 else: j -= 1 return(ans) # file = open("input.txt", "r") def solve(): for _ in range(nin()): n, l, r = read(); arr = read() arr.sort() ans_.append(f(arr, r+1) - f(arr, l)) # file.close() solve() for i in ans_:print(i) ``` Yes
8,601
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a of n integers. Find the number of pairs (i, j) (1 ≀ i < j ≀ n) where the sum of a_i + a_j is greater than or equal to l and less than or equal to r (that is, l ≀ a_i + a_j ≀ r). For example, if n = 3, a = [5, 1, 2], l = 4 and r = 7, then two pairs are suitable: * i=1 and j=2 (4 ≀ 5 + 1 ≀ 7); * i=1 and j=3 (4 ≀ 5 + 2 ≀ 7). Input The first line contains an integer t (1 ≀ t ≀ 10^4). Then t test cases follow. The first line of each test case contains three integers n, l, r (1 ≀ n ≀ 2 β‹… 10^5, 1 ≀ l ≀ r ≀ 10^9) β€” the length of the array and the limits on the sum in the pair. The second line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 10^9). It is guaranteed that the sum of n overall test cases does not exceed 2 β‹… 10^5. Output For each test case, output a single integer β€” the number of index pairs (i, j) (i < j), such that l ≀ a_i + a_j ≀ r. Example Input 4 3 4 7 5 1 2 5 5 8 5 1 2 4 3 4 100 1000 1 1 1 1 5 9 13 2 5 5 1 1 Output 2 7 0 1 Submitted Solution: ``` from sys import stdin, stdout case = int(stdin.readline()) for c in range(case): n, l, r = map(int, stdin.readline().split()) arr = list(map(int, stdin.readline().split())) arr.sort() if n == 1: print(0) continue if arr[-1] + arr[-2] < l: print(0) continue if arr[0] + arr[1] > r: print(0) continue cnt1 = 0 lp = 0 rp = n-1 while 1: if lp >= rp: break if arr[lp] + arr[rp] > r: rp -= 1 else: if rp == n-1: cnt1 += (rp - lp) lp += 1 elif arr[lp] + arr[rp+1] > r: cnt1 += (rp - lp) lp += 1 else: rp += 1 cnt2 = 0 lp = 0 rp = n-1 while 1: if lp >= rp: break if arr[lp] + arr[rp] >= l: rp -= 1 else: if rp == n-1: cnt2 += (rp - lp) lp += 1 elif arr[lp] + arr[rp+1] >= l: cnt2 += (rp - lp) lp += 1 else: rp += 1 print(cnt1 - cnt2) ``` Yes
8,602
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a of n integers. Find the number of pairs (i, j) (1 ≀ i < j ≀ n) where the sum of a_i + a_j is greater than or equal to l and less than or equal to r (that is, l ≀ a_i + a_j ≀ r). For example, if n = 3, a = [5, 1, 2], l = 4 and r = 7, then two pairs are suitable: * i=1 and j=2 (4 ≀ 5 + 1 ≀ 7); * i=1 and j=3 (4 ≀ 5 + 2 ≀ 7). Input The first line contains an integer t (1 ≀ t ≀ 10^4). Then t test cases follow. The first line of each test case contains three integers n, l, r (1 ≀ n ≀ 2 β‹… 10^5, 1 ≀ l ≀ r ≀ 10^9) β€” the length of the array and the limits on the sum in the pair. The second line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 10^9). It is guaranteed that the sum of n overall test cases does not exceed 2 β‹… 10^5. Output For each test case, output a single integer β€” the number of index pairs (i, j) (i < j), such that l ≀ a_i + a_j ≀ r. Example Input 4 3 4 7 5 1 2 5 5 8 5 1 2 4 3 4 100 1000 1 1 1 1 5 9 13 2 5 5 1 1 Output 2 7 0 1 Submitted Solution: ``` t = int(input()) def do(): n, l, r = map(int, input().split()) nums = sorted(map(int, input().split())) #print(nums) ans = 0 for i in range(n - 1): lmin = 0 start = i + 1 end = n - 1 mid = (start + end)//2 while start < end: if nums[i] + nums[mid] < l : start = mid + 1 else : end = mid mid = (start + end)//2 lmin = mid if nums[lmin] + nums[i] < l: continue rmax = 0 start = i + 1 end = n - 1 mid = (start + end)//2 while start < end: if nums[i] + nums[mid] > r: end = mid - 1 else: start = mid + 1 mid = (start + end)//2 rmax = mid if nums[i] + nums[rmax] > r: continue #print( nums[i], lmin, rmax, "|", l, r, "|" ) ans += rmax - lmin + 1 print(ans) for _ in range(t): do() ``` No
8,603
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a of n integers. Find the number of pairs (i, j) (1 ≀ i < j ≀ n) where the sum of a_i + a_j is greater than or equal to l and less than or equal to r (that is, l ≀ a_i + a_j ≀ r). For example, if n = 3, a = [5, 1, 2], l = 4 and r = 7, then two pairs are suitable: * i=1 and j=2 (4 ≀ 5 + 1 ≀ 7); * i=1 and j=3 (4 ≀ 5 + 2 ≀ 7). Input The first line contains an integer t (1 ≀ t ≀ 10^4). Then t test cases follow. The first line of each test case contains three integers n, l, r (1 ≀ n ≀ 2 β‹… 10^5, 1 ≀ l ≀ r ≀ 10^9) β€” the length of the array and the limits on the sum in the pair. The second line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 10^9). It is guaranteed that the sum of n overall test cases does not exceed 2 β‹… 10^5. Output For each test case, output a single integer β€” the number of index pairs (i, j) (i < j), such that l ≀ a_i + a_j ≀ r. Example Input 4 3 4 7 5 1 2 5 5 8 5 1 2 4 3 4 100 1000 1 1 1 1 5 9 13 2 5 5 1 1 Output 2 7 0 1 Submitted Solution: ``` import array as arr t = int(input()) def solve(): n,l,r = list(map(int,input().split())) n = int(n) l = int(l) r = int(r) a = arr.array('i') a.extend(list(map(int,input().split()))) a = sorted(a) i = len(a)-1 j = 0 pos = -1 flag = True while(i>=j and flag): mid = (i+j)//2 if(a[mid] == r): pos = mid flag = False elif(a[mid] > r): i = mid-1 else : j = mid+1 if(flag): pos = i ctr = 0 while pos>=0 and a[pos] >= l//2: for k in range(pos,-1,-1): if (a[pos]+a[k] >= l and a[pos]+a[k]<=r): ctr = ctr + 1 elif(a[pos]+a[k] < l): break pos = pos - 1 print(ctr) for i in range(t): solve() ``` No
8,604
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a of n integers. Find the number of pairs (i, j) (1 ≀ i < j ≀ n) where the sum of a_i + a_j is greater than or equal to l and less than or equal to r (that is, l ≀ a_i + a_j ≀ r). For example, if n = 3, a = [5, 1, 2], l = 4 and r = 7, then two pairs are suitable: * i=1 and j=2 (4 ≀ 5 + 1 ≀ 7); * i=1 and j=3 (4 ≀ 5 + 2 ≀ 7). Input The first line contains an integer t (1 ≀ t ≀ 10^4). Then t test cases follow. The first line of each test case contains three integers n, l, r (1 ≀ n ≀ 2 β‹… 10^5, 1 ≀ l ≀ r ≀ 10^9) β€” the length of the array and the limits on the sum in the pair. The second line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 10^9). It is guaranteed that the sum of n overall test cases does not exceed 2 β‹… 10^5. Output For each test case, output a single integer β€” the number of index pairs (i, j) (i < j), such that l ≀ a_i + a_j ≀ r. Example Input 4 3 4 7 5 1 2 5 5 8 5 1 2 4 3 4 100 1000 1 1 1 1 5 9 13 2 5 5 1 1 Output 2 7 0 1 Submitted Solution: ``` def inp(): return(int(input())) def inlt(): return(list(map(int,input().split()))) def insr(): s = input() return(s) def invr(): return(map(int,input().split())) x = inp() for _ in range(x): [n,l,r] = inlt() a = inlt() a.sort() ans = 0 lp = 0 rp = n - 1 #print(a) while(lp < rp): #print(lp,rp, a[lp], a[rp]) if(a[lp] + a[rp] < l): lp += 1 elif(a[lp] + a[rp] > r): rp -= 1 else: lower = lp upper = rp flag = 1 while(lower < upper): mid = (lower+upper)//2 #print(lower,upper, mid) if(a[mid + 1] + a[rp] > r and a[mid] + a[rp] <= r): ans += mid - lp flag = 0 break elif(a[mid] + a[rp] > r): upper = mid - 1 else: lower = mid + 1 if(a[lower] + a[upper]< l): flag = 0 if(flag): ans += rp - lp else: ans += 1 rp -= 1 #print(ans) #print("ans" + str(ans)) print(ans) ``` No
8,605
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a of n integers. Find the number of pairs (i, j) (1 ≀ i < j ≀ n) where the sum of a_i + a_j is greater than or equal to l and less than or equal to r (that is, l ≀ a_i + a_j ≀ r). For example, if n = 3, a = [5, 1, 2], l = 4 and r = 7, then two pairs are suitable: * i=1 and j=2 (4 ≀ 5 + 1 ≀ 7); * i=1 and j=3 (4 ≀ 5 + 2 ≀ 7). Input The first line contains an integer t (1 ≀ t ≀ 10^4). Then t test cases follow. The first line of each test case contains three integers n, l, r (1 ≀ n ≀ 2 β‹… 10^5, 1 ≀ l ≀ r ≀ 10^9) β€” the length of the array and the limits on the sum in the pair. The second line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 10^9). It is guaranteed that the sum of n overall test cases does not exceed 2 β‹… 10^5. Output For each test case, output a single integer β€” the number of index pairs (i, j) (i < j), such that l ≀ a_i + a_j ≀ r. Example Input 4 3 4 7 5 1 2 5 5 8 5 1 2 4 3 4 100 1000 1 1 1 1 5 9 13 2 5 5 1 1 Output 2 7 0 1 Submitted Solution: ``` import sys t = int(sys.stdin.readline()) while t: t -= 1 n, l, r = map(int, sys.stdin.readline().split()) arr = list(map(int, sys.stdin.readline().split())) arr.sort() ans, A, B = 0, 0, 0 cnt = 0 for i in range(n): lo, hi = i + 1, n - 1 while lo <= hi: mid = lo + (hi - lo) // 2 if arr[mid] + arr[i] <= r: ans = mid lo = mid + 1 else: hi = mid - 1 if ans != 0: A += (ans - i) ans = 0 lo, hi = i + 1, n - 1 while lo <= hi: mid = lo + (hi - lo) // 2 if arr[mid] + arr[i] <= l - 1: ans = mid lo = mid + 1 else: hi = mid - 1 if ans != 0: B += (ans - i) cnt += (A - B) A, B = 0, 0 print(cnt) ``` No
8,606
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One remarkable day company "X" received k machines. And they were not simple machines, they were mechanical programmers! This was the last unsuccessful step before switching to android programmers, but that's another story. The company has now n tasks, for each of them we know the start time of its execution si, the duration of its execution ti, and the company profit from its completion ci. Any machine can perform any task, exactly one at a time. If a machine has started to perform the task, it is busy at all moments of time from si to si + ti - 1, inclusive, and it cannot switch to another task. You are required to select a set of tasks which can be done with these k machines, and which will bring the maximum total profit. Input The first line contains two integer numbers n and k (1 ≀ n ≀ 1000, 1 ≀ k ≀ 50) β€” the numbers of tasks and machines, correspondingly. The next n lines contain space-separated groups of three integers si, ti, ci (1 ≀ si, ti ≀ 109, 1 ≀ ci ≀ 106), si is the time where they start executing the i-th task, ti is the duration of the i-th task and ci is the profit of its execution. Output Print n integers x1, x2, ..., xn. Number xi should equal 1, if task i should be completed and otherwise it should equal 0. If there are several optimal solutions, print any of them. Examples Input 3 1 2 7 5 1 3 3 4 1 3 Output 0 1 1 Input 5 2 1 5 4 1 4 5 1 3 2 4 1 2 5 6 1 Output 1 1 0 0 1 Note In the first sample the tasks need to be executed at moments of time 2 ... 8, 1 ... 3 and 4 ... 4, correspondingly. The first task overlaps with the second and the third ones, so we can execute either task one (profit 5) or tasks two and three (profit 6). Submitted Solution: ``` from math import sqrt n,m = map(int,input().split()) def dist(x1,y1,x2,y2): d = (x1-x2)**2 + (y2-y1)**2 if sqrt(d)!=int(sqrt(d)): return True else: return False z = min(n,m) print(z+1) ans = [] ba = [] if n !=m : for i in range(z+1): if i!=0: ans.append([i,i]) else: ans.append([z,0]) for i in range(n+1): for j in range(m+1): if i!=0 or j!=0: ba.append([i,j]) if m!=n: for i in ba: x,y = i flag = 0 for j in ans: a,b = j z = dist(x,y,a,b) if z == False: flag = 1 break if flag == 0 : ans.append(i) break else: for i in ba: x,y = i flag = 0 for j in ans: a,b = j z = dist(x,y,a,b) if z == False: flag = 1 break if flag == 0 : ans.append(i) for i in ans: print(i[0],i[1]) ``` No
8,607
Provide tags and a correct Python 3 solution for this coding contest problem. A connected undirected graph is called a vertex cactus, if each vertex of this graph belongs to at most one simple cycle. A simple cycle in a undirected graph is a sequence of distinct vertices v1, v2, ..., vt (t > 2), such that for any i (1 ≀ i < t) exists an edge between vertices vi and vi + 1, and also exists an edge between vertices v1 and vt. A simple path in a undirected graph is a sequence of not necessarily distinct vertices v1, v2, ..., vt (t > 0), such that for any i (1 ≀ i < t) exists an edge between vertices vi and vi + 1 and furthermore each edge occurs no more than once. We'll say that a simple path v1, v2, ..., vt starts at vertex v1 and ends at vertex vt. You've got a graph consisting of n vertices and m edges, that is a vertex cactus. Also, you've got a list of k pairs of interesting vertices xi, yi, for which you want to know the following information β€” the number of distinct simple paths that start at vertex xi and end at vertex yi. We will consider two simple paths distinct if the sets of edges of the paths are distinct. For each pair of interesting vertices count the number of distinct simple paths between them. As this number can be rather large, you should calculate it modulo 1000000007 (109 + 7). Input The first line contains two space-separated integers n, m (2 ≀ n ≀ 105; 1 ≀ m ≀ 105) β€” the number of vertices and edges in the graph, correspondingly. Next m lines contain the description of the edges: the i-th line contains two space-separated integers ai, bi (1 ≀ ai, bi ≀ n) β€” the indexes of the vertices connected by the i-th edge. The next line contains a single integer k (1 ≀ k ≀ 105) β€” the number of pairs of interesting vertices. Next k lines contain the list of pairs of interesting vertices: the i-th line contains two space-separated numbers xi, yi (1 ≀ xi, yi ≀ n; xi β‰  yi) β€” the indexes of interesting vertices in the i-th pair. It is guaranteed that the given graph is a vertex cactus. It is guaranteed that the graph contains no loops or multiple edges. Consider the graph vertices are numbered from 1 to n. Output Print k lines: in the i-th line print a single integer β€” the number of distinct simple ways, starting at xi and ending at yi, modulo 1000000007 (109 + 7). Examples Input 10 11 1 2 2 3 3 4 1 4 3 5 5 6 8 6 8 7 7 6 7 9 9 10 6 1 2 3 5 6 9 9 2 9 3 9 10 Output 2 2 2 4 4 1 Tags: data structures, dfs and similar, dp, graphs, trees Correct Solution: ``` from collections import defaultdict import os import sys from io import BytesIO, IOBase from types import GeneratorType from collections import defaultdict 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") sys.setrecursionlimit(3*10**4) def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc @bootstrap def dfs1(cur,prev,v): depth[cur] = depth[prev] + 1 parent[cur][0] = prev blacks[cur]=v if val[cur]: blacks[cur]+=1 for i in tree[cur]: if (i != prev): yield dfs1(i, cur,blacks[cur]) yield def precomputeSparseMatrix(n): for i in range(1,level): for node in range(1,n+1): if (parent[node][i-1] != -1): parent[node][i] =parent[parent[node][i-1]][i-1] def lca(u,v): if (depth[v] < depth[u]): u,v=v,u diff = depth[v] - depth[u] for i in range(level): if ((diff >> i) & 1): v = parent[v][i] if (u == v): return u i=level-1 while(i>=0): if (parent[u][i] != parent[v][i]): u = parent[u][i] v = parent[v][i] i+=-1 return parent[u][0] @bootstrap def dfs(u,p): global curr for j in adj[u]: if j!=p: if id[j]==0: id[j]=id[u]+1 yield dfs(j,u) elif id[u]>id[j]: up[u]=curr down[j]=curr curr+=1 yield @bootstrap def dfs2(u,p): vis[u]=1 for j in adj[u]: if not vis[j]: yield dfs2(j,u) if up[u]: id[u]=up[u] else: id[u]=u for j in adj[u]: if j!=p: if id[j]!=j and down[j]==0: id[u]=id[j] yield n,m=map(int,input().split()) adj=[[] for i in range(n+1)] edges=[] for j in range(m): u,v=map(int,input().split()) edges.append([u,v]) adj[u].append(v) adj[v].append(u) up=defaultdict(lambda:0) down=defaultdict(lambda:0) curr=n+1 id=[] vis=[] val=[] tree=[] depth=[] for j in range(n+1): id.append(0) vis.append(0) val.append(0) tree.append([]) depth.append(0) id[1]=1 dfs(1,0) dfs2(1,0) res=sorted(list(set(id[1:]))) up=defaultdict(lambda:0) l=len(res) for j in range(l): up[res[j]]=j+1 d=defaultdict(lambda:0) for j in range(1,n+1): id[j]=up[id[j]] d[id[j]]+=1 if d[id[j]]>1: val[id[j]]=1 level=17 parent=[[0 for i in range(level)] for j in range(l+1)] blacks=[0]*(l+1) d=defaultdict(lambda:0) for j in edges: u,v=j[0],j[1] p,q=id[u],id[v] if not d[p,q] and p!=q: tree[p].append(q) tree[q].append(p) d[p,q]=1 d[q,p]=1 dfs1(1,0,0) precomputeSparseMatrix(l) k=int(input()) mod=10**9+7 value=[1] for j in range(1,l+1): value.append((2*value[-1])%(mod)) for j in range(k): a,b=map(int,input().split()) u1,v1=id[a],id[b] lc=lca(u1,v1) res=value[blacks[u1]+blacks[v1]-2*blacks[lc]] if val[lc]: res*=2 print(res%mod) ```
8,608
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai ≀ ai + 1 ≀ 2Β·ai for any positive integer i (i < n). Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs "+" and "-" before each number so that the value of expression s meets the limits 0 ≀ s ≀ a1. Print a sequence of signs "+" and "-", satisfying the given limits. It is guaranteed that the solution for the problem exists. Input The first line contains integer n (1 ≀ n ≀ 105) β€” the size of the array. The second line contains space-separated integers a1, a2, ..., an (0 ≀ ai ≀ 109) β€” the original array. It is guaranteed that the condition ai ≀ ai + 1 ≀ 2Β·ai fulfills for any positive integer i (i < n). Output In a single line print the sequence of n characters "+" and "-", where the i-th character is the sign that is placed in front of number ai. The value of the resulting expression s must fit into the limits 0 ≀ s ≀ a1. If there are multiple solutions, you are allowed to print any of them. Examples Input 4 1 2 3 5 Output +++- Input 3 3 3 5 Output ++- Tags: greedy, math Correct Solution: ``` n=int(input()) a=list(map(int,input().split(' '))) temp_sgn=1 sgns=[] curr_sum=0 for i in range(n): if(curr_sum>=a[n-i-1]): sgns.append(1) sgns.append(-1) curr_sum-=a[n-i-1] else: sgns.append(-1) sgns.append(1) curr_sum-=a[n-i-1] curr_sum*=-1 sgns.reverse() ans=[] for i in range(2*n): if(i%2==0): ans.append(temp_sgn*sgns[i]) else: temp_sgn*=sgns[i] for x in ans: if(x==1): print('+',end='') else: print('-',end='') ```
8,609
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai ≀ ai + 1 ≀ 2Β·ai for any positive integer i (i < n). Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs "+" and "-" before each number so that the value of expression s meets the limits 0 ≀ s ≀ a1. Print a sequence of signs "+" and "-", satisfying the given limits. It is guaranteed that the solution for the problem exists. Input The first line contains integer n (1 ≀ n ≀ 105) β€” the size of the array. The second line contains space-separated integers a1, a2, ..., an (0 ≀ ai ≀ 109) β€” the original array. It is guaranteed that the condition ai ≀ ai + 1 ≀ 2Β·ai fulfills for any positive integer i (i < n). Output In a single line print the sequence of n characters "+" and "-", where the i-th character is the sign that is placed in front of number ai. The value of the resulting expression s must fit into the limits 0 ≀ s ≀ a1. If there are multiple solutions, you are allowed to print any of them. Examples Input 4 1 2 3 5 Output +++- Input 3 3 3 5 Output ++- Tags: greedy, math Correct Solution: ``` n=int(input()) b=list(map(int,input().split())) s=0 res=[] j=n-1 while(j>=0): if s<=0: s+=b[j] res.append(1) else: s-=b[j] res.append(0) j+=-1 res.reverse() if s>=0: for j in res: if j: print("+",end="") else: print("-",end="") else: for j in res: if j: print("-",end="") else: print("+",end="") ```
8,610
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai ≀ ai + 1 ≀ 2Β·ai for any positive integer i (i < n). Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs "+" and "-" before each number so that the value of expression s meets the limits 0 ≀ s ≀ a1. Print a sequence of signs "+" and "-", satisfying the given limits. It is guaranteed that the solution for the problem exists. Input The first line contains integer n (1 ≀ n ≀ 105) β€” the size of the array. The second line contains space-separated integers a1, a2, ..., an (0 ≀ ai ≀ 109) β€” the original array. It is guaranteed that the condition ai ≀ ai + 1 ≀ 2Β·ai fulfills for any positive integer i (i < n). Output In a single line print the sequence of n characters "+" and "-", where the i-th character is the sign that is placed in front of number ai. The value of the resulting expression s must fit into the limits 0 ≀ s ≀ a1. If there are multiple solutions, you are allowed to print any of them. Examples Input 4 1 2 3 5 Output +++- Input 3 3 3 5 Output ++- Tags: greedy, math Correct Solution: ``` #!/usr/bin/python3 n = int(input()) a = list(map(int, input().split())) s = a[-1] ans = ['+'] for v in reversed(a[:-1]): if s > 0: s -= v ans.append('-') else: s += v ans.append('+') if 0 <= s <= a[-1]: print(''.join(reversed(ans))) else: s = -a[-1] ans = ['-'] for v in reversed(a[:-1]): if s > 0: s -= v ans.append('-') else: s += v ans.append('+') if 0 <= s <= a[-1]: print(''.join(reversed(ans))) else: s = a[-1] ans = ['+'] for v in reversed(a[:-1]): if s >= 0: s -= v ans.append('-') else: s += v ans.append('+') if 0 <= s <= a[-1]: print(''.join(reversed(ans))) else: s = -a[-1] ans = ['-'] for v in reversed(a[:-1]): if s >= 0: s -= v ans.append('-') else: s += v ans.append('+') print(''.join(reversed(ans))) ```
8,611
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai ≀ ai + 1 ≀ 2Β·ai for any positive integer i (i < n). Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs "+" and "-" before each number so that the value of expression s meets the limits 0 ≀ s ≀ a1. Print a sequence of signs "+" and "-", satisfying the given limits. It is guaranteed that the solution for the problem exists. Input The first line contains integer n (1 ≀ n ≀ 105) β€” the size of the array. The second line contains space-separated integers a1, a2, ..., an (0 ≀ ai ≀ 109) β€” the original array. It is guaranteed that the condition ai ≀ ai + 1 ≀ 2Β·ai fulfills for any positive integer i (i < n). Output In a single line print the sequence of n characters "+" and "-", where the i-th character is the sign that is placed in front of number ai. The value of the resulting expression s must fit into the limits 0 ≀ s ≀ a1. If there are multiple solutions, you are allowed to print any of them. Examples Input 4 1 2 3 5 Output +++- Input 3 3 3 5 Output ++- Tags: greedy, math Correct Solution: ``` n = int(input()) arr = list(map(int, input().split())) if n == 1: print('+') elif n == 2: print('-+') else: ans = ['+'] cur = arr[-1] for i in range(n - 2, -1, -1): if cur > 0: cur -= arr[i] ans.append('-') else: cur += arr[i] ans.append('+') ans.reverse() if cur < 0: for i in range(n): if ans[i] == '-': ans[i] = '+' else: ans[i] = '-' print(''.join(ans)) ```
8,612
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai ≀ ai + 1 ≀ 2Β·ai for any positive integer i (i < n). Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs "+" and "-" before each number so that the value of expression s meets the limits 0 ≀ s ≀ a1. Print a sequence of signs "+" and "-", satisfying the given limits. It is guaranteed that the solution for the problem exists. Input The first line contains integer n (1 ≀ n ≀ 105) β€” the size of the array. The second line contains space-separated integers a1, a2, ..., an (0 ≀ ai ≀ 109) β€” the original array. It is guaranteed that the condition ai ≀ ai + 1 ≀ 2Β·ai fulfills for any positive integer i (i < n). Output In a single line print the sequence of n characters "+" and "-", where the i-th character is the sign that is placed in front of number ai. The value of the resulting expression s must fit into the limits 0 ≀ s ≀ a1. If there are multiple solutions, you are allowed to print any of them. Examples Input 4 1 2 3 5 Output +++- Input 3 3 3 5 Output ++- Tags: greedy, math Correct Solution: ``` # ---------------------------iye ha aam zindegi--------------------------------------------- import math import random import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys import threading from collections import defaultdict threading.stack_size(10**8) mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase sys.setrecursionlimit(300000) BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # -------------------game starts now----------------------------------------------------import math class TreeNode: def __init__(self, k, v): self.key = k self.value = v self.left = None self.right = None self.parent = None self.height = 1 self.num_left = 1 self.num_total = 1 class AvlTree: def __init__(self): self._tree = None def add(self, k, v): if not self._tree: self._tree = TreeNode(k, v) return node = self._add(k, v) if node: self._rebalance(node) def _add(self, k, v): node = self._tree while node: if k < node.key: if node.left: node = node.left else: node.left = TreeNode(k, v) node.left.parent = node return node.left elif node.key < k: if node.right: node = node.right else: node.right = TreeNode(k, v) node.right.parent = node return node.right else: node.value = v return @staticmethod def get_height(x): return x.height if x else 0 @staticmethod def get_num_total(x): return x.num_total if x else 0 def _rebalance(self, node): n = node while n: lh = self.get_height(n.left) rh = self.get_height(n.right) n.height = max(lh, rh) + 1 balance_factor = lh - rh n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right) n.num_left = 1 + self.get_num_total(n.left) if balance_factor > 1: if self.get_height(n.left.left) < self.get_height(n.left.right): self._rotate_left(n.left) self._rotate_right(n) elif balance_factor < -1: if self.get_height(n.right.right) < self.get_height(n.right.left): self._rotate_right(n.right) self._rotate_left(n) else: n = n.parent def _remove_one(self, node): """ Side effect!!! Changes node. Node should have exactly one child """ replacement = node.left or node.right if node.parent: if AvlTree._is_left(node): node.parent.left = replacement else: node.parent.right = replacement replacement.parent = node.parent node.parent = None else: self._tree = replacement replacement.parent = None node.left = None node.right = None node.parent = None self._rebalance(replacement) def _remove_leaf(self, node): if node.parent: if AvlTree._is_left(node): node.parent.left = None else: node.parent.right = None self._rebalance(node.parent) else: self._tree = None node.parent = None node.left = None node.right = None def remove(self, k): node = self._get_node(k) if not node: return if AvlTree._is_leaf(node): self._remove_leaf(node) return if node.left and node.right: nxt = AvlTree._get_next(node) node.key = nxt.key node.value = nxt.value if self._is_leaf(nxt): self._remove_leaf(nxt) else: self._remove_one(nxt) self._rebalance(node) else: self._remove_one(node) def get(self, k): node = self._get_node(k) return node.value if node else -1 def _get_node(self, k): if not self._tree: return None node = self._tree while node: if k < node.key: node = node.left elif node.key < k: node = node.right else: return node return None def get_at(self, pos): x = pos + 1 node = self._tree while node: if x < node.num_left: node = node.left elif node.num_left < x: x -= node.num_left node = node.right else: return (node.key, node.value) raise IndexError("Out of ranges") @staticmethod def _is_left(node): return node.parent.left and node.parent.left == node @staticmethod def _is_leaf(node): return node.left is None and node.right is None def _rotate_right(self, node): if not node.parent: self._tree = node.left node.left.parent = None elif AvlTree._is_left(node): node.parent.left = node.left node.left.parent = node.parent else: node.parent.right = node.left node.left.parent = node.parent bk = node.left.right node.left.right = node node.parent = node.left node.left = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) def _rotate_left(self, node): if not node.parent: self._tree = node.right node.right.parent = None elif AvlTree._is_left(node): node.parent.left = node.right node.right.parent = node.parent else: node.parent.right = node.right node.right.parent = node.parent bk = node.right.left node.right.left = node node.parent = node.right node.right = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) @staticmethod def _get_next(node): if not node.right: return node.parent n = node.right while n.left: n = n.left return n # -----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default=2**51, func=lambda a, b: a & b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------game starts now----------------------------------------------------import math class SegmentTree: def __init__(self, data, default=0, func=lambda a, b: a + b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------------------iye ha chutiya zindegi------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD # --------------------------------------iye ha combinations ka zindegi--------------------------------- def powm(a, n, m): if a == 1 or n == 0: return 1 if n % 2 == 0: s = powm(a, n // 2, m) return s * s % m else: return a * powm(a, n - 1, m) % m # --------------------------------------iye ha power ka zindegi--------------------------------- def sort_list(list1, list2): zipped_pairs = zip(list2, list1) z = [x for _, x in sorted(zipped_pairs)] return z # --------------------------------------------------product---------------------------------------- def product(l): por = 1 for i in range(len(l)): por *= l[i] return por # --------------------------------------------------binary---------------------------------------- def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left) / 2) # Check if middle element is # less than or equal to key if (arr[mid] <=key): count = mid + 1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # --------------------------------------------------binary---------------------------------------- def countdig(n): c = 0 while (n > 0): n //= 10 c += 1 return c def binary(x, length): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y def countGreater(arr, n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) if (arr[m] >= k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) # --------------------------------------------------binary------------------------------------ n=int(input()) l=list(map(int,input().split())) s=sum(l) ans=['+']*n for i in range(n-1,-1,-1): if abs(s)<=l[0]: break if s-2*l[i]>=-l[0]: s-=2*l[i] ans[i]='-' s=0 for i in range(n): if ans[i]=='+': s+=l[i] else: s-=l[i] if s>0: print(*ans,sep="") else: for i in range(n): if ans[i]=='+': ans[i]='-' else: ans[i]='+' print(*ans,sep="") ```
8,613
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai ≀ ai + 1 ≀ 2Β·ai for any positive integer i (i < n). Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs "+" and "-" before each number so that the value of expression s meets the limits 0 ≀ s ≀ a1. Print a sequence of signs "+" and "-", satisfying the given limits. It is guaranteed that the solution for the problem exists. Input The first line contains integer n (1 ≀ n ≀ 105) β€” the size of the array. The second line contains space-separated integers a1, a2, ..., an (0 ≀ ai ≀ 109) β€” the original array. It is guaranteed that the condition ai ≀ ai + 1 ≀ 2Β·ai fulfills for any positive integer i (i < n). Output In a single line print the sequence of n characters "+" and "-", where the i-th character is the sign that is placed in front of number ai. The value of the resulting expression s must fit into the limits 0 ≀ s ≀ a1. If there are multiple solutions, you are allowed to print any of them. Examples Input 4 1 2 3 5 Output +++- Input 3 3 3 5 Output ++- Tags: greedy, math Correct Solution: ``` n = int(input()) a = list(map(int, input().split())) r = [0] * n s = 0 for i in range(n - 1, -1, -1): if abs(s + a[i]) <= a[i]: s += a[i] else: s -= a[i] r[i] = 1 if s<0: print(''.join(['-', '+'][i] for i in r)) else: print(''.join(['+', '-'][i] for i in r)) ```
8,614
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai ≀ ai + 1 ≀ 2Β·ai for any positive integer i (i < n). Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs "+" and "-" before each number so that the value of expression s meets the limits 0 ≀ s ≀ a1. Print a sequence of signs "+" and "-", satisfying the given limits. It is guaranteed that the solution for the problem exists. Input The first line contains integer n (1 ≀ n ≀ 105) β€” the size of the array. The second line contains space-separated integers a1, a2, ..., an (0 ≀ ai ≀ 109) β€” the original array. It is guaranteed that the condition ai ≀ ai + 1 ≀ 2Β·ai fulfills for any positive integer i (i < n). Output In a single line print the sequence of n characters "+" and "-", where the i-th character is the sign that is placed in front of number ai. The value of the resulting expression s must fit into the limits 0 ≀ s ≀ a1. If there are multiple solutions, you are allowed to print any of them. Examples Input 4 1 2 3 5 Output +++- Input 3 3 3 5 Output ++- Tags: greedy, math Correct Solution: ``` n = int(input()) t = list(map(int, input().split())) t.reverse() s, p = 0, [0] * n for i, j in enumerate(t): if s > 0: p[i] = 1 s -= j else: s += j p.reverse() if s < 0: print(''.join('-+'[i] for i in p)) else: print(''.join('+-'[i] for i in p)) ```
8,615
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai ≀ ai + 1 ≀ 2Β·ai for any positive integer i (i < n). Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs "+" and "-" before each number so that the value of expression s meets the limits 0 ≀ s ≀ a1. Print a sequence of signs "+" and "-", satisfying the given limits. It is guaranteed that the solution for the problem exists. Input The first line contains integer n (1 ≀ n ≀ 105) β€” the size of the array. The second line contains space-separated integers a1, a2, ..., an (0 ≀ ai ≀ 109) β€” the original array. It is guaranteed that the condition ai ≀ ai + 1 ≀ 2Β·ai fulfills for any positive integer i (i < n). Output In a single line print the sequence of n characters "+" and "-", where the i-th character is the sign that is placed in front of number ai. The value of the resulting expression s must fit into the limits 0 ≀ s ≀ a1. If there are multiple solutions, you are allowed to print any of them. Examples Input 4 1 2 3 5 Output +++- Input 3 3 3 5 Output ++- Tags: greedy, math Correct Solution: ``` def invert(s): t = '' for i in s: if(i =='+'): t += '-' else: t += '+' #print(s,t) return t n = int(input()) if(n==1): print('+') exit() a=list(map(int,input().split())) cur = a[-1] s = '+' for i in range(n-2,0,-1): if(cur > 0): cur -= a[i] s += '-' else: cur += a[i] s += '+' #print(s[::-1]) if(cur >= a[0]): s += '-' elif(abs(cur) <= a[0] and cur <= 0): s += '+' elif( 0 < cur < a[0]): s=invert(s) s += '+' else: s=invert(s) s += '-' print(s[::-1]) ```
8,616
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai ≀ ai + 1 ≀ 2Β·ai for any positive integer i (i < n). Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs "+" and "-" before each number so that the value of expression s meets the limits 0 ≀ s ≀ a1. Print a sequence of signs "+" and "-", satisfying the given limits. It is guaranteed that the solution for the problem exists. Input The first line contains integer n (1 ≀ n ≀ 105) β€” the size of the array. The second line contains space-separated integers a1, a2, ..., an (0 ≀ ai ≀ 109) β€” the original array. It is guaranteed that the condition ai ≀ ai + 1 ≀ 2Β·ai fulfills for any positive integer i (i < n). Output In a single line print the sequence of n characters "+" and "-", where the i-th character is the sign that is placed in front of number ai. The value of the resulting expression s must fit into the limits 0 ≀ s ≀ a1. If there are multiple solutions, you are allowed to print any of them. Examples Input 4 1 2 3 5 Output +++- Input 3 3 3 5 Output ++- Submitted Solution: ``` #Code by Sounak, IIESTS #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase from fractions import Fraction import collections from itertools import permutations from collections import defaultdict from collections import deque import threading #sys.setrecursionlimit(300000) #threading.stack_size(10**8) 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") #------------------------------------------------------------------------- #mod = 9223372036854775807 class SegmentTree: def __init__(self, data, default=-10**6, func=lambda a, b: max(a,b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) class SegmentTree1: def __init__(self, data, default=10**6, func=lambda a, b: min(a,b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) MOD=10**9+7 class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD mod=10**9+7 omod=998244353 #------------------------------------------------------------------------- prime = [True for i in range(50001)] pp=[] def SieveOfEratosthenes(n=50000): # Create a boolean array "prime[0..n]" and initialize # all entries it as true. A value in prime[i] will # finally be false if i is Not a prime, else true. p = 2 while (p * p <= n): # If prime[p] is not changed, then it is a prime if (prime[p] == True): # Update all multiples of p for i in range(p * p, n+1, p): prime[i] = False p += 1 for i in range(50001): if prime[i]: pp.append(i) #---------------------------------running code------------------------------------------ n=int(input()) a=list(map(int,input().split())) if n==1: print('+') sys.exit(0) s=a[-1] d=[0]*n d[-1]=1 for i in range (n-2,-1,-1): if s+a[i]>=-a[0] and s+a[i]<=a[0]: d[i]=1 s+=a[i] elif s-a[i]>=-a[0] and s-a[i]<=a[0]: d[i]=-1 s-=a[i] elif s+a[i]<-a[0]: d[i]=1 s+=a[i] elif s-a[i]>a[0]: d[i]=-1 s-=a[i] elif s>a[i]: d[i]=-1 s-=a[i] elif s<-a[i]: d[i]=1 s+=a[i] else: m1=s+a[i]-a[0] m2=abs(s-a[i])-a[0] m=min(m1,m2) if m==m1: s+=a[i] d[i]=1 else: s-=a[i] d[i]=-1 if s<0: for i in range (n): d[i]=-1*d[i] for i in d: if i>0: print('+',end='') else: print('-',end='') ``` Yes
8,617
Evaluate the correctness of the submitted Python 2 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai ≀ ai + 1 ≀ 2Β·ai for any positive integer i (i < n). Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs "+" and "-" before each number so that the value of expression s meets the limits 0 ≀ s ≀ a1. Print a sequence of signs "+" and "-", satisfying the given limits. It is guaranteed that the solution for the problem exists. Input The first line contains integer n (1 ≀ n ≀ 105) β€” the size of the array. The second line contains space-separated integers a1, a2, ..., an (0 ≀ ai ≀ 109) β€” the original array. It is guaranteed that the condition ai ≀ ai + 1 ≀ 2Β·ai fulfills for any positive integer i (i < n). Output In a single line print the sequence of n characters "+" and "-", where the i-th character is the sign that is placed in front of number ai. The value of the resulting expression s must fit into the limits 0 ≀ s ≀ a1. If there are multiple solutions, you are allowed to print any of them. Examples Input 4 1 2 3 5 Output +++- Input 3 3 3 5 Output ++- Submitted Solution: ``` from sys import stdin, stdout from collections import Counter, defaultdict from itertools import permutations, combinations raw_input = stdin.readline pr = stdout.write def in_num(): return int(raw_input()) def in_arr(): return map(int,raw_input().split()) def pr_num(n): stdout.write(str(n)+'\n') def pr_arr(arr): pr(' '.join(map(str,arr))+'\n') # fast read function for total integer input def inp(): # this function returns whole input of # space/line seperated integers # Use Ctrl+D to flush stdin. return map(int,stdin.read().split()) range = xrange # not for python 3.0+ n=in_num() l=in_arr() ans=[] sm=0 for i in range(n-1,-1,-1): if sm<=0: sm+=l[i] ans.append('+') else: sm-=l[i] ans.append('-') if sm<0: for i in range(n): ans[i]='+'*(ans[i]=='-')+'-'*(ans[i]=='+') pr(''.join(reversed(ans))) ``` Yes
8,618
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai ≀ ai + 1 ≀ 2Β·ai for any positive integer i (i < n). Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs "+" and "-" before each number so that the value of expression s meets the limits 0 ≀ s ≀ a1. Print a sequence of signs "+" and "-", satisfying the given limits. It is guaranteed that the solution for the problem exists. Input The first line contains integer n (1 ≀ n ≀ 105) β€” the size of the array. The second line contains space-separated integers a1, a2, ..., an (0 ≀ ai ≀ 109) β€” the original array. It is guaranteed that the condition ai ≀ ai + 1 ≀ 2Β·ai fulfills for any positive integer i (i < n). Output In a single line print the sequence of n characters "+" and "-", where the i-th character is the sign that is placed in front of number ai. The value of the resulting expression s must fit into the limits 0 ≀ s ≀ a1. If there are multiple solutions, you are allowed to print any of them. Examples Input 4 1 2 3 5 Output +++- Input 3 3 3 5 Output ++- Submitted Solution: ``` #!/usr/bin/python3 n = int(input()) a = list(map(int, input().split())) s = a[-1] ans = ['+'] for v in reversed(a[:-1]): if s > 0: s -= v ans.append('-') else: s += v ans.append('+') if 0 <= s <= a[-1]: print(''.join(reversed(ans))) else: s = -a[-1] ans = ['-'] for v in reversed(a[:-1]): if s > 0: s -= v ans.append('-') else: s += v ans.append('+') print(''.join(reversed(ans))) ``` No
8,619
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai ≀ ai + 1 ≀ 2Β·ai for any positive integer i (i < n). Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs "+" and "-" before each number so that the value of expression s meets the limits 0 ≀ s ≀ a1. Print a sequence of signs "+" and "-", satisfying the given limits. It is guaranteed that the solution for the problem exists. Input The first line contains integer n (1 ≀ n ≀ 105) β€” the size of the array. The second line contains space-separated integers a1, a2, ..., an (0 ≀ ai ≀ 109) β€” the original array. It is guaranteed that the condition ai ≀ ai + 1 ≀ 2Β·ai fulfills for any positive integer i (i < n). Output In a single line print the sequence of n characters "+" and "-", where the i-th character is the sign that is placed in front of number ai. The value of the resulting expression s must fit into the limits 0 ≀ s ≀ a1. If there are multiple solutions, you are allowed to print any of them. Examples Input 4 1 2 3 5 Output +++- Input 3 3 3 5 Output ++- Submitted Solution: ``` if __name__ == "__main__": n = int(input()) array = input() if n == 1: print('+') print('+'*(n-1) + '-') ``` No
8,620
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai ≀ ai + 1 ≀ 2Β·ai for any positive integer i (i < n). Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs "+" and "-" before each number so that the value of expression s meets the limits 0 ≀ s ≀ a1. Print a sequence of signs "+" and "-", satisfying the given limits. It is guaranteed that the solution for the problem exists. Input The first line contains integer n (1 ≀ n ≀ 105) β€” the size of the array. The second line contains space-separated integers a1, a2, ..., an (0 ≀ ai ≀ 109) β€” the original array. It is guaranteed that the condition ai ≀ ai + 1 ≀ 2Β·ai fulfills for any positive integer i (i < n). Output In a single line print the sequence of n characters "+" and "-", where the i-th character is the sign that is placed in front of number ai. The value of the resulting expression s must fit into the limits 0 ≀ s ≀ a1. If there are multiple solutions, you are allowed to print any of them. Examples Input 4 1 2 3 5 Output +++- Input 3 3 3 5 Output ++- Submitted Solution: ``` n=int(input()) a=list(map(int,input().split())) s=-1*sum(a) str=['-']*n k=0 while(s<0 and k<n): if(s+2*a[k]<=a[0]): s=s+2*a[k] str[k]='+' k=k+1 if(s>=0 and s<=a[0]): for i in range(0,n): print(str[i],end='') else: print(-1) ``` No
8,621
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai ≀ ai + 1 ≀ 2Β·ai for any positive integer i (i < n). Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs "+" and "-" before each number so that the value of expression s meets the limits 0 ≀ s ≀ a1. Print a sequence of signs "+" and "-", satisfying the given limits. It is guaranteed that the solution for the problem exists. Input The first line contains integer n (1 ≀ n ≀ 105) β€” the size of the array. The second line contains space-separated integers a1, a2, ..., an (0 ≀ ai ≀ 109) β€” the original array. It is guaranteed that the condition ai ≀ ai + 1 ≀ 2Β·ai fulfills for any positive integer i (i < n). Output In a single line print the sequence of n characters "+" and "-", where the i-th character is the sign that is placed in front of number ai. The value of the resulting expression s must fit into the limits 0 ≀ s ≀ a1. If there are multiple solutions, you are allowed to print any of them. Examples Input 4 1 2 3 5 Output +++- Input 3 3 3 5 Output ++- Submitted Solution: ``` def invert(s): t = '' for i in s: if(i =='+'): t += '-' else: t += '+' #print(s,t) return t n = int(input()) a=list(map(int,input().split())) cur = a[-1] s = '+' for i in range(n-2,0,-1): if(cur > 0): cur -= a[i] s += '-' else: cur += a[i] s += '+' #print(s[::-1]) if(cur >= a[0]): s += '-' elif(abs(cur) <= a[0] and cur <= 0): s += '+' elif( 0 < cur < a[0]): s=invert(s) s += '+' else: s=invert(s) s += '-' print(s[::-1]) ``` No
8,622
Provide tags and a correct Python 3 solution for this coding contest problem. A star map in Berland is a checked field n Γ— m squares. In each square there is or there is not a star. The favourite constellation of all Berland's astronomers is the constellation of the Cross. This constellation can be formed by any 5 stars so, that for some integer x (radius of the constellation) the following is true: * the 2nd is on the same vertical line as the 1st, but x squares up * the 3rd is on the same vertical line as the 1st, but x squares down * the 4th is on the same horizontal line as the 1st, but x squares left * the 5th is on the same horizontal line as the 1st, but x squares right Such constellations can be very numerous, that's why they are numbered with integers from 1 on the following principle: when two constellations are compared, the one with a smaller radius gets a smaller index; if their radii are equal β€” the one, whose central star if higher than the central star of the other one; if their central stars are at the same level β€” the one, whose central star is to the left of the central star of the other one. Your task is to find the constellation with index k by the given Berland's star map. Input The first line contains three integers n, m and k (1 ≀ n, m ≀ 300, 1 ≀ k ≀ 3Β·107) β€” height and width of the map and index of the required constellation respectively. The upper-left corner has coordinates (1, 1), and the lower-right β€” (n, m). Then there follow n lines, m characters each β€” description of the map. j-th character in i-th line is Β«*Β», if there is a star in the corresponding square, and Β«.Β» if this square is empty. Output If the number of the constellations is less than k, output -1. Otherwise output 5 lines, two integers each β€” coordinates of the required constellation. Output the stars in the following order: central, upper, lower, left, right. Examples Input 5 6 1 ....*. ...*** ....*. ..*... .***.. Output 2 5 1 5 3 5 2 4 2 6 Input 5 6 2 ....*. ...*** ....*. ..*... .***.. Output -1 Input 7 7 2 ...*... ....... ...*... *.***.* ...*... ....... ...*... Output 4 4 1 4 7 4 4 1 4 7 Tags: implementation Correct Solution: ``` import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') n, m, k = map(int, input().split()) a = [tuple(map(lambda c: c == '*', input().rstrip())) for _ in range(n)] cnt = [0] * 400 for i in range(1, n - 1): for j in range(1, m - 1): if not a[i][j]: continue for rad, ui, di, lj, rj in zip(range(1, 400), range(i - 1, -1, -1), range(i + 1, n), range(j - 1, -1, -1), range(j + 1, m)): if a[ui][j] and a[di][j] and a[i][lj] and a[i][rj]: cnt[rad] += 1 rad = -1 for i in range(300): cnt[i + 1] += cnt[i] if cnt[i] >= k: rad = i k -= cnt[i - 1] break else: print(-1) exit() for i in range(rad, n - rad): for j in range(rad, m - rad): if a[i][j] and a[i - rad][j] and a[i + rad][j] and a[i][j - rad] and a[i][j + rad]: k -= 1 if k == 0: print(f'{i+1} {j+1}\n{i-rad+1} {j+1}\n{i+rad+1} {j+1}\n{i+1} {j-rad+1}\n{i+1} {j+rad+1}') exit() ```
8,623
Provide tags and a correct Python 3 solution for this coding contest problem. A star map in Berland is a checked field n Γ— m squares. In each square there is or there is not a star. The favourite constellation of all Berland's astronomers is the constellation of the Cross. This constellation can be formed by any 5 stars so, that for some integer x (radius of the constellation) the following is true: * the 2nd is on the same vertical line as the 1st, but x squares up * the 3rd is on the same vertical line as the 1st, but x squares down * the 4th is on the same horizontal line as the 1st, but x squares left * the 5th is on the same horizontal line as the 1st, but x squares right Such constellations can be very numerous, that's why they are numbered with integers from 1 on the following principle: when two constellations are compared, the one with a smaller radius gets a smaller index; if their radii are equal β€” the one, whose central star if higher than the central star of the other one; if their central stars are at the same level β€” the one, whose central star is to the left of the central star of the other one. Your task is to find the constellation with index k by the given Berland's star map. Input The first line contains three integers n, m and k (1 ≀ n, m ≀ 300, 1 ≀ k ≀ 3Β·107) β€” height and width of the map and index of the required constellation respectively. The upper-left corner has coordinates (1, 1), and the lower-right β€” (n, m). Then there follow n lines, m characters each β€” description of the map. j-th character in i-th line is Β«*Β», if there is a star in the corresponding square, and Β«.Β» if this square is empty. Output If the number of the constellations is less than k, output -1. Otherwise output 5 lines, two integers each β€” coordinates of the required constellation. Output the stars in the following order: central, upper, lower, left, right. Examples Input 5 6 1 ....*. ...*** ....*. ..*... .***.. Output 2 5 1 5 3 5 2 4 2 6 Input 5 6 2 ....*. ...*** ....*. ..*... .***.. Output -1 Input 7 7 2 ...*... ....... ...*... *.***.* ...*... ....... ...*... Output 4 4 1 4 7 4 4 1 4 7 Tags: implementation Correct Solution: ``` import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') n, m, k = map(int, input().split()) a = [tuple(map(lambda c: c == '*', input().rstrip())) for _ in range(n)] cnt = [0] * 400 for i in range(1, n - 1): for j in range(1, m - 1): if not a[i][j]: continue for rad, ui, di, lj, rj in zip(range(1, 400), range(i - 1, -1, -1), range(i + 1, n), range(j - 1, -1, -1), range(j + 1, m)): if all((a[ui][j], a[di][j], a[i][lj], a[i][rj])): cnt[rad] += 1 rad = -1 for i in range(300): cnt[i + 1] += cnt[i] if cnt[i] >= k: rad = i k -= cnt[i - 1] break else: print(-1) exit() for i in range(rad, n - rad): for j in range(rad, m - rad): if all((a[i][j], a[i - rad][j], a[i + rad][j], a[i][j - rad], a[i][j + rad])): k -= 1 if k == 0: print(f'{i+1} {j+1}\n{i-rad+1} {j+1}\n{i+rad+1} {j+1}\n{i+1} {j-rad+1}\n{i+1} {j+rad+1}') exit() ```
8,624
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A star map in Berland is a checked field n Γ— m squares. In each square there is or there is not a star. The favourite constellation of all Berland's astronomers is the constellation of the Cross. This constellation can be formed by any 5 stars so, that for some integer x (radius of the constellation) the following is true: * the 2nd is on the same vertical line as the 1st, but x squares up * the 3rd is on the same vertical line as the 1st, but x squares down * the 4th is on the same horizontal line as the 1st, but x squares left * the 5th is on the same horizontal line as the 1st, but x squares right Such constellations can be very numerous, that's why they are numbered with integers from 1 on the following principle: when two constellations are compared, the one with a smaller radius gets a smaller index; if their radii are equal β€” the one, whose central star if higher than the central star of the other one; if their central stars are at the same level β€” the one, whose central star is to the left of the central star of the other one. Your task is to find the constellation with index k by the given Berland's star map. Input The first line contains three integers n, m and k (1 ≀ n, m ≀ 300, 1 ≀ k ≀ 3Β·107) β€” height and width of the map and index of the required constellation respectively. The upper-left corner has coordinates (1, 1), and the lower-right β€” (n, m). Then there follow n lines, m characters each β€” description of the map. j-th character in i-th line is Β«*Β», if there is a star in the corresponding square, and Β«.Β» if this square is empty. Output If the number of the constellations is less than k, output -1. Otherwise output 5 lines, two integers each β€” coordinates of the required constellation. Output the stars in the following order: central, upper, lower, left, right. Examples Input 5 6 1 ....*. ...*** ....*. ..*... .***.. Output 2 5 1 5 3 5 2 4 2 6 Input 5 6 2 ....*. ...*** ....*. ..*... .***.. Output -1 Input 7 7 2 ...*... ....... ...*... *.***.* ...*... ....... ...*... Output 4 4 1 4 7 4 4 1 4 7 Submitted Solution: ``` x,y,n = map(int,input().split()) count = 0 space = [[0 for i in range(y + 300)] for j in range(x + 300)] for i in range(x): dd = input() for j in range(y): space[i + 1][j + 1] = dd[j] for i in range(2,x ): for j in range(2,y ): for k in range (1,max(x,y)): if space[i][j] == '*'and space[i - k][j] == '*' and space[i + k][j] == '*' and space[i][j - k] == '*' and space[i][j + k] == '*': count += 1 if count == n and space[i][j] == '*'and space[i - k][j] == '*' and space[i + k][j] == '*' and space[i][j - k] == '*' and space[i][j + k] == '*': print(i,j,"\n",i-k,j,"\n",i+k,j,"\n",i,j-k,"\n",i,j+k) if count < n : print('-1') ``` No
8,625
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A star map in Berland is a checked field n Γ— m squares. In each square there is or there is not a star. The favourite constellation of all Berland's astronomers is the constellation of the Cross. This constellation can be formed by any 5 stars so, that for some integer x (radius of the constellation) the following is true: * the 2nd is on the same vertical line as the 1st, but x squares up * the 3rd is on the same vertical line as the 1st, but x squares down * the 4th is on the same horizontal line as the 1st, but x squares left * the 5th is on the same horizontal line as the 1st, but x squares right Such constellations can be very numerous, that's why they are numbered with integers from 1 on the following principle: when two constellations are compared, the one with a smaller radius gets a smaller index; if their radii are equal β€” the one, whose central star if higher than the central star of the other one; if their central stars are at the same level β€” the one, whose central star is to the left of the central star of the other one. Your task is to find the constellation with index k by the given Berland's star map. Input The first line contains three integers n, m and k (1 ≀ n, m ≀ 300, 1 ≀ k ≀ 3Β·107) β€” height and width of the map and index of the required constellation respectively. The upper-left corner has coordinates (1, 1), and the lower-right β€” (n, m). Then there follow n lines, m characters each β€” description of the map. j-th character in i-th line is Β«*Β», if there is a star in the corresponding square, and Β«.Β» if this square is empty. Output If the number of the constellations is less than k, output -1. Otherwise output 5 lines, two integers each β€” coordinates of the required constellation. Output the stars in the following order: central, upper, lower, left, right. Examples Input 5 6 1 ....*. ...*** ....*. ..*... .***.. Output 2 5 1 5 3 5 2 4 2 6 Input 5 6 2 ....*. ...*** ....*. ..*... .***.. Output -1 Input 7 7 2 ...*... ....... ...*... *.***.* ...*... ....... ...*... Output 4 4 1 4 7 4 4 1 4 7 Submitted Solution: ``` x,y,n = map(int,input().split()) count = 0 space = [[0 for i in range(y + 300)] for j in range(x + 300)] for i in range(x): dd = input() for j in range(y): space[i + 1][j + 1] = dd[j] f = int(max(x,y) / 2) + 1 print(f) for k in range(1, f): for i in range(2,x): for j in range (2,y): if space[i][j] == '*'and space[i - k][j] == '*' and space[i + k][j] == '*' and space[i][j - k] == '*' and space[i][j + k] == '*': count += 1 if count == n and space[i][j] == '*'and space[i - k][j] == '*' and space[i + k][j] == '*' and space[i][j - k] == '*' and space[i][j + k] == '*': print(i,j,"\n",i-k,j,"\n",i+k,j,"\n",i,j-k,"\n",i,j+k) break if count < n : print('-1') ``` No
8,626
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A star map in Berland is a checked field n Γ— m squares. In each square there is or there is not a star. The favourite constellation of all Berland's astronomers is the constellation of the Cross. This constellation can be formed by any 5 stars so, that for some integer x (radius of the constellation) the following is true: * the 2nd is on the same vertical line as the 1st, but x squares up * the 3rd is on the same vertical line as the 1st, but x squares down * the 4th is on the same horizontal line as the 1st, but x squares left * the 5th is on the same horizontal line as the 1st, but x squares right Such constellations can be very numerous, that's why they are numbered with integers from 1 on the following principle: when two constellations are compared, the one with a smaller radius gets a smaller index; if their radii are equal β€” the one, whose central star if higher than the central star of the other one; if their central stars are at the same level β€” the one, whose central star is to the left of the central star of the other one. Your task is to find the constellation with index k by the given Berland's star map. Input The first line contains three integers n, m and k (1 ≀ n, m ≀ 300, 1 ≀ k ≀ 3Β·107) β€” height and width of the map and index of the required constellation respectively. The upper-left corner has coordinates (1, 1), and the lower-right β€” (n, m). Then there follow n lines, m characters each β€” description of the map. j-th character in i-th line is Β«*Β», if there is a star in the corresponding square, and Β«.Β» if this square is empty. Output If the number of the constellations is less than k, output -1. Otherwise output 5 lines, two integers each β€” coordinates of the required constellation. Output the stars in the following order: central, upper, lower, left, right. Examples Input 5 6 1 ....*. ...*** ....*. ..*... .***.. Output 2 5 1 5 3 5 2 4 2 6 Input 5 6 2 ....*. ...*** ....*. ..*... .***.. Output -1 Input 7 7 2 ...*... ....... ...*... *.***.* ...*... ....... ...*... Output 4 4 1 4 7 4 4 1 4 7 Submitted Solution: ``` import sys n,m,k=map(int,input().split(' ')) star=[] for i in range(n): star.append(list(input())) c=0 for i in range(n): for j in range(m): for z in range(min(i,j,(m-1-j),(n-1-i))): if(star[i][j]=='*' and star[i-(z+1)][j]=='*' and star[i+(z+1)][j]=='*' and star[i][j-(z+1)]=='*' and star[i][j+(z+1)]=='*'): c+=1 if(c==k): print(str(i+1)+' '+str(j+1)) print(str(i-z)+' '+str(j+1)) print(str(i+z+2)+' '+str(j+1)) print(str(i+1)+' '+str(j-z)) print(str(i+1)+' '+str(j+z+2)) sys.exit() print(-1) ``` No
8,627
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A star map in Berland is a checked field n Γ— m squares. In each square there is or there is not a star. The favourite constellation of all Berland's astronomers is the constellation of the Cross. This constellation can be formed by any 5 stars so, that for some integer x (radius of the constellation) the following is true: * the 2nd is on the same vertical line as the 1st, but x squares up * the 3rd is on the same vertical line as the 1st, but x squares down * the 4th is on the same horizontal line as the 1st, but x squares left * the 5th is on the same horizontal line as the 1st, but x squares right Such constellations can be very numerous, that's why they are numbered with integers from 1 on the following principle: when two constellations are compared, the one with a smaller radius gets a smaller index; if their radii are equal β€” the one, whose central star if higher than the central star of the other one; if their central stars are at the same level β€” the one, whose central star is to the left of the central star of the other one. Your task is to find the constellation with index k by the given Berland's star map. Input The first line contains three integers n, m and k (1 ≀ n, m ≀ 300, 1 ≀ k ≀ 3Β·107) β€” height and width of the map and index of the required constellation respectively. The upper-left corner has coordinates (1, 1), and the lower-right β€” (n, m). Then there follow n lines, m characters each β€” description of the map. j-th character in i-th line is Β«*Β», if there is a star in the corresponding square, and Β«.Β» if this square is empty. Output If the number of the constellations is less than k, output -1. Otherwise output 5 lines, two integers each β€” coordinates of the required constellation. Output the stars in the following order: central, upper, lower, left, right. Examples Input 5 6 1 ....*. ...*** ....*. ..*... .***.. Output 2 5 1 5 3 5 2 4 2 6 Input 5 6 2 ....*. ...*** ....*. ..*... .***.. Output -1 Input 7 7 2 ...*... ....... ...*... *.***.* ...*... ....... ...*... Output 4 4 1 4 7 4 4 1 4 7 Submitted Solution: ``` import os import sys from io import BytesIO, IOBase import math def main(): pass 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") def binary(n): return (bin(n).replace("0b", "")) def decimal(s): return (int(s, 2)) def pow2(n): p = 0 while (n > 1): n //= 2 p += 1 return (p) def primeFactors(n): l=[] while n % 2 == 0: l.append(2) n = n / 2 for i in range(3, int(math.sqrt(n)) + 1, 2): while n % i == 0: l.append(i) n = n / i if n > 2: l.append(int(n)) return (l) def isPrime(n): if (n == 1): return (False) else: root = int(n ** 0.5) root += 1 for i in range(2, root): if (n % i == 0): return (False) return (True) def maxPrimeFactors(n): maxPrime = -1 while n % 2 == 0: maxPrime = 2 n >>= 1 for i in range(3, int(math.sqrt(n)) + 1, 2): while n % i == 0: maxPrime = i n = n / i if n > 2: maxPrime = n return int(maxPrime) def reVal(num): if (num >= 0 and num <= 9): return chr(num + ord('0')); else: return chr(num - 10 + ord('A')); def strev(str): len = len(str); for i in range(int(len / 2)): temp = str[i]; str[i] = str[len - i - 1]; str[len - i - 1] = temp; def fromDeci(res, base, inputNum): index = 0; while (inputNum > 0): res += reVal(inputNum % base); inputNum = int(inputNum / base); res = res[::-1]; return res; def norm(s,l): tba="0"*(l-len(s)) return(tba+s) def check(x,y,k): if(mat[x-k][y]==mat[x+k][y]==mat[x][y-k]==mat[x][y+k]=="*"): return(True) else: return(False) n,m,k=map(int,input().split()) mat=[] for i in range(0,n): mat.append(input()) tc=0 ans=False ansr=0 for r in range(1,1+(min(n,m)-1)//2): if(not(ans)): for x in range(r,n-r): if(not(ans)): for y in range(r,m-r): if(check(x,y,r)): tc+=1 if(tc==k): ansr=r ansx,ansy=x,y ans=True break if(ans): ansx,ansy=ansx+1,ansy+1 print(ansx,ansy) print(ansx-ansr,ansy) print(ansx+ansr,ansy) print(ansx,ansy-ansr) print(ansx,ansy+ansr) else: print(-1) ``` No
8,628
Provide tags and a correct Python 3 solution for this coding contest problem. Jeff has become friends with Furik. Now these two are going to play one quite amusing game. At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and i + 1, for which an inequality pi > pi + 1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and i + 1, for which the inequality pi < pi + 1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order. Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well. You can consider that the coin shows the heads (or tails) with the probability of 50 percent. Input The first line contains integer n (1 ≀ n ≀ 3000). The next line contains n distinct integers p1, p2, ..., pn (1 ≀ pi ≀ n) β€” the permutation p. The numbers are separated by spaces. Output In a single line print a single real value β€” the answer to the problem. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6. Examples Input 2 1 2 Output 0.000000 Input 5 3 5 2 4 1 Output 13.000000 Note In the first test the sequence is already sorted, so the answer is 0. Tags: combinatorics, dp, probabilities Correct Solution: ``` from sys import * n=int(stdin.readline().strip()) s1=stdin.readline().strip() a=list(map(int,s1.split())) if n==1: print('0') else: x=0 n0=1 while n0<n: n0=n0*2 b=[0]*(2*n0+10) '''for i in range (n-1): for j in range (i+1,n): if a[i]>a[j]: x+=1''' for i in range (n): t=a[i] u=0 k=1 j=1 while t>0: if (t>>j)<<j!=t: u=u+b[(n0+t-1)>>(j-1)] t=t-k k=k<<1 j=j+1 x=x+u j=n0+a[i]-1 while j>0: b[j]+=1 j=j>>1 x=((n*(n-1))//2)-x '''n=x//2 print(x,n,' !!!') r=x i=1 bi=n eps=0.0000001 if x>0: while (x+2*i)*bi*((0.5)**i)>eps: r=r+(x+2*i)*bi*((0.5)**i) #print(r) bi=(bi*(n+i))//(i+1) i=i+1 #print(bi,i) else: r=0 r=r*((0.5)**n) print("%.7f"%r)''' if x%2 ==1: print(2*x-1) else: print(2*x) ```
8,629
Provide tags and a correct Python 3 solution for this coding contest problem. Jeff has become friends with Furik. Now these two are going to play one quite amusing game. At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and i + 1, for which an inequality pi > pi + 1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and i + 1, for which the inequality pi < pi + 1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order. Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well. You can consider that the coin shows the heads (or tails) with the probability of 50 percent. Input The first line contains integer n (1 ≀ n ≀ 3000). The next line contains n distinct integers p1, p2, ..., pn (1 ≀ pi ≀ n) β€” the permutation p. The numbers are separated by spaces. Output In a single line print a single real value β€” the answer to the problem. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6. Examples Input 2 1 2 Output 0.000000 Input 5 3 5 2 4 1 Output 13.000000 Note In the first test the sequence is already sorted, so the answer is 0. Tags: combinatorics, dp, probabilities Correct Solution: ``` n=int(input().strip()) p=[0]+list(map(int,input().split())) c=[0]*(n+1) def lowbit(x): return x&(-x) def add(x,v): while x<=n: c[x]+=v x+=lowbit(x) def get(x): ans=0 while x: ans+=c[x] x-=lowbit(x) return ans ans=0 for i in range(n,0,-1): ans+=get(p[i]) add(p[i],1) if ans%2: print(2*ans-1) else: print(2*ans) ```
8,630
Provide tags and a correct Python 3 solution for this coding contest problem. Jeff has become friends with Furik. Now these two are going to play one quite amusing game. At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and i + 1, for which an inequality pi > pi + 1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and i + 1, for which the inequality pi < pi + 1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order. Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well. You can consider that the coin shows the heads (or tails) with the probability of 50 percent. Input The first line contains integer n (1 ≀ n ≀ 3000). The next line contains n distinct integers p1, p2, ..., pn (1 ≀ pi ≀ n) β€” the permutation p. The numbers are separated by spaces. Output In a single line print a single real value β€” the answer to the problem. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6. Examples Input 2 1 2 Output 0.000000 Input 5 3 5 2 4 1 Output 13.000000 Note In the first test the sequence is already sorted, so the answer is 0. Tags: combinatorics, dp, probabilities Correct Solution: ``` n=int(input()) b=list(map(int,input().split())) cnt=0 for i in range(n): j=i-1 while(j>=0): if b[j]>b[i]: cnt+=1 j+=-1 i+=-1 print(2*cnt-cnt%2) ```
8,631
Provide tags and a correct Python 3 solution for this coding contest problem. Jeff has become friends with Furik. Now these two are going to play one quite amusing game. At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and i + 1, for which an inequality pi > pi + 1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and i + 1, for which the inequality pi < pi + 1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order. Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well. You can consider that the coin shows the heads (or tails) with the probability of 50 percent. Input The first line contains integer n (1 ≀ n ≀ 3000). The next line contains n distinct integers p1, p2, ..., pn (1 ≀ pi ≀ n) β€” the permutation p. The numbers are separated by spaces. Output In a single line print a single real value β€” the answer to the problem. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6. Examples Input 2 1 2 Output 0.000000 Input 5 3 5 2 4 1 Output 13.000000 Note In the first test the sequence is already sorted, so the answer is 0. Tags: combinatorics, dp, probabilities Correct Solution: ``` #!/usr/bin/python3 import sys class CumTree: def __init__(self, a, b): self.a = a self.b = b self.count = 0 if a == b: return mid = (a + b) // 2 self.levo = CumTree(a, mid) self.desno = CumTree(mid+1, b) def manjsi(self, t): if self.a >= t: return 0 if self.b < t: return self.count return self.levo.manjsi(t) + self.desno.manjsi(t) def vstavi(self, t): if self.a <= t <= self.b: self.count += 1 if self.a == self.b: return self.levo.vstavi(t) self.desno.vstavi(t) n = int(sys.stdin.readline()) p = [int(x) for x in sys.stdin.readline().strip().split()] ct = CumTree(1, 4096) vsota = 0 while len(p) > 0: x = p.pop() vsota += ct.manjsi(x) ct.vstavi(x) k, d = vsota // 2, vsota % 2 print("%f" % (4*k + d)) ```
8,632
Provide tags and a correct Python 3 solution for this coding contest problem. Jeff has become friends with Furik. Now these two are going to play one quite amusing game. At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and i + 1, for which an inequality pi > pi + 1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and i + 1, for which the inequality pi < pi + 1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order. Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well. You can consider that the coin shows the heads (or tails) with the probability of 50 percent. Input The first line contains integer n (1 ≀ n ≀ 3000). The next line contains n distinct integers p1, p2, ..., pn (1 ≀ pi ≀ n) β€” the permutation p. The numbers are separated by spaces. Output In a single line print a single real value β€” the answer to the problem. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6. Examples Input 2 1 2 Output 0.000000 Input 5 3 5 2 4 1 Output 13.000000 Note In the first test the sequence is already sorted, so the answer is 0. Tags: combinatorics, dp, probabilities Correct Solution: ``` def count(a): n = len(a) cnt = 0 for i in range(n): for j in range(i+1, n): if a[i] > a[j]: cnt+=1 return cnt n = int(input()) p = list(map(int, input().split())) num = count(p) print(num*2 - num%2) ```
8,633
Provide tags and a correct Python 3 solution for this coding contest problem. Jeff has become friends with Furik. Now these two are going to play one quite amusing game. At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and i + 1, for which an inequality pi > pi + 1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and i + 1, for which the inequality pi < pi + 1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order. Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well. You can consider that the coin shows the heads (or tails) with the probability of 50 percent. Input The first line contains integer n (1 ≀ n ≀ 3000). The next line contains n distinct integers p1, p2, ..., pn (1 ≀ pi ≀ n) β€” the permutation p. The numbers are separated by spaces. Output In a single line print a single real value β€” the answer to the problem. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6. Examples Input 2 1 2 Output 0.000000 Input 5 3 5 2 4 1 Output 13.000000 Note In the first test the sequence is already sorted, so the answer is 0. Tags: combinatorics, dp, probabilities Correct Solution: ``` def merge_sort(a, l, r): res = 0 if l < r: m = (l + r) // 2 res += merge_sort(a, l, m) res += merge_sort(a, m + 1, r) i = l j = m + 1 b = [] while i <= m and j <= r: if a[i] <= a[j]: b.append(a[i]) i += 1 else: b.append(a[j]) j += 1 res += m - i + 1 while i <= m: b.append(a[i]) i += 1 while j <= r: b.append(a[j]) j += 1 for idx, val in enumerate(b): a[idx + l] = val return res input() a = [int(x) for x in input().split()] n = len(a) ans = merge_sort(a, 0, n - 1) if ans & 1 == 0: ans *= 2 else: ans = ans * 2 - 1 print(ans) ```
8,634
Provide tags and a correct Python 3 solution for this coding contest problem. Jeff has become friends with Furik. Now these two are going to play one quite amusing game. At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and i + 1, for which an inequality pi > pi + 1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and i + 1, for which the inequality pi < pi + 1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order. Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well. You can consider that the coin shows the heads (or tails) with the probability of 50 percent. Input The first line contains integer n (1 ≀ n ≀ 3000). The next line contains n distinct integers p1, p2, ..., pn (1 ≀ pi ≀ n) β€” the permutation p. The numbers are separated by spaces. Output In a single line print a single real value β€” the answer to the problem. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6. Examples Input 2 1 2 Output 0.000000 Input 5 3 5 2 4 1 Output 13.000000 Note In the first test the sequence is already sorted, so the answer is 0. Tags: combinatorics, dp, probabilities Correct Solution: ``` def merge_sort(a, l, r): res = 0 if l < r: m = (l + r) // 2 res += merge_sort(a, l, m) res += merge_sort(a, m + 1, r) i = l j = m + 1 b = [] while i <= m and j <= r: if a[i] <= a[j]: b.append(a[i]) i += 1 else: b.append(a[j]) j += 1 res += m - i + 1 while i <= m: b.append(a[i]) i += 1 while j <= r: b.append(a[j]) j += 1 for idx, val in enumerate(b): a[idx + l] = val return res input() a = [int(x) for x in input().split()] n = len(a) ans = merge_sort(a, 0, n - 1) if ans & 1 == 0: ans *= 2 else: ans = ans * 2 - 1 print(ans) # Made By Mostafa_Khaled ```
8,635
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Jeff has become friends with Furik. Now these two are going to play one quite amusing game. At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and i + 1, for which an inequality pi > pi + 1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and i + 1, for which the inequality pi < pi + 1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order. Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well. You can consider that the coin shows the heads (or tails) with the probability of 50 percent. Input The first line contains integer n (1 ≀ n ≀ 3000). The next line contains n distinct integers p1, p2, ..., pn (1 ≀ pi ≀ n) β€” the permutation p. The numbers are separated by spaces. Output In a single line print a single real value β€” the answer to the problem. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6. Examples Input 2 1 2 Output 0.000000 Input 5 3 5 2 4 1 Output 13.000000 Note In the first test the sequence is already sorted, so the answer is 0. Submitted Solution: ``` from sys import * n=int(stdin.readline().strip()) s1=stdin.readline().strip() a=list(map(int,s1.split())) x=0 for i in range (n-1): for j in range (i+1,n): if a[i]>a[j]: x+=1 n=x//2 #print(x,n,' !!!') r=(x)*((0.5)**n) i=1 bi=3 eps=0.00000001 if x>0: while (x+2*i)*bi*((0.5)**(n+i))>eps: r=r+(x+2*i)*bi*(0.5)**(n+i) #print(r) bi=(bi*(n+i))//(i+1) i=i+1 #print(bi,i) else: r=0 print("%.7f"%r) ``` No
8,636
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Jeff has become friends with Furik. Now these two are going to play one quite amusing game. At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and i + 1, for which an inequality pi > pi + 1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and i + 1, for which the inequality pi < pi + 1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order. Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well. You can consider that the coin shows the heads (or tails) with the probability of 50 percent. Input The first line contains integer n (1 ≀ n ≀ 3000). The next line contains n distinct integers p1, p2, ..., pn (1 ≀ pi ≀ n) β€” the permutation p. The numbers are separated by spaces. Output In a single line print a single real value β€” the answer to the problem. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6. Examples Input 2 1 2 Output 0.000000 Input 5 3 5 2 4 1 Output 13.000000 Note In the first test the sequence is already sorted, so the answer is 0. Submitted Solution: ``` from sys import * n=int(stdin.readline().strip()) s1=stdin.readline().strip() a=list(map(int,s1.split())) if n==1: print('0') else: x=0 n0=1 while n0<n: n0=n0*2 b=[0]*(2*n0+10) '''for i in range (n-1): for j in range (i+1,n): if a[i]>a[j]: x+=1''' for i in range (n): t=a[i] u=0 k=1 j=1 while t>0: if (t>>j)<<j!=t: u=u+b[(n0+t-1)>>(j-1)] t=t-k k=k<<1 j=j+1 x=x+u j=n0+a[i]-1 while j>0: b[j]+=1 j=j>>1 x=((n*(n-1))//2)-x n=x//2 #print(x,n,' !!!') r=x*((0.5)**n) i=1 bi=n eps=0.00000001 if x>0: while (x+2*i)*bi*((0.5)**(n+i))>eps: r=r+(x+2*i)*bi*(0.5)**(n+i) #print(r) bi=(bi*(n+i))//(i+1) i=i+1 #print(bi,i) else: r=0 print("%.7f"%r) ``` No
8,637
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a rooted tree consisting of n vertices numbered from 1 to n. The root of the tree is a vertex number 1. Initially all vertices contain number 0. Then come q queries, each query has one of the two types: * The format of the query: 1 v x k. In response to the query, you need to add to the number at vertex v number x; to the numbers at the descendants of vertex v at distance 1, add x - k; and so on, to the numbers written in the descendants of vertex v at distance i, you need to add x - (iΒ·k). The distance between two vertices is the number of edges in the shortest path between these vertices. * The format of the query: 2 v. In reply to the query you should print the number written in vertex v modulo 1000000007 (109 + 7). Process the queries given in the input. Input The first line contains integer n (1 ≀ n ≀ 3Β·105) β€” the number of vertices in the tree. The second line contains n - 1 integers p2, p3, ... pn (1 ≀ pi < i), where pi is the number of the vertex that is the parent of vertex i in the tree. The third line contains integer q (1 ≀ q ≀ 3Β·105) β€” the number of queries. Next q lines contain the queries, one per line. The first number in the line is type. It represents the type of the query. If type = 1, then next follow space-separated integers v, x, k (1 ≀ v ≀ n; 0 ≀ x < 109 + 7; 0 ≀ k < 109 + 7). If type = 2, then next follows integer v (1 ≀ v ≀ n) β€” the vertex where you need to find the value of the number. Output For each query of the second type print on a single line the number written in the vertex from the query. Print the number modulo 1000000007 (109 + 7). Examples Input 3 1 1 3 1 1 2 1 2 1 2 2 Output 2 1 Note You can read about a rooted tree here: http://en.wikipedia.org/wiki/Tree_(graph_theory). Submitted Solution: ``` n = int(input()) MOD = int(1e9)+7 vertex = {} parent = {1:1} for i in range(1,n+1): vertex[i] = [0,0] x = list(map(int,input().split(' '))) for i in range(n-1): parent[i+2] = x[i] q = int(input()) for _ in range(q): query = list(map(int,input().split(' '))) qt = query[0] if qt ==1: v,x,k = query[1:] vertex[v][0] = (vertex[v][0]+x)%MOD vertex[v][1] = (vertex[v][1]+k)%MOD else: v = query[1] node = v dis = 0 while(parent[node]!=node): dis = (dis+1)%MOD node = parent[node] if vertex[node][1] == 0: continue vertex[v][0] = (vertex[v][0]%MOD + (vertex[node][0]%MOD-(dis*(vertex[node][1]))%MOD)%MOD)%MOD print(vertex[v][0]%MOD) ``` No
8,638
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a rooted tree consisting of n vertices numbered from 1 to n. The root of the tree is a vertex number 1. Initially all vertices contain number 0. Then come q queries, each query has one of the two types: * The format of the query: 1 v x k. In response to the query, you need to add to the number at vertex v number x; to the numbers at the descendants of vertex v at distance 1, add x - k; and so on, to the numbers written in the descendants of vertex v at distance i, you need to add x - (iΒ·k). The distance between two vertices is the number of edges in the shortest path between these vertices. * The format of the query: 2 v. In reply to the query you should print the number written in vertex v modulo 1000000007 (109 + 7). Process the queries given in the input. Input The first line contains integer n (1 ≀ n ≀ 3Β·105) β€” the number of vertices in the tree. The second line contains n - 1 integers p2, p3, ... pn (1 ≀ pi < i), where pi is the number of the vertex that is the parent of vertex i in the tree. The third line contains integer q (1 ≀ q ≀ 3Β·105) β€” the number of queries. Next q lines contain the queries, one per line. The first number in the line is type. It represents the type of the query. If type = 1, then next follow space-separated integers v, x, k (1 ≀ v ≀ n; 0 ≀ x < 109 + 7; 0 ≀ k < 109 + 7). If type = 2, then next follows integer v (1 ≀ v ≀ n) β€” the vertex where you need to find the value of the number. Output For each query of the second type print on a single line the number written in the vertex from the query. Print the number modulo 1000000007 (109 + 7). Examples Input 3 1 1 3 1 1 2 1 2 1 2 2 Output 2 1 Note You can read about a rooted tree here: http://en.wikipedia.org/wiki/Tree_(graph_theory). Submitted Solution: ``` import sys import threading _M_ = 1000000007 tr = [[] for _ in range(300001)] cnt = 0 node = [(0,0,0) for i in range(300001)] def createRange(root, ht): global cnt, node cnt += 1 st = cnt for ch in tr[root]: createRange(ch, ht+1) en = cnt node[root] = (st,en,ht) #print node bit = [(0,0) for i in range(700001)] def update(n, hkx,k,posi): global bit, cnt if posi <= 0: return while posi <= cnt: #print(posi) bit[posi] = (bit[posi][0]+hkx, bit[posi][1]+k) posi += (posi&-posi) #print(pos) def get(pos,h): global bit, _M_ ret = 0 while(pos>0): ret += bit[pos][0] - h*bit[pos][1] pos -= (pos&-pos) #print(ret) return ret%_M_ def main(): n = int(input()) par = list(map(int, input().split())) ind = 2 for p in par: tr[p].append(ind) ind+=1 createRange(1,0) for _ in range(int(input())): q = list(map(int, input().split())) st,en,ht = node[q[1]] #print(st,en) #print(node[q[1]]) if (q[0]==1): update(q[2]+ht*q[3], q[3], st) #print(bit) if (en < cnt): update(-q[2]-ht*q[3], -q[3], en+1) else: print(get(st,ht)) if __name__ == "__main__": sys.setrecursionlimit(2000 * 1000) threading.stack_size(128 * 1024 * 1024) main_thread = threading.Thread(target=main) main_thread.start() main_thread.join() ``` No
8,639
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a rooted tree consisting of n vertices numbered from 1 to n. The root of the tree is a vertex number 1. Initially all vertices contain number 0. Then come q queries, each query has one of the two types: * The format of the query: 1 v x k. In response to the query, you need to add to the number at vertex v number x; to the numbers at the descendants of vertex v at distance 1, add x - k; and so on, to the numbers written in the descendants of vertex v at distance i, you need to add x - (iΒ·k). The distance between two vertices is the number of edges in the shortest path between these vertices. * The format of the query: 2 v. In reply to the query you should print the number written in vertex v modulo 1000000007 (109 + 7). Process the queries given in the input. Input The first line contains integer n (1 ≀ n ≀ 3Β·105) β€” the number of vertices in the tree. The second line contains n - 1 integers p2, p3, ... pn (1 ≀ pi < i), where pi is the number of the vertex that is the parent of vertex i in the tree. The third line contains integer q (1 ≀ q ≀ 3Β·105) β€” the number of queries. Next q lines contain the queries, one per line. The first number in the line is type. It represents the type of the query. If type = 1, then next follow space-separated integers v, x, k (1 ≀ v ≀ n; 0 ≀ x < 109 + 7; 0 ≀ k < 109 + 7). If type = 2, then next follows integer v (1 ≀ v ≀ n) β€” the vertex where you need to find the value of the number. Output For each query of the second type print on a single line the number written in the vertex from the query. Print the number modulo 1000000007 (109 + 7). Examples Input 3 1 1 3 1 1 2 1 2 1 2 2 Output 2 1 Note You can read about a rooted tree here: http://en.wikipedia.org/wiki/Tree_(graph_theory). Submitted Solution: ``` def getdistance(orvertice,dstvertice): distance=0 actual=orvertice while actual != dstvertice: if actual['Parent']==-1: raise ValueError('Not a descendent') actual=actual['Parent'] distance+=1 return distance vertices=list() input() vertices.append({'Parent':-1,'Value':0}) for parent in input().split(' '): vertices.append({'Parent':vertices[int(parent)-1],'Value':0}) for i in range(0,int(input())): query = input().split(' ') if int(query[0]) == 1: for vertice in vertices: try: vertice['Value'] += int(query[2]) - int(query[3]) * getdistance(vertice,vertices[int(query[1])-1]) except Exception as e: pass else: print(vertices[int(query[1])-1]['Value']%1000000007) ``` No
8,640
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a rooted tree consisting of n vertices numbered from 1 to n. The root of the tree is a vertex number 1. Initially all vertices contain number 0. Then come q queries, each query has one of the two types: * The format of the query: 1 v x k. In response to the query, you need to add to the number at vertex v number x; to the numbers at the descendants of vertex v at distance 1, add x - k; and so on, to the numbers written in the descendants of vertex v at distance i, you need to add x - (iΒ·k). The distance between two vertices is the number of edges in the shortest path between these vertices. * The format of the query: 2 v. In reply to the query you should print the number written in vertex v modulo 1000000007 (109 + 7). Process the queries given in the input. Input The first line contains integer n (1 ≀ n ≀ 3Β·105) β€” the number of vertices in the tree. The second line contains n - 1 integers p2, p3, ... pn (1 ≀ pi < i), where pi is the number of the vertex that is the parent of vertex i in the tree. The third line contains integer q (1 ≀ q ≀ 3Β·105) β€” the number of queries. Next q lines contain the queries, one per line. The first number in the line is type. It represents the type of the query. If type = 1, then next follow space-separated integers v, x, k (1 ≀ v ≀ n; 0 ≀ x < 109 + 7; 0 ≀ k < 109 + 7). If type = 2, then next follows integer v (1 ≀ v ≀ n) β€” the vertex where you need to find the value of the number. Output For each query of the second type print on a single line the number written in the vertex from the query. Print the number modulo 1000000007 (109 + 7). Examples Input 3 1 1 3 1 1 2 1 2 1 2 2 Output 2 1 Note You can read about a rooted tree here: http://en.wikipedia.org/wiki/Tree_(graph_theory). Submitted Solution: ``` def getdistance(orvertice,dstvertice): distance=0 actual=orvertice while actual != dstvertice: if actual['Parent']==-1: raise ValueError('Not a descendent') actual=actual['Parent'] distance+=1 return distance vertices=list() input() vertices.append({'Parent':-1,'Value':0}) for parent in input().split(' '): vertices.append({'Parent':vertices[int(parent)-1],'Value':0}) for i in range(0,int(input())): query = input().split(' ') if int(query[0]) == 1: for vertice in vertices: try: vertice['Value'] += int(query[2]) - int(query[3]) * getdistance(vertice,vertices[int(query[1])-1]) except Exception as e: pass else: print(vertices[int(query[1])-1]['Value']) ``` No
8,641
Provide tags and a correct Python 3 solution for this coding contest problem. Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it? The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out the name of the company on a piece of paper in a line (horizontally, from left to right) with large English letters, then put this piece of paper in front of the mirror, then the reflection of the name in the mirror should perfectly match the line written on the piece of paper. There are many suggestions for the company name, so coming up to the mirror with a piece of paper for each name wouldn't be sensible. The founders of the company decided to automatize this process. They asked you to write a program that can, given a word, determine whether the word is a 'mirror' word or not. Input The first line contains a non-empty name that needs to be checked. The name contains at most 105 large English letters. The name will be written with the next sans serif font: <image> Output Print 'YES' (without the quotes), if the given name matches its mirror reflection. Otherwise, print 'NO' (without the quotes). Examples Input AHA Output YES Input Z Output NO Input XO Output NO Tags: implementation Correct Solution: ``` symmetric = 'AHIMOTUVWXY' s = input() if s == s[::-1] and all([x in symmetric for x in s]): print('YES') else: print('NO') ```
8,642
Provide tags and a correct Python 3 solution for this coding contest problem. Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it? The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out the name of the company on a piece of paper in a line (horizontally, from left to right) with large English letters, then put this piece of paper in front of the mirror, then the reflection of the name in the mirror should perfectly match the line written on the piece of paper. There are many suggestions for the company name, so coming up to the mirror with a piece of paper for each name wouldn't be sensible. The founders of the company decided to automatize this process. They asked you to write a program that can, given a word, determine whether the word is a 'mirror' word or not. Input The first line contains a non-empty name that needs to be checked. The name contains at most 105 large English letters. The name will be written with the next sans serif font: <image> Output Print 'YES' (without the quotes), if the given name matches its mirror reflection. Otherwise, print 'NO' (without the quotes). Examples Input AHA Output YES Input Z Output NO Input XO Output NO Tags: implementation Correct Solution: ``` '''input XO ''' s = input() if all(s[x] == s[~x] for x in range(len(s)//2)): if any(y not in "AHIMOTUVWXY" for y in s[:len(s)//2+1]): print("NO") else: print("YES") else: print("NO") ```
8,643
Provide tags and a correct Python 3 solution for this coding contest problem. Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it? The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out the name of the company on a piece of paper in a line (horizontally, from left to right) with large English letters, then put this piece of paper in front of the mirror, then the reflection of the name in the mirror should perfectly match the line written on the piece of paper. There are many suggestions for the company name, so coming up to the mirror with a piece of paper for each name wouldn't be sensible. The founders of the company decided to automatize this process. They asked you to write a program that can, given a word, determine whether the word is a 'mirror' word or not. Input The first line contains a non-empty name that needs to be checked. The name contains at most 105 large English letters. The name will be written with the next sans serif font: <image> Output Print 'YES' (without the quotes), if the given name matches its mirror reflection. Otherwise, print 'NO' (without the quotes). Examples Input AHA Output YES Input Z Output NO Input XO Output NO Tags: implementation Correct Solution: ``` def palindrome(n): for i in range(0,len(n)): if n[i] != n[-(i+1)]: return 0 return 1 lessgo = ['a','h','i','m','o','t','u','v','w','x','y'] i = list(input()) for j in range(len(i)): i[j] = i[j].lower() mir = 1 for j in range(len(i)): if i[j] not in lessgo: mir = 0 if palindrome(i) == 1 and mir == 1: print("YES") else: print("NO") ```
8,644
Provide tags and a correct Python 3 solution for this coding contest problem. Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it? The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out the name of the company on a piece of paper in a line (horizontally, from left to right) with large English letters, then put this piece of paper in front of the mirror, then the reflection of the name in the mirror should perfectly match the line written on the piece of paper. There are many suggestions for the company name, so coming up to the mirror with a piece of paper for each name wouldn't be sensible. The founders of the company decided to automatize this process. They asked you to write a program that can, given a word, determine whether the word is a 'mirror' word or not. Input The first line contains a non-empty name that needs to be checked. The name contains at most 105 large English letters. The name will be written with the next sans serif font: <image> Output Print 'YES' (without the quotes), if the given name matches its mirror reflection. Otherwise, print 'NO' (without the quotes). Examples Input AHA Output YES Input Z Output NO Input XO Output NO Tags: implementation Correct Solution: ``` s = input() print('YES' if all(ch in 'AHIMOTUVWXY' for ch in s) and s==s[::-1] else 'NO') ```
8,645
Provide tags and a correct Python 3 solution for this coding contest problem. Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it? The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out the name of the company on a piece of paper in a line (horizontally, from left to right) with large English letters, then put this piece of paper in front of the mirror, then the reflection of the name in the mirror should perfectly match the line written on the piece of paper. There are many suggestions for the company name, so coming up to the mirror with a piece of paper for each name wouldn't be sensible. The founders of the company decided to automatize this process. They asked you to write a program that can, given a word, determine whether the word is a 'mirror' word or not. Input The first line contains a non-empty name that needs to be checked. The name contains at most 105 large English letters. The name will be written with the next sans serif font: <image> Output Print 'YES' (without the quotes), if the given name matches its mirror reflection. Otherwise, print 'NO' (without the quotes). Examples Input AHA Output YES Input Z Output NO Input XO Output NO Tags: implementation Correct Solution: ``` n=input() i=0 k=len(n)-1 _b=True while i<=k and _b: if n[i]==n[k] and n[i] in ['A','H','I','M','O','T','U','V','W','X','Y']: _b=True i+=1 k-=1 else: _b=False if _b: print('YES') else: print('NO') ```
8,646
Provide tags and a correct Python 3 solution for this coding contest problem. Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it? The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out the name of the company on a piece of paper in a line (horizontally, from left to right) with large English letters, then put this piece of paper in front of the mirror, then the reflection of the name in the mirror should perfectly match the line written on the piece of paper. There are many suggestions for the company name, so coming up to the mirror with a piece of paper for each name wouldn't be sensible. The founders of the company decided to automatize this process. They asked you to write a program that can, given a word, determine whether the word is a 'mirror' word or not. Input The first line contains a non-empty name that needs to be checked. The name contains at most 105 large English letters. The name will be written with the next sans serif font: <image> Output Print 'YES' (without the quotes), if the given name matches its mirror reflection. Otherwise, print 'NO' (without the quotes). Examples Input AHA Output YES Input Z Output NO Input XO Output NO Tags: implementation Correct Solution: ``` n=list(input()) m=n+[] m.reverse() l=['A','H','I','M','O','T','U','V','W','X','Y'] if(m==n ): e=0 for i in range(len(n)): if n[i] not in l: print("NO") e=1 break if(e==0): print("YES") else: print("NO") ```
8,647
Provide tags and a correct Python 3 solution for this coding contest problem. Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it? The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out the name of the company on a piece of paper in a line (horizontally, from left to right) with large English letters, then put this piece of paper in front of the mirror, then the reflection of the name in the mirror should perfectly match the line written on the piece of paper. There are many suggestions for the company name, so coming up to the mirror with a piece of paper for each name wouldn't be sensible. The founders of the company decided to automatize this process. They asked you to write a program that can, given a word, determine whether the word is a 'mirror' word or not. Input The first line contains a non-empty name that needs to be checked. The name contains at most 105 large English letters. The name will be written with the next sans serif font: <image> Output Print 'YES' (without the quotes), if the given name matches its mirror reflection. Otherwise, print 'NO' (without the quotes). Examples Input AHA Output YES Input Z Output NO Input XO Output NO Tags: implementation Correct Solution: ``` s = input() a = ['A','H','I','M','O','T','U','V','W','X','Y'] a = set(a) count = 0 if len(s)%2 == 0: for i in range(int(len(s)/2)): if s[i] == s[len(s)-i-1] and s[i] in a: count = count + 1 else : if s[int(len(s)/2)] in a: for i in range(int(len(s)/2)): if s[i] == s[len(s)-i-1] and s[i] in a: count = count + 1 if count == int(len(s)/2) and s[0] in a : print("YES") else: print("NO") ```
8,648
Provide tags and a correct Python 3 solution for this coding contest problem. Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it? The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out the name of the company on a piece of paper in a line (horizontally, from left to right) with large English letters, then put this piece of paper in front of the mirror, then the reflection of the name in the mirror should perfectly match the line written on the piece of paper. There are many suggestions for the company name, so coming up to the mirror with a piece of paper for each name wouldn't be sensible. The founders of the company decided to automatize this process. They asked you to write a program that can, given a word, determine whether the word is a 'mirror' word or not. Input The first line contains a non-empty name that needs to be checked. The name contains at most 105 large English letters. The name will be written with the next sans serif font: <image> Output Print 'YES' (without the quotes), if the given name matches its mirror reflection. Otherwise, print 'NO' (without the quotes). Examples Input AHA Output YES Input Z Output NO Input XO Output NO Tags: implementation Correct Solution: ``` def ic(s): ss=set('AHIMOTUVWXY') m=len(s)//2+1 for c in range(m): if s[c]!=s[-(c+1)] or s[c] not in ss: return 0 return 1 s='YES' if ic(input()) else 'NO' print(s) ```
8,649
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it? The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out the name of the company on a piece of paper in a line (horizontally, from left to right) with large English letters, then put this piece of paper in front of the mirror, then the reflection of the name in the mirror should perfectly match the line written on the piece of paper. There are many suggestions for the company name, so coming up to the mirror with a piece of paper for each name wouldn't be sensible. The founders of the company decided to automatize this process. They asked you to write a program that can, given a word, determine whether the word is a 'mirror' word or not. Input The first line contains a non-empty name that needs to be checked. The name contains at most 105 large English letters. The name will be written with the next sans serif font: <image> Output Print 'YES' (without the quotes), if the given name matches its mirror reflection. Otherwise, print 'NO' (without the quotes). Examples Input AHA Output YES Input Z Output NO Input XO Output NO Submitted Solution: ``` def isMirror(s): x = s[::-1] if(x != s): return False n = s.count('A') + s.count('H') + s.count('I') + s.count('M') + s.count('O') + s.count('T') + s.count('U') + s.count('V') + s.count('W') + s.count('X') + s.count('Y') if(n != len(s)): return False return True s = input() if(isMirror(s) == True): print('YES') else: print('NO') ``` Yes
8,650
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it? The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out the name of the company on a piece of paper in a line (horizontally, from left to right) with large English letters, then put this piece of paper in front of the mirror, then the reflection of the name in the mirror should perfectly match the line written on the piece of paper. There are many suggestions for the company name, so coming up to the mirror with a piece of paper for each name wouldn't be sensible. The founders of the company decided to automatize this process. They asked you to write a program that can, given a word, determine whether the word is a 'mirror' word or not. Input The first line contains a non-empty name that needs to be checked. The name contains at most 105 large English letters. The name will be written with the next sans serif font: <image> Output Print 'YES' (without the quotes), if the given name matches its mirror reflection. Otherwise, print 'NO' (without the quotes). Examples Input AHA Output YES Input Z Output NO Input XO Output NO Submitted Solution: ``` import string def is_palindrome(s): for i in range(len(s) // 2): k = len(s) - 1 - i if s[i] != s[k]: return False return True # def main_function(): s = input() is_answer_found = False mirror_letter = ['B', 'C', 'D', 'E', 'F', 'G', 'J', 'K', 'L', 'N', 'P', 'Q', 'R', 'S', 'Z'] hash_table = [0 for i in range(150)] if not is_palindrome(s): print("NO") else: for i in s: hash_table[ord(i)] += 1 for i in range(len(mirror_letter)): order = ord(mirror_letter[i]) if hash_table[order] != 0: print("NO") is_answer_found = True break if not is_answer_found: print("YES") # # # # main_function() ``` Yes
8,651
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it? The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out the name of the company on a piece of paper in a line (horizontally, from left to right) with large English letters, then put this piece of paper in front of the mirror, then the reflection of the name in the mirror should perfectly match the line written on the piece of paper. There are many suggestions for the company name, so coming up to the mirror with a piece of paper for each name wouldn't be sensible. The founders of the company decided to automatize this process. They asked you to write a program that can, given a word, determine whether the word is a 'mirror' word or not. Input The first line contains a non-empty name that needs to be checked. The name contains at most 105 large English letters. The name will be written with the next sans serif font: <image> Output Print 'YES' (without the quotes), if the given name matches its mirror reflection. Otherwise, print 'NO' (without the quotes). Examples Input AHA Output YES Input Z Output NO Input XO Output NO Submitted Solution: ``` def main(): name = input() s = ('B', 'C', 'D', 'E', 'F', 'G', 'J', 'K', 'L', 'N', 'P', 'Q', 'R', 'S', 'Z') for ch in s: if ch in name: print('NO') return if name[:len(name) // 2] != name[::-1][:len(name) // 2]: print('NO') return print('YES') main() ``` Yes
8,652
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it? The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out the name of the company on a piece of paper in a line (horizontally, from left to right) with large English letters, then put this piece of paper in front of the mirror, then the reflection of the name in the mirror should perfectly match the line written on the piece of paper. There are many suggestions for the company name, so coming up to the mirror with a piece of paper for each name wouldn't be sensible. The founders of the company decided to automatize this process. They asked you to write a program that can, given a word, determine whether the word is a 'mirror' word or not. Input The first line contains a non-empty name that needs to be checked. The name contains at most 105 large English letters. The name will be written with the next sans serif font: <image> Output Print 'YES' (without the quotes), if the given name matches its mirror reflection. Otherwise, print 'NO' (without the quotes). Examples Input AHA Output YES Input Z Output NO Input XO Output NO Submitted Solution: ``` def isPalindrome(s): return(s == s[::-1]) s=input() l=['A','H','I','M','O','T','U','V','W','X','Y'] bool=[1 for i in s if i not in l] if isPalindrome(s) and len(bool)==0: print("YES") else: print("NO") ``` Yes
8,653
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it? The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out the name of the company on a piece of paper in a line (horizontally, from left to right) with large English letters, then put this piece of paper in front of the mirror, then the reflection of the name in the mirror should perfectly match the line written on the piece of paper. There are many suggestions for the company name, so coming up to the mirror with a piece of paper for each name wouldn't be sensible. The founders of the company decided to automatize this process. They asked you to write a program that can, given a word, determine whether the word is a 'mirror' word or not. Input The first line contains a non-empty name that needs to be checked. The name contains at most 105 large English letters. The name will be written with the next sans serif font: <image> Output Print 'YES' (without the quotes), if the given name matches its mirror reflection. Otherwise, print 'NO' (without the quotes). Examples Input AHA Output YES Input Z Output NO Input XO Output NO Submitted Solution: ``` import sys a = input() b = "".join(reversed(a)) if "H" in a or "A" in a or "U" in a or "V" in a or "W" in a or "X" in a or "I" in a or "T" in a or "M" in a or "Y" in a: if "B" not in a and "C" not in a and "D" not in a and "E" not in a and "F" not in a and "G" not in a and "J" not in a and "K" not in a and "L" not in a and "N" not in a and "P" not in a and "Q" not in a and "R" not in a and "S" not in a and "Z" not in a: if a == b: print("YES") sys.exit() print("NO") ``` No
8,654
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it? The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out the name of the company on a piece of paper in a line (horizontally, from left to right) with large English letters, then put this piece of paper in front of the mirror, then the reflection of the name in the mirror should perfectly match the line written on the piece of paper. There are many suggestions for the company name, so coming up to the mirror with a piece of paper for each name wouldn't be sensible. The founders of the company decided to automatize this process. They asked you to write a program that can, given a word, determine whether the word is a 'mirror' word or not. Input The first line contains a non-empty name that needs to be checked. The name contains at most 105 large English letters. The name will be written with the next sans serif font: <image> Output Print 'YES' (without the quotes), if the given name matches its mirror reflection. Otherwise, print 'NO' (without the quotes). Examples Input AHA Output YES Input Z Output NO Input XO Output NO Submitted Solution: ``` x = input() array1=[] array2=[] for i in x: array1.append(i) array2.append(i) array2.reverse() if (array1==array2) and (len(x)>1):print('YES') else:print('NO') # ``` No
8,655
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it? The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out the name of the company on a piece of paper in a line (horizontally, from left to right) with large English letters, then put this piece of paper in front of the mirror, then the reflection of the name in the mirror should perfectly match the line written on the piece of paper. There are many suggestions for the company name, so coming up to the mirror with a piece of paper for each name wouldn't be sensible. The founders of the company decided to automatize this process. They asked you to write a program that can, given a word, determine whether the word is a 'mirror' word or not. Input The first line contains a non-empty name that needs to be checked. The name contains at most 105 large English letters. The name will be written with the next sans serif font: <image> Output Print 'YES' (without the quotes), if the given name matches its mirror reflection. Otherwise, print 'NO' (without the quotes). Examples Input AHA Output YES Input Z Output NO Input XO Output NO Submitted Solution: ``` import sys import math st = sys.stdin.readline() l = len(st) - 1 dct = {'A' : 1, 'B': 0, 'C': 0, 'D': 0, 'E': 0, 'F': 0, 'G': 0, 'H': 1, 'I': 1, 'J': 0, 'K': 0, 'L': 0, 'M': 1, 'N': 0, 'O': 1, 'P': 0, 'Q': 0, 'R': 0, 'S': 1, 'T': 1, 'U': 1, 'V': 1, 'W': 1, 'X': 1, 'Y': 1, 'Z': 0 } if(l == 1 and dct[st[0]] == 0): print("NO") exit() j = l for i in range(int(l / 2)): if(st[i] != st[j - 1] or dct[st[i]] == 0): print("NO") exit() j -= 1 print("YES") ``` No
8,656
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it? The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out the name of the company on a piece of paper in a line (horizontally, from left to right) with large English letters, then put this piece of paper in front of the mirror, then the reflection of the name in the mirror should perfectly match the line written on the piece of paper. There are many suggestions for the company name, so coming up to the mirror with a piece of paper for each name wouldn't be sensible. The founders of the company decided to automatize this process. They asked you to write a program that can, given a word, determine whether the word is a 'mirror' word or not. Input The first line contains a non-empty name that needs to be checked. The name contains at most 105 large English letters. The name will be written with the next sans serif font: <image> Output Print 'YES' (without the quotes), if the given name matches its mirror reflection. Otherwise, print 'NO' (without the quotes). Examples Input AHA Output YES Input Z Output NO Input XO Output NO Submitted Solution: ``` s = input() t = ['B', 'C', 'Z', 'Q', 'E', 'R', 'P', 'L', 'K', 'J', 'G', 'F', 'D', 'S', 'N'] k = 0 for i in range(len(s)): if s[i] in t: k+=1 print("YES" if k==0 else "NO") ``` No
8,657
Provide tags and a correct Python 3 solution for this coding contest problem. Peter wrote on the board a strictly increasing sequence of positive integers a1, a2, ..., an. Then Vasil replaced some digits in the numbers of this sequence by question marks. Thus, each question mark corresponds to exactly one lost digit. Restore the the original sequence knowing digits remaining on the board. Input The first line of the input contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. Next n lines contain one element of the sequence each. Each element consists only of digits and question marks. No element starts from digit 0. Each element has length from 1 to 8 characters, inclusive. Output If the answer exists, print in the first line "YES" (without the quotes). Next n lines must contain the sequence of positive integers β€” a possible variant of Peter's sequence. The found sequence must be strictly increasing, it must be transformed from the given one by replacing each question mark by a single digit. All numbers on the resulting sequence must be written without leading zeroes. If there are multiple solutions, print any of them. If there is no answer, print a single line "NO" (without the quotes). Examples Input 3 ? 18 1? Output YES 1 18 19 Input 2 ?? ? Output NO Input 5 12224 12??5 12226 ?0000 ?00000 Output YES 12224 12225 12226 20000 100000 Tags: binary search, brute force, greedy, implementation Correct Solution: ``` def solve(s, t, i, l): if i == l: return False if s[i] == "?": if solve(s, t, i + 1, l): s[i] = t[i] return True elif t[i] == "9": return False s[i] = nxt[t[i]] for j in range(i, l): if s[j] == "?": s[j] = "0" return True elif s[i] > t[i]: for j in range(i, l): if s[j] == "?": s[j] = "0" return True elif s[i] < t[i]: return False else: return solve(s, t, i + 1, l) n = int(input()) a = [list(input()) for _ in range(n)] p = ["0"] nxt = {str(x): str(x + 1) for x in range(9)} for i, ai in enumerate(a): if len(p) > len(ai): print("NO") break if len(p) < len(ai): if a[i][0] == "?": a[i][0] = "1" for j in range(len(ai)): if a[i][j] == "?": a[i][j] = "0" elif not solve(a[i], p, 0, len(ai)): print("NO") break p = a[i] else: print("YES") print("\n".join("".join(line) for line in a)) ```
8,658
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Peter wrote on the board a strictly increasing sequence of positive integers a1, a2, ..., an. Then Vasil replaced some digits in the numbers of this sequence by question marks. Thus, each question mark corresponds to exactly one lost digit. Restore the the original sequence knowing digits remaining on the board. Input The first line of the input contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. Next n lines contain one element of the sequence each. Each element consists only of digits and question marks. No element starts from digit 0. Each element has length from 1 to 8 characters, inclusive. Output If the answer exists, print in the first line "YES" (without the quotes). Next n lines must contain the sequence of positive integers β€” a possible variant of Peter's sequence. The found sequence must be strictly increasing, it must be transformed from the given one by replacing each question mark by a single digit. All numbers on the resulting sequence must be written without leading zeroes. If there are multiple solutions, print any of them. If there is no answer, print a single line "NO" (without the quotes). Examples Input 3 ? 18 1? Output YES 1 18 19 Input 2 ?? ? Output NO Input 5 12224 12??5 12226 ?0000 ?00000 Output YES 12224 12225 12226 20000 100000 Submitted Solution: ``` def restore_seq(num_list): result = [] flag = False for i in range(len(num_list)): if '?' not in num_list[i]: if num_list[i] > num_list[i-1]: result.append(num_list[i]) continue else: return False this_string = num_list[i] list_format = [] for c in num_list[i]: list_format.append(c) if i == 0: # if it is the first number, just make a at least as possible for j in range(len(num_list[0])): if j == 0 and this_string[j] == '?': list_format[j] = '1' else: if this_string[j] == '?': list_format[j] = '0' else: list_format[j] = this_string[j] result.append(''.join(list_format)) continue else: # if current num's length is shorter than previous one, simple # False last_string = result[i-1] if len(this_string) < len(last_string): return False # if current num's length's longer, set every ? smallerst: elif len(this_string) > len(last_string): for k in range(len(this_string)): if k == 0 and this_string[k] == '?': list_format[k] = '1' else: if this_string[k] == '?': list_format[k] = '0' else: list_format[k] = this_string[k] result.append(''.join(list_format)) continue else: # if the current number's length equals with previous one maxpossible = '' for index in range(len(this_string)): if this_string[index] == '?': maxpossible += '9' else: maxpossible += this_string[index] if int(maxpossible) <= int(last_string): return False # turn list_format's ? to be same with last string for m in range(len(this_string)): if this_string[m] == '?': list_format[m] = last_string[m] minpossible = '' for index in range(len(this_string)): if index == 0 and this_string[index] == '?': minpossible += '1' elif this_string[index] == '?': minpossible += '0' else: minpossible += this_string[index] if int(minpossible) > int(last_string): result.append(minpossible) continue # if list_format is same as last string, then plus 1 to the first ? which is not 9 # and turn ? behind to 0 if ''.join(list_format) == last_string: for index in range(len(this_string)-1, -1, -1): if this_string[index] == '?' and list_format[index] != '9': list_format[index] = str(int(list_format[index])+1) break for the_index in range(index+1, len(this_string)): if this_string[the_index] == '?': list_format[the_index] = '0' result.append(''.join(list_format)) continue ##################################################################### for index in range(len(list_format)): if list_format[index] == last_string[index]: continue elif int(list_format[index]) < int(last_string[index]): for the_index in range(index-1, -1, -1): if this_string[the_index] == '?' and list_format[the_index] != '9': list_format[the_index] = str( int(list_format[the_index])+1) break for z in range(the_index+1, len(this_string)): if this_string[z] == '?': list_format[z] = '0' result.append(''.join(list_format)) break else: for the_index in range(index+1, len(this_string)): if this_string[the_index] == '?': list_format[the_index] = '0' result.append(''.join(list_format)) break return result ################################################ num_list = [] n = int(input()) for i in range(n): num_list.append(input()) result = restore_seq(num_list) if result: print('YES') for item in result: print(item) else: print('NO') ``` No
8,659
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Peter wrote on the board a strictly increasing sequence of positive integers a1, a2, ..., an. Then Vasil replaced some digits in the numbers of this sequence by question marks. Thus, each question mark corresponds to exactly one lost digit. Restore the the original sequence knowing digits remaining on the board. Input The first line of the input contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. Next n lines contain one element of the sequence each. Each element consists only of digits and question marks. No element starts from digit 0. Each element has length from 1 to 8 characters, inclusive. Output If the answer exists, print in the first line "YES" (without the quotes). Next n lines must contain the sequence of positive integers β€” a possible variant of Peter's sequence. The found sequence must be strictly increasing, it must be transformed from the given one by replacing each question mark by a single digit. All numbers on the resulting sequence must be written without leading zeroes. If there are multiple solutions, print any of them. If there is no answer, print a single line "NO" (without the quotes). Examples Input 3 ? 18 1? Output YES 1 18 19 Input 2 ?? ? Output NO Input 5 12224 12??5 12226 ?0000 ?00000 Output YES 12224 12225 12226 20000 100000 Submitted Solution: ``` count = int(input()) nprev = 0 sprev = "0" ans = list() trouble = False for num in range(count): s = input() incr = 0 if len(s) < len(sprev): incr = 1 elif len(s) > len(sprev): n = 0 for i in range(len(s)): if s[i] == "?": if i == 0: n = 1 else: n *= 10 else: n *= 10 n += int(s[i]) else: n = 0 nprev += 1 sprev = str(nprev) k10 = 1 incr = 0 for i in range(len(s)-1, -1, -1): if s[i] == "?": if incr == 0: n += int(sprev[i]) * k10 k10 *= 10 else: if sprev[i] < '9': n += (int(sprev[i]) + 1) * k10 k10 *= 10 incr = 0 else: k10 *= 10 else: if s[i] < sprev[i]: incr = 1 n += int(s[i]) * k10 k10 *= 10 if incr == 1: print("NO") trouble = True break else: ans.append(n) nprev = n sprev = str(n) if not trouble: print("YES") for n in ans: print(n) ``` No
8,660
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Peter wrote on the board a strictly increasing sequence of positive integers a1, a2, ..., an. Then Vasil replaced some digits in the numbers of this sequence by question marks. Thus, each question mark corresponds to exactly one lost digit. Restore the the original sequence knowing digits remaining on the board. Input The first line of the input contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. Next n lines contain one element of the sequence each. Each element consists only of digits and question marks. No element starts from digit 0. Each element has length from 1 to 8 characters, inclusive. Output If the answer exists, print in the first line "YES" (without the quotes). Next n lines must contain the sequence of positive integers β€” a possible variant of Peter's sequence. The found sequence must be strictly increasing, it must be transformed from the given one by replacing each question mark by a single digit. All numbers on the resulting sequence must be written without leading zeroes. If there are multiple solutions, print any of them. If there is no answer, print a single line "NO" (without the quotes). Examples Input 3 ? 18 1? Output YES 1 18 19 Input 2 ?? ? Output NO Input 5 12224 12??5 12226 ?0000 ?00000 Output YES 12224 12225 12226 20000 100000 Submitted Solution: ``` n = int(input()) ni = [input() for i in range(n)] miss = 0 if ni[0].find("?") != -1: ni[0] = ni[0][0].replace("?","1")+ni[0][1:].replace("?","0") ni[0]=int(ni[0]) for num in range(1,n): lol = ni[num].find("?") lol1 = ni[num].rfind("?") if lol != -1: if len(ni[num])==len(str(ni[num-1])): if (str(ni[num][:lol])>str(ni[num-1])[:lol] or str(ni[num][lol1+1:])>str(ni[num-1])[lol1+1:]): ni[num] = (str(ni[num])[:lol]+str(ni[num-1])[lol:lol1+1] +str(ni[num])[lol1+1:]) else: if len(str(int(str(ni[num-1])[lol1:lol1+1])+1))==1: ni[num] = (str(ni[num])[:lol]+str(ni[num-1])[lol:lol1]+ str(int(str(ni[num-1])[lol1:lol1+1])+1)+str(ni[num])[lol1+1:]) else: miss = 0 break elif len(ni[num]) > len(str(ni[num-1])): ni[num] = ni[num][0].replace("?","1")+ni[num][1:].replace("?","0") else: miss = 1 break ni[num] = int(ni[num]) if ni[num-1] >= ni[num]: miss = 1 break if miss == 1: print("NO") else: print("YES") for num in range(n): print(ni[num]) ``` No
8,661
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Peter wrote on the board a strictly increasing sequence of positive integers a1, a2, ..., an. Then Vasil replaced some digits in the numbers of this sequence by question marks. Thus, each question mark corresponds to exactly one lost digit. Restore the the original sequence knowing digits remaining on the board. Input The first line of the input contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. Next n lines contain one element of the sequence each. Each element consists only of digits and question marks. No element starts from digit 0. Each element has length from 1 to 8 characters, inclusive. Output If the answer exists, print in the first line "YES" (without the quotes). Next n lines must contain the sequence of positive integers β€” a possible variant of Peter's sequence. The found sequence must be strictly increasing, it must be transformed from the given one by replacing each question mark by a single digit. All numbers on the resulting sequence must be written without leading zeroes. If there are multiple solutions, print any of them. If there is no answer, print a single line "NO" (without the quotes). Examples Input 3 ? 18 1? Output YES 1 18 19 Input 2 ?? ? Output NO Input 5 12224 12??5 12226 ?0000 ?00000 Output YES 12224 12225 12226 20000 100000 Submitted Solution: ``` length = int(input()) number_list = [] for _ in range(length): number = input() number_list.append(number) for i in range(len(number_list[0])): if number_list[0][i] == "?": if i == 0: number_list[0] = "1" + number_list[0][i+1:] else: number_list[0] = number_list[0][:i] + "0" +number_list[0][i+1:] answer = "YES" for current in range(1,length): prev = current - 1 if len(number_list[current])<len(number_list[prev]): answer = "NO" print ("NO") break elif len(number_list[current])>len(number_list[prev]): for i in range(len(number_list[current])): if (number_list[current][i] == "?"): if i == 0: number_list[current] = "1" + number_list[current][i+1:] else: number_list[current] = number_list[current][:i]+"0"+number_list[current][i+1:] elif len(number_list[current])==len(number_list[prev]): position = -1 for i in range(len(number_list[current])): if position == -1 and number_list[prev][i]>number_list[current][i]: answer="NO" print("NO") break elif number_list[current][i] > number_list[prev][i]: position = i if answer == "YES": for i in range(len(number_list[current])): if i < position and number_list[current][i] == "?": if number_list[current][:i] > number_list[prev][:i]: number_list[current] = number_list[current][:i]+"0"+number_list[current][i+1:] else: number_list[current] = number_list[current][:i] +number_list[prev][i] + number_list[current][i + 1:] elif i>position and number_list[current][i] == "?": number_list[current] = number_list[current][:i] +"0"+ number_list[current][i+1:] elif i==position and number_list[current][i]=="?": number_list[current] = number_list[current][:i] + str(min(int(number_list[prev][i])+1,9))+ number_list[current][i + 1:] if answer == "YES": print("YES") for item in number_list: print(int(item)) ``` No
8,662
Provide tags and a correct Python 3 solution for this coding contest problem. When Darth Vader gets bored, he sits down on the sofa, closes his eyes and thinks of an infinite rooted tree where each node has exactly n sons, at that for each node, the distance between it an its i-th left child equals to di. The Sith Lord loves counting the number of nodes in the tree that are at a distance at most x from the root. The distance is the sum of the lengths of edges on the path between nodes. But he has got used to this activity and even grew bored of it. 'Why does he do that, then?' β€” you may ask. It's just that he feels superior knowing that only he can solve this problem. Do you want to challenge Darth Vader himself? Count the required number of nodes. As the answer can be rather large, find it modulo 109 + 7. Input The first line contains two space-separated integers n and x (1 ≀ n ≀ 105, 0 ≀ x ≀ 109) β€” the number of children of each node and the distance from the root within the range of which you need to count the nodes. The next line contains n space-separated integers di (1 ≀ di ≀ 100) β€” the length of the edge that connects each node with its i-th child. Output Print a single number β€” the number of vertexes in the tree at distance from the root equal to at most x. Examples Input 3 3 1 2 3 Output 8 Note Pictures to the sample (the yellow color marks the nodes the distance to which is at most three) <image> Tags: dp, matrices Correct Solution: ``` # fast io from sys import stdin _data = iter(stdin.read().split('\n')) input = lambda: next(_data) N = 101 MOD = 1000000007 def mul_vec_mat(v, a): c = [0] * N for i in range(N): c[i] = sum(a[j][i] * v[j] % MOD for j in range(N)) % MOD return c def mul_vec_sparse_mat(v, a): c = [0] * N for i in range(N): c[i] = sum(x * v[j] % MOD for j, x in a[i]) % MOD return c _, x = [int(v) for v in input().split()] a = [[0] * N for i in range(N)] a[0][0] = 1 a[N - 1][0] = 1 for i in range(1, N - 1): a[i][i + 1] = 1 for d in map(int, input().split()): a[N - 1][N - d] += 1 sa = [[] for i in range(N)] for i in range(N): for j in range(N): if a[i][j] != 0: sa[j].append((i, a[i][j])) r = [[1 if i == j else 0 for j in range(N)] for i in range(N)] while x > 0: if x & 1: r[0] = mul_vec_mat(r[0], a) r[1] = mul_vec_mat(r[1], a) aa = [[0] * N for i in range(N)] aa[0] = mul_vec_mat(a[0], a) aa[1] = mul_vec_mat(a[1], a) for i in range(2, N): aa[i] = mul_vec_sparse_mat(aa[i - 1], sa) a = aa x >>= 1 for i in range(2, N): r[i] = mul_vec_sparse_mat(r[i - 1], sa) b = [0] * N b[0] = 1 b[N - 1] = 1 print(sum(r[N - 1][i] * b[i] % MOD for i in range(N)) % MOD) ```
8,663
Provide tags and a correct Python 3 solution for this coding contest problem. When Darth Vader gets bored, he sits down on the sofa, closes his eyes and thinks of an infinite rooted tree where each node has exactly n sons, at that for each node, the distance between it an its i-th left child equals to di. The Sith Lord loves counting the number of nodes in the tree that are at a distance at most x from the root. The distance is the sum of the lengths of edges on the path between nodes. But he has got used to this activity and even grew bored of it. 'Why does he do that, then?' β€” you may ask. It's just that he feels superior knowing that only he can solve this problem. Do you want to challenge Darth Vader himself? Count the required number of nodes. As the answer can be rather large, find it modulo 109 + 7. Input The first line contains two space-separated integers n and x (1 ≀ n ≀ 105, 0 ≀ x ≀ 109) β€” the number of children of each node and the distance from the root within the range of which you need to count the nodes. The next line contains n space-separated integers di (1 ≀ di ≀ 100) β€” the length of the edge that connects each node with its i-th child. Output Print a single number β€” the number of vertexes in the tree at distance from the root equal to at most x. Examples Input 3 3 1 2 3 Output 8 Note Pictures to the sample (the yellow color marks the nodes the distance to which is at most three) <image> Tags: dp, matrices Correct Solution: ``` # fast io from sys import stdin _data = iter(stdin.read().split('\n')) input = lambda: next(_data) N = 101 MOD = 1000000007 def mul_vec_mat(v, a): n = len(a[0]) m = len(v) c = [0] * n for i in range(n): c[i] = sum(a[j][i] * v[j] % MOD for j in range(m)) % MOD return c def mul_vec_sparse_mat(v, ta): n = len(ta) c = [0] * n for i in range(n): c[i] = sum(x * v[j] % MOD for j, x in ta[i]) % MOD return c def mod_pow_kitamasa(a, x): n = len(a) # sparse matrix of a^T ta = [[] for i in range(n)] for i in range(n): for j in range(n): if a[i][j] != 0: ta[j].append((i, a[i][j])) r = [[1 if i == j else 0 for j in range(n)] for i in range(n)] while x > 0: if x & 1: r[1] = mul_vec_mat(r[1], a) aa = [[0] * n for i in range(n)] aa[0] = a[0] aa[1] = mul_vec_mat(a[1], a) for i in range(2, n): aa[i] = mul_vec_sparse_mat(aa[i - 1], ta) a = aa x >>= 1 for i in range(2, n): r[i] = mul_vec_sparse_mat(r[i - 1], ta) return r _, x = [int(v) for v in input().split()] a = [[0] * N for i in range(N)] a[0][0] = 1 a[N - 1][0] = 1 for i in range(1, N - 1): a[i][i + 1] = 1 for d in map(int, input().split()): a[N - 1][N - d] += 1 a = mod_pow_kitamasa(a, x) b = [0] * N b[0] = 1 b[N - 1] = 1 print(sum(a[N - 1][i] * b[i] % MOD for i in range(N)) % MOD) ```
8,664
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. When Darth Vader gets bored, he sits down on the sofa, closes his eyes and thinks of an infinite rooted tree where each node has exactly n sons, at that for each node, the distance between it an its i-th left child equals to di. The Sith Lord loves counting the number of nodes in the tree that are at a distance at most x from the root. The distance is the sum of the lengths of edges on the path between nodes. But he has got used to this activity and even grew bored of it. 'Why does he do that, then?' β€” you may ask. It's just that he feels superior knowing that only he can solve this problem. Do you want to challenge Darth Vader himself? Count the required number of nodes. As the answer can be rather large, find it modulo 109 + 7. Input The first line contains two space-separated integers n and x (1 ≀ n ≀ 105, 0 ≀ x ≀ 109) β€” the number of children of each node and the distance from the root within the range of which you need to count the nodes. The next line contains n space-separated integers di (1 ≀ di ≀ 100) β€” the length of the edge that connects each node with its i-th child. Output Print a single number β€” the number of vertexes in the tree at distance from the root equal to at most x. Examples Input 3 3 1 2 3 Output 8 Note Pictures to the sample (the yellow color marks the nodes the distance to which is at most three) <image> Submitted Solution: ``` # fast io from sys import stdin _data = iter(stdin.read().split('\n')) input = lambda: next(_data) N = 101 MOD = 1000000007 c = [[0] * N for i in range(N)] def mod_mul(a, b): for i in range(N): for j in range(N): c[i][j] = 0 for i in range(N): for k in range(N): for j in range(N): c[i][j] = (c[i][j] + a[i][k] * b[k][j]) % MOD return c _, x = [int(v) for v in input().split()] a = [[0] * N for i in range(N)] a[0][N - 1] = 1 a[N - 1][N - 1] = 1 for d in map(int, input().split()): a[0][d - 1] += 1 for i in range(1, N - 1): a[i][i - 1] = 1 b = [0 for i in range(N)] b[0] = 1 b[N - 1] = 1 r = [[1 if i == j else 0 for j in range(N)] for i in range(N)] while x > 0: if x & 1: r, c = mod_mul(a, r), r a, c = mod_mul(a, a), a x >>= 1 c = [0] * N for i in range(N): for j in range(N): c[i] = (c[i] + a[i][j] * b[j]) % MOD print(c[0]) ``` No
8,665
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. When Darth Vader gets bored, he sits down on the sofa, closes his eyes and thinks of an infinite rooted tree where each node has exactly n sons, at that for each node, the distance between it an its i-th left child equals to di. The Sith Lord loves counting the number of nodes in the tree that are at a distance at most x from the root. The distance is the sum of the lengths of edges on the path between nodes. But he has got used to this activity and even grew bored of it. 'Why does he do that, then?' β€” you may ask. It's just that he feels superior knowing that only he can solve this problem. Do you want to challenge Darth Vader himself? Count the required number of nodes. As the answer can be rather large, find it modulo 109 + 7. Input The first line contains two space-separated integers n and x (1 ≀ n ≀ 105, 0 ≀ x ≀ 109) β€” the number of children of each node and the distance from the root within the range of which you need to count the nodes. The next line contains n space-separated integers di (1 ≀ di ≀ 100) β€” the length of the edge that connects each node with its i-th child. Output Print a single number β€” the number of vertexes in the tree at distance from the root equal to at most x. Examples Input 3 3 1 2 3 Output 8 Note Pictures to the sample (the yellow color marks the nodes the distance to which is at most three) <image> Submitted Solution: ``` # fast io from sys import stdin _data = iter(stdin.read().split('\n')) input = lambda: next(_data) N = 101 MOD = 1000000007 def mul_vec_mat(v, a): n = len(a[0]) m = len(v) c = [0] * n for i in range(n): c[i] = sum(a[j][i] * v[j] % MOD for j in range(m)) % MOD return c def mul_vec_sparse_mat(v, ta): n = len(ta) c = [0] * n for i in range(n): c[i] = sum(x * v[j] % MOD for j, x in ta[i]) % MOD return c def mod_pow_kitamasa(a, x): n = len(a) # sparse matrix of a^T ta = [[] for i in range(n)] for i in range(n): for j in range(n): if a[i][j] != 0: ta[j].append((i, a[i][j])) r = [[1 if i == j else 0 for j in range(n)] for i in range(n)] while x > 0: if x & 1: r[1] = mul_vec_mat(r[1], a) aa = [[0] * n for i in range(n)] aa[1] = mul_vec_mat(a[1], a) for i in range(2, n): aa[i] = mul_vec_sparse_mat(aa[i - 1], ta) a = aa x >>= 1 for i in range(2, n): r[i] = mul_vec_sparse_mat(r[i - 1], ta) return r _, x = [int(v) for v in input().split()] a = [[0] * N for i in range(N)] a[0][0] = 1 a[N - 1][0] = 1 for i in range(1, N - 1): a[i][i + 1] = 1 for d in map(int, input().split()): a[N - 1][N - d] += 1 a = mod_pow_kitamasa(a, x) b = [0] * N b[0] = 1 b[N - 1] = 1 print(sum(a[N - 1][i] * b[i] % MOD for i in range(N)) % MOD) ``` No
8,666
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ivan Anatolyevich's agency is starting to become famous in the town. They have already ordered and made n TV commercial videos. Each video is made in a special way: the colors and the soundtrack are adjusted to the time of the day and the viewers' mood. That's why the i-th video can only be shown within the time range of [li, ri] (it is not necessary to use the whole segment but the broadcast time should be within this segment). Now it's time to choose a TV channel to broadcast the commercial. Overall, there are m TV channels broadcasting in the city, the j-th one has cj viewers, and is ready to sell time [aj, bj] to broadcast the commercial. Ivan Anatolyevich is facing a hard choice: he has to choose exactly one video i and exactly one TV channel j to broadcast this video and also a time range to broadcast [x, y]. At that the time range should be chosen so that it is both within range [li, ri] and within range [aj, bj]. Let's define the efficiency of the broadcast as value (y - x)Β·cj β€” the total sum of time that all the viewers of the TV channel are going to spend watching the commercial. Help Ivan Anatolyevich choose the broadcast with the maximum efficiency! Input The first line contains two integers n and m (1 ≀ n, m ≀ 2Β·105) β€” the number of commercial videos and channels, respectively. Each of the following n lines contains two integers li, ri (0 ≀ li ≀ ri ≀ 109) β€” the segment of time when it is possible to show the corresponding video. Each of the following m lines contains three integers aj, bj, cj (0 ≀ aj ≀ bj ≀ 109, 1 ≀ cj ≀ 109), characterizing the TV channel. Output In the first line print an integer β€” the maximum possible efficiency of the broadcast. If there is no correct way to get a strictly positive efficiency, print a zero. If the maximum efficiency is strictly positive, in the second line also print the number of the video i (1 ≀ i ≀ n) and the number of the TV channel j (1 ≀ j ≀ m) in the most effective broadcast. If there are multiple optimal answers, you can print any of them. Examples Input 2 3 7 9 1 4 2 8 2 0 4 1 8 9 3 Output 4 2 1 Input 1 1 0 0 1 1 10 Output 0 Note In the first sample test the most optimal solution is to show the second commercial using the first TV channel at time [2, 4]. The efficiency of such solution is equal to (4 - 2)Β·2 = 4. In the second sample test Ivan Anatolievich's wish does not meet the options of the TV channel, the segments do not intersect, so the answer is zero. Submitted Solution: ``` def intersect(a, b, c, d): if c < a and d > b: return b - a elif c < a: return d - a else: if d > b: return b - c else: return d - c class CodeforcesTask542ASolution: def __init__(self): self.result = '' self.n_m = [] self.videos = [] def read_input(self): self.n_m = [int(x) for x in input().split(" ")] for x in range(self.n_m[0]): self.videos.append([int(y) for y in input().split(" ")]) def process_task(self): eff = [0 for x in range(self.n_m[0])] st = [0 for x in range(self.n_m[0])] for x in range(self.n_m[1]): channel = [int(y) for y in input().split(" ")] neff = [intersect(*v, *channel[:2])*channel[2] for v in self.videos] #eff = [max(eff[x], neff[x]) for x in range(self.n_m[0])] for x in range(self.n_m[0]): if neff[x] > eff[x]: eff[x] = neff[x] st[x] = x + 1 max_eff = max(eff) max_vid = eff.index(max_eff) + 1 max_st = st[max_vid - 1] if max_eff > 0: self.result = "{0}\n{1} {2}".format(max_eff, max_vid, max_st) else: self.result = "0" def get_result(self): return self.result if __name__ == "__main__": Solution = CodeforcesTask542ASolution() Solution.read_input() Solution.process_task() print(Solution.get_result()) ``` No
8,667
Provide tags and a correct Python 3 solution for this coding contest problem. Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything. During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering. You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. Input The first line contains a single integer n β€” the number of items (1 ≀ n ≀ 105). The second line contains n numbers a1, a2, ..., an (1 ≀ ai ≀ 105) β€” the initial inventory numbers of the items. Output Print n numbers β€” the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. Examples Input 3 1 3 2 Output 1 3 2 Input 4 2 2 3 3 Output 2 1 3 4 Input 1 2 Output 1 Note In the first test the numeration is already a permutation, so there is no need to change anything. In the second test there are two pairs of equal numbers, in each pair you need to replace one number. In the third test you need to replace 2 by 1, as the numbering should start from one. Tags: greedy, math Correct Solution: ``` from collections import Counter n = int(input()) c = list(map(int, input().split())) count = Counter(c) unused = list(set(range(1, n+1)) - set(count.keys())) for i in range(n): if count[c[i]] > 1 or c[i] > n or c[i] <= 0: count[c[i]] -= 1 c[i] = unused.pop() print(" ".join(map(str, c))) ```
8,668
Provide tags and a correct Python 3 solution for this coding contest problem. Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything. During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering. You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. Input The first line contains a single integer n β€” the number of items (1 ≀ n ≀ 105). The second line contains n numbers a1, a2, ..., an (1 ≀ ai ≀ 105) β€” the initial inventory numbers of the items. Output Print n numbers β€” the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. Examples Input 3 1 3 2 Output 1 3 2 Input 4 2 2 3 3 Output 2 1 3 4 Input 1 2 Output 1 Note In the first test the numeration is already a permutation, so there is no need to change anything. In the second test there are two pairs of equal numbers, in each pair you need to replace one number. In the third test you need to replace 2 by 1, as the numbering should start from one. Tags: greedy, math Correct Solution: ``` n = int(input()) pin = input().split(" ") arr = [int(i)-1 for i in pin] free = [True]*n change = [] for i in range(n): if arr[i] <n: if free[arr[i]]: free[arr[i]] = False else: change.append(i) else: change.append(i) for i in range (n): if free[i]: arr[change.pop()] = i for i in arr: print (i+1, end=" ") ```
8,669
Provide tags and a correct Python 3 solution for this coding contest problem. Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything. During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering. You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. Input The first line contains a single integer n β€” the number of items (1 ≀ n ≀ 105). The second line contains n numbers a1, a2, ..., an (1 ≀ ai ≀ 105) β€” the initial inventory numbers of the items. Output Print n numbers β€” the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. Examples Input 3 1 3 2 Output 1 3 2 Input 4 2 2 3 3 Output 2 1 3 4 Input 1 2 Output 1 Note In the first test the numeration is already a permutation, so there is no need to change anything. In the second test there are two pairs of equal numbers, in each pair you need to replace one number. In the third test you need to replace 2 by 1, as the numbering should start from one. Tags: greedy, math Correct Solution: ``` import queue n= int(input()) mas = list(map(int,input().split(" "))) s=set([i for i in range(1,n+1)]) di=queue.Queue() bo=0 for i in range(n): if (mas[i] in s): s.remove(mas[i]) else: di.put(i) for i in s: mas[di.get()]=i print(' '.join(list(map(str,mas)))) ```
8,670
Provide tags and a correct Python 3 solution for this coding contest problem. Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything. During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering. You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. Input The first line contains a single integer n β€” the number of items (1 ≀ n ≀ 105). The second line contains n numbers a1, a2, ..., an (1 ≀ ai ≀ 105) β€” the initial inventory numbers of the items. Output Print n numbers β€” the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. Examples Input 3 1 3 2 Output 1 3 2 Input 4 2 2 3 3 Output 2 1 3 4 Input 1 2 Output 1 Note In the first test the numeration is already a permutation, so there is no need to change anything. In the second test there are two pairs of equal numbers, in each pair you need to replace one number. In the third test you need to replace 2 by 1, as the numbering should start from one. Tags: greedy, math Correct Solution: ``` import sys #sys.stdin = open("input2","r") n = int(input()) arr = list(map(int,input().split())) #cnt = 0 #print('arr',arr) store = [0]*n for i in range(n): """count occurences """ if arr[i] > n: continue elif store[arr[i]-1] == 0: store[arr[i]-1] = 1 else: store[arr[i] - 1] += 1 #print("store",store) zero = [] for i in range(n): """count zero occurences""" if store[i] == 0: zero.append(i+1) pos = 0 p = 1 for i in range(n): if arr[i] > n: if pos < len(zero): arr[i] = zero[pos] pos += 1 else: arr[i] = p if p < n: p += 1 else: p = 1 elif store[arr[i]-1] > 1: store[arr[i]-1] -= 1 arr[i] = zero[pos] pos += 1 print(*arr,sep=' ') ```
8,671
Provide tags and a correct Python 3 solution for this coding contest problem. Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything. During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering. You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. Input The first line contains a single integer n β€” the number of items (1 ≀ n ≀ 105). The second line contains n numbers a1, a2, ..., an (1 ≀ ai ≀ 105) β€” the initial inventory numbers of the items. Output Print n numbers β€” the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. Examples Input 3 1 3 2 Output 1 3 2 Input 4 2 2 3 3 Output 2 1 3 4 Input 1 2 Output 1 Note In the first test the numeration is already a permutation, so there is no need to change anything. In the second test there are two pairs of equal numbers, in each pair you need to replace one number. In the third test you need to replace 2 by 1, as the numbering should start from one. Tags: greedy, math Correct Solution: ``` def main(): read = lambda: map(int, input().split()) n = int(input()) a = list(read()) used = [True] * (n + 1) C = {i + 1 for i in range(n)} A = {i for i in a if i <= n} B = A ^ C for i in a: if i > n or not used[i]: print(B.pop(), end = ' ') else: print(i, end = ' ') used[i] = False main() ```
8,672
Provide tags and a correct Python 3 solution for this coding contest problem. Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything. During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering. You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. Input The first line contains a single integer n β€” the number of items (1 ≀ n ≀ 105). The second line contains n numbers a1, a2, ..., an (1 ≀ ai ≀ 105) β€” the initial inventory numbers of the items. Output Print n numbers β€” the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. Examples Input 3 1 3 2 Output 1 3 2 Input 4 2 2 3 3 Output 2 1 3 4 Input 1 2 Output 1 Note In the first test the numeration is already a permutation, so there is no need to change anything. In the second test there are two pairs of equal numbers, in each pair you need to replace one number. In the third test you need to replace 2 by 1, as the numbering should start from one. Tags: greedy, math Correct Solution: ``` n = int(input()) a = list(map(int, input().split())) c = [0] * 100000 for i in range(n): c[a[i] - 1] += 1 s = [] for i in range(n): if c[i] == 0: s.append(i + 1) if not s: print(*a) exit() ans = a[:] x = 0 for i in range(n): if c[a[i] - 1] > 1 or a[i] > n: c[a[i] - 1] -= 1 ans[i] = s[x] x += 1 print(*ans) ```
8,673
Provide tags and a correct Python 3 solution for this coding contest problem. Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything. During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering. You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. Input The first line contains a single integer n β€” the number of items (1 ≀ n ≀ 105). The second line contains n numbers a1, a2, ..., an (1 ≀ ai ≀ 105) β€” the initial inventory numbers of the items. Output Print n numbers β€” the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. Examples Input 3 1 3 2 Output 1 3 2 Input 4 2 2 3 3 Output 2 1 3 4 Input 1 2 Output 1 Note In the first test the numeration is already a permutation, so there is no need to change anything. In the second test there are two pairs of equal numbers, in each pair you need to replace one number. In the third test you need to replace 2 by 1, as the numbering should start from one. Tags: greedy, math Correct Solution: ``` n = int(input()) s = list(map(int,input().split())) f = [0]*n for i in range(n): if s[i]>n: s[i]=0 else: if f[s[i]-1]==0: f[s[i]-1]=1 else: s[i]=0 a = 0 for i in range(n): if s[i]==0: while 1: if f[a]==1: a+=1 else: s[i]=a+1 a+=1 break print(' '.join(map(str,s))) ```
8,674
Provide tags and a correct Python 3 solution for this coding contest problem. Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything. During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering. You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. Input The first line contains a single integer n β€” the number of items (1 ≀ n ≀ 105). The second line contains n numbers a1, a2, ..., an (1 ≀ ai ≀ 105) β€” the initial inventory numbers of the items. Output Print n numbers β€” the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. Examples Input 3 1 3 2 Output 1 3 2 Input 4 2 2 3 3 Output 2 1 3 4 Input 1 2 Output 1 Note In the first test the numeration is already a permutation, so there is no need to change anything. In the second test there are two pairs of equal numbers, in each pair you need to replace one number. In the third test you need to replace 2 by 1, as the numbering should start from one. Tags: greedy, math Correct Solution: ``` n = int(input()) inp = list(map(int,input().split(' '))) used = set(inp) seen = set() toadd = set(i+1 for i in range(n) if i+1 not in used) res = [] for num in inp: if num < 1 or num > n or num in seen: num = toadd.pop() else: seen.add(num) res.append(num) print(*res) ```
8,675
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything. During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering. You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. Input The first line contains a single integer n β€” the number of items (1 ≀ n ≀ 105). The second line contains n numbers a1, a2, ..., an (1 ≀ ai ≀ 105) β€” the initial inventory numbers of the items. Output Print n numbers β€” the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. Examples Input 3 1 3 2 Output 1 3 2 Input 4 2 2 3 3 Output 2 1 3 4 Input 1 2 Output 1 Note In the first test the numeration is already a permutation, so there is no need to change anything. In the second test there are two pairs of equal numbers, in each pair you need to replace one number. In the third test you need to replace 2 by 1, as the numbering should start from one. Submitted Solution: ``` def main(): read = lambda: tuple(map(int, input().split())) n = read()[0] l = read() ans = [0] * (n + 1) was = [0] * (n + 1) c = 0 for i, v in enumerate(l): if v >= 1 and v <= n and not was[v]: was[v] = 1 ans[i + 1] = v j = 1 for v in range(1, n + 1): if not was[v]: while ans[j] != 0: j += 1 ans[j] = v print(*ans[1:]) main() ``` Yes
8,676
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything. During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering. You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. Input The first line contains a single integer n β€” the number of items (1 ≀ n ≀ 105). The second line contains n numbers a1, a2, ..., an (1 ≀ ai ≀ 105) β€” the initial inventory numbers of the items. Output Print n numbers β€” the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. Examples Input 3 1 3 2 Output 1 3 2 Input 4 2 2 3 3 Output 2 1 3 4 Input 1 2 Output 1 Note In the first test the numeration is already a permutation, so there is no need to change anything. In the second test there are two pairs of equal numbers, in each pair you need to replace one number. In the third test you need to replace 2 by 1, as the numbering should start from one. Submitted Solution: ``` n = int(input()) inp = list(map(int,input().split(' '))) toreplace = set() values = set(range(1,n+1)) for i in range(n): num = inp[i] if num in values: values.remove(num) else: toreplace.add(i) for index in toreplace: inp[index] = values.pop() print(*inp) ``` Yes
8,677
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything. During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering. You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. Input The first line contains a single integer n β€” the number of items (1 ≀ n ≀ 105). The second line contains n numbers a1, a2, ..., an (1 ≀ ai ≀ 105) β€” the initial inventory numbers of the items. Output Print n numbers β€” the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. Examples Input 3 1 3 2 Output 1 3 2 Input 4 2 2 3 3 Output 2 1 3 4 Input 1 2 Output 1 Note In the first test the numeration is already a permutation, so there is no need to change anything. In the second test there are two pairs of equal numbers, in each pair you need to replace one number. In the third test you need to replace 2 by 1, as the numbering should start from one. Submitted Solution: ``` n = int(input()) a = [int(x) for x in input().split()] cnt = [0]*100013 for i in a: cnt[i]+=1 need = [] for i in range(1,n+1): if cnt[i]==0: need.append(i) on = 0 for i in a: if i>n: print(need[on]) on+=1 else: if cnt[i]>1: print(need[on]) on+=1 cnt[i]-=1 else: print(i) ``` Yes
8,678
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything. During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering. You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. Input The first line contains a single integer n β€” the number of items (1 ≀ n ≀ 105). The second line contains n numbers a1, a2, ..., an (1 ≀ ai ≀ 105) β€” the initial inventory numbers of the items. Output Print n numbers β€” the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. Examples Input 3 1 3 2 Output 1 3 2 Input 4 2 2 3 3 Output 2 1 3 4 Input 1 2 Output 1 Note In the first test the numeration is already a permutation, so there is no need to change anything. In the second test there are two pairs of equal numbers, in each pair you need to replace one number. In the third test you need to replace 2 by 1, as the numbering should start from one. Submitted Solution: ``` from collections import Counter n = int(input()) a = list(map(int, input().rstrip().split())) c = Counter(i for i in range(1, n + 1)) inp = Counter(a) c.subtract(inp) c += Counter() # print(inp) ans = [] for x in a: if inp[x] == -1 or x > n: for y in c: ans += [y] del c[y] break else: ans += [x] inp[x] = -1 print(*ans) ``` Yes
8,679
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything. During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering. You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. Input The first line contains a single integer n β€” the number of items (1 ≀ n ≀ 105). The second line contains n numbers a1, a2, ..., an (1 ≀ ai ≀ 105) β€” the initial inventory numbers of the items. Output Print n numbers β€” the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. Examples Input 3 1 3 2 Output 1 3 2 Input 4 2 2 3 3 Output 2 1 3 4 Input 1 2 Output 1 Note In the first test the numeration is already a permutation, so there is no need to change anything. In the second test there are two pairs of equal numbers, in each pair you need to replace one number. In the third test you need to replace 2 by 1, as the numbering should start from one. Submitted Solution: ``` n = input() a = [int(s) for s in input().split()] b = [] for x in range(1,len(a)+1): if x not in a: b.append(x) if len(a)==1: print(1) exit() if b == []: for x in a: print(x, end=' ') exit() for x in range(len(a)): if a.count(a[x])>1: a[x] = b.pop(0) for x in a: print(x, end=' ') ``` No
8,680
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything. During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering. You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. Input The first line contains a single integer n β€” the number of items (1 ≀ n ≀ 105). The second line contains n numbers a1, a2, ..., an (1 ≀ ai ≀ 105) β€” the initial inventory numbers of the items. Output Print n numbers β€” the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. Examples Input 3 1 3 2 Output 1 3 2 Input 4 2 2 3 3 Output 2 1 3 4 Input 1 2 Output 1 Note In the first test the numeration is already a permutation, so there is no need to change anything. In the second test there are two pairs of equal numbers, in each pair you need to replace one number. In the third test you need to replace 2 by 1, as the numbering should start from one. Submitted Solution: ``` n = int(input()) inventory = input().split(' ') inventory = [int(x) for x in inventory] if n == 1: inventory[0] = 1 else: ref = [int(i) for i in range(1,n+1)] for i in range(n): if inventory[i] in ref: ref.remove(inventory[i]) else: inventory[i] = ref[0] ref.remove(inventory[i]) out = ' '.join(str(x) for x in inventory) print(out) ``` No
8,681
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything. During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering. You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. Input The first line contains a single integer n β€” the number of items (1 ≀ n ≀ 105). The second line contains n numbers a1, a2, ..., an (1 ≀ ai ≀ 105) β€” the initial inventory numbers of the items. Output Print n numbers β€” the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. Examples Input 3 1 3 2 Output 1 3 2 Input 4 2 2 3 3 Output 2 1 3 4 Input 1 2 Output 1 Note In the first test the numeration is already a permutation, so there is no need to change anything. In the second test there are two pairs of equal numbers, in each pair you need to replace one number. In the third test you need to replace 2 by 1, as the numbering should start from one. Submitted Solution: ``` n = int(input()) a = list(map(int, input().split(' '))) used = [i for i in range(1, n + 1)] for i in range(n): if a[i] not in used: a[i] = used[0] used.remove(a[i]) print(' '.join(map(str, a))) ``` No
8,682
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything. During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering. You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. Input The first line contains a single integer n β€” the number of items (1 ≀ n ≀ 105). The second line contains n numbers a1, a2, ..., an (1 ≀ ai ≀ 105) β€” the initial inventory numbers of the items. Output Print n numbers β€” the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. Examples Input 3 1 3 2 Output 1 3 2 Input 4 2 2 3 3 Output 2 1 3 4 Input 1 2 Output 1 Note In the first test the numeration is already a permutation, so there is no need to change anything. In the second test there are two pairs of equal numbers, in each pair you need to replace one number. In the third test you need to replace 2 by 1, as the numbering should start from one. Submitted Solution: ``` n = int(input()) a = list(map(int, input().split())) d = {x: a.count(x) for x in a} d1 = [x for x in range(1, n + 1) if a.count(x) == 0] print(d1) m = max(a) + 1 for x in range(len(a)): if d[a[x]] > 1: d[a[x]] -= 1 a[x] = d1.pop() print(*a) ``` No
8,683
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day Vasya was solving arithmetical problems. He wrote down an expression a + b = c in his notebook. When the teacher checked Vasya's work it turned out that Vasya had solved the problem incorrectly. Now Vasya tries to find excuses. He says that he simply forgot to write down several digits in numbers a, b and c, but he can't remember what numbers they actually were. Help Vasya, find such numbers x, y and z, with which the following conditions are met: * x + y = z, * from the expression x + y = z several digits can be erased in such a way that the result will be a + b = c, * the expression x + y = z should have the minimal length. Input The first and only input line contains the expression a + b = c (1 ≀ a, b, c ≀ 106, a, b and c don't contain leading zeroes) which is the expression Vasya wrote down. Output Print the correct expression x + y = z (x, y and z are non-negative numbers without leading zeroes). The expression a + b = c must be met in x + y = z as a subsequence. The printed solution should have the minimal possible number of characters. If there are several such solutions, you can print any of them. Examples Input 2+4=5 Output 21+4=25 Input 1+1=3 Output 1+31=32 Input 1+1=2 Output 1+1=2 Submitted Solution: ``` n=input() l=list(n.split("+")) l[1]=l[1].split("=") l.append((l[1][1])) l[1]=(l[1][0]) for i in range(10): if l[2] in str(int(str(i)+l[0])+int(l[1])): l[2]=str(int(str(i)+l[0])+int(l[1])) l[0]=str(int(str(i)+l[0])) break; elif l[2] in str(int(l[0]+str(i))+int(l[1])): l[2]=str(int(l[0]+str(i))+int(l[1])) l[0]=str(int(l[0]+str(i))) break; a=l[0]+'+'+l[1]+'='+l[2] print(a) ``` No
8,684
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day Vasya was solving arithmetical problems. He wrote down an expression a + b = c in his notebook. When the teacher checked Vasya's work it turned out that Vasya had solved the problem incorrectly. Now Vasya tries to find excuses. He says that he simply forgot to write down several digits in numbers a, b and c, but he can't remember what numbers they actually were. Help Vasya, find such numbers x, y and z, with which the following conditions are met: * x + y = z, * from the expression x + y = z several digits can be erased in such a way that the result will be a + b = c, * the expression x + y = z should have the minimal length. Input The first and only input line contains the expression a + b = c (1 ≀ a, b, c ≀ 106, a, b and c don't contain leading zeroes) which is the expression Vasya wrote down. Output Print the correct expression x + y = z (x, y and z are non-negative numbers without leading zeroes). The expression a + b = c must be met in x + y = z as a subsequence. The printed solution should have the minimal possible number of characters. If there are several such solutions, you can print any of them. Examples Input 2+4=5 Output 21+4=25 Input 1+1=3 Output 1+31=32 Input 1+1=2 Output 1+1=2 Submitted Solution: ``` from heapq import heappush, heappop equation = input() fi, rest = equation.split('+') se, td = rest.split('=') lx = len(fi) ly = len(se) lz = len(td) h = [] max_len = max(lx, ly, lz) fi = fi[::-1] se = se[::-1] td = td[::-1] a = [[[''for _ in range(max_len + 1)] for _ in range(max_len + 1)] for _ in range(max_len + 1)] b = [[[''for _ in range(max_len + 1)] for _ in range(max_len + 1)] for _ in range(max_len + 1)] c = [[[''for _ in range(max_len + 1)] for _ in range(max_len + 1)] for _ in range(max_len + 1)] h = [] ans = None heappush(h, (0, 0, 0, 0, 0)) while h: cost, px, py, pz, carry = heappop(h) if px == lx and py == ly and pz == lz: if carry == 1: c[px][py][pz] = c[px][py][pz] + '1' ans = a[px][py][pz][::-1] + '+' + b[px][py][pz][::-1] + '=' + c[px][py][pz][::-1] print(ans) break if px == lx: if py == ly: last = int(td[pz:][::-1]) last -= carry if last > 0: c[px][py][lz] = c[px][py][pz] + td[pz:] cost += len(str(last)) else: c[px][py][lz] = c[px][py][pz] a[px][py][lz] = a[px][py][pz] b[px][py][lz] = b[px][py][pz] + str(last)[::-1] heappush(h, (cost + len(str(last)), px, py, lz, 0)) elif pz == lz: last = int(se[py:][::-1]) last += carry c[px][ly][pz] = c[px][py][pz] + str(last)[::-1] a[px][ly][pz] = a[px][py][pz] b[px][ly][pz] = b[px][py][pz] + se[py:] heappush(h, (cost + len(str(last)), px, ly, pz, 0)) else: cy = ord(se[py]) - ord('0') cz = ord(td[pz]) - ord('0') if (cy + carry) % 10 == cz: a[px][py + 1][pz + 1] = a[px][py][pz] b[px][py + 1][pz + 1] = b[px][py][pz] + se[py] c[px][py + 1][pz + 1] = c[px][py][pz] + td[pz] heappush(h, (cost, px, py + 1, pz + 1, (cy + carry) // 10)) else: # first case: cc = (cy + carry) % 10 a[px][py + 1][pz] = a[px][py][pz] b[px][py + 1][pz] = b[px][py][pz] + se[py] c[px][py + 1][pz] = c[px][py][pz] + chr(cc + ord('0')) heappush(h, (cost + 1, px, py + 1, pz, (cy + carry) // 10)) # second case: a[px][py][pz + 1] = a[px][py][pz] if cz == 0 and carry == 1: cc = 9 else: cc = cz - carry carry = 0 b[px][py][pz + 1] = b[px][py][pz] + chr(cc + ord('0')) c[px][py][pz + 1] = c[px][py][pz] + td[pz] heappush(h, (cost + 1, px, py, pz + 1, carry)) continue if py == ly: if pz == lz: last = int(fi[px:][::-1]) last += carry c[lx][py][pz] = c[px][py][pz] + str(last)[::-1] a[lx][py][pz] = a[px][py][pz] + fi[px:] b[lx][py][pz] = b[px][py][pz] heappush(h, (cost + len(str(last)), lx, py, pz, 0)) else: cx = ord(fi[px]) - ord('0') cz = ord(td[pz]) - ord('0') # first case if (cx + carry) % 10 == cz: a[px + 1][py][pz + 1] = a[px][py][pz] + fi[px] b[px + 1][py][pz + 1] = b[px][py][pz] c[px + 1][py][pz + 1] = c[px][py][pz] + td[pz] heappush(h, (cost, px + 1, py, pz + 1, (cx + carry) // 10)) else: cc = (cx + carry) % 10 a[px + 1][py][pz] = a[px][py][pz] + fi[px] b[px + 1][py][pz] = b[px][py][pz] c[px + 1][py][pz] = c[px + 1][py][pz] + chr(ord('0') + cc) heappush(h, (cost + 1, px + 1, py, pz, (cx + carry) // 10)) if cz == 0 and carry == 1: cc = 9 else: cc = cz - carry carry = 0 a[px][py][pz + 1] = a[px][py][pz] + chr(ord('0') + cc) b[px][py][pz + 1] = b[px][py][pz] c[px][py][pz + 1] = c[px][py][pz] + td[pz] heappush(h, (cost + 1, px, py, pz + 1, carry)) continue if lz == pz: cx = ord(fi[px]) - ord('0') cy = ord(se[py]) - ord('0') cc = (cx + cy + carry) % 10 carry = (cx + cy + carry) // 10 a[px + 1][py + 1][pz] = a[px][py][pz] + fi[px] b[px + 1][py + 1][pz] = b[px][py][pz] + se[py] c[px + 1][py + 1][pz] = c[px][py][pz] + chr(ord('0') + cc) heappush(h, (cost + 1, px + 1, py + 1, pz, carry)) continue cx = ord(fi[px]) - ord('0') cy = ord(se[py]) - ord('0') cz = ord(td[pz]) - ord('0') if (cx + cy + carry) % 10 == cz: a[px + 1][py + 1][pz + 1] = a[px][py][pz] + fi[px] b[px + 1][py + 1][pz + 1] = b[px][py][pz] + se[py] c[px + 1][py + 1][pz + 1] = c[px][py][pz] + td[pz] heappush(h, (cost, px + 1, py + 1, pz + 1, (cx + cy + carry) // 10)) else: # first case cc = (cx + cy + carry) % 10 a[px + 1][py + 1][pz] = a[px][py][pz] + fi[px] b[px + 1][py + 1][pz] = b[px][py][pz] + se[py] c[px + 1][py + 1][pz] = c[px][py][pz] + chr(ord('0') + cc) heappush(h, (cost + 1, px + 1, py + 1, pz, (cx + cy + carry) // 10)) # second case if (cx + carry) <= cz: cc = cz - (cx - carry) else: cc = (cz + 10) - (cx + carry) a[px + 1][py][pz + 1] = a[px][py][pz] + fi[px] b[px + 1][py][pz + 1] = b[px][py][pz] + chr(ord('0') + cc) c[px + 1][py][pz + 1] = c[px][py][pz] + td[pz] heappush(h, (cost + 1, px + 1, py, pz + 1, (cc + cx + carry) // 10)) # third case if (cy + carry) <= cz: cc = cz - (cy + carry) else: cc = (cz + 10) - (cy + carry) a[px][py + 1][pz + 1] = a[px][py][pz] + chr(ord('0') + cc) b[px][py + 1][pz + 1] = b[px][py][pz] + se[py] c[px][py + 1][pz + 1] = c[px][py][pz] + td[pz] heappush(h, (cost + 1, px, py + 1, pz + 1, (cc + cx + carry) // 10)) ``` No
8,685
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day Vasya was solving arithmetical problems. He wrote down an expression a + b = c in his notebook. When the teacher checked Vasya's work it turned out that Vasya had solved the problem incorrectly. Now Vasya tries to find excuses. He says that he simply forgot to write down several digits in numbers a, b and c, but he can't remember what numbers they actually were. Help Vasya, find such numbers x, y and z, with which the following conditions are met: * x + y = z, * from the expression x + y = z several digits can be erased in such a way that the result will be a + b = c, * the expression x + y = z should have the minimal length. Input The first and only input line contains the expression a + b = c (1 ≀ a, b, c ≀ 106, a, b and c don't contain leading zeroes) which is the expression Vasya wrote down. Output Print the correct expression x + y = z (x, y and z are non-negative numbers without leading zeroes). The expression a + b = c must be met in x + y = z as a subsequence. The printed solution should have the minimal possible number of characters. If there are several such solutions, you can print any of them. Examples Input 2+4=5 Output 21+4=25 Input 1+1=3 Output 1+31=32 Input 1+1=2 Output 1+1=2 Submitted Solution: ``` n=input() l=list(n.split("+")) l[1]=l[1].split("=") l.append((l[1][1])) l[1]=(l[1][0]) l1=l; for i in range(1000000): if l[2] in str(int(str(i)+l[0])+int(l[1])): l[2]=str(int(str(i)+l[0])+int(l[1])) l[0]=str(int(str(i)+l[0])) break; elif l[2] in str(int(l[0]+str(i))+int(l[1])): l[2]=str(int(l[0]+str(i))+int(l[1])) l[0]=str(int(l[0]+str(i))) break; for i in range(1000000): if l1[2] in str(int(str(i)+l[1])+int(l[0])): l1[2]=str(int(str(i)+l[1])+int(l[0])) l1[1]=str(int(str(i)+l[1])) break; elif l1[2] in str(int(l[1]+str(i))+int(l[0])): l1[2]=str(int(l[1]+str(i))+int(l[0])) l1[1]=str(int(l[1]+str(i))) break; if int(l[2])<int(l1[2]): a=l[0]+'+'+l[1]+'='+l[2] else: a=l1[0]+'+'+l1[1]+'='+l1[2] print(a) ``` No
8,686
Provide tags and a correct Python 3 solution for this coding contest problem. Each employee of the "Blake Techologies" company uses a special messaging app "Blake Messenger". All the stuff likes this app and uses it constantly. However, some important futures are missing. For example, many users want to be able to search through the message history. It was already announced that the new feature will appear in the nearest update, when developers faced some troubles that only you may help them to solve. All the messages are represented as a strings consisting of only lowercase English letters. In order to reduce the network load strings are represented in the special compressed form. Compression algorithm works as follows: string is represented as a concatenation of n blocks, each block containing only equal characters. One block may be described as a pair (li, ci), where li is the length of the i-th block and ci is the corresponding letter. Thus, the string s may be written as the sequence of pairs <image>. Your task is to write the program, that given two compressed string t and s finds all occurrences of s in t. Developers know that there may be many such occurrences, so they only ask you to find the number of them. Note that p is the starting position of some occurrence of s in t if and only if tptp + 1...tp + |s| - 1 = s, where ti is the i-th character of string t. Note that the way to represent the string in compressed form may not be unique. For example string "aaaa" may be given as <image>, <image>, <image>... Input The first line of the input contains two integers n and m (1 ≀ n, m ≀ 200 000) β€” the number of blocks in the strings t and s, respectively. The second line contains the descriptions of n parts of string t in the format "li-ci" (1 ≀ li ≀ 1 000 000) β€” the length of the i-th part and the corresponding lowercase English letter. The second line contains the descriptions of m parts of string s in the format "li-ci" (1 ≀ li ≀ 1 000 000) β€” the length of the i-th part and the corresponding lowercase English letter. Output Print a single integer β€” the number of occurrences of s in t. Examples Input 5 3 3-a 2-b 4-c 3-a 2-c 2-a 2-b 1-c Output 1 Input 6 1 3-a 6-b 7-a 4-c 8-e 2-a 3-a Output 6 Input 5 5 1-h 1-e 1-l 1-l 1-o 1-w 1-o 1-r 1-l 1-d Output 0 Note In the first sample, t = "aaabbccccaaacc", and string s = "aabbc". The only occurrence of string s in string t starts at position p = 2. In the second sample, t = "aaabbbbbbaaaaaaacccceeeeeeeeaa", and s = "aaa". The occurrences of s in t start at positions p = 1, p = 10, p = 11, p = 12, p = 13 and p = 14. Tags: data structures, hashing, implementation, string suffix structures, strings Correct Solution: ``` #!/usr/bin/env python3 def cal_last(s): n = len(s) last = [-1]*(n+1) i,j = 0,-1 while i<n: while j!=-1 and s[i]!=s[j]: j=last[j] i,j = i+1,j+1 last[i] = j return last def kmp(p,t,last): m = len(p) n = len(t) i = j = 0 rl = [] while i<n: while j!=-1 and t[i]!=p[j]: j=last[j] i,j = i+1,j+1 if j>=m: rl.append(i) j=last[j] return rl def solve1(p,t): pn,pc = p[0] return sum([tn-pn+1 for tn,tc in t if tn>=pn and tc==pc]) def solve2(p,t): return sum([t[i][0]>=p[0][0] and t[i][1]==p[0][1] and t[i+1][0]>=p[1][0] and t[i+1][1]==p[1][1] for i in range(len(t)-1)]) def compact(s): t = [[int(s[0][:-2]),s[0][-1]]] for i in range(1,len(s)): n = int(s[i][:-2]) c = s[i][-1] if c == t[-1][-1]: t[-1][0] += n else: t.append([n,c]) return t def f(p,t): tt,pp = compact(t),compact(p) if len(pp)==1: return solve1(pp,tt) if len(pp)==2: return solve2(pp,tt) last = cal_last(pp[1:-1]) ml = kmp(pp[1:-1],tt,last) x = len(pp)-2 n = len(tt) return sum([i-x>0 and tt[i-x-1][0]>=pp[0][0] and tt[i-x-1][1]==pp[0][1] and i<n and tt[i][0]>=pp[-1][0] and tt[i][1]==pp[-1][1] for i in ml]) _ = input() t = input().split() p = input().split() print(f(p,t)) ```
8,687
Provide tags and a correct Python 3 solution for this coding contest problem. Each employee of the "Blake Techologies" company uses a special messaging app "Blake Messenger". All the stuff likes this app and uses it constantly. However, some important futures are missing. For example, many users want to be able to search through the message history. It was already announced that the new feature will appear in the nearest update, when developers faced some troubles that only you may help them to solve. All the messages are represented as a strings consisting of only lowercase English letters. In order to reduce the network load strings are represented in the special compressed form. Compression algorithm works as follows: string is represented as a concatenation of n blocks, each block containing only equal characters. One block may be described as a pair (li, ci), where li is the length of the i-th block and ci is the corresponding letter. Thus, the string s may be written as the sequence of pairs <image>. Your task is to write the program, that given two compressed string t and s finds all occurrences of s in t. Developers know that there may be many such occurrences, so they only ask you to find the number of them. Note that p is the starting position of some occurrence of s in t if and only if tptp + 1...tp + |s| - 1 = s, where ti is the i-th character of string t. Note that the way to represent the string in compressed form may not be unique. For example string "aaaa" may be given as <image>, <image>, <image>... Input The first line of the input contains two integers n and m (1 ≀ n, m ≀ 200 000) β€” the number of blocks in the strings t and s, respectively. The second line contains the descriptions of n parts of string t in the format "li-ci" (1 ≀ li ≀ 1 000 000) β€” the length of the i-th part and the corresponding lowercase English letter. The second line contains the descriptions of m parts of string s in the format "li-ci" (1 ≀ li ≀ 1 000 000) β€” the length of the i-th part and the corresponding lowercase English letter. Output Print a single integer β€” the number of occurrences of s in t. Examples Input 5 3 3-a 2-b 4-c 3-a 2-c 2-a 2-b 1-c Output 1 Input 6 1 3-a 6-b 7-a 4-c 8-e 2-a 3-a Output 6 Input 5 5 1-h 1-e 1-l 1-l 1-o 1-w 1-o 1-r 1-l 1-d Output 0 Note In the first sample, t = "aaabbccccaaacc", and string s = "aabbc". The only occurrence of string s in string t starts at position p = 2. In the second sample, t = "aaabbbbbbaaaaaaacccceeeeeeeeaa", and s = "aaa". The occurrences of s in t start at positions p = 1, p = 10, p = 11, p = 12, p = 13 and p = 14. Tags: data structures, hashing, implementation, string suffix structures, strings Correct Solution: ``` def ziped(a): p = [] for i in a: x = int(i.split('-')[0]) y = i.split('-')[1] if len(p) > 0 and p[-1][1] == y: p[-1][0] += x else: p.append([x, y]) return p def solve(a, b , c): ans = 0 if len(b) == 1: for token in a: if c(token, b[0]): ans += token[0] - b[0][0] + 1 return ans if len(b) == 2: for i in range(len(a) - 1): if c(a[i], b[0]) and c(a[i + 1], b[-1]): ans += 1 return ans v = b[1 : -1] + [[100500, '#']] + a p = [0] * len(v) for i in range(1, len(v)): j = p[i - 1] while j > 0 and v[i] != v[j]: j = p[j - 1] if v[i] == v[j]: j += 1 p[i] = j for i in range(len(v) - 1): if p[i] == len(b) - 2 and c(v[i - p[i]], b[0]) and c(v[i + 1], b[-1]): ans += 1 return ans n, m = map(int, input().split()) a = ziped(input().split()) b = ziped(input().split()) print(solve(a, b, lambda x, y: x[1] == y[1] and x[0] >= y[0])) ```
8,688
Provide tags and a correct Python 3 solution for this coding contest problem. Each employee of the "Blake Techologies" company uses a special messaging app "Blake Messenger". All the stuff likes this app and uses it constantly. However, some important futures are missing. For example, many users want to be able to search through the message history. It was already announced that the new feature will appear in the nearest update, when developers faced some troubles that only you may help them to solve. All the messages are represented as a strings consisting of only lowercase English letters. In order to reduce the network load strings are represented in the special compressed form. Compression algorithm works as follows: string is represented as a concatenation of n blocks, each block containing only equal characters. One block may be described as a pair (li, ci), where li is the length of the i-th block and ci is the corresponding letter. Thus, the string s may be written as the sequence of pairs <image>. Your task is to write the program, that given two compressed string t and s finds all occurrences of s in t. Developers know that there may be many such occurrences, so they only ask you to find the number of them. Note that p is the starting position of some occurrence of s in t if and only if tptp + 1...tp + |s| - 1 = s, where ti is the i-th character of string t. Note that the way to represent the string in compressed form may not be unique. For example string "aaaa" may be given as <image>, <image>, <image>... Input The first line of the input contains two integers n and m (1 ≀ n, m ≀ 200 000) β€” the number of blocks in the strings t and s, respectively. The second line contains the descriptions of n parts of string t in the format "li-ci" (1 ≀ li ≀ 1 000 000) β€” the length of the i-th part and the corresponding lowercase English letter. The second line contains the descriptions of m parts of string s in the format "li-ci" (1 ≀ li ≀ 1 000 000) β€” the length of the i-th part and the corresponding lowercase English letter. Output Print a single integer β€” the number of occurrences of s in t. Examples Input 5 3 3-a 2-b 4-c 3-a 2-c 2-a 2-b 1-c Output 1 Input 6 1 3-a 6-b 7-a 4-c 8-e 2-a 3-a Output 6 Input 5 5 1-h 1-e 1-l 1-l 1-o 1-w 1-o 1-r 1-l 1-d Output 0 Note In the first sample, t = "aaabbccccaaacc", and string s = "aabbc". The only occurrence of string s in string t starts at position p = 2. In the second sample, t = "aaabbbbbbaaaaaaacccceeeeeeeeaa", and s = "aaa". The occurrences of s in t start at positions p = 1, p = 10, p = 11, p = 12, p = 13 and p = 14. Tags: data structures, hashing, implementation, string suffix structures, strings Correct Solution: ``` def main(): input() ts = [] for _ in 0, 1: tmp = input().split() a, x, l = tmp[0][-1], 0, [] for st in tmp: y = int(st[:-2]) b = st[-1] if a != b: l.append(((x, a))) x, a = y, b else: x += y l.append(((x, a))) ts.append(l) t, s = ts res, m, x, a, y, b = 0, len(s), *s[0], *s[-1] if m == 1: res = sum(y - x + 1 for y, b in t if a == b and x <= y) elif m == 2: i, u = 0, ' ' for j, v in t: if a == u and b == v and x <= i and y <= j: res += 1 i, u = j, v else: t[:0] = s[1: -1] + [(0, ' ')] tmp = [0] * len(t) for i, j in zip(range(1, len(t)), tmp): while j > 0 and t[i] != t[j]: j = tmp[j - 1] tmp[i] = j + 1 if t[i] == t[j] else j m -= 2 del tmp[-1] for i, q in enumerate(tmp): if q == m: i, u, j, v = *t[i - q], *t[i + 1] if a == u and b == v and x <= i and y <= j: res += 1 print(res) if __name__ == '__main__': main() ```
8,689
Provide tags and a correct Python 3 solution for this coding contest problem. Each employee of the "Blake Techologies" company uses a special messaging app "Blake Messenger". All the stuff likes this app and uses it constantly. However, some important futures are missing. For example, many users want to be able to search through the message history. It was already announced that the new feature will appear in the nearest update, when developers faced some troubles that only you may help them to solve. All the messages are represented as a strings consisting of only lowercase English letters. In order to reduce the network load strings are represented in the special compressed form. Compression algorithm works as follows: string is represented as a concatenation of n blocks, each block containing only equal characters. One block may be described as a pair (li, ci), where li is the length of the i-th block and ci is the corresponding letter. Thus, the string s may be written as the sequence of pairs <image>. Your task is to write the program, that given two compressed string t and s finds all occurrences of s in t. Developers know that there may be many such occurrences, so they only ask you to find the number of them. Note that p is the starting position of some occurrence of s in t if and only if tptp + 1...tp + |s| - 1 = s, where ti is the i-th character of string t. Note that the way to represent the string in compressed form may not be unique. For example string "aaaa" may be given as <image>, <image>, <image>... Input The first line of the input contains two integers n and m (1 ≀ n, m ≀ 200 000) β€” the number of blocks in the strings t and s, respectively. The second line contains the descriptions of n parts of string t in the format "li-ci" (1 ≀ li ≀ 1 000 000) β€” the length of the i-th part and the corresponding lowercase English letter. The second line contains the descriptions of m parts of string s in the format "li-ci" (1 ≀ li ≀ 1 000 000) β€” the length of the i-th part and the corresponding lowercase English letter. Output Print a single integer β€” the number of occurrences of s in t. Examples Input 5 3 3-a 2-b 4-c 3-a 2-c 2-a 2-b 1-c Output 1 Input 6 1 3-a 6-b 7-a 4-c 8-e 2-a 3-a Output 6 Input 5 5 1-h 1-e 1-l 1-l 1-o 1-w 1-o 1-r 1-l 1-d Output 0 Note In the first sample, t = "aaabbccccaaacc", and string s = "aabbc". The only occurrence of string s in string t starts at position p = 2. In the second sample, t = "aaabbbbbbaaaaaaacccceeeeeeeeaa", and s = "aaa". The occurrences of s in t start at positions p = 1, p = 10, p = 11, p = 12, p = 13 and p = 14. Tags: data structures, hashing, implementation, string suffix structures, strings Correct Solution: ``` def ziped(a): p = [] for i in a: x = int(i.split('-')[0]) y = i.split('-')[1] if len(p) > 0 and p[-1][1] == y: p[-1][0] += x else: p.append([x, y]) return p def solve(a, b , c): ans = 0 if len(b) == 1: for token in a: #print("token",token) if c(token, b[0]): ans += token[0] - b[0][0] + 1 return ans if len(b) == 2: for i in range(len(a) - 1): if c(a[i], b[0]) and c(a[i + 1], b[-1]): ans += 1 return ans v = b[1 : -1] + [[100500, '#']] + a p = [0] * len(v) for i in range(1, len(v)): j = p[i - 1] while j > 0 and v[i] != v[j]: j = p[j - 1] if v[i] == v[j]: j += 1 p[i] = j for i in range(len(v) - 1): if p[i] == len(b) - 2 and c(v[i - p[i]], b[0]) and c(v[i + 1], b[-1]): ans += 1 return ans n, m = map(int, input().split()) a = ziped(input().split()) b = ziped(input().split()) print(solve(a, b, lambda x, y: x[1] == y[1] and x[0] >= y[0])) ```
8,690
Provide tags and a correct Python 3 solution for this coding contest problem. Each employee of the "Blake Techologies" company uses a special messaging app "Blake Messenger". All the stuff likes this app and uses it constantly. However, some important futures are missing. For example, many users want to be able to search through the message history. It was already announced that the new feature will appear in the nearest update, when developers faced some troubles that only you may help them to solve. All the messages are represented as a strings consisting of only lowercase English letters. In order to reduce the network load strings are represented in the special compressed form. Compression algorithm works as follows: string is represented as a concatenation of n blocks, each block containing only equal characters. One block may be described as a pair (li, ci), where li is the length of the i-th block and ci is the corresponding letter. Thus, the string s may be written as the sequence of pairs <image>. Your task is to write the program, that given two compressed string t and s finds all occurrences of s in t. Developers know that there may be many such occurrences, so they only ask you to find the number of them. Note that p is the starting position of some occurrence of s in t if and only if tptp + 1...tp + |s| - 1 = s, where ti is the i-th character of string t. Note that the way to represent the string in compressed form may not be unique. For example string "aaaa" may be given as <image>, <image>, <image>... Input The first line of the input contains two integers n and m (1 ≀ n, m ≀ 200 000) β€” the number of blocks in the strings t and s, respectively. The second line contains the descriptions of n parts of string t in the format "li-ci" (1 ≀ li ≀ 1 000 000) β€” the length of the i-th part and the corresponding lowercase English letter. The second line contains the descriptions of m parts of string s in the format "li-ci" (1 ≀ li ≀ 1 000 000) β€” the length of the i-th part and the corresponding lowercase English letter. Output Print a single integer β€” the number of occurrences of s in t. Examples Input 5 3 3-a 2-b 4-c 3-a 2-c 2-a 2-b 1-c Output 1 Input 6 1 3-a 6-b 7-a 4-c 8-e 2-a 3-a Output 6 Input 5 5 1-h 1-e 1-l 1-l 1-o 1-w 1-o 1-r 1-l 1-d Output 0 Note In the first sample, t = "aaabbccccaaacc", and string s = "aabbc". The only occurrence of string s in string t starts at position p = 2. In the second sample, t = "aaabbbbbbaaaaaaacccceeeeeeeeaa", and s = "aaa". The occurrences of s in t start at positions p = 1, p = 10, p = 11, p = 12, p = 13 and p = 14. Tags: data structures, hashing, implementation, string suffix structures, strings Correct Solution: ``` def compress(bstr): pk, pc = None, None for block in bstr: if pc is None: pk, pc = block elif pc == block[1]: pk += block[0] else: yield pk, pc pk, pc = block if pc is not None: yield pk, pc def find1(text, query): (bk, bc), = query return sum(k-bk+1 for k, c in text if c == bc and k >= bk) class Query: def __init__(self, query): self._query = query self._len = len(query) self._suffixes = {} def precompute(self): for i in range(self._len-1): self._suffix(i) def _suffix(self, i, pblock=None): if not i: return None if pblock is None and i is not None: pblock = self._query[i] if (i, pblock) in self._suffixes: return self._suffixes[i, pblock] else: sfx = self.next(self._suffix(i-1), pblock) self._suffixes[i, pblock] = sfx return sfx def _match(self, i, block): if i == 0 or i == self._len -1: return (block[1] == self._query[i][1] and block[0] >= self._query[i][0]) else: return block == self._query[i] def next(self, i, block, pblock=None): while True: if i is None: return 0 if self._match(0, block) else None elif i < self._len-1: if self._match(i+1, block): return i+1 else: i = self._suffix(i) else: i = self._suffix(i, pblock) pblock = None def is_match(self, i): return i == self._len-1 def find2(text, query): qobj = Query(query) qobj.precompute() i = None pblock = None c = 0 for block in text: i, pblock = qobj.next(i, block, pblock), block if qobj.is_match(i): c += 1 return c def find(text, query): text = list(compress(text)) query = list(compress(query)) return (find1 if len(query) == 1 else find2)(text, query) def parse_block(s): k, c = s.split('-') return int(k), c def get_input(): n, m = map(int, input().split()) text = list(map(parse_block, input().split())) assert len(text) == n query = list(map(parse_block, input().split())) assert len(query) == m return text, query if __name__ == '__main__': print(find(*get_input())) ```
8,691
Provide tags and a correct Python 3 solution for this coding contest problem. Each employee of the "Blake Techologies" company uses a special messaging app "Blake Messenger". All the stuff likes this app and uses it constantly. However, some important futures are missing. For example, many users want to be able to search through the message history. It was already announced that the new feature will appear in the nearest update, when developers faced some troubles that only you may help them to solve. All the messages are represented as a strings consisting of only lowercase English letters. In order to reduce the network load strings are represented in the special compressed form. Compression algorithm works as follows: string is represented as a concatenation of n blocks, each block containing only equal characters. One block may be described as a pair (li, ci), where li is the length of the i-th block and ci is the corresponding letter. Thus, the string s may be written as the sequence of pairs <image>. Your task is to write the program, that given two compressed string t and s finds all occurrences of s in t. Developers know that there may be many such occurrences, so they only ask you to find the number of them. Note that p is the starting position of some occurrence of s in t if and only if tptp + 1...tp + |s| - 1 = s, where ti is the i-th character of string t. Note that the way to represent the string in compressed form may not be unique. For example string "aaaa" may be given as <image>, <image>, <image>... Input The first line of the input contains two integers n and m (1 ≀ n, m ≀ 200 000) β€” the number of blocks in the strings t and s, respectively. The second line contains the descriptions of n parts of string t in the format "li-ci" (1 ≀ li ≀ 1 000 000) β€” the length of the i-th part and the corresponding lowercase English letter. The second line contains the descriptions of m parts of string s in the format "li-ci" (1 ≀ li ≀ 1 000 000) β€” the length of the i-th part and the corresponding lowercase English letter. Output Print a single integer β€” the number of occurrences of s in t. Examples Input 5 3 3-a 2-b 4-c 3-a 2-c 2-a 2-b 1-c Output 1 Input 6 1 3-a 6-b 7-a 4-c 8-e 2-a 3-a Output 6 Input 5 5 1-h 1-e 1-l 1-l 1-o 1-w 1-o 1-r 1-l 1-d Output 0 Note In the first sample, t = "aaabbccccaaacc", and string s = "aabbc". The only occurrence of string s in string t starts at position p = 2. In the second sample, t = "aaabbbbbbaaaaaaacccceeeeeeeeaa", and s = "aaa". The occurrences of s in t start at positions p = 1, p = 10, p = 11, p = 12, p = 13 and p = 14. Tags: data structures, hashing, implementation, string suffix structures, strings Correct Solution: ``` def compress(bstr): pk, pc = None, None for block in bstr: if pc is None: pk, pc = block elif pc == block[1]: pk += block[0] else: yield pk, pc pk, pc = block if pc is not None: yield pk, pc def find1(text, query): (bk, bc), = query return sum(k-bk+1 for k, c in text if c == bc and k >= bk) class Query: def __init__(self, query): self._query = query self._len = len(query) self._suffixes = [None] def _suffix(self, i, pblock=None): if i is None: return None for j in range(len(self._suffixes), min(i+1, self._len-1)): self._suffixes.append( self.next(self._suffixes[j-1], self._query[j])) if i < self._len - 1: return self._suffixes[i] else: return self.next(self._suffixes[i-1], pblock) def _match(self, i, block): if i == 0 or i == self._len -1: return (block[1] == self._query[i][1] and block[0] >= self._query[i][0]) else: return block == self._query[i] def next(self, i, block, pblock=None): while True: if i is None: return 0 if self._match(0, block) else None elif i < self._len-1: if self._match(i+1, block): return i+1 else: i = self._suffix(i) else: i = self._suffix(i, pblock) pblock = None def is_match(self, i): return i == self._len-1 def find2(text, query): qobj = Query(query) i = None pblock = None c = 0 for block in text: i, pblock = qobj.next(i, block, pblock), block if qobj.is_match(i): c += 1 return c def find(text, query): text = list(compress(text)) query = list(compress(query)) return (find1 if len(query) == 1 else find2)(text, query) def parse_block(s): k, c = s.split('-') return int(k), c def get_input(): n, m = map(int, input().split()) text = list(map(parse_block, input().split())) assert len(text) == n query = list(map(parse_block, input().split())) assert len(query) == m return text, query if __name__ == '__main__': print(find(*get_input())) ```
8,692
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Each employee of the "Blake Techologies" company uses a special messaging app "Blake Messenger". All the stuff likes this app and uses it constantly. However, some important futures are missing. For example, many users want to be able to search through the message history. It was already announced that the new feature will appear in the nearest update, when developers faced some troubles that only you may help them to solve. All the messages are represented as a strings consisting of only lowercase English letters. In order to reduce the network load strings are represented in the special compressed form. Compression algorithm works as follows: string is represented as a concatenation of n blocks, each block containing only equal characters. One block may be described as a pair (li, ci), where li is the length of the i-th block and ci is the corresponding letter. Thus, the string s may be written as the sequence of pairs <image>. Your task is to write the program, that given two compressed string t and s finds all occurrences of s in t. Developers know that there may be many such occurrences, so they only ask you to find the number of them. Note that p is the starting position of some occurrence of s in t if and only if tptp + 1...tp + |s| - 1 = s, where ti is the i-th character of string t. Note that the way to represent the string in compressed form may not be unique. For example string "aaaa" may be given as <image>, <image>, <image>... Input The first line of the input contains two integers n and m (1 ≀ n, m ≀ 200 000) β€” the number of blocks in the strings t and s, respectively. The second line contains the descriptions of n parts of string t in the format "li-ci" (1 ≀ li ≀ 1 000 000) β€” the length of the i-th part and the corresponding lowercase English letter. The second line contains the descriptions of m parts of string s in the format "li-ci" (1 ≀ li ≀ 1 000 000) β€” the length of the i-th part and the corresponding lowercase English letter. Output Print a single integer β€” the number of occurrences of s in t. Examples Input 5 3 3-a 2-b 4-c 3-a 2-c 2-a 2-b 1-c Output 1 Input 6 1 3-a 6-b 7-a 4-c 8-e 2-a 3-a Output 6 Input 5 5 1-h 1-e 1-l 1-l 1-o 1-w 1-o 1-r 1-l 1-d Output 0 Note In the first sample, t = "aaabbccccaaacc", and string s = "aabbc". The only occurrence of string s in string t starts at position p = 2. In the second sample, t = "aaabbbbbbaaaaaaacccceeeeeeeeaa", and s = "aaa". The occurrences of s in t start at positions p = 1, p = 10, p = 11, p = 12, p = 13 and p = 14. Submitted Solution: ``` n,m = map(int, input().split()) a = list(map(str,input().split())) b = list(map(str,input().split())) str1 = '' str2 = '' for i in a: x = int(i[0]) c = i[2] str1 += (c*x) for i in b: x = int(i[0]) c = i[2] str2 += (c*x) i = 0 ans = 0 while (True): r = str1.find(str2,i) if r!=-1: ans +=1 i = r+1 else: break print(ans) ``` No
8,693
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Each employee of the "Blake Techologies" company uses a special messaging app "Blake Messenger". All the stuff likes this app and uses it constantly. However, some important futures are missing. For example, many users want to be able to search through the message history. It was already announced that the new feature will appear in the nearest update, when developers faced some troubles that only you may help them to solve. All the messages are represented as a strings consisting of only lowercase English letters. In order to reduce the network load strings are represented in the special compressed form. Compression algorithm works as follows: string is represented as a concatenation of n blocks, each block containing only equal characters. One block may be described as a pair (li, ci), where li is the length of the i-th block and ci is the corresponding letter. Thus, the string s may be written as the sequence of pairs <image>. Your task is to write the program, that given two compressed string t and s finds all occurrences of s in t. Developers know that there may be many such occurrences, so they only ask you to find the number of them. Note that p is the starting position of some occurrence of s in t if and only if tptp + 1...tp + |s| - 1 = s, where ti is the i-th character of string t. Note that the way to represent the string in compressed form may not be unique. For example string "aaaa" may be given as <image>, <image>, <image>... Input The first line of the input contains two integers n and m (1 ≀ n, m ≀ 200 000) β€” the number of blocks in the strings t and s, respectively. The second line contains the descriptions of n parts of string t in the format "li-ci" (1 ≀ li ≀ 1 000 000) β€” the length of the i-th part and the corresponding lowercase English letter. The second line contains the descriptions of m parts of string s in the format "li-ci" (1 ≀ li ≀ 1 000 000) β€” the length of the i-th part and the corresponding lowercase English letter. Output Print a single integer β€” the number of occurrences of s in t. Examples Input 5 3 3-a 2-b 4-c 3-a 2-c 2-a 2-b 1-c Output 1 Input 6 1 3-a 6-b 7-a 4-c 8-e 2-a 3-a Output 6 Input 5 5 1-h 1-e 1-l 1-l 1-o 1-w 1-o 1-r 1-l 1-d Output 0 Note In the first sample, t = "aaabbccccaaacc", and string s = "aabbc". The only occurrence of string s in string t starts at position p = 2. In the second sample, t = "aaabbbbbbaaaaaaacccceeeeeeeeaa", and s = "aaa". The occurrences of s in t start at positions p = 1, p = 10, p = 11, p = 12, p = 13 and p = 14. Submitted Solution: ``` def main(): input().split() ts = [] for _ in 0, 1: tmp = input().split() a, x, l = tmp[0][-1], 0, [] for st in tmp: y = int(st[:-2]) b = st[-1] if a != b: l.append(((x, a))) x, a = y, b else: x += y l.append(((x, a))) ts.append(l) t, s = ts res, m, x, a, y, b = 0, len(s), *s[0], *s[-1] if m == 1: res = sum(y - x + 1 for y, b in t if a == b and x <= y) elif m == 2: i, u = 0, ' ' for j, v in t: if a == u and b == v and x <= i and y <= j: res += 1 else: t[:0] = s[1: -1] + [(0, ' ')] tmp = [0] * len(t) for i, j in zip(range(1, len(t)), tmp): while j > 0 and t[i] != t[j]: j = tmp[j - 1] tmp[i] = j + 1 if t[i] == t[j] else j m -= 2 del tmp[-1] for i, q in enumerate(tmp): if q == m: i, u, j, v = *t[i - q], *t[i + 1] if a == u and b == v and x <= i and y <= j: res += 1 print(res) if __name__ == '__main__': main() ``` No
8,694
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Each employee of the "Blake Techologies" company uses a special messaging app "Blake Messenger". All the stuff likes this app and uses it constantly. However, some important futures are missing. For example, many users want to be able to search through the message history. It was already announced that the new feature will appear in the nearest update, when developers faced some troubles that only you may help them to solve. All the messages are represented as a strings consisting of only lowercase English letters. In order to reduce the network load strings are represented in the special compressed form. Compression algorithm works as follows: string is represented as a concatenation of n blocks, each block containing only equal characters. One block may be described as a pair (li, ci), where li is the length of the i-th block and ci is the corresponding letter. Thus, the string s may be written as the sequence of pairs <image>. Your task is to write the program, that given two compressed string t and s finds all occurrences of s in t. Developers know that there may be many such occurrences, so they only ask you to find the number of them. Note that p is the starting position of some occurrence of s in t if and only if tptp + 1...tp + |s| - 1 = s, where ti is the i-th character of string t. Note that the way to represent the string in compressed form may not be unique. For example string "aaaa" may be given as <image>, <image>, <image>... Input The first line of the input contains two integers n and m (1 ≀ n, m ≀ 200 000) β€” the number of blocks in the strings t and s, respectively. The second line contains the descriptions of n parts of string t in the format "li-ci" (1 ≀ li ≀ 1 000 000) β€” the length of the i-th part and the corresponding lowercase English letter. The second line contains the descriptions of m parts of string s in the format "li-ci" (1 ≀ li ≀ 1 000 000) β€” the length of the i-th part and the corresponding lowercase English letter. Output Print a single integer β€” the number of occurrences of s in t. Examples Input 5 3 3-a 2-b 4-c 3-a 2-c 2-a 2-b 1-c Output 1 Input 6 1 3-a 6-b 7-a 4-c 8-e 2-a 3-a Output 6 Input 5 5 1-h 1-e 1-l 1-l 1-o 1-w 1-o 1-r 1-l 1-d Output 0 Note In the first sample, t = "aaabbccccaaacc", and string s = "aabbc". The only occurrence of string s in string t starts at position p = 2. In the second sample, t = "aaabbbbbbaaaaaaacccceeeeeeeeaa", and s = "aaa". The occurrences of s in t start at positions p = 1, p = 10, p = 11, p = 12, p = 13 and p = 14. Submitted Solution: ``` def Z_function(L, l): Z = [] for i in range(len(L)): if i == 0: Z.append(0) else: c = 0 for j in range(i, len(L)): if L[j][1] == L[j - i][1]: if l == 1 and L[j][0] > L[j - i][0]: c = L[j][0] - L[j - i][0] + 1 elif (L[j][0] == L[j - i][0] or ((j - i == 0 or j - i == l - 1) and L[j][0] >= L[j - i][0])): c += 1 else: break else: break Z.append(c) return Z def parse_string(string): L = [] L = string.split(' ') for i in range(len(L)): L[i] = [int(L[i][0]), L[i][-1]] i = 0 while i < len(L)-1: if L[i][1] == L[i+1][1]: L[i][0] += L[i+1][0] L.remove(L[i+1]) i+=1 return L def get_count_entering(t,s): count = 0 #Creating United List UL = s[:] UL.append([0,'$']) UL.extend(t) #End of Creating len_s = len(s) Z = Z_function(UL, len_s) for z in Z: if len_s == 1: count+=z elif z == len_s: count+=1 return count def main(): nm = input() del nm # string = input() t = parse_string(string) string = input() s = parse_string(string) print(get_count_entering(t,s)) if __name__ == '__main__': main() ``` No
8,695
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Each employee of the "Blake Techologies" company uses a special messaging app "Blake Messenger". All the stuff likes this app and uses it constantly. However, some important futures are missing. For example, many users want to be able to search through the message history. It was already announced that the new feature will appear in the nearest update, when developers faced some troubles that only you may help them to solve. All the messages are represented as a strings consisting of only lowercase English letters. In order to reduce the network load strings are represented in the special compressed form. Compression algorithm works as follows: string is represented as a concatenation of n blocks, each block containing only equal characters. One block may be described as a pair (li, ci), where li is the length of the i-th block and ci is the corresponding letter. Thus, the string s may be written as the sequence of pairs <image>. Your task is to write the program, that given two compressed string t and s finds all occurrences of s in t. Developers know that there may be many such occurrences, so they only ask you to find the number of them. Note that p is the starting position of some occurrence of s in t if and only if tptp + 1...tp + |s| - 1 = s, where ti is the i-th character of string t. Note that the way to represent the string in compressed form may not be unique. For example string "aaaa" may be given as <image>, <image>, <image>... Input The first line of the input contains two integers n and m (1 ≀ n, m ≀ 200 000) β€” the number of blocks in the strings t and s, respectively. The second line contains the descriptions of n parts of string t in the format "li-ci" (1 ≀ li ≀ 1 000 000) β€” the length of the i-th part and the corresponding lowercase English letter. The second line contains the descriptions of m parts of string s in the format "li-ci" (1 ≀ li ≀ 1 000 000) β€” the length of the i-th part and the corresponding lowercase English letter. Output Print a single integer β€” the number of occurrences of s in t. Examples Input 5 3 3-a 2-b 4-c 3-a 2-c 2-a 2-b 1-c Output 1 Input 6 1 3-a 6-b 7-a 4-c 8-e 2-a 3-a Output 6 Input 5 5 1-h 1-e 1-l 1-l 1-o 1-w 1-o 1-r 1-l 1-d Output 0 Note In the first sample, t = "aaabbccccaaacc", and string s = "aabbc". The only occurrence of string s in string t starts at position p = 2. In the second sample, t = "aaabbbbbbaaaaaaacccceeeeeeeeaa", and s = "aaa". The occurrences of s in t start at positions p = 1, p = 10, p = 11, p = 12, p = 13 and p = 14. Submitted Solution: ``` n,m = map(int, input().split()) a = list(map(str,input().split())) b = list(map(str,input().split())) str1 = '' str2 = '' for i in a: x = int(i[0]) c = i[2] str1 += (c*x) for i in b: x = int(i[0]) c = i[2] str2 += (c*x) i = 0 ans = 0 while (True): r = str1.rfind(str2,i) if r!=-1: ans +=1 i = r+1 else: break print(ans) ``` No
8,696
Provide tags and a correct Python 3 solution for this coding contest problem. Consider 2n rows of the seats in a bus. n rows of the seats on the left and n rows of the seats on the right. Each row can be filled by two people. So the total capacity of the bus is 4n. Consider that m (m ≀ 4n) people occupy the seats in the bus. The passengers entering the bus are numbered from 1 to m (in the order of their entering the bus). The pattern of the seat occupation is as below: 1-st row left window seat, 1-st row right window seat, 2-nd row left window seat, 2-nd row right window seat, ... , n-th row left window seat, n-th row right window seat. After occupying all the window seats (for m > 2n) the non-window seats are occupied: 1-st row left non-window seat, 1-st row right non-window seat, ... , n-th row left non-window seat, n-th row right non-window seat. All the passengers go to a single final destination. In the final destination, the passengers get off in the given order. 1-st row left non-window seat, 1-st row left window seat, 1-st row right non-window seat, 1-st row right window seat, ... , n-th row left non-window seat, n-th row left window seat, n-th row right non-window seat, n-th row right window seat. <image> The seating for n = 9 and m = 36. You are given the values n and m. Output m numbers from 1 to m, the order in which the passengers will get off the bus. Input The only line contains two integers, n and m (1 ≀ n ≀ 100, 1 ≀ m ≀ 4n) β€” the number of pairs of rows and the number of passengers. Output Print m distinct integers from 1 to m β€” the order in which the passengers will get off the bus. Examples Input 2 7 Output 5 1 6 2 7 3 4 Input 9 36 Output 19 1 20 2 21 3 22 4 23 5 24 6 25 7 26 8 27 9 28 10 29 11 30 12 31 13 32 14 33 15 34 16 35 17 36 18 Tags: implementation Correct Solution: ``` #parse_int = list(map(int, input().split())) lines, ppl = list(map(int, input().split())) bus = [ [2*i-1, 2*lines+2*i-1, 2*lines+2*i, 2*i] for i in range(1, lines+1) ] #for line in bus: print(line) #for line in bus: exit_bus.append([ line[1], line[0], line[2], line[3] ]) for line in bus: line[1], line[0] = line[0], line[1] exit_seq = [man for line in bus for man in line if man<=ppl] for _ in exit_seq[:len(exit_seq)-1]: print(_, end=' ') print(exit_seq[-1]) ```
8,697
Provide tags and a correct Python 3 solution for this coding contest problem. Consider 2n rows of the seats in a bus. n rows of the seats on the left and n rows of the seats on the right. Each row can be filled by two people. So the total capacity of the bus is 4n. Consider that m (m ≀ 4n) people occupy the seats in the bus. The passengers entering the bus are numbered from 1 to m (in the order of their entering the bus). The pattern of the seat occupation is as below: 1-st row left window seat, 1-st row right window seat, 2-nd row left window seat, 2-nd row right window seat, ... , n-th row left window seat, n-th row right window seat. After occupying all the window seats (for m > 2n) the non-window seats are occupied: 1-st row left non-window seat, 1-st row right non-window seat, ... , n-th row left non-window seat, n-th row right non-window seat. All the passengers go to a single final destination. In the final destination, the passengers get off in the given order. 1-st row left non-window seat, 1-st row left window seat, 1-st row right non-window seat, 1-st row right window seat, ... , n-th row left non-window seat, n-th row left window seat, n-th row right non-window seat, n-th row right window seat. <image> The seating for n = 9 and m = 36. You are given the values n and m. Output m numbers from 1 to m, the order in which the passengers will get off the bus. Input The only line contains two integers, n and m (1 ≀ n ≀ 100, 1 ≀ m ≀ 4n) β€” the number of pairs of rows and the number of passengers. Output Print m distinct integers from 1 to m β€” the order in which the passengers will get off the bus. Examples Input 2 7 Output 5 1 6 2 7 3 4 Input 9 36 Output 19 1 20 2 21 3 22 4 23 5 24 6 25 7 26 8 27 9 28 10 29 11 30 12 31 13 32 14 33 15 34 16 35 17 36 18 Tags: implementation Correct Solution: ``` import sys import math #sys.stdin = open('test.inp','r') n, k = map(int, input().split()) l, r, i, ok= n * 2 + 1, 1, 1, False while l <= k or r <= k and (l <= 4*n and r <= 2*n): if l <= k and l <= 4*n: print(l, end=' ') l = l + 1 if r <= k and r <= 2*n: print(r, end=' ') r = r + 1 ```
8,698
Provide tags and a correct Python 3 solution for this coding contest problem. Consider 2n rows of the seats in a bus. n rows of the seats on the left and n rows of the seats on the right. Each row can be filled by two people. So the total capacity of the bus is 4n. Consider that m (m ≀ 4n) people occupy the seats in the bus. The passengers entering the bus are numbered from 1 to m (in the order of their entering the bus). The pattern of the seat occupation is as below: 1-st row left window seat, 1-st row right window seat, 2-nd row left window seat, 2-nd row right window seat, ... , n-th row left window seat, n-th row right window seat. After occupying all the window seats (for m > 2n) the non-window seats are occupied: 1-st row left non-window seat, 1-st row right non-window seat, ... , n-th row left non-window seat, n-th row right non-window seat. All the passengers go to a single final destination. In the final destination, the passengers get off in the given order. 1-st row left non-window seat, 1-st row left window seat, 1-st row right non-window seat, 1-st row right window seat, ... , n-th row left non-window seat, n-th row left window seat, n-th row right non-window seat, n-th row right window seat. <image> The seating for n = 9 and m = 36. You are given the values n and m. Output m numbers from 1 to m, the order in which the passengers will get off the bus. Input The only line contains two integers, n and m (1 ≀ n ≀ 100, 1 ≀ m ≀ 4n) β€” the number of pairs of rows and the number of passengers. Output Print m distinct integers from 1 to m β€” the order in which the passengers will get off the bus. Examples Input 2 7 Output 5 1 6 2 7 3 4 Input 9 36 Output 19 1 20 2 21 3 22 4 23 5 24 6 25 7 26 8 27 9 28 10 29 11 30 12 31 13 32 14 33 15 34 16 35 17 36 18 Tags: implementation Correct Solution: ``` n,m=input().split(' ') n=int(n) m=int(m) L=[] for i in range (1,2*n+1) : L.append(2*n+i) L.append(i) for i in range(4*n) : if L[i]<=m : print(L[i],end=' ') ```
8,699