text
stringlengths
198
433k
conversation_id
int64
0
109k
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree with n nodes, numerated from 0 to n-1. For each k between 0 and n, inclusive, you have to count the number of unordered pairs (u,v), u ≠ v, such that the MEX of all the node labels in the shortest path from u to v (including end points) is k. The MEX of a sequence of integers is the smallest non-negative integer that does not belong to the sequence. Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^{5}). The next n-1 lines of each test case describe the tree that has to be constructed. These lines contain two integers u and v (0 ≤ u,v ≤ n-1) denoting an edge between u and v (u ≠ v). It is guaranteed that the given edges form a tree. It is also guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^{5}. Output For each test case, print n+1 integers: the number of paths in the tree, such that the MEX of all the node labels in that path is k for each k from 0 to n. Example Input 2 4 0 1 0 2 2 3 2 1 0 Output 1 2 1 1 1 0 0 1 Note 1. In example case 1, <image> * For k = 0, there is 1 path that is from 2 to 3 as MEX([2, 3]) = 0. * For k = 1, there are 2 paths that is from 0 to 2 as MEX([0, 2]) = 1 and 0 to 3 as MEX([0, 2, 3]) = 1. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. * For k = 3, there is 1 path that is from 1 to 2 as MEX([1, 0, 2]) = 3 * For k = 4, there is 1 path that is from 1 to 3 as MEX([1, 0, 2, 3]) = 4. 2. In example case 2, <image> * For k = 0, there are no such paths. * For k = 1, there are no such paths. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. Tags: combinatorics, dfs and similar, implementation, math, trees Correct Solution: ``` import sys from collections import deque input = sys.stdin.readline def solve(): n = int(input()) G = [[] for _ in range(n)] for _ in range(n-1): a,b = map(int,input().split()) G[a].append(b) G[b].append(a) size = [0]*n par = [-1]*n stk = [0] visited = [False]*n while stk: x = stk[-1] if not visited[x]: visited[x] = True for y in G[x]: if not visited[y]: par[y] = x stk.append(y) else: stk.pop() for y in G[x]: size[x] += size[y] size[x] += 1 visited = [False]*n ans = [0]*(n+1) for y in G[0]: ans[0] += size[y] * (size[y]-1) // 2 P = n*(n-1)//2 P -= ans[0] visited[0] = True l,r = 0,0 for i in range(1,n): if visited[i]: ans[i] = P - size[r] * size[l] continue u = i acc = 0 while not visited[u]: visited[u] = True if par[u] == 0: size[0] -= size[u] u = par[u] if u == l: ans[i] = P - size[r] * size[i] l = i P = size[r] * size[l] elif u == r: ans[i] = P - size[l] * size[i] r = i P = size[r] * size[l] else: ans[i] = P P = 0 break ans[-1] = P print(*ans) for nt in range(int(input())): solve() ```
7,800
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree with n nodes, numerated from 0 to n-1. For each k between 0 and n, inclusive, you have to count the number of unordered pairs (u,v), u ≠ v, such that the MEX of all the node labels in the shortest path from u to v (including end points) is k. The MEX of a sequence of integers is the smallest non-negative integer that does not belong to the sequence. Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^{5}). The next n-1 lines of each test case describe the tree that has to be constructed. These lines contain two integers u and v (0 ≤ u,v ≤ n-1) denoting an edge between u and v (u ≠ v). It is guaranteed that the given edges form a tree. It is also guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^{5}. Output For each test case, print n+1 integers: the number of paths in the tree, such that the MEX of all the node labels in that path is k for each k from 0 to n. Example Input 2 4 0 1 0 2 2 3 2 1 0 Output 1 2 1 1 1 0 0 1 Note 1. In example case 1, <image> * For k = 0, there is 1 path that is from 2 to 3 as MEX([2, 3]) = 0. * For k = 1, there are 2 paths that is from 0 to 2 as MEX([0, 2]) = 1 and 0 to 3 as MEX([0, 2, 3]) = 1. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. * For k = 3, there is 1 path that is from 1 to 2 as MEX([1, 0, 2]) = 3 * For k = 4, there is 1 path that is from 1 to 3 as MEX([1, 0, 2, 3]) = 4. 2. In example case 2, <image> * For k = 0, there are no such paths. * For k = 1, there are no such paths. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. Tags: combinatorics, dfs and similar, implementation, math, trees Correct Solution: ``` import sys;from collections import Counter;input = sys.stdin.readline def tree_dfs(g, root=0): s = [root];d = [1] * len(g);order = [] while s:p = s.pop();d[p] = 0;order.append(p);s += [node for node in g[p] if d[node]] return order class LCA: def __init__(self,n,s,edge): self.logn=n.bit_length() self.parent=[n*[-1]for _ in range(self.logn)] self.dist=[0]*n stack=[s] visited={s} for i in stack: for j in edge[i]: if j in visited:continue stack.append(j) visited.add(j) self.parent[0][j]=i self.dist[j]=self.dist[i]+1 for k in range(1,self.logn):self.parent[k][j]=self.parent[k-1][self.parent[k-1][j]] def query(self,a,b): if self.dist[a]<self.dist[b]:a,b=b,a if self.dist[a]>self.dist[b]: for i in range(self.logn): if (self.dist[a]-self.dist[b])&(1<<i):a=self.parent[i][a] if a==b:return a for i in range(self.logn-1,-1,-1): if self.parent[i][a]!=self.parent[i][b]: a=self.parent[i][a] b=self.parent[i][b] return self.parent[0][a] def path_range(self,a,b):return self.dist[a]+self.dist[b]-2*self.dist[self.query(a,b)] def x_in_abpath(self,x,a,b):return self.path_range(a,x)+self.path_range(b,x)==self.path_range(a,b) for _ in range(int(input())): n = int(input()) g = [[] for _ in range(n)] for _ in range(n - 1): a, b = map(int, input().split()); g[a].append(b); g[b].append(a) ans = [0] * (n + 1); ans[0] = n * (n - 1) // 2; order = tree_dfs(g); d = [0] * n for v in order[::-1]:d[v] += (sum([d[node] for node in g[v]]) + 1) lca = LCA(n, 0, g);a, b = 0, 0 for node in g[0]: a += d[node]; b += d[node] * d[node] if lca.query(node, 1) == node: d[0] -= d[node] ans[1] = (a * a - b) // 2 + n - 1; l, r = 0, 0 for i in range(1, n): if lca.x_in_abpath(i, l, r): ans[i + 1] = ans[i]; continue elif lca.query(i, l) == l and lca.query(i, r) == 0: l = i elif lca.query(i, r) == r and lca.query(i, l) == 0: r = i else: break ans[i + 1] = d[l] * d[r] for i in range(n):ans[i] = ans[i] - ans[i + 1] print(*ans) ```
7,801
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree with n nodes, numerated from 0 to n-1. For each k between 0 and n, inclusive, you have to count the number of unordered pairs (u,v), u ≠ v, such that the MEX of all the node labels in the shortest path from u to v (including end points) is k. The MEX of a sequence of integers is the smallest non-negative integer that does not belong to the sequence. Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^{5}). The next n-1 lines of each test case describe the tree that has to be constructed. These lines contain two integers u and v (0 ≤ u,v ≤ n-1) denoting an edge between u and v (u ≠ v). It is guaranteed that the given edges form a tree. It is also guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^{5}. Output For each test case, print n+1 integers: the number of paths in the tree, such that the MEX of all the node labels in that path is k for each k from 0 to n. Example Input 2 4 0 1 0 2 2 3 2 1 0 Output 1 2 1 1 1 0 0 1 Note 1. In example case 1, <image> * For k = 0, there is 1 path that is from 2 to 3 as MEX([2, 3]) = 0. * For k = 1, there are 2 paths that is from 0 to 2 as MEX([0, 2]) = 1 and 0 to 3 as MEX([0, 2, 3]) = 1. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. * For k = 3, there is 1 path that is from 1 to 2 as MEX([1, 0, 2]) = 3 * For k = 4, there is 1 path that is from 1 to 3 as MEX([1, 0, 2, 3]) = 4. 2. In example case 2, <image> * For k = 0, there are no such paths. * For k = 1, there are no such paths. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. Tags: combinatorics, dfs and similar, implementation, math, trees Correct Solution: ``` import sys from collections import Counter input = sys.stdin.readline def tree_dfs(g, root=0): s = [root] d = [1] * len(g) order = [] while s: p = s.pop() d[p] = 0 order.append(p) for node in g[p]: if d[node]: s.append(node) return order class LCA: def __init__(self,n,s,edge): self.logn=n.bit_length() self.parent=[n*[-1]for _ in range(self.logn)] self.dist=[0]*n stack=[s] visited={s} for i in stack: for j in edge[i]: if j in visited:continue stack.append(j) visited.add(j) self.parent[0][j]=i self.dist[j]=self.dist[i]+1 for k in range(1,self.logn):self.parent[k][j]=self.parent[k-1][self.parent[k-1][j]] def query(self,a,b): if self.dist[a]<self.dist[b]:a,b=b,a if self.dist[a]>self.dist[b]: for i in range(self.logn): if (self.dist[a]-self.dist[b])&(1<<i):a=self.parent[i][a] if a==b:return a for i in range(self.logn-1,-1,-1): if self.parent[i][a]!=self.parent[i][b]: a=self.parent[i][a] b=self.parent[i][b] return self.parent[0][a] def path_range(self,a,b):return self.dist[a]+self.dist[b]-2*self.dist[self.query(a,b)] def x_in_abpath(self,x,a,b):return self.path_range(a,x)+self.path_range(b,x)==self.path_range(a,b) t = int(input()) for _ in range(t): n = int(input()) g = [[] for _ in range(n)] for _ in range(n - 1): a, b = map(int, input().split()) g[a].append(b) g[b].append(a) ans = [0] * (n + 1) ans[0] = n * (n - 1) // 2 order = tree_dfs(g) d = [0] * n for v in order[::-1]: for node in g[v]: d[v] += d[node] d[v] += 1 lca = LCA(n, 0, g) a, b = 0, 0 for node in g[0]: a += d[node] b += d[node] * d[node] if lca.query(node, 1) == node: d[0] -= d[node] ans[1] = (a * a - b) // 2 + n - 1 l, r = 0, 0 for i in range(1, n): if lca.x_in_abpath(i, l, r): ans[i + 1] = ans[i] continue elif lca.query(i, l) == l and lca.query(i, r) == 0: l = i elif lca.query(i, r) == r and lca.query(i, l) == 0: r = i else: break ans[i + 1] = d[l] * d[r] for i in range(n): ans[i] = ans[i] - ans[i + 1] print(*ans) ```
7,802
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree with n nodes, numerated from 0 to n-1. For each k between 0 and n, inclusive, you have to count the number of unordered pairs (u,v), u ≠ v, such that the MEX of all the node labels in the shortest path from u to v (including end points) is k. The MEX of a sequence of integers is the smallest non-negative integer that does not belong to the sequence. Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^{5}). The next n-1 lines of each test case describe the tree that has to be constructed. These lines contain two integers u and v (0 ≤ u,v ≤ n-1) denoting an edge between u and v (u ≠ v). It is guaranteed that the given edges form a tree. It is also guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^{5}. Output For each test case, print n+1 integers: the number of paths in the tree, such that the MEX of all the node labels in that path is k for each k from 0 to n. Example Input 2 4 0 1 0 2 2 3 2 1 0 Output 1 2 1 1 1 0 0 1 Note 1. In example case 1, <image> * For k = 0, there is 1 path that is from 2 to 3 as MEX([2, 3]) = 0. * For k = 1, there are 2 paths that is from 0 to 2 as MEX([0, 2]) = 1 and 0 to 3 as MEX([0, 2, 3]) = 1. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. * For k = 3, there is 1 path that is from 1 to 2 as MEX([1, 0, 2]) = 3 * For k = 4, there is 1 path that is from 1 to 3 as MEX([1, 0, 2, 3]) = 4. 2. In example case 2, <image> * For k = 0, there are no such paths. * For k = 1, there are no such paths. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. Tags: combinatorics, dfs and similar, implementation, math, trees Correct Solution: ``` def divisors(M): d=[] i=1 while M>=i**2: if M%i==0: d.append(i) if i**2!=M: d.append(M//i) i=i+1 return d def popcount(x): x = x - ((x >> 1) & 0x55555555) x = (x & 0x33333333) + ((x >> 2) & 0x33333333) x = (x + (x >> 4)) & 0x0f0f0f0f x = x + (x >> 8) x = x + (x >> 16) return x & 0x0000007f def eratosthenes(n): res=[0 for i in range(n+1)] prime=set([]) for i in range(2,n+1): if not res[i]: prime.add(i) for j in range(1,n//i+1): res[i*j]=1 return prime def factorization(n): res=[] for p in prime: if n%p==0: while n%p==0: n//=p res.append(p) if n!=1: res.append(n) return res def euler_phi(n): res = n for x in range(2,n+1): if x ** 2 > n: break if n%x==0: res = res//x * (x-1) while n%x==0: n //= x if n!=1: res = res//n * (n-1) return res def ind(b,n): res=0 while n%b==0: res+=1 n//=b return res def isPrimeMR(n): d = n - 1 d = d // (d & -d) L = [2, 3, 5, 7, 11, 13, 17] for a in L: t = d y = pow(a, t, n) if y == 1: continue while y != n - 1: y = (y * y) % n if y == 1 or t == n - 1: return 0 t <<= 1 return 1 def findFactorRho(n): from math import gcd m = 1 << n.bit_length() // 8 for c in range(1, 99): f = lambda x: (x * x + c) % n y, r, q, g = 2, 1, 1, 1 while g == 1: x = y for i in range(r): y = f(y) k = 0 while k < r and g == 1: ys = y for i in range(min(m, r - k)): y = f(y) q = q * abs(x - y) % n g = gcd(q, n) k += m r <<= 1 if g == n: g = 1 while g == 1: ys = f(ys) g = gcd(abs(x - ys), n) if g < n: if isPrimeMR(g): return g elif isPrimeMR(n // g): return n // g return findFactorRho(g) def primeFactor(n): i = 2 ret = {} rhoFlg = 0 while i*i <= n: k = 0 while n % i == 0: n //= i k += 1 if k: ret[i] = k i += 1 + i % 2 if i == 101 and n >= 2 ** 20: while n > 1: if isPrimeMR(n): ret[n], n = 1, 1 else: rhoFlg = 1 j = findFactorRho(n) k = 0 while n % j == 0: n //= j k += 1 ret[j] = k if n > 1: ret[n] = 1 if rhoFlg: ret = {x: ret[x] for x in sorted(ret)} return ret def divisors(n): res = [1] prime = primeFactor(n) for p in prime: newres = [] for d in res: for j in range(prime[p]+1): newres.append(d*p**j) res = newres res.sort() return res def xorfactorial(num): if num==0: return 0 elif num==1: return 1 elif num==2: return 3 elif num==3: return 0 else: x=baseorder(num) return (2**x)*((num-2**x+1)%2)+function(num-2**x) def xorconv(n,X,Y): if n==0: res=[(X[0]*Y[0])%mod] return res x=[X[i]+X[i+2**(n-1)] for i in range(2**(n-1))] y=[Y[i]+Y[i+2**(n-1)] for i in range(2**(n-1))] z=[X[i]-X[i+2**(n-1)] for i in range(2**(n-1))] w=[Y[i]-Y[i+2**(n-1)] for i in range(2**(n-1))] res1=xorconv(n-1,x,y) res2=xorconv(n-1,z,w) former=[(res1[i]+res2[i])*inv for i in range(2**(n-1))] latter=[(res1[i]-res2[i])*inv for i in range(2**(n-1))] former=list(map(lambda x:x%mod,former)) latter=list(map(lambda x:x%mod,latter)) return former+latter def merge_sort(A,B): pos_A,pos_B = 0,0 n,m = len(A),len(B) res = [] while pos_A < n and pos_B < m: a,b = A[pos_A],B[pos_B] if a < b: res.append(a) pos_A += 1 else: res.append(b) pos_B += 1 res += A[pos_A:] res += B[pos_B:] return res class UnionFindVerSize(): def __init__(self, N): self._parent = [n for n in range(0, N)] self._size = [1] * N self.group = N def find_root(self, x): if self._parent[x] == x: return x self._parent[x] = self.find_root(self._parent[x]) stack = [x] while self._parent[stack[-1]]!=stack[-1]: stack.append(self._parent[stack[-1]]) for v in stack: self._parent[v] = stack[-1] return self._parent[x] def unite(self, x, y): gx = self.find_root(x) gy = self.find_root(y) if gx == gy: return self.group -= 1 if self._size[gx] < self._size[gy]: self._parent[gx] = gy self._size[gy] += self._size[gx] else: self._parent[gy] = gx self._size[gx] += self._size[gy] def get_size(self, x): return self._size[self.find_root(x)] def is_same_group(self, x, y): return self.find_root(x) == self.find_root(y) class WeightedUnionFind(): def __init__(self,N): self.parent = [i for i in range(N)] self.size = [1 for i in range(N)] self.val = [0 for i in range(N)] self.flag = True self.edge = [[] for i in range(N)] def dfs(self,v,pv): stack = [(v,pv)] new_parent = self.parent[pv] while stack: v,pv = stack.pop() self.parent[v] = new_parent for nv,w in self.edge[v]: if nv!=pv: self.val[nv] = self.val[v] + w stack.append((nv,v)) def unite(self,x,y,w): if not self.flag: return if self.parent[x]==self.parent[y]: self.flag = (self.val[x] - self.val[y] == w) return if self.size[self.parent[x]]>self.size[self.parent[y]]: self.edge[x].append((y,-w)) self.edge[y].append((x,w)) self.size[x] += self.size[y] self.val[y] = self.val[x] - w self.dfs(y,x) else: self.edge[x].append((y,-w)) self.edge[y].append((x,w)) self.size[y] += self.size[x] self.val[x] = self.val[y] + w self.dfs(x,y) class Dijkstra(): class Edge(): def __init__(self, _to, _cost): self.to = _to self.cost = _cost def __init__(self, V): self.G = [[] for i in range(V)] self._E = 0 self._V = V @property def E(self): return self._E @property def V(self): return self._V def add_edge(self, _from, _to, _cost): self.G[_from].append(self.Edge(_to, _cost)) self._E += 1 def shortest_path(self, s): import heapq que = [] d = [10**15] * self.V d[s] = 0 heapq.heappush(que, (0, s)) while len(que) != 0: cost, v = heapq.heappop(que) if d[v] < cost: continue for i in range(len(self.G[v])): e = self.G[v][i] if d[e.to] > d[v] + e.cost: d[e.to] = d[v] + e.cost heapq.heappush(que, (d[e.to], e.to)) return d #Z[i]:length of the longest list starting from S[i] which is also a prefix of S #O(|S|) def Z_algorithm(s): N = len(s) Z_alg = [0]*N Z_alg[0] = N i = 1 j = 0 while i < N: while i+j < N and s[j] == s[i+j]: j += 1 Z_alg[i] = j if j == 0: i += 1 continue k = 1 while i+k < N and k + Z_alg[k]<j: Z_alg[i+k] = Z_alg[k] k += 1 i += k j -= k return Z_alg class BIT(): def __init__(self,n,mod=0): self.BIT = [0]*(n+1) self.num = n self.mod = mod def query(self,idx): res_sum = 0 mod = self.mod while idx > 0: res_sum += self.BIT[idx] if mod: res_sum %= mod idx -= idx&(-idx) return res_sum #Ai += x O(logN) def update(self,idx,x): mod = self.mod while idx <= self.num: self.BIT[idx] += x if mod: self.BIT[idx] %= mod idx += idx&(-idx) return class dancinglink(): def __init__(self,n,debug=False): self.n = n self.debug = debug self._left = [i-1 for i in range(n)] self._right = [i+1 for i in range(n)] self.exist = [True for i in range(n)] def pop(self,k): if self.debug: assert self.exist[k] L = self._left[k] R = self._right[k] if L!=-1: if R!=self.n: self._right[L],self._left[R] = R,L else: self._right[L] = self.n elif R!=self.n: self._left[R] = -1 self.exist[k] = False def left(self,idx,k=1): if self.debug: assert self.exist[idx] res = idx while k: res = self._left[res] if res==-1: break k -= 1 return res def right(self,idx,k=1): if self.debug: assert self.exist[idx] res = idx while k: res = self._right[res] if res==self.n: break k -= 1 return res class SparseTable(): def __init__(self,A,merge_func,ide_ele): N=len(A) n=N.bit_length() self.table=[[ide_ele for i in range(n)] for i in range(N)] self.merge_func=merge_func for i in range(N): self.table[i][0]=A[i] for j in range(1,n): for i in range(0,N-2**j+1): f=self.table[i][j-1] s=self.table[i+2**(j-1)][j-1] self.table[i][j]=self.merge_func(f,s) def query(self,s,t): b=t-s+1 m=b.bit_length()-1 return self.merge_func(self.table[s][m],self.table[t-2**m+1][m]) class BinaryTrie: class node: def __init__(self,val): self.left = None self.right = None self.max = val def __init__(self): self.root = self.node(-10**15) def append(self,key,val): pos = self.root for i in range(29,-1,-1): pos.max = max(pos.max,val) if key>>i & 1: if pos.right is None: pos.right = self.node(val) pos = pos.right else: pos = pos.right else: if pos.left is None: pos.left = self.node(val) pos = pos.left else: pos = pos.left pos.max = max(pos.max,val) def search(self,M,xor): res = -10**15 pos = self.root for i in range(29,-1,-1): if pos is None: break if M>>i & 1: if xor>>i & 1: if pos.right: res = max(res,pos.right.max) pos = pos.left else: if pos.left: res = max(res,pos.left.max) pos = pos.right else: if xor>>i & 1: pos = pos.right else: pos = pos.left if pos: res = max(res,pos.max) return res def solveequation(edge,ans,n,m): #edge=[[to,dire,id]...] x=[0]*m used=[False]*n for v in range(n): if used[v]: continue y = dfs(v) if y!=0: return False return x def dfs(v): used[v]=True r=ans[v] for to,dire,id in edge[v]: if used[to]: continue y=dfs(to) if dire==-1: x[id]=y else: x[id]=-y r+=y return r class SegmentTree: def __init__(self, init_val, segfunc, ide_ele): n = len(init_val) self.segfunc = segfunc self.ide_ele = ide_ele self.num = 1 << (n - 1).bit_length() self.tree = [ide_ele] * 2 * self.num self.size = n for i in range(n): self.tree[self.num + i] = init_val[i] for i in range(self.num - 1, 0, -1): self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1]) def update(self, k, x): k += self.num self.tree[k] = x while k > 1: self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1]) k >>= 1 def query(self, l, r): if r==self.size: r = self.num res = self.ide_ele l += self.num r += self.num while l < r: if l & 1: res = self.segfunc(res, self.tree[l]) l += 1 if r & 1: res = self.segfunc(res, self.tree[r - 1]) l >>= 1 r >>= 1 return res def bisect_l(self,l,r,x): l += self.num r += self.num Lmin = -1 Rmin = -1 while l<r: if l & 1: if self.tree[l] <= x and Lmin==-1: Lmin = l l += 1 if r & 1: if self.tree[r-1] <=x: Rmin = r-1 l >>= 1 r >>= 1 if Lmin != -1: pos = Lmin while pos<self.num: if self.tree[2 * pos] <=x: pos = 2 * pos else: pos = 2 * pos +1 return pos-self.num elif Rmin != -1: pos = Rmin while pos<self.num: if self.tree[2 * pos] <=x: pos = 2 * pos else: pos = 2 * pos +1 return pos-self.num else: return -1 import sys,random,bisect from collections import deque,defaultdict from heapq import heapify,heappop,heappush from itertools import permutations from math import gcd,log input = lambda :sys.stdin.readline().rstrip() mi = lambda :map(int,input().split()) li = lambda :list(mi()) for _ in range(int(input())): n = int(input()) edge = [[] for i in range(n)] for _ in range(n-1): u,v = mi() edge[u].append(v) edge[v].append(u) stack = [0] cnt = [0 for i in range(n)] parent = [-1 for i in range(n)] begin = [0 for i in range(n)] end = [0 for i in range(n)] size = [1 for i in range(n)] next_id = 1 while stack: v = stack[-1] if cnt[v]==len(edge[v]): pv = parent[v] if pv!=-1: size[pv] += size[v] end[v] = next_id next_id += 1 stack.pop() else: nv = edge[v][cnt[v]] cnt[v] += 1 if nv==parent[v]: continue parent[nv] = v stack.append(nv) begin[nv] = next_id next_id += 1 def is_child(u,v): return begin[u] <= begin[v] and end[v] <= end[u] res = [0 for i in range(n+1)] res[0] = n*(n-1)//2 res[1] = n*(n-1)//2 a = 1 pa = -1 b = -1 pb = -1 for v in edge[0]: res[1] -= size[v] * (size[v]-1)//2 if is_child(v,1): res[2] = size[1] * (n - size[v]) pa = v for i in range(2,n): if is_child(a,i): a = i elif is_child(i,a): pass elif b==-1: for v in edge[0]: if is_child(v,i): pb = v break if pa==pb: break else: b = i elif is_child(b,i): b = i elif is_child(i,b): pass else: break if b==-1: res[i+1] = size[a] * (n-size[pa]) else: res[i+1] = size[a] * size[b] for i in range(n): res[i] -= res[i+1] print(*res) ```
7,803
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree with n nodes, numerated from 0 to n-1. For each k between 0 and n, inclusive, you have to count the number of unordered pairs (u,v), u ≠ v, such that the MEX of all the node labels in the shortest path from u to v (including end points) is k. The MEX of a sequence of integers is the smallest non-negative integer that does not belong to the sequence. Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^{5}). The next n-1 lines of each test case describe the tree that has to be constructed. These lines contain two integers u and v (0 ≤ u,v ≤ n-1) denoting an edge between u and v (u ≠ v). It is guaranteed that the given edges form a tree. It is also guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^{5}. Output For each test case, print n+1 integers: the number of paths in the tree, such that the MEX of all the node labels in that path is k for each k from 0 to n. Example Input 2 4 0 1 0 2 2 3 2 1 0 Output 1 2 1 1 1 0 0 1 Note 1. In example case 1, <image> * For k = 0, there is 1 path that is from 2 to 3 as MEX([2, 3]) = 0. * For k = 1, there are 2 paths that is from 0 to 2 as MEX([0, 2]) = 1 and 0 to 3 as MEX([0, 2, 3]) = 1. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. * For k = 3, there is 1 path that is from 1 to 2 as MEX([1, 0, 2]) = 3 * For k = 4, there is 1 path that is from 1 to 3 as MEX([1, 0, 2, 3]) = 4. 2. In example case 2, <image> * For k = 0, there are no such paths. * For k = 1, there are no such paths. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. Tags: combinatorics, dfs and similar, implementation, math, trees Correct Solution: ``` import sys from sys import stdin from collections import deque def NC_Dij(lis,start): N = len(lis) ret = [float("inf")] * len(lis) ret[start] = 0 chnum = [1] * N q = deque([start]) plis = [i for i in range(len(lis))] while len(q) > 0: now = q.popleft() for nex in lis[now]: if ret[nex] > ret[now] + 1: ret[nex] = ret[now] + 1 plis[nex] = now q.append(nex) td = [(ret[i],i) for i in range(N)] td.sort() td.reverse() for tmp,i in td: if plis[i] != i: chnum[ plis[i] ] += chnum[i] return ret,plis,chnum tt = int(stdin.readline()) for loop in range(tt): n = int(stdin.readline()) lis = [ [] for i in range(n) ] for i in range(n-1): u,v = map(int,stdin.readline().split()) lis[u].append(v) lis[v].append(u) dlis,plis,chnum = NC_Dij(lis,0) ans = [0] * (n+1) ans[0] = n * (n-1)//2 in_flag = [False] * n in_flag[0] = True l,r = 0,0 llast = None #parent is 0 and l is child flag = True for v in range(n): nv = v if in_flag[nv] == False: while True: if in_flag[nv] == True: if nv == l: l = v elif nv == r: r = v else: flag = False break in_flag[nv] = True nv = plis[nv] if not flag: break if l == 0 and r == 0: nans = n * (n-1)//2 for nex in lis[0]: nans -= chnum[nex] * (chnum[nex]-1)//2 elif r == 0: if llast == None: tv = l while plis[tv] != 0: tv = plis[tv] llast = tv nans = chnum[l] * (n-chnum[llast]) else: nans = chnum[l] * chnum[r] ans[v+1] = nans for i in range(n): ans[i] -= ans[i+1] #print (chnum) print (*ans) ```
7,804
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree with n nodes, numerated from 0 to n-1. For each k between 0 and n, inclusive, you have to count the number of unordered pairs (u,v), u ≠ v, such that the MEX of all the node labels in the shortest path from u to v (including end points) is k. The MEX of a sequence of integers is the smallest non-negative integer that does not belong to the sequence. Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^{5}). The next n-1 lines of each test case describe the tree that has to be constructed. These lines contain two integers u and v (0 ≤ u,v ≤ n-1) denoting an edge between u and v (u ≠ v). It is guaranteed that the given edges form a tree. It is also guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^{5}. Output For each test case, print n+1 integers: the number of paths in the tree, such that the MEX of all the node labels in that path is k for each k from 0 to n. Example Input 2 4 0 1 0 2 2 3 2 1 0 Output 1 2 1 1 1 0 0 1 Note 1. In example case 1, <image> * For k = 0, there is 1 path that is from 2 to 3 as MEX([2, 3]) = 0. * For k = 1, there are 2 paths that is from 0 to 2 as MEX([0, 2]) = 1 and 0 to 3 as MEX([0, 2, 3]) = 1. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. * For k = 3, there is 1 path that is from 1 to 2 as MEX([1, 0, 2]) = 3 * For k = 4, there is 1 path that is from 1 to 3 as MEX([1, 0, 2, 3]) = 4. 2. In example case 2, <image> * For k = 0, there are no such paths. * For k = 1, there are no such paths. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. Tags: combinatorics, dfs and similar, implementation, math, trees Correct Solution: ``` import sys def putin(): return map(int, sys.stdin.readline().split()) def sol(): n = int(sys.stdin.readline()) G = [] for i in range(n): G.append([]) for i in range(n - 1): u, v = putin() G[u].append(v) G[v].append(u) parents = [0] * n parents[0] = -1 capacity = [0] * n DFS_stack = [0] colors = [0] * n while DFS_stack: new_v = DFS_stack[-1] if colors[new_v] == 0: colors[new_v] = 1 for elem in G[new_v]: if colors[elem] == 0: DFS_stack.append(elem) parents[elem] = new_v elif colors[new_v] == 1: colors[new_v] = 2 DFS_stack.pop() S = 0 for elem in G[new_v]: if colors[elem] == 2: S += capacity[elem] capacity[new_v] = S + 1 else: DFS_stack.pop() L = 0 R = 0 answer = [n * (n - 1) // 2] S = 0 for children in G[0]: S += capacity[children] * (capacity[children] - 1) // 2 answer.append(n * (n - 1) // 2 - S) cur_v = 0 path = {0} while len(answer) < n + 1: cur_v += 1 ancestor = cur_v while ancestor not in path: path.add(ancestor) if parents[ancestor] == 0: capacity[0] -= capacity[ancestor] ancestor = parents[ancestor] if ancestor != cur_v: if ancestor != L and ancestor != R: break if ancestor == L: L = cur_v else: R = cur_v answer.append((capacity[L]) * (capacity[R])) while len(answer) < n + 2: answer.append(0) for i in range(n + 1): print(answer[i] - answer[i + 1], end=' ') print() for iter in range(int(sys.stdin.readline())): sol() ```
7,805
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree with n nodes, numerated from 0 to n-1. For each k between 0 and n, inclusive, you have to count the number of unordered pairs (u,v), u ≠ v, such that the MEX of all the node labels in the shortest path from u to v (including end points) is k. The MEX of a sequence of integers is the smallest non-negative integer that does not belong to the sequence. Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^{5}). The next n-1 lines of each test case describe the tree that has to be constructed. These lines contain two integers u and v (0 ≤ u,v ≤ n-1) denoting an edge between u and v (u ≠ v). It is guaranteed that the given edges form a tree. It is also guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^{5}. Output For each test case, print n+1 integers: the number of paths in the tree, such that the MEX of all the node labels in that path is k for each k from 0 to n. Example Input 2 4 0 1 0 2 2 3 2 1 0 Output 1 2 1 1 1 0 0 1 Note 1. In example case 1, <image> * For k = 0, there is 1 path that is from 2 to 3 as MEX([2, 3]) = 0. * For k = 1, there are 2 paths that is from 0 to 2 as MEX([0, 2]) = 1 and 0 to 3 as MEX([0, 2, 3]) = 1. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. * For k = 3, there is 1 path that is from 1 to 2 as MEX([1, 0, 2]) = 3 * For k = 4, there is 1 path that is from 1 to 3 as MEX([1, 0, 2, 3]) = 4. 2. In example case 2, <image> * For k = 0, there are no such paths. * For k = 1, there are no such paths. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. Tags: combinatorics, dfs and similar, implementation, math, trees Correct Solution: ``` import sys from collections import Counter input = sys.stdin.readline def tree_dfs(g, root=0): s = [root] d = [1] * len(g) order = [] while s: p = s.pop() d[p] = 0 order.append(p) for node in g[p]: if d[node]: s.append(node) return order class LCA: def __init__(self,n,s,edge): self.logn=n.bit_length() self.parent=[n*[-1]for _ in range(self.logn)] self.dist=[0]*n stack=[s] visited={s} for i in stack: for j in edge[i]: if j in visited:continue stack.append(j) visited.add(j) self.parent[0][j]=i self.dist[j]=self.dist[i]+1 for k in range(1,self.logn):self.parent[k][j]=self.parent[k-1][self.parent[k-1][j]] def query(self,a,b): if self.dist[a]<self.dist[b]:a,b=b,a if self.dist[a]>self.dist[b]: for i in range(self.logn): if (self.dist[a]-self.dist[b])&(1<<i):a=self.parent[i][a] if a==b:return a for i in range(self.logn-1,-1,-1): if self.parent[i][a]!=self.parent[i][b]: a=self.parent[i][a] b=self.parent[i][b] return self.parent[0][a] def path_range(self,a,b):return self.dist[a]+self.dist[b]-2*self.dist[self.query(a,b)] def x_in_abpath(self,x,a,b):return self.path_range(a,x)+self.path_range(b,x)==self.path_range(a,b) for _ in range(int(input())): n = int(input()) g = [[] for _ in range(n)] for _ in range(n - 1): a, b = map(int, input().split()) g[a].append(b) g[b].append(a) ans = [0] * (n + 1) ans[0] = n * (n - 1) // 2 order = tree_dfs(g) d = [0] * n for v in order[::-1]: for node in g[v]: d[v] += d[node] d[v] += 1 lca = LCA(n, 0, g) a, b = 0, 0 for node in g[0]: a += d[node] b += d[node] * d[node] if lca.query(node, 1) == node: d[0] -= d[node] ans[1] = (a * a - b) // 2 + n - 1 l, r = 0, 0 for i in range(1, n): if lca.x_in_abpath(i, l, r): ans[i + 1] = ans[i] continue elif lca.query(i, l) == l and lca.query(i, r) == 0: l = i elif lca.query(i, r) == r and lca.query(i, l) == 0: r = i else: break ans[i + 1] = d[l] * d[r] for i in range(n): ans[i] = ans[i] - ans[i + 1] print(*ans) ```
7,806
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree with n nodes, numerated from 0 to n-1. For each k between 0 and n, inclusive, you have to count the number of unordered pairs (u,v), u ≠ v, such that the MEX of all the node labels in the shortest path from u to v (including end points) is k. The MEX of a sequence of integers is the smallest non-negative integer that does not belong to the sequence. Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^{5}). The next n-1 lines of each test case describe the tree that has to be constructed. These lines contain two integers u and v (0 ≤ u,v ≤ n-1) denoting an edge between u and v (u ≠ v). It is guaranteed that the given edges form a tree. It is also guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^{5}. Output For each test case, print n+1 integers: the number of paths in the tree, such that the MEX of all the node labels in that path is k for each k from 0 to n. Example Input 2 4 0 1 0 2 2 3 2 1 0 Output 1 2 1 1 1 0 0 1 Note 1. In example case 1, <image> * For k = 0, there is 1 path that is from 2 to 3 as MEX([2, 3]) = 0. * For k = 1, there are 2 paths that is from 0 to 2 as MEX([0, 2]) = 1 and 0 to 3 as MEX([0, 2, 3]) = 1. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. * For k = 3, there is 1 path that is from 1 to 2 as MEX([1, 0, 2]) = 3 * For k = 4, there is 1 path that is from 1 to 3 as MEX([1, 0, 2, 3]) = 4. 2. In example case 2, <image> * For k = 0, there are no such paths. * For k = 1, there are no such paths. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. Tags: combinatorics, dfs and similar, implementation, math, trees Correct Solution: ``` #CF1527D from bisect import bisect,bisect_left from collections import * from heapq import * from math import gcd,ceil,sqrt,floor,inf from itertools import * from operator import add,mul,sub,xor,truediv,floordiv from functools import * #------------------------------------------------------------------------ import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #------------------------------------------------------------------------ def RL(): return map(int, sys.stdin.readline().split()) def RLL(): return list(map(int, sys.stdin.readline().split())) def N(): return int(input()) def A(n):return [0]*n def AI(n,x): return [x]*n def A2(n,m): return [[0]*m for i in range(n)] def G(n): return [[] for i in range(n)] def GP(it): return [[ch,len(list(g))] for ch,g in groupby(it)] #------------------------------------------------------------------------ from types import GeneratorType 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 mod=10**9+7 farr=[1] ifa=[] def fact(x,mod=0): if mod: while x>=len(farr): farr.append(farr[-1]*len(farr)%mod) else: while x>=len(farr): farr.append(farr[-1]*len(farr)) return farr[x] def ifact(x,mod): global ifa fact(x,mod) ifa.append(pow(farr[-1],mod-2,mod)) for i in range(x,0,-1): ifa.append(ifa[-1]*i%mod) ifa.reverse() def per(i,j,mod=0): if i<j: return 0 if not mod: return fact(i)//fact(i-j) return farr[i]*ifa[i-j]%mod def com(i,j,mod=0): if i<j: return 0 if not mod: return per(i,j)//fact(j) return per(i,j,mod)*ifa[j]%mod def catalan(n): return com(2*n,n)//(n+1) def isprime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True def floorsum(a,b,c,n):#sum((a*i+b)//c for i in range(n+1)) if a==0:return b//c*(n+1) if a>=c or b>=c: return floorsum(a%c,b%c,c,n)+b//c*(n+1)+a//c*n*(n+1)//2 m=(a*n+b)//c return n*m-floorsum(c,c-b-1,a,m-1) def inverse(a,m): a%=m if a<=1: return a return ((1-inverse(m,a)*m)//a)%m def lowbit(n): return n&-n class BIT: def __init__(self,arr): self.arr=arr self.n=len(arr)-1 def update(self,x,v): while x<=self.n: self.arr[x]+=v x+=x&-x def query(self,x): ans=0 while x: ans+=self.arr[x] x&=x-1 return ans class ST: def __init__(self,arr):#n!=0 n=len(arr) mx=n.bit_length()#取不到 self.st=[[0]*mx for i in range(n)] for i in range(n): self.st[i][0]=arr[i] for j in range(1,mx): for i in range(n-(1<<j)+1): self.st[i][j]=max(self.st[i][j-1],self.st[i+(1<<j-1)][j-1]) def query(self,l,r): if l>r:return -inf s=(r+1-l).bit_length()-1 return max(self.st[l][s],self.st[r-(1<<s)+1][s]) class DSU:#容量+路径压缩 def __init__(self,n): self.c=[-1]*n def same(self,x,y): return self.find(x)==self.find(y) def find(self,x): if self.c[x]<0: return x self.c[x]=self.find(self.c[x]) return self.c[x] def union(self,u,v): u,v=self.find(u),self.find(v) if u==v: return False if self.c[u]>self.c[v]: u,v=v,u self.c[u]+=self.c[v] self.c[v]=u return True def size(self,x): return -self.c[self.find(x)] class UFS:#秩+路径 def __init__(self,n): self.parent=[i for i in range(n)] self.ranks=[0]*n def find(self,x): if x!=self.parent[x]: self.parent[x]=self.find(self.parent[x]) return self.parent[x] def union(self,u,v): pu,pv=self.find(u),self.find(v) if pu==pv: return False if self.ranks[pu]>=self.ranks[pv]: self.parent[pv]=pu if self.ranks[pv]==self.ranks[pu]: self.ranks[pu]+=1 else: self.parent[pu]=pv class UF:#秩+路径+容量,边数 def __init__(self,n): self.parent=[i for i in range(n)] self.ranks=[0]*n self.size=AI(n,1) self.edge=A(n) def find(self,x): if x!=self.parent[x]: self.parent[x]=self.find(self.parent[x]) return self.parent[x] def union(self,u,v): pu,pv=self.find(u),self.find(v) if pu==pv: self.edge[pu]+=1 return False if self.ranks[pu]>=self.ranks[pv]: self.parent[pv]=pu self.edge[pu]+=self.edge[pv]+1 self.size[pu]+=self.size[pv] if self.ranks[pv]==self.ranks[pu]: self.ranks[pu]+=1 else: self.parent[pu]=pv self.edge[pv]+=self.edge[pu]+1 self.size[pv]+=self.size[pu] def Prime(n): c=0 prime=[] flag=[0]*(n+1) for i in range(2,n+1): if not flag[i]: prime.append(i) c+=1 for j in range(c): if i*prime[j]>n: break flag[i*prime[j]]=prime[j] if i%prime[j]==0: break return prime def dij(s,graph): d=AI(n,inf) d[s]=0 heap=[(0,s)] vis=A(n) while heap: dis,u=heappop(heap) if vis[u]: continue vis[u]=1 for v,w in graph[u]: if d[v]>d[u]+w: d[v]=d[u]+w heappush(heap,(d[v],v)) return d def bell(s,g):#bellman-Ford dis=AI(n,inf) dis[s]=0 for i in range(n-1): for u,v,w in edge: if dis[v]>dis[u]+w: dis[v]=dis[u]+w change=A(n) for i in range(n): for u,v,w in edge: if dis[v]>dis[u]+w: dis[v]=dis[u]+w change[v]=1 return dis def lcm(a,b): return a*b//gcd(a,b) def lis(nums): res=[] for k in nums: i=bisect.bisect_left(res,k) if i==len(res): res.append(k) else: res[i]=k return len(res) def RP(nums):#逆序对 n = len(nums) s=set(nums) d={} for i,k in enumerate(sorted(s),1): d[k]=i bi=BIT([0]*(len(s)+1)) ans=0 for i in range(n-1,-1,-1): ans+=bi.query(d[nums[i]]-1) bi.update(d[nums[i]],1) return ans class DLN: def __init__(self,val): self.val=val self.pre=None self.next=None def nb(i,j,n,m): for ni,nj in [[i+1,j],[i-1,j],[i,j-1],[i,j+1]]: if 0<=ni<n and 0<=nj<m: yield ni,nj def topo(n): q=deque() res=[] for i in range(1,n+1): if ind[i]==0: q.append(i) res.append(i) while q: u=q.popleft() for v in g[u]: ind[v]-=1 if ind[v]==0: q.append(v) res.append(v) return res @bootstrap def gdfs(r,p): for ch in g[r]: if ch!=p: yield gdfs(ch,r) yield None @bootstrap def dfs(r,p): par[r]=p for ch in g[r]: if ch!=p: yield dfs(ch,r) cnt[r]+=cnt[ch] yield None #from random import randint t=N() for i in range(t): n=N() g=G(n) ans=A(n+1) for i in range(n-1): u,v=RL() g[u].append(v) g[v].append(u) par=A(n) cnt=AI(n,1) dfs(0,-1) vis=A(n) vis[0]=1 for v in g[0]: ans[0]+=cnt[v]*(cnt[v]-1)//2 u=1 while par[u]: vis[u]=1 u=par[u] vis[u]=1 k=n-cnt[1] ans[1]=n*(n-1)//2-ans[0]-cnt[1]*(n-cnt[u]) l=0 lc=n-cnt[u] rc=cnt[1] r=1 f=True for i in range(2,n): if vis[i]: continue u=i while not vis[u]: vis[u]=1 u=par[u] if u==l: ans[i]=(lc-cnt[i])*rc l=i lc=cnt[l] elif u==r: ans[i]=(rc-cnt[i])*lc r=i rc=cnt[r] else: ans[i]=lc*rc f=False break if f: ans[-1]=1 print(*ans) ```
7,807
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree with n nodes, numerated from 0 to n-1. For each k between 0 and n, inclusive, you have to count the number of unordered pairs (u,v), u ≠ v, such that the MEX of all the node labels in the shortest path from u to v (including end points) is k. The MEX of a sequence of integers is the smallest non-negative integer that does not belong to the sequence. Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^{5}). The next n-1 lines of each test case describe the tree that has to be constructed. These lines contain two integers u and v (0 ≤ u,v ≤ n-1) denoting an edge between u and v (u ≠ v). It is guaranteed that the given edges form a tree. It is also guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^{5}. Output For each test case, print n+1 integers: the number of paths in the tree, such that the MEX of all the node labels in that path is k for each k from 0 to n. Example Input 2 4 0 1 0 2 2 3 2 1 0 Output 1 2 1 1 1 0 0 1 Note 1. In example case 1, <image> * For k = 0, there is 1 path that is from 2 to 3 as MEX([2, 3]) = 0. * For k = 1, there are 2 paths that is from 0 to 2 as MEX([0, 2]) = 1 and 0 to 3 as MEX([0, 2, 3]) = 1. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. * For k = 3, there is 1 path that is from 1 to 2 as MEX([1, 0, 2]) = 3 * For k = 4, there is 1 path that is from 1 to 3 as MEX([1, 0, 2, 3]) = 4. 2. In example case 2, <image> * For k = 0, there are no such paths. * For k = 1, there are no such paths. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. Submitted Solution: ``` import sys def putin(): return map(int, sys.stdin.readline().split()) def sol(): n = int(sys.stdin.readline()) G = [] for i in range(n): G.append([]) for i in range(n - 1): u, v = putin() G[u].append(v) G[v].append(u) parents = [0] * n parents[0] = -1 capacity = [0] * n DFS_stack = [0] colors = [0] * n while DFS_stack: new_v = DFS_stack[-1] if colors[new_v] == 0: colors[new_v] = 1 for elem in G[new_v]: if colors[elem] == 0: DFS_stack.append(elem) parents[elem] = new_v elif colors[new_v] == 1: colors[new_v] = 2 DFS_stack.pop() S = 0 for elem in G[new_v]: if colors[elem] == 2: S += capacity[elem] capacity[new_v] = S + 1 else: DFS_stack.pop() L = 0 R = 0 answer = [n * (n - 1) // 2] S = 0 for children in G[0]: S += capacity[children] * (capacity[children] - 1) // 2 answer.append(n * (n - 1) // 2 - S) path = {0} for cur_v in range(1, n): if cur_v not in path: ancestor = cur_v while ancestor not in path: path.add(ancestor) if parents[ancestor] == 0: capacity[0] -= capacity[ancestor] ancestor = parents[ancestor] if ancestor == L: L = cur_v elif ancestor == R: R = cur_v else: break answer.append((capacity[L]) * (capacity[R])) while len(answer) < n + 2: answer.append(0) for i in range(n + 1): print(answer[i] - answer[i + 1], end=' ') print() for iter in range(int(sys.stdin.readline())): sol() ``` Yes
7,808
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree with n nodes, numerated from 0 to n-1. For each k between 0 and n, inclusive, you have to count the number of unordered pairs (u,v), u ≠ v, such that the MEX of all the node labels in the shortest path from u to v (including end points) is k. The MEX of a sequence of integers is the smallest non-negative integer that does not belong to the sequence. Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^{5}). The next n-1 lines of each test case describe the tree that has to be constructed. These lines contain two integers u and v (0 ≤ u,v ≤ n-1) denoting an edge between u and v (u ≠ v). It is guaranteed that the given edges form a tree. It is also guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^{5}. Output For each test case, print n+1 integers: the number of paths in the tree, such that the MEX of all the node labels in that path is k for each k from 0 to n. Example Input 2 4 0 1 0 2 2 3 2 1 0 Output 1 2 1 1 1 0 0 1 Note 1. In example case 1, <image> * For k = 0, there is 1 path that is from 2 to 3 as MEX([2, 3]) = 0. * For k = 1, there are 2 paths that is from 0 to 2 as MEX([0, 2]) = 1 and 0 to 3 as MEX([0, 2, 3]) = 1. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. * For k = 3, there is 1 path that is from 1 to 2 as MEX([1, 0, 2]) = 3 * For k = 4, there is 1 path that is from 1 to 3 as MEX([1, 0, 2, 3]) = 4. 2. In example case 2, <image> * For k = 0, there are no such paths. * For k = 1, there are no such paths. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. Submitted Solution: ``` import sys;from collections import Counter;input = sys.stdin.readline def tree_dfs(g, root=0): s = [root];d = [1] * len(g);order = [] while s:p = s.pop();d[p] = 0;order.append(p);s += [node for node in g[p] if d[node]] return order class LCA: def __init__(self,n,s,edge): self.logn=n.bit_length();self.parent=[n*[-1]for _ in range(self.logn)];self.dist=[0]*n;stack=[s];visited={s} for i in stack: for j in edge[i]: if j in visited:continue stack.append(j); visited.add(j); self.parent[0][j]=i; self.dist[j]=self.dist[i]+1 for k in range(1,self.logn):self.parent[k][j]=self.parent[k-1][self.parent[k-1][j]] def query(self,a,b): if self.dist[a]<self.dist[b]:a,b=b,a if self.dist[a]>self.dist[b]: for i in range(self.logn): if (self.dist[a]-self.dist[b])&(1<<i):a=self.parent[i][a] if a==b:return a for i in range(self.logn-1,-1,-1): if self.parent[i][a]!=self.parent[i][b]: a=self.parent[i][a]; b=self.parent[i][b] return self.parent[0][a] def path_range(self,a,b):return self.dist[a]+self.dist[b]-2*self.dist[self.query(a,b)] def x_in_abpath(self,x,a,b):return self.path_range(a,x)+self.path_range(b,x)==self.path_range(a,b) for _ in range(int(input())): n = int(input()) g = [[] for _ in range(n)] for _ in range(n - 1): a, b = map(int, input().split()); g[a].append(b); g[b].append(a) ans = [0] * (n + 1); ans[0] = n * (n - 1) // 2; order = tree_dfs(g); d = [0] * n for v in order[::-1]:d[v] += (sum([d[node] for node in g[v]]) + 1) lca = LCA(n, 0, g);a, b = 0, 0 for node in g[0]: a += d[node]; b += d[node] * d[node] if lca.query(node, 1) == node: d[0] -= d[node] ans[1] = (a * a - b) // 2 + n - 1; l, r = 0, 0 for i in range(1, n): if lca.x_in_abpath(i, l, r): ans[i + 1] = ans[i]; continue elif lca.query(i, l) == l and lca.query(i, r) == 0: l = i elif lca.query(i, r) == r and lca.query(i, l) == 0: r = i else: break ans[i + 1] = d[l] * d[r] for i in range(n):ans[i] = ans[i] - ans[i + 1] print(*ans) ``` Yes
7,809
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree with n nodes, numerated from 0 to n-1. For each k between 0 and n, inclusive, you have to count the number of unordered pairs (u,v), u ≠ v, such that the MEX of all the node labels in the shortest path from u to v (including end points) is k. The MEX of a sequence of integers is the smallest non-negative integer that does not belong to the sequence. Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^{5}). The next n-1 lines of each test case describe the tree that has to be constructed. These lines contain two integers u and v (0 ≤ u,v ≤ n-1) denoting an edge between u and v (u ≠ v). It is guaranteed that the given edges form a tree. It is also guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^{5}. Output For each test case, print n+1 integers: the number of paths in the tree, such that the MEX of all the node labels in that path is k for each k from 0 to n. Example Input 2 4 0 1 0 2 2 3 2 1 0 Output 1 2 1 1 1 0 0 1 Note 1. In example case 1, <image> * For k = 0, there is 1 path that is from 2 to 3 as MEX([2, 3]) = 0. * For k = 1, there are 2 paths that is from 0 to 2 as MEX([0, 2]) = 1 and 0 to 3 as MEX([0, 2, 3]) = 1. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. * For k = 3, there is 1 path that is from 1 to 2 as MEX([1, 0, 2]) = 3 * For k = 4, there is 1 path that is from 1 to 3 as MEX([1, 0, 2, 3]) = 4. 2. In example case 2, <image> * For k = 0, there are no such paths. * For k = 1, there are no such paths. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. Submitted Solution: ``` import math from bisect import bisect_left 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(2*10**5) 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 def solve(): n = int(input()) MA = n + 1 level = 25 tree = [[] for i in range(MA)] depth = [0 for i in range(MA)] parent = [[0 for i in range(level)] for j in range(MA)] size = [1 for i in range(MA)] ans= [0 for i in range(MA)] @bootstrap def dfs(cur, prev): depth[cur] = depth[prev] + 1 parent[cur][0] = prev for i in range(len(tree[cur])): if (tree[cur][i] != prev): yield dfs(tree[cur][i], cur) size[cur]+=size[tree[cur][i]] yield def precomputeSparseMatrix(n): for i in range(1, level): for node in range(n): 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] def add(a, b): tree[a].append(b) tree[b].append(a) for j in range(n-1): u,v=map(int,input().split()) add(u,v) dfs(0, -1) precomputeSparseMatrix(n) s1=0 for j in tree[0]: ans[0]+=(size[j]*(size[j]-1))//2 if lca(j,1)==j: s1=n-size[j] rem=n*(n-1)//2-ans[0] ans[1]=rem-s1*size[1] rem=s1*size[1] size[0]=s1 u=1 v=0 for i in range(2,n): if v==0: val1=1 p1=lca(u,i) p2=lca(v,i) if p1==u: u=i elif p1==i: pass elif p1==0: if lca(v,i)==v: v=i else: val1=0 if val1!=0: val1=size[u]*size[v] ans[i]=rem-val1 rem=val1 else: p1=lca(u,i) p2=lca(v,i) if p1==u: u=i val1 = size[u] * size[v] elif p2==v: v=i val1 = size[u] * size[v] elif p1==i: val1=size[u]*size[v] elif p2==i: val1 = size[u] * size[v] else: val1=0 ans[i]=rem-val1 rem=val1 if rem==0: break ans[-1]=rem print(*ans) t=int(input()) for _ in range(t): solve() ``` Yes
7,810
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree with n nodes, numerated from 0 to n-1. For each k between 0 and n, inclusive, you have to count the number of unordered pairs (u,v), u ≠ v, such that the MEX of all the node labels in the shortest path from u to v (including end points) is k. The MEX of a sequence of integers is the smallest non-negative integer that does not belong to the sequence. Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^{5}). The next n-1 lines of each test case describe the tree that has to be constructed. These lines contain two integers u and v (0 ≤ u,v ≤ n-1) denoting an edge between u and v (u ≠ v). It is guaranteed that the given edges form a tree. It is also guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^{5}. Output For each test case, print n+1 integers: the number of paths in the tree, such that the MEX of all the node labels in that path is k for each k from 0 to n. Example Input 2 4 0 1 0 2 2 3 2 1 0 Output 1 2 1 1 1 0 0 1 Note 1. In example case 1, <image> * For k = 0, there is 1 path that is from 2 to 3 as MEX([2, 3]) = 0. * For k = 1, there are 2 paths that is from 0 to 2 as MEX([0, 2]) = 1 and 0 to 3 as MEX([0, 2, 3]) = 1. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. * For k = 3, there is 1 path that is from 1 to 2 as MEX([1, 0, 2]) = 3 * For k = 4, there is 1 path that is from 1 to 3 as MEX([1, 0, 2, 3]) = 4. 2. In example case 2, <image> * For k = 0, there are no such paths. * For k = 1, there are no such paths. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. Submitted Solution: ``` class RangeQuery: def __init__(self, data, func=min): self.func = func self._data = _data = [list(data)] i, n = 1, len(_data[0]) while 2 * i <= n: prev = _data[-1] _data.append([func(prev[j], prev[j + i]) for j in range(n - 2 * i + 1)]) i <<= 1 def query(self, begin, end): depth = (end - begin).bit_length() - 1 return self.func(self._data[depth][begin], self._data[depth][end - (1 << depth)]) class LCA: def __init__(self, root, graph): self.time = [-1] * len(graph) self.path = [-1] * len(graph) P = [-1] * len(graph) t = -1 dfs = [root] while dfs: node = dfs.pop() self.path[t] = P[node] self.time[node] = t = t + 1 for nei in graph[node]: if self.time[nei] == -1: P[nei] = node dfs.append(nei) self.rmq = RangeQuery(self.time[node] for node in self.path) def __call__(self, a, b): if a == b: return a a = self.time[a] b = self.time[b] if a > b: a, b = b, a return self.path[self.rmq.query(a, b)] import sys,io,os try:Z=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline except:Z=lambda:sys.stdin.readline().encode() Y=lambda:map(int,Z().split()) O=[] for _ in range(int(Z())): n=int(Z());g=[[]for i in range(n)] for i in range(n-1):u,v=Y();g[u].append(v);g[v].append(u) L=LCA(0,g);e=[1,0];r=[0]*(n+1) c=[-1]*n;d=[0]*n;p=[-1]*n;q=[0] while q: v=q.pop() if c[v]==-1: c[v]=0 for i in g[v]: if i!=p[v]:p[i]=v;q.append(i);c[v]+=1 if c[v]==0: d[v]+=1 if p[v]!=-1: d[p[v]]+=d[v];c[p[v]]-=1 if c[p[v]]==0:q.append(p[v]) u,w=p[1],1 while u:u,w=p[u],u d[0]-=d[w];t=0 for i in g[0]: v=d[i];r[0]+=(v*v-v)//2 if i==w:v-=d[1] r[1]+=t*v+v;t+=v for i in range(2,n): v=L(i,e[0]) if v==i:continue elif v==e[0]:r[i]=d[e[1]]*(d[v]-d[i]);e[0]=i;continue elif v!=0:r[i]=d[e[0]]*d[e[1]];break v=L(i,e[1]) if v==i:continue elif v==e[1]:r[i]=d[e[0]]*(d[v]-d[i]);e[1]=i;continue r[i]=d[e[0]]*d[e[1]];break else:r[-1]=1 O.append(' '.join(map(str,r))) print('\n'.join(O)) ``` Yes
7,811
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree with n nodes, numerated from 0 to n-1. For each k between 0 and n, inclusive, you have to count the number of unordered pairs (u,v), u ≠ v, such that the MEX of all the node labels in the shortest path from u to v (including end points) is k. The MEX of a sequence of integers is the smallest non-negative integer that does not belong to the sequence. Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^{5}). The next n-1 lines of each test case describe the tree that has to be constructed. These lines contain two integers u and v (0 ≤ u,v ≤ n-1) denoting an edge between u and v (u ≠ v). It is guaranteed that the given edges form a tree. It is also guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^{5}. Output For each test case, print n+1 integers: the number of paths in the tree, such that the MEX of all the node labels in that path is k for each k from 0 to n. Example Input 2 4 0 1 0 2 2 3 2 1 0 Output 1 2 1 1 1 0 0 1 Note 1. In example case 1, <image> * For k = 0, there is 1 path that is from 2 to 3 as MEX([2, 3]) = 0. * For k = 1, there are 2 paths that is from 0 to 2 as MEX([0, 2]) = 1 and 0 to 3 as MEX([0, 2, 3]) = 1. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. * For k = 3, there is 1 path that is from 1 to 2 as MEX([1, 0, 2]) = 3 * For k = 4, there is 1 path that is from 1 to 3 as MEX([1, 0, 2, 3]) = 4. 2. In example case 2, <image> * For k = 0, there are no such paths. * For k = 1, there are no such paths. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. Submitted Solution: ``` from sys import stdin, gettrace if gettrace(): def inputi(): return input() else: def input(): return next(stdin)[:-1] def inputi(): return stdin.buffer.readline() def readGraph(n, m): adj = [[] for _ in range(n)] for _ in range(m): u, v = map(int, input().split()) adj[u].append(v) adj[v].append(u) return adj def readTree(n): return readGraph(n, n - 1) def euler_dfs(n, adj): parent = [None] * n depth = [-1] * n depth[0] = 0 stack = [(0, adj[0])] euler = [] eulerfirst = [-1] * n eulerlast = [-1] * n dcount = [0] * n pcount = [0] * n seen = 0 while stack: p, aa = stack.pop() if eulerfirst[p] == -1: pcount[p] = seen seen += 1 eulerfirst[p] = len(euler) eulerlast[p] = len(euler) dcount[p] = seen - pcount[p] euler.append(p) for c in aa[::-1]: if c != parent[p]: parent[c] = p depth[c] = depth[p] + 1 stack.append((p, [])) stack.append((c, adj[c])) return eulerfirst, eulerlast, parent, dcount def solve(): n = int(input()) adj = readTree(n) eulerfirst, eulerlast, parent, dcount = euler_dfs(n, adj) def is_decendant(u, v): return eulerfirst[v] < eulerfirst[u] < eulerlast[v] res = [0] * (n + 1) paths = [0] * n res[0] = sum(dcount[v] * (dcount[v] - 1) for v in adj[0]) // 2 paths[0] = (n * (n - 1)) // 2 - res[0] oneb = 1 while oneb not in adj[0]: oneb = parent[oneb] paths[1] = dcount[1] * (n - dcount[oneb]) pends = [1] for i in range(2, n): for x, e in enumerate(pends): if is_decendant(e, i): break elif is_decendant(i, e): pends[x] = i break else: if len(pends) == 2: break p = parent[i] j = 0 while p != 0: if p < i: j = p break p = parent[p] if j != 0: break pends.append(i) if len(pends) == 2: paths[i] = dcount[pends[0]] * dcount[pends[1]] else: paths[i] = dcount[pends[0]] * (n - dcount[oneb]) for i in range(1, n): res[i] = paths[i - 1] - paths[i] res[n] = paths[n - 1] print(' '.join(map(str, res))) def main(): t = int(input()) for _ in range(t): solve() if __name__ == "__main__": main() ``` No
7,812
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree with n nodes, numerated from 0 to n-1. For each k between 0 and n, inclusive, you have to count the number of unordered pairs (u,v), u ≠ v, such that the MEX of all the node labels in the shortest path from u to v (including end points) is k. The MEX of a sequence of integers is the smallest non-negative integer that does not belong to the sequence. Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^{5}). The next n-1 lines of each test case describe the tree that has to be constructed. These lines contain two integers u and v (0 ≤ u,v ≤ n-1) denoting an edge between u and v (u ≠ v). It is guaranteed that the given edges form a tree. It is also guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^{5}. Output For each test case, print n+1 integers: the number of paths in the tree, such that the MEX of all the node labels in that path is k for each k from 0 to n. Example Input 2 4 0 1 0 2 2 3 2 1 0 Output 1 2 1 1 1 0 0 1 Note 1. In example case 1, <image> * For k = 0, there is 1 path that is from 2 to 3 as MEX([2, 3]) = 0. * For k = 1, there are 2 paths that is from 0 to 2 as MEX([0, 2]) = 1 and 0 to 3 as MEX([0, 2, 3]) = 1. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. * For k = 3, there is 1 path that is from 1 to 2 as MEX([1, 0, 2]) = 3 * For k = 4, there is 1 path that is from 1 to 3 as MEX([1, 0, 2, 3]) = 4. 2. In example case 2, <image> * For k = 0, there are no such paths. * For k = 1, there are no such paths. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. Submitted Solution: ``` from collections import deque import sys input = sys.stdin.readline def bfs(s): q = deque() q.append(s) visit = [0] * n visit[s] = 1 p = deque() parent = [-1] * n while q: i = q.popleft() p.append(i) for j in G[i]: if not visit[j]: visit[j] = 1 q.append(j) parent[j] = i childcnt = [1] * n p.popleft() while p: i = p.pop() childcnt[parent[i]] += childcnt[i] return parent, childcnt t = int(input()) for _ in range(t): n = int(input()) G = [[] for _ in range(n)] for _ in range(n - 1): u, v = map(int, input().split()) G[u].append(v) G[v].append(u) parent, childcnt = bfs(0) x = n * (n - 1) // 2 c = 0 for i in G[0]: cc = childcnt[i] c += cc * (cc - 1) // 2 ans = [c] x -= c i, j = 1, 1 ok = set() ok.add(0) while not i in ok: ok.add(i) j = i i = parent[i] c = [] for i in G[0]: cc = childcnt[i] if i == j: cc -= childcnt[1] c.append(cc) childcnt[0] -= childcnt[j] c0 = [] y = 0 for i in range(len(c)): y += c[i] c0.append(y) cc = 0 for i in range(len(c) - 1): cc += c0[i] * c[i + 1] cc += c0[-1] x -= cc ans.append(cc) lr = set([0, 1]) ng = 0 for i in range(2, n): if ng: ans.append(0) continue if i in ok: continue j = i while not j in ok: ok.add(j) j = parent[j] if j in lr: childcnt[j] -= childcnt[i] c = 1 for k in lr: c *= childcnt[k] ans.append(c) x -= c lr.remove(j) lr.add(i) else: childcnt[j] -= childcnt[i] c = 1 for k in lr: c *= childcnt[k] ans.append(c) x -= c ng = 1 continue while not len(ans) == n: ans.append(0) x = 1 for i in G: if len(i) > 2: x = 0 break ans.append(x) print(*ans) ``` No
7,813
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree with n nodes, numerated from 0 to n-1. For each k between 0 and n, inclusive, you have to count the number of unordered pairs (u,v), u ≠ v, such that the MEX of all the node labels in the shortest path from u to v (including end points) is k. The MEX of a sequence of integers is the smallest non-negative integer that does not belong to the sequence. Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^{5}). The next n-1 lines of each test case describe the tree that has to be constructed. These lines contain two integers u and v (0 ≤ u,v ≤ n-1) denoting an edge between u and v (u ≠ v). It is guaranteed that the given edges form a tree. It is also guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^{5}. Output For each test case, print n+1 integers: the number of paths in the tree, such that the MEX of all the node labels in that path is k for each k from 0 to n. Example Input 2 4 0 1 0 2 2 3 2 1 0 Output 1 2 1 1 1 0 0 1 Note 1. In example case 1, <image> * For k = 0, there is 1 path that is from 2 to 3 as MEX([2, 3]) = 0. * For k = 1, there are 2 paths that is from 0 to 2 as MEX([0, 2]) = 1 and 0 to 3 as MEX([0, 2, 3]) = 1. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. * For k = 3, there is 1 path that is from 1 to 2 as MEX([1, 0, 2]) = 3 * For k = 4, there is 1 path that is from 1 to 3 as MEX([1, 0, 2, 3]) = 4. 2. In example case 2, <image> * For k = 0, there are no such paths. * For k = 1, there are no such paths. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. Submitted Solution: ``` import sys input = sys.stdin.readline def solve(): n = int(input()) G = [[] for _ in range(n)] for _ in range(n-1): a,b = map(int,input().split()) G[a].append(b) G[b].append(a) size = [0]*n par = [-1]*n stk = [0] visited = [False]*n while stk: x = stk[-1] if not visited[x]: visited[x] = True for y in G[x]: if not visited[y]: par[y] = x stk.append(y) else: stk.pop() for y in G[x]: size[x] += size[y] size[x] += 1 visited = [False]*n ans = [0]*(n+1) for y in G[0]: ans[0] += size[y] * (size[y]-1) // 2 P = n*(n-1)//2 P -= ans[0] visited[0] = True l,r = 0,0 for i in range(1,n): u = i while not visited[u]: visited[u] = True size[par[u]] -= size[u] u = par[u] if n == 200000: print("is 1 a child of 0?",1 in G[0]) print("size[0]",size[0],"size[1]",size[1],"P",P) if u == l: ans[i] = P - size[r] * size[i] l = i P -= ans[i] elif u == r: ans[i] = P - size[l] * size[i] r = i P -= ans[i] else: ans[i] = size[l] * size[r] P -= ans[i] break ans[-1] = P print(*ans) for nt in range(int(input())): solve() ``` No
7,814
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree with n nodes, numerated from 0 to n-1. For each k between 0 and n, inclusive, you have to count the number of unordered pairs (u,v), u ≠ v, such that the MEX of all the node labels in the shortest path from u to v (including end points) is k. The MEX of a sequence of integers is the smallest non-negative integer that does not belong to the sequence. Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^{5}). The next n-1 lines of each test case describe the tree that has to be constructed. These lines contain two integers u and v (0 ≤ u,v ≤ n-1) denoting an edge between u and v (u ≠ v). It is guaranteed that the given edges form a tree. It is also guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^{5}. Output For each test case, print n+1 integers: the number of paths in the tree, such that the MEX of all the node labels in that path is k for each k from 0 to n. Example Input 2 4 0 1 0 2 2 3 2 1 0 Output 1 2 1 1 1 0 0 1 Note 1. In example case 1, <image> * For k = 0, there is 1 path that is from 2 to 3 as MEX([2, 3]) = 0. * For k = 1, there are 2 paths that is from 0 to 2 as MEX([0, 2]) = 1 and 0 to 3 as MEX([0, 2, 3]) = 1. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. * For k = 3, there is 1 path that is from 1 to 2 as MEX([1, 0, 2]) = 3 * For k = 4, there is 1 path that is from 1 to 3 as MEX([1, 0, 2, 3]) = 4. 2. In example case 2, <image> * For k = 0, there are no such paths. * For k = 1, there are no such paths. * For k = 2, there is 1 path that is from 0 to 1 as MEX([0, 1]) = 2. Submitted Solution: ``` import sys from collections import Counter input = sys.stdin.readline def tree_dfs(g, root=0): s = [root] d = [1] * len(g) order = [] while s: p = s.pop() d[p] = 0 order.append(p) for node in g[p]: if d[node]: s.append(node) return order class LCA: def __init__(self,n,s,edge): self.logn=n.bit_length() self.parent=[n*[-1]for _ in range(self.logn)] self.dist=[0]*n stack=[s] visited={s} for i in stack: for j in edge[i]: if j in visited:continue stack.append(j) visited.add(j) self.parent[0][j]=i self.dist[j]=self.dist[i]+1 for k in range(1,self.logn):self.parent[k][j]=self.parent[k-1][self.parent[k-1][j]] def query(self,a,b): if self.dist[a]<self.dist[b]:a,b=b,a if self.dist[a]>self.dist[b]: for i in range(self.logn): if (self.dist[a]-self.dist[b])&(1<<i):a=self.parent[i][a] if a==b:return a for i in range(self.logn-1,-1,-1): if self.parent[i][a]!=self.parent[i][b]: a=self.parent[i][a] b=self.parent[i][b] return self.parent[0][a] def path_range(self,a,b):return self.dist[a]+self.dist[b]-2*self.dist[self.query(a,b)] def x_in_abpath(self,x,a,b):return self.path_range(a,x)+self.path_range(b,x)==self.path_range(a,b) t = int(input()) for _ in range(t): n = int(input()) g = [[] for _ in range(n)] for _ in range(n - 1): a, b = map(int, input().split()) g[a].append(b) g[b].append(a) ans = [0] * (n + 1) ans[0] = n * (n - 1) // 2 order = tree_dfs(g) d = [0] * n for v in order[::-1]: for node in g[v]: d[v] += d[node] d[v] += 1 lca = LCA(n, 0, g) a, b = 0, 0 for node in g[0]: a += d[node] b += d[node] * d[node] if lca.query(node, 1) == node: d[0] -= d[node] ans[1] = (a * a - b) // 2 + n - 1 l, r = 0, 0 for i in range(1, n): if lca.x_in_abpath(i, l, r): ans[i + 1] = ans[i] continue elif lca.query(i, l) == l: l = i elif lca.query(i, r) == r: r = i else: break ans[i + 1] = d[l] * d[r] for i in range(n): ans[i] = ans[i] - ans[i + 1] print(*ans) ``` No
7,815
Provide tags and a correct Python 3 solution for this coding contest problem. One popular website developed an unusual username editing procedure. One can change the username only by deleting some characters from it: to change the current name s, a user can pick number p and character c and delete the p-th occurrence of character c from the name. After the user changed his name, he can't undo the change. For example, one can change name "arca" by removing the second occurrence of character "a" to get "arc". Polycarpus learned that some user initially registered under nickname t, where t is a concatenation of k copies of string s. Also, Polycarpus knows the sequence of this user's name changes. Help Polycarpus figure out the user's final name. Input The first line contains an integer k (1 ≤ k ≤ 2000). The second line contains a non-empty string s, consisting of lowercase Latin letters, at most 100 characters long. The third line contains an integer n (0 ≤ n ≤ 20000) — the number of username changes. Each of the next n lines contains the actual changes, one per line. The changes are written as "pi ci" (without the quotes), where pi (1 ≤ pi ≤ 200000) is the number of occurrences of letter ci, ci is a lowercase Latin letter. It is guaranteed that the operations are correct, that is, the letter to be deleted always exists, and after all operations not all letters are deleted from the name. The letters' occurrences are numbered starting from 1. Output Print a single string — the user's final name after all changes are applied to it. Examples Input 2 bac 3 2 a 1 b 2 c Output acb Input 1 abacaba 4 1 a 1 a 1 c 2 b Output baa Note Let's consider the first sample. Initially we have name "bacbac"; the first operation transforms it into "bacbc", the second one — to "acbc", and finally, the third one transforms it into "acb". Tags: *special, binary search, brute force, data structures, strings Correct Solution: ``` # cook your dish here n=int(input()) s=list(input())*n d={} for i in range(len(s)): if s[i] not in d: d[s[i]]=[i] else: d[s[i]].append(i) m=int(input()) for i in range(m): o,c=input().split() s[d[c].pop(int(o)-1)]='' print(''.join(s)) ```
7,816
Provide tags and a correct Python 3 solution for this coding contest problem. One popular website developed an unusual username editing procedure. One can change the username only by deleting some characters from it: to change the current name s, a user can pick number p and character c and delete the p-th occurrence of character c from the name. After the user changed his name, he can't undo the change. For example, one can change name "arca" by removing the second occurrence of character "a" to get "arc". Polycarpus learned that some user initially registered under nickname t, where t is a concatenation of k copies of string s. Also, Polycarpus knows the sequence of this user's name changes. Help Polycarpus figure out the user's final name. Input The first line contains an integer k (1 ≤ k ≤ 2000). The second line contains a non-empty string s, consisting of lowercase Latin letters, at most 100 characters long. The third line contains an integer n (0 ≤ n ≤ 20000) — the number of username changes. Each of the next n lines contains the actual changes, one per line. The changes are written as "pi ci" (without the quotes), where pi (1 ≤ pi ≤ 200000) is the number of occurrences of letter ci, ci is a lowercase Latin letter. It is guaranteed that the operations are correct, that is, the letter to be deleted always exists, and after all operations not all letters are deleted from the name. The letters' occurrences are numbered starting from 1. Output Print a single string — the user's final name after all changes are applied to it. Examples Input 2 bac 3 2 a 1 b 2 c Output acb Input 1 abacaba 4 1 a 1 a 1 c 2 b Output baa Note Let's consider the first sample. Initially we have name "bacbac"; the first operation transforms it into "bacbc", the second one — to "acbc", and finally, the third one transforms it into "acb". Tags: *special, binary search, brute force, data structures, strings Correct Solution: ``` k = int(input()) string = list(input()) * k d = {} for i, letter in enumerate(string): if letter not in d: d[letter] = [i] else: d[letter].append(i) n = int(input()) for i in range(n): inp = input().split() p, c = int(inp[0]), inp[1] index = d[c][p-1] string[index] = '$' d[c].pop(p-1) print(*filter(lambda x: x != '$', string), sep='') ```
7,817
Provide tags and a correct Python 3 solution for this coding contest problem. One popular website developed an unusual username editing procedure. One can change the username only by deleting some characters from it: to change the current name s, a user can pick number p and character c and delete the p-th occurrence of character c from the name. After the user changed his name, he can't undo the change. For example, one can change name "arca" by removing the second occurrence of character "a" to get "arc". Polycarpus learned that some user initially registered under nickname t, where t is a concatenation of k copies of string s. Also, Polycarpus knows the sequence of this user's name changes. Help Polycarpus figure out the user's final name. Input The first line contains an integer k (1 ≤ k ≤ 2000). The second line contains a non-empty string s, consisting of lowercase Latin letters, at most 100 characters long. The third line contains an integer n (0 ≤ n ≤ 20000) — the number of username changes. Each of the next n lines contains the actual changes, one per line. The changes are written as "pi ci" (without the quotes), where pi (1 ≤ pi ≤ 200000) is the number of occurrences of letter ci, ci is a lowercase Latin letter. It is guaranteed that the operations are correct, that is, the letter to be deleted always exists, and after all operations not all letters are deleted from the name. The letters' occurrences are numbered starting from 1. Output Print a single string — the user's final name after all changes are applied to it. Examples Input 2 bac 3 2 a 1 b 2 c Output acb Input 1 abacaba 4 1 a 1 a 1 c 2 b Output baa Note Let's consider the first sample. Initially we have name "bacbac"; the first operation transforms it into "bacbc", the second one — to "acbc", and finally, the third one transforms it into "acb". Tags: *special, binary search, brute force, data structures, strings Correct Solution: ``` n = int(input()) t = input() l = len(t) m = int(input()) q = {c: [] for c in 'abcdefghijklmnopqrstuvwxyz'} for j, c in enumerate(t): q[c].append(j) q = {c: [i + j for i in range(0, n * l, l) for j in q[c]] for c in q} t = n * list(t) for i in range(m): j, c = input().split() t[q[c].pop(int(j) - 1)] = '' print(''.join(t)) # Made By Mostafa_Khaled ```
7,818
Provide tags and a correct Python 3 solution for this coding contest problem. One popular website developed an unusual username editing procedure. One can change the username only by deleting some characters from it: to change the current name s, a user can pick number p and character c and delete the p-th occurrence of character c from the name. After the user changed his name, he can't undo the change. For example, one can change name "arca" by removing the second occurrence of character "a" to get "arc". Polycarpus learned that some user initially registered under nickname t, where t is a concatenation of k copies of string s. Also, Polycarpus knows the sequence of this user's name changes. Help Polycarpus figure out the user's final name. Input The first line contains an integer k (1 ≤ k ≤ 2000). The second line contains a non-empty string s, consisting of lowercase Latin letters, at most 100 characters long. The third line contains an integer n (0 ≤ n ≤ 20000) — the number of username changes. Each of the next n lines contains the actual changes, one per line. The changes are written as "pi ci" (without the quotes), where pi (1 ≤ pi ≤ 200000) is the number of occurrences of letter ci, ci is a lowercase Latin letter. It is guaranteed that the operations are correct, that is, the letter to be deleted always exists, and after all operations not all letters are deleted from the name. The letters' occurrences are numbered starting from 1. Output Print a single string — the user's final name after all changes are applied to it. Examples Input 2 bac 3 2 a 1 b 2 c Output acb Input 1 abacaba 4 1 a 1 a 1 c 2 b Output baa Note Let's consider the first sample. Initially we have name "bacbac"; the first operation transforms it into "bacbc", the second one — to "acbc", and finally, the third one transforms it into "acb". Tags: *special, binary search, brute force, data structures, strings Correct Solution: ``` from collections import defaultdict k = int(input()) s = list(input() * k) p = defaultdict(list) for i in range(len(s)): p[(s[i])].append(i) for _ in range(int(input())): x, c = input().split() x = int(x) s[p[(c)].pop(int(x) - 1)] = "" print("".join(s)) ```
7,819
Provide tags and a correct Python 3 solution for this coding contest problem. One popular website developed an unusual username editing procedure. One can change the username only by deleting some characters from it: to change the current name s, a user can pick number p and character c and delete the p-th occurrence of character c from the name. After the user changed his name, he can't undo the change. For example, one can change name "arca" by removing the second occurrence of character "a" to get "arc". Polycarpus learned that some user initially registered under nickname t, where t is a concatenation of k copies of string s. Also, Polycarpus knows the sequence of this user's name changes. Help Polycarpus figure out the user's final name. Input The first line contains an integer k (1 ≤ k ≤ 2000). The second line contains a non-empty string s, consisting of lowercase Latin letters, at most 100 characters long. The third line contains an integer n (0 ≤ n ≤ 20000) — the number of username changes. Each of the next n lines contains the actual changes, one per line. The changes are written as "pi ci" (without the quotes), where pi (1 ≤ pi ≤ 200000) is the number of occurrences of letter ci, ci is a lowercase Latin letter. It is guaranteed that the operations are correct, that is, the letter to be deleted always exists, and after all operations not all letters are deleted from the name. The letters' occurrences are numbered starting from 1. Output Print a single string — the user's final name after all changes are applied to it. Examples Input 2 bac 3 2 a 1 b 2 c Output acb Input 1 abacaba 4 1 a 1 a 1 c 2 b Output baa Note Let's consider the first sample. Initially we have name "bacbac"; the first operation transforms it into "bacbc", the second one — to "acbc", and finally, the third one transforms it into "acb". Tags: *special, binary search, brute force, data structures, strings Correct Solution: ``` k=int(input()) e={} s=input() t=list(s*k) for i in range(len(t)): if t[i] in e:e[t[i]]+=[i] else:e[t[i]]=[i] for i in range(int(input())): q,w=input().split() q=int(q)-1 t[e[w][q]]="" e[w].pop(q) print("".join(t)) ```
7,820
Provide tags and a correct Python 3 solution for this coding contest problem. One popular website developed an unusual username editing procedure. One can change the username only by deleting some characters from it: to change the current name s, a user can pick number p and character c and delete the p-th occurrence of character c from the name. After the user changed his name, he can't undo the change. For example, one can change name "arca" by removing the second occurrence of character "a" to get "arc". Polycarpus learned that some user initially registered under nickname t, where t is a concatenation of k copies of string s. Also, Polycarpus knows the sequence of this user's name changes. Help Polycarpus figure out the user's final name. Input The first line contains an integer k (1 ≤ k ≤ 2000). The second line contains a non-empty string s, consisting of lowercase Latin letters, at most 100 characters long. The third line contains an integer n (0 ≤ n ≤ 20000) — the number of username changes. Each of the next n lines contains the actual changes, one per line. The changes are written as "pi ci" (without the quotes), where pi (1 ≤ pi ≤ 200000) is the number of occurrences of letter ci, ci is a lowercase Latin letter. It is guaranteed that the operations are correct, that is, the letter to be deleted always exists, and after all operations not all letters are deleted from the name. The letters' occurrences are numbered starting from 1. Output Print a single string — the user's final name after all changes are applied to it. Examples Input 2 bac 3 2 a 1 b 2 c Output acb Input 1 abacaba 4 1 a 1 a 1 c 2 b Output baa Note Let's consider the first sample. Initially we have name "bacbac"; the first operation transforms it into "bacbc", the second one — to "acbc", and finally, the third one transforms it into "acb". Tags: *special, binary search, brute force, data structures, strings Correct Solution: ``` import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") ########################################################## from collections import Counter # c=sorted((i,int(val))for i,val in enumerate(input().split())) import heapq # c=sorted((i,int(val))for i,val in enumerate(input().split())) # n = int(input()) # ls = list(map(int, input().split())) # n, k = map(int, input().split()) # n =int(input()) # e=list(map(int, input().split())) from collections import Counter #for _ in range(int(input())): k=int(input()) ans=list(input()*k) d={} #print(ans) for i,ch in enumerate(ans): if ch not in d: d[ch]=[i] else: d[ch].append(i) #print(d) for _ in range(int(input())): var=input().split() ch=var[1] pos=int(var[0]) ans[d[ch][pos-1]]="" d[ch].pop(pos-1) print("".join(ans)) ```
7,821
Provide tags and a correct Python 3 solution for this coding contest problem. One popular website developed an unusual username editing procedure. One can change the username only by deleting some characters from it: to change the current name s, a user can pick number p and character c and delete the p-th occurrence of character c from the name. After the user changed his name, he can't undo the change. For example, one can change name "arca" by removing the second occurrence of character "a" to get "arc". Polycarpus learned that some user initially registered under nickname t, where t is a concatenation of k copies of string s. Also, Polycarpus knows the sequence of this user's name changes. Help Polycarpus figure out the user's final name. Input The first line contains an integer k (1 ≤ k ≤ 2000). The second line contains a non-empty string s, consisting of lowercase Latin letters, at most 100 characters long. The third line contains an integer n (0 ≤ n ≤ 20000) — the number of username changes. Each of the next n lines contains the actual changes, one per line. The changes are written as "pi ci" (without the quotes), where pi (1 ≤ pi ≤ 200000) is the number of occurrences of letter ci, ci is a lowercase Latin letter. It is guaranteed that the operations are correct, that is, the letter to be deleted always exists, and after all operations not all letters are deleted from the name. The letters' occurrences are numbered starting from 1. Output Print a single string — the user's final name after all changes are applied to it. Examples Input 2 bac 3 2 a 1 b 2 c Output acb Input 1 abacaba 4 1 a 1 a 1 c 2 b Output baa Note Let's consider the first sample. Initially we have name "bacbac"; the first operation transforms it into "bacbc", the second one — to "acbc", and finally, the third one transforms it into "acb". Tags: *special, binary search, brute force, data structures, strings Correct Solution: ``` n = int(input()) t = input() l = len(t) m = int(input()) q = {c: [] for c in 'abcdefghijklmnopqrstuvwxyz'} for j, c in enumerate(t): q[c].append(j) q = {c: [i + j for i in range(0, n * l, l) for j in q[c]] for c in q} t = n * list(t) for i in range(m): j, c = input().split() t[q[c].pop(int(j) - 1)] = '' print(''.join(t)) ```
7,822
Provide tags and a correct Python 3 solution for this coding contest problem. One popular website developed an unusual username editing procedure. One can change the username only by deleting some characters from it: to change the current name s, a user can pick number p and character c and delete the p-th occurrence of character c from the name. After the user changed his name, he can't undo the change. For example, one can change name "arca" by removing the second occurrence of character "a" to get "arc". Polycarpus learned that some user initially registered under nickname t, where t is a concatenation of k copies of string s. Also, Polycarpus knows the sequence of this user's name changes. Help Polycarpus figure out the user's final name. Input The first line contains an integer k (1 ≤ k ≤ 2000). The second line contains a non-empty string s, consisting of lowercase Latin letters, at most 100 characters long. The third line contains an integer n (0 ≤ n ≤ 20000) — the number of username changes. Each of the next n lines contains the actual changes, one per line. The changes are written as "pi ci" (without the quotes), where pi (1 ≤ pi ≤ 200000) is the number of occurrences of letter ci, ci is a lowercase Latin letter. It is guaranteed that the operations are correct, that is, the letter to be deleted always exists, and after all operations not all letters are deleted from the name. The letters' occurrences are numbered starting from 1. Output Print a single string — the user's final name after all changes are applied to it. Examples Input 2 bac 3 2 a 1 b 2 c Output acb Input 1 abacaba 4 1 a 1 a 1 c 2 b Output baa Note Let's consider the first sample. Initially we have name "bacbac"; the first operation transforms it into "bacbc", the second one — to "acbc", and finally, the third one transforms it into "acb". Tags: *special, binary search, brute force, data structures, strings Correct Solution: ``` #copied... idea def main(): mode="filee" if mode=="file":f=open("test.txt","r") get = lambda :[int(x) for x in (f.readline() if mode=="file" else input()).split()] gets = lambda :[str(x) for x in (f.readline() if mode=="file" else input()).split()] [k]=get() [g]=gets() h = g*k h = list(h) p = [] for i in range(128): p.append([0]) for i in range(len(h)): p[ord(h[i])].append(i) [n]=get() for i in range(n): [x,y]=gets() x = int(x) h[p[ord(y)][x]]='' p[ord(y)].pop(x) print("".join(h)) if mode=="file":f.close() if __name__=="__main__": main() ```
7,823
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One popular website developed an unusual username editing procedure. One can change the username only by deleting some characters from it: to change the current name s, a user can pick number p and character c and delete the p-th occurrence of character c from the name. After the user changed his name, he can't undo the change. For example, one can change name "arca" by removing the second occurrence of character "a" to get "arc". Polycarpus learned that some user initially registered under nickname t, where t is a concatenation of k copies of string s. Also, Polycarpus knows the sequence of this user's name changes. Help Polycarpus figure out the user's final name. Input The first line contains an integer k (1 ≤ k ≤ 2000). The second line contains a non-empty string s, consisting of lowercase Latin letters, at most 100 characters long. The third line contains an integer n (0 ≤ n ≤ 20000) — the number of username changes. Each of the next n lines contains the actual changes, one per line. The changes are written as "pi ci" (without the quotes), where pi (1 ≤ pi ≤ 200000) is the number of occurrences of letter ci, ci is a lowercase Latin letter. It is guaranteed that the operations are correct, that is, the letter to be deleted always exists, and after all operations not all letters are deleted from the name. The letters' occurrences are numbered starting from 1. Output Print a single string — the user's final name after all changes are applied to it. Examples Input 2 bac 3 2 a 1 b 2 c Output acb Input 1 abacaba 4 1 a 1 a 1 c 2 b Output baa Note Let's consider the first sample. Initially we have name "bacbac"; the first operation transforms it into "bacbc", the second one — to "acbc", and finally, the third one transforms it into "acb". Submitted Solution: ``` n = int(input()) s = input() sens = [[]] for i in s: sens[-1].append(i) if i in ['.', '!', '?']: sens.append([]) for i in range(len(sens)): if sens[i]: sens[i] = ''.join(sens[i]) sens[i] = sens[i].strip() if len(sens[i]) > n: print('Impossible') exit(0) sens.pop() i = 0 ans = 0 while i < len(sens): l = len(sens[i]) while i + 1 < len(sens) and l + 1 + len(sens[i + 1]) <= n: i += 1 l += len(sens[i + 1]) + 1 i += 1 ans += 1 print(ans) ``` No
7,824
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One popular website developed an unusual username editing procedure. One can change the username only by deleting some characters from it: to change the current name s, a user can pick number p and character c and delete the p-th occurrence of character c from the name. After the user changed his name, he can't undo the change. For example, one can change name "arca" by removing the second occurrence of character "a" to get "arc". Polycarpus learned that some user initially registered under nickname t, where t is a concatenation of k copies of string s. Also, Polycarpus knows the sequence of this user's name changes. Help Polycarpus figure out the user's final name. Input The first line contains an integer k (1 ≤ k ≤ 2000). The second line contains a non-empty string s, consisting of lowercase Latin letters, at most 100 characters long. The third line contains an integer n (0 ≤ n ≤ 20000) — the number of username changes. Each of the next n lines contains the actual changes, one per line. The changes are written as "pi ci" (without the quotes), where pi (1 ≤ pi ≤ 200000) is the number of occurrences of letter ci, ci is a lowercase Latin letter. It is guaranteed that the operations are correct, that is, the letter to be deleted always exists, and after all operations not all letters are deleted from the name. The letters' occurrences are numbered starting from 1. Output Print a single string — the user's final name after all changes are applied to it. Examples Input 2 bac 3 2 a 1 b 2 c Output acb Input 1 abacaba 4 1 a 1 a 1 c 2 b Output baa Note Let's consider the first sample. Initially we have name "bacbac"; the first operation transforms it into "bacbc", the second one — to "acbc", and finally, the third one transforms it into "acb". Submitted Solution: ``` n = int(input()) t = input() l = len(t[0]) m = int(input()) q = {c: [] for c in 'abcdefghijklmnopqrstuvwxyz'} for j, c in enumerate(t): q[c].append(j) q = {c: [i + j for i in range(0, n * l, l) for j in q[c]] for c in q} t = n * list(t) for i in range(m): j, c = input().split() t[q[c].pop(int(j) - 1)] = '' print(''.join(t)) ``` No
7,825
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One popular website developed an unusual username editing procedure. One can change the username only by deleting some characters from it: to change the current name s, a user can pick number p and character c and delete the p-th occurrence of character c from the name. After the user changed his name, he can't undo the change. For example, one can change name "arca" by removing the second occurrence of character "a" to get "arc". Polycarpus learned that some user initially registered under nickname t, where t is a concatenation of k copies of string s. Also, Polycarpus knows the sequence of this user's name changes. Help Polycarpus figure out the user's final name. Input The first line contains an integer k (1 ≤ k ≤ 2000). The second line contains a non-empty string s, consisting of lowercase Latin letters, at most 100 characters long. The third line contains an integer n (0 ≤ n ≤ 20000) — the number of username changes. Each of the next n lines contains the actual changes, one per line. The changes are written as "pi ci" (without the quotes), where pi (1 ≤ pi ≤ 200000) is the number of occurrences of letter ci, ci is a lowercase Latin letter. It is guaranteed that the operations are correct, that is, the letter to be deleted always exists, and after all operations not all letters are deleted from the name. The letters' occurrences are numbered starting from 1. Output Print a single string — the user's final name after all changes are applied to it. Examples Input 2 bac 3 2 a 1 b 2 c Output acb Input 1 abacaba 4 1 a 1 a 1 c 2 b Output baa Note Let's consider the first sample. Initially we have name "bacbac"; the first operation transforms it into "bacbc", the second one — to "acbc", and finally, the third one transforms it into "acb". Submitted Solution: ``` n = int(input()) t = input() r = [''] + [t] * n m = int(input()) q = {c: [] for c in set(t)} for j, c in enumerate(t): q[c].append(j) p = {c: [] for c in q} for i in range(m): j, c = input().split() p[c].append(int(j)) for c in p: for i in range(len(p[c])): k = p[c][i] for j in range(i + 1, len(p[c])): if p[c][j] >= k: p[c][j] += 1 for c in p: l = len(q[c]) for i in range(len(p[c])): x, y = p[c][i] // l, p[c][i] % l r[x] = r[x][: q[c][y]] + ' ' + r[x][q[c][y] + 1: ] t = ''.join(r) print(t.replace(' ', '')) ``` No
7,826
Provide tags and a correct Python 3 solution for this coding contest problem. Consider some square matrix A with side n consisting of zeros and ones. There are n rows numbered from 1 to n from top to bottom and n columns numbered from 1 to n from left to right in this matrix. We'll denote the element of the matrix which is located at the intersection of the i-row and the j-th column as Ai, j. Let's call matrix A clear if no two cells containing ones have a common side. Let's call matrix A symmetrical if it matches the matrices formed from it by a horizontal and/or a vertical reflection. Formally, for each pair (i, j) (1 ≤ i, j ≤ n) both of the following conditions must be met: Ai, j = An - i + 1, j and Ai, j = Ai, n - j + 1. Let's define the sharpness of matrix A as the number of ones in it. Given integer x, your task is to find the smallest positive integer n such that there exists a clear symmetrical matrix A with side n and sharpness x. Input The only line contains a single integer x (1 ≤ x ≤ 100) — the required sharpness of the matrix. Output Print a single number — the sought value of n. Examples Input 4 Output 3 Input 9 Output 5 Note The figure below shows the matrices that correspond to the samples: <image> Tags: constructive algorithms, dp, math Correct Solution: ``` from math import ceil i=int(input()) if i==3: k=5 else: k=ceil(((2*i)-1)**0.5) if k%2==0: k+=1 for j in range(k,101): if (j**2+1)/2>=i: print(j) break ```
7,827
Provide tags and a correct Python 3 solution for this coding contest problem. Consider some square matrix A with side n consisting of zeros and ones. There are n rows numbered from 1 to n from top to bottom and n columns numbered from 1 to n from left to right in this matrix. We'll denote the element of the matrix which is located at the intersection of the i-row and the j-th column as Ai, j. Let's call matrix A clear if no two cells containing ones have a common side. Let's call matrix A symmetrical if it matches the matrices formed from it by a horizontal and/or a vertical reflection. Formally, for each pair (i, j) (1 ≤ i, j ≤ n) both of the following conditions must be met: Ai, j = An - i + 1, j and Ai, j = Ai, n - j + 1. Let's define the sharpness of matrix A as the number of ones in it. Given integer x, your task is to find the smallest positive integer n such that there exists a clear symmetrical matrix A with side n and sharpness x. Input The only line contains a single integer x (1 ≤ x ≤ 100) — the required sharpness of the matrix. Output Print a single number — the sought value of n. Examples Input 4 Output 3 Input 9 Output 5 Note The figure below shows the matrices that correspond to the samples: <image> Tags: constructive algorithms, dp, math Correct Solution: ``` #------------------------template--------------------------# import os import sys from math import * from collections import * from fractions import * from bisect import * from heapq import* from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') 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") ALPHA='abcdefghijklmnopqrstuvwxyz' MOD=1000000007 def value():return tuple(map(int,input().split())) def array():return [int(i) for i in input().split()] def Int():return int(input()) def Str():return input() def arrayS():return [i for i in input().split()] #-------------------------code---------------------------# # vsInput() cap=[0,1] for i in range(2,101): k=ceil(i/2) k+=k-1 cap.append(cap[-1]+k) def possible(x): quad=x//2 load=cap[quad] if(quad%2==0): for i in range(quad*2+2): rem=n-i if(rem%4==0 and rem//4<=load): return True else: quad-=1 for i in range(quad*2+2): rem=n-i if(rem%4==0 and rem//4<=load): return True quad+=1 rem=n-ceil(quad/2)*4 if(rem%4==0 and rem//4<=load-4): return True return False n=Int() if(n==2): print(3) exit() for mid in range(1,100,2): if(possible(mid)): print(mid) break ```
7,828
Provide tags and a correct Python 3 solution for this coding contest problem. Consider some square matrix A with side n consisting of zeros and ones. There are n rows numbered from 1 to n from top to bottom and n columns numbered from 1 to n from left to right in this matrix. We'll denote the element of the matrix which is located at the intersection of the i-row and the j-th column as Ai, j. Let's call matrix A clear if no two cells containing ones have a common side. Let's call matrix A symmetrical if it matches the matrices formed from it by a horizontal and/or a vertical reflection. Formally, for each pair (i, j) (1 ≤ i, j ≤ n) both of the following conditions must be met: Ai, j = An - i + 1, j and Ai, j = Ai, n - j + 1. Let's define the sharpness of matrix A as the number of ones in it. Given integer x, your task is to find the smallest positive integer n such that there exists a clear symmetrical matrix A with side n and sharpness x. Input The only line contains a single integer x (1 ≤ x ≤ 100) — the required sharpness of the matrix. Output Print a single number — the sought value of n. Examples Input 4 Output 3 Input 9 Output 5 Note The figure below shows the matrices that correspond to the samples: <image> Tags: constructive algorithms, dp, math Correct Solution: ``` n=int(input()) if n==3 : print(5) exit() for i in range(1,200) : if i%2!=0 : v=(i*i)//2+1 if n<=v : print(i) exit() ```
7,829
Provide tags and a correct Python 3 solution for this coding contest problem. Consider some square matrix A with side n consisting of zeros and ones. There are n rows numbered from 1 to n from top to bottom and n columns numbered from 1 to n from left to right in this matrix. We'll denote the element of the matrix which is located at the intersection of the i-row and the j-th column as Ai, j. Let's call matrix A clear if no two cells containing ones have a common side. Let's call matrix A symmetrical if it matches the matrices formed from it by a horizontal and/or a vertical reflection. Formally, for each pair (i, j) (1 ≤ i, j ≤ n) both of the following conditions must be met: Ai, j = An - i + 1, j and Ai, j = Ai, n - j + 1. Let's define the sharpness of matrix A as the number of ones in it. Given integer x, your task is to find the smallest positive integer n such that there exists a clear symmetrical matrix A with side n and sharpness x. Input The only line contains a single integer x (1 ≤ x ≤ 100) — the required sharpness of the matrix. Output Print a single number — the sought value of n. Examples Input 4 Output 3 Input 9 Output 5 Note The figure below shows the matrices that correspond to the samples: <image> Tags: constructive algorithms, dp, math Correct Solution: ``` def solve(n): if n == 1: return 1 if n == 3: return 5 for k in range(100): val = 4 * (((k - 1) ** 2 + 1) // 2 + (k + 1) // 2) - 3 if val >= n: return 2 * k - 1 print(solve(int(input()))) ```
7,830
Provide tags and a correct Python 3 solution for this coding contest problem. Consider some square matrix A with side n consisting of zeros and ones. There are n rows numbered from 1 to n from top to bottom and n columns numbered from 1 to n from left to right in this matrix. We'll denote the element of the matrix which is located at the intersection of the i-row and the j-th column as Ai, j. Let's call matrix A clear if no two cells containing ones have a common side. Let's call matrix A symmetrical if it matches the matrices formed from it by a horizontal and/or a vertical reflection. Formally, for each pair (i, j) (1 ≤ i, j ≤ n) both of the following conditions must be met: Ai, j = An - i + 1, j and Ai, j = Ai, n - j + 1. Let's define the sharpness of matrix A as the number of ones in it. Given integer x, your task is to find the smallest positive integer n such that there exists a clear symmetrical matrix A with side n and sharpness x. Input The only line contains a single integer x (1 ≤ x ≤ 100) — the required sharpness of the matrix. Output Print a single number — the sought value of n. Examples Input 4 Output 3 Input 9 Output 5 Note The figure below shows the matrices that correspond to the samples: <image> Tags: constructive algorithms, dp, math Correct Solution: ``` import sys from math import gcd,sqrt,ceil,log2 from collections import defaultdict,Counter,deque from bisect import bisect_left,bisect_right import math sys.setrecursionlimit(2*10**5+10) import heapq from itertools import permutations # input=sys.stdin.readline # def print(x): # sys.stdout.write(str(x)+"\n") # sys.stdin = open('input.txt', 'r') # sys.stdout = open('output.txt', 'w') import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 aa='abcdefghijklmnopqrstuvwxyz' 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") # import sys # import io, os # input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline def get_sum(bit,i): s = 0 i+=1 while i>0: s+=bit[i] i-=i&(-i) return s def update(bit,n,i,v): i+=1 while i<=n: bit[i]+=v i+=i&(-i) def modInverse(b,m): g = math.gcd(b, m) if (g != 1): return -1 else: return pow(b, m - 2, m) def primeFactors(n): sa = [] # sa.add(n) while n % 2 == 0: sa.append(2) n = n // 2 for i in range(3,int(math.sqrt(n))+1,2): while n % i== 0: sa.append(i) n = n // i # sa.add(n) if n > 2: sa.append(n) return sa def seive(n): pri = [True]*(n+1) p = 2 while p*p<=n: if pri[p] == True: for i in range(p*p,n+1,p): pri[i] = False p+=1 return pri def check_prim(n): if n<0: return False for i in range(2,int(sqrt(n))+1): if n%i == 0: return False return True def getZarr(string, z): n = len(string) # [L,R] make a window which matches # with prefix of s l, r, k = 0, 0, 0 for i in range(1, n): # if i>R nothing matches so we will calculate. # Z[i] using naive way. if i > r: l, r = i, i # R-L = 0 in starting, so it will start # checking from 0'th index. For example, # for "ababab" and i = 1, the value of R # remains 0 and Z[i] becomes 0. For string # "aaaaaa" and i = 1, Z[i] and R become 5 while r < n and string[r - l] == string[r]: r += 1 z[i] = r - l r -= 1 else: # k = i-L so k corresponds to number which # matches in [L,R] interval. k = i - l # if Z[k] is less than remaining interval # then Z[i] will be equal to Z[k]. # For example, str = "ababab", i = 3, R = 5 # and L = 2 if z[k] < r - i + 1: z[i] = z[k] # For example str = "aaaaaa" and i = 2, # R is 5, L is 0 else: # else start from R and check manually l = i while r < n and string[r - l] == string[r]: r += 1 z[i] = r - l r -= 1 def search(text, pattern): # Create concatenated string "P$T" concat = pattern + "$" + text l = len(concat) z = [0] * l getZarr(concat, z) ha = [] for i in range(l): if z[i] == len(pattern): ha.append(i - len(pattern) - 1) return ha # n,k = map(int,input().split()) # l = list(map(int,input().split())) # # n = int(input()) # l = list(map(int,input().split())) # # hash = defaultdict(list) # la = [] # # for i in range(n): # la.append([l[i],i+1]) # # la.sort(key = lambda x: (x[0],-x[1])) # ans = [] # r = n # flag = 0 # lo = [] # ha = [i for i in range(n,0,-1)] # yo = [] # for a,b in la: # # if a == 1: # ans.append([r,b]) # # hash[(1,1)].append([b,r]) # lo.append((r,b)) # ha.pop(0) # yo.append([r,b]) # r-=1 # # elif a == 2: # # print(yo,lo) # # print(hash[1,1]) # if lo == []: # flag = 1 # break # c,d = lo.pop(0) # yo.pop(0) # if b>=d: # flag = 1 # break # ans.append([c,b]) # yo.append([c,b]) # # # # elif a == 3: # # if yo == []: # flag = 1 # break # c,d = yo.pop(0) # if b>=d: # flag = 1 # break # if ha == []: # flag = 1 # break # # ka = ha.pop(0) # # ans.append([ka,b]) # ans.append([ka,d]) # yo.append([ka,b]) # # if flag: # print(-1) # else: # print(len(ans)) # for a,b in ans: # print(a,b) def mergeIntervals(arr): # Sorting based on the increasing order # of the start intervals arr.sort(key = lambda x: x[0]) # array to hold the merged intervals m = [] s = -10000 max = -100000 for i in range(len(arr)): a = arr[i] if a[0] > max: if i != 0: m.append([s,max]) max = a[1] s = a[0] else: if a[1] >= max: max = a[1] #'max' value gives the last point of # that particular interval # 's' gives the starting point of that interval # 'm' array contains the list of all merged intervals if max != -100000 and [s, max] not in m: m.append([s, max]) return m class SortedList: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" values = sorted(iterable) self._len = _len = len(values) self._load = _load self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)] self._list_lens = [len(_list) for _list in _lists] self._mins = [_list[0] for _list in _lists] self._fen_tree = [] self._rebuild = True def _fen_build(self): """Build a fenwick tree instance.""" self._fen_tree[:] = self._list_lens _fen_tree = self._fen_tree for i in range(len(_fen_tree)): if i | i + 1 < len(_fen_tree): _fen_tree[i | i + 1] += _fen_tree[i] self._rebuild = False def _fen_update(self, index, value): """Update `fen_tree[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree while index < len(_fen_tree): _fen_tree[index] += value index |= index + 1 def _fen_query(self, end): """Return `sum(_fen_tree[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree x = 0 while end: x += _fen_tree[end - 1] end &= end - 1 return x def _fen_findkth(self, k): """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).""" _list_lens = self._list_lens if k < _list_lens[0]: return 0, k if k >= self._len - _list_lens[-1]: return len(_list_lens) - 1, k + _list_lens[-1] - self._len if self._rebuild: self._fen_build() _fen_tree = self._fen_tree idx = -1 for d in reversed(range(len(_fen_tree).bit_length())): right_idx = idx + (1 << d) if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]: idx = right_idx k -= _fen_tree[idx] return idx + 1, k def _delete(self, pos, idx): """Delete value at the given `(pos, idx)`.""" _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len -= 1 self._fen_update(pos, -1) del _lists[pos][idx] _list_lens[pos] -= 1 if _list_lens[pos]: _mins[pos] = _lists[pos][0] else: del _lists[pos] del _list_lens[pos] del _mins[pos] self._rebuild = True def _loc_left(self, value): """Return an index pair that corresponds to the first position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins lo, pos = -1, len(_lists) - 1 while lo + 1 < pos: mi = (lo + pos) >> 1 if value <= _mins[mi]: pos = mi else: lo = mi if pos and value <= _lists[pos - 1][-1]: pos -= 1 _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value <= _list[mi]: idx = mi else: lo = mi return pos, idx def _loc_right(self, value): """Return an index pair that corresponds to the last position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins pos, hi = 0, len(_lists) while pos + 1 < hi: mi = (pos + hi) >> 1 if value < _mins[mi]: hi = mi else: pos = mi _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value < _list[mi]: idx = mi else: lo = mi return pos, idx def add(self, value): """Add `value` to sorted list.""" _load = self._load _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len += 1 if _lists: pos, idx = self._loc_right(value) self._fen_update(pos, 1) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 _mins[pos] = _list[0] if _load + _load < len(_list): _lists.insert(pos + 1, _list[_load:]) _list_lens.insert(pos + 1, len(_list) - _load) _mins.insert(pos + 1, _list[_load]) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _mins.append(value) _list_lens.append(1) self._rebuild = True def discard(self, value): """Remove `value` from sorted list if it is a member.""" _lists = self._lists if _lists: pos, idx = self._loc_right(value) if idx and _lists[pos][idx - 1] == value: self._delete(pos, idx - 1) def remove(self, value): """Remove `value` from sorted list; `value` must be a member.""" _len = self._len self.discard(value) if _len == self._len: raise ValueError('{0!r} not in list'.format(value)) def pop(self, index=-1): """Remove and return value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) value = self._lists[pos][idx] self._delete(pos, idx) return value def bisect_left(self, value): """Return the first index to insert `value` in the sorted list.""" pos, idx = self._loc_left(value) return self._fen_query(pos) + idx def bisect_right(self, value): """Return the last index to insert `value` in the sorted list.""" pos, idx = self._loc_right(value) return self._fen_query(pos) + idx def count(self, value): """Return number of occurrences of `value` in the sorted list.""" return self.bisect_right(value) - self.bisect_left(value) def __len__(self): """Return the size of the sorted list.""" return self._len def __getitem__(self, index): """Lookup value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) return self._lists[pos][idx] def __delitem__(self, index): """Remove value at `index` from sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._delete(pos, idx) def __contains__(self, value): """Return true if `value` is an element of the sorted list.""" _lists = self._lists if _lists: pos, idx = self._loc_left(value) return idx < len(_lists[pos]) and _lists[pos][idx] == value return False def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return 'SortedList({0})'.format(list(self)) def ncr(n, r, p): num = den = 1 for i in range(r): num = (num * (n - i)) % p den = (den * (i + 1)) % p return (num * pow(den, p - 2, p)) % p def sol(n): seti = set() for i in range(1,int(sqrt(n))+1): if n%i == 0: seti.add(n//i) seti.add(i) return seti def lcm(a,b): return (a*b)//gcd(a,b) # # n,p = map(int,input().split()) # # s = input() # # if n <=2: # if n == 1: # pass # if n == 2: # pass # i = n-1 # idx = -1 # while i>=0: # z = ord(s[i])-96 # k = chr(z+1+96) # flag = 1 # if i-1>=0: # if s[i-1]!=k: # flag+=1 # else: # flag+=1 # if i-2>=0: # if s[i-2]!=k: # flag+=1 # else: # flag+=1 # if flag == 2: # idx = i # s[i] = k # break # if idx == -1: # print('NO') # exit() # for i in range(idx+1,n): # if # def moore_voting(l): count1 = 0 count2 = 0 first = 10**18 second = 10**18 n = len(l) for i in range(n): if l[i] == first: count1+=1 elif l[i] == second: count2+=1 elif count1 == 0: count1+=1 first = l[i] elif count2 == 0: count2+=1 second = l[i] else: count1-=1 count2-=1 for i in range(n): if l[i] == first: count1+=1 elif l[i] == second: count2+=1 if count1>n//3: return first if count2>n//3: return second return -1 def find_parent(u,parent): if u!=parent[u]: parent[u] = find_parent(parent[u],parent) return parent[u] def dis_union(n,e): par = [i for i in range(n+1)] rank = [1]*(n+1) for a,b in e: z1,z2 = find_parent(a,par),find_parent(b,par) if rank[z1]>rank[z2]: z1,z2 = z2,z1 if z1!=z2: par[z1] = z2 rank[z2]+=rank[z1] else: return a,b def dijkstra(n,tot,hash): hea = [[0,n]] dis = [10**18]*(tot+1) dis[n] = 0 boo = defaultdict(bool) check = defaultdict(int) while hea: a,b = heapq.heappop(hea) if boo[b]: continue boo[b] = True for i,w in hash[b]: if b == 1: c = 0 if (1,i,w) in nodes: c = nodes[(1,i,w)] del nodes[(1,i,w)] if dis[b]+w<dis[i]: dis[i] = dis[b]+w check[i] = c elif dis[b]+w == dis[i] and c == 0: dis[i] = dis[b]+w check[i] = c else: if dis[b]+w<=dis[i]: dis[i] = dis[b]+w check[i] = check[b] heapq.heappush(hea,[dis[i],i]) return check def power(x,y,p): res = 1 x = x%p if x == 0: return 0 while y>0: if (y&1) == 1: res*=x x = x*x y = y>>1 return res import sys from math import ceil,log2 INT_MAX = sys.maxsize def minVal(x, y) : return x if (x < y) else y def getMid(s, e) : return s + (e - s) // 2 def RMQUtil( st, ss, se, qs, qe, index) : if (qs <= ss and qe >= se) : return st[index] if (se < qs or ss > qe) : return INT_MAX mid = getMid(ss, se) return minVal(RMQUtil(st, ss, mid, qs, qe, 2 * index + 1), RMQUtil(st, mid + 1, se, qs, qe, 2 * index + 2)) def RMQ( st, n, qs, qe) : if (qs < 0 or qe > n - 1 or qs > qe) : print("Invalid Input") return -1 return RMQUtil(st, 0, n - 1, qs, qe, 0) def constructSTUtil(arr, ss, se, st, si) : if (ss == se) : st[si] = arr[ss] return arr[ss] mid = getMid(ss, se) st[si] = minVal(constructSTUtil(arr, ss, mid, st, si * 2 + 1), constructSTUtil(arr, mid + 1, se, st, si * 2 + 2)) return st[si] def constructST( arr, n) : x = (int)(ceil(log2(n))) max_size = 2 * (int)(2**x) - 1 st = [0] * (max_size) constructSTUtil(arr, 0, n - 1, st, 0) return st # t = int(input()) # for _ in range(t): # # n = int(input()) # l = list(map(int,input().split())) # # x,y = 0,10 # st = constructST(l, n) # # pre = [0] # suf = [0] # for i in range(n): # pre.append(max(pre[-1],l[i])) # for i in range(n-1,-1,-1): # suf.append(max(suf[-1],l[i])) # # # i = 1 # # print(pre,suf) # flag = 0 # x,y,z = -1,-1,-1 # # suf.reverse() # print(suf) # while i<len(pre): # # z = pre[i] # j = bisect_left(suf,z) # if suf[j] == z: # while i<n and l[i]<=z: # i+=1 # if pre[i]>z: # break # while j<n and l[n-j]<=z: # j+=1 # if suf[j]>z: # break # # j-=1 # print(i,n-j) # # break/ # if RMQ(st,n,i,j) == z: # c = i+j-i+1 # x,y,z = i,j-i+1,n-c # break # else: # i+=1 # # else: # i+=1 # # # # if x!=-1: # print('Yes') # print(x,y,z) # else: # print('No') # t = int(input()) # # for _ in range(t): # # def debug(n): # ans = [] # for i in range(1,n+1): # for j in range(i+1,n+1): # if (i*(j+1))%(j-i) == 0 : # ans.append([i,j]) # return ans # # # n = int(input()) # print(debug(n)) # import sys # input = sys.stdin.readline # import bisect # # t=int(input()) # for tests in range(t): # n=int(input()) # A=list(map(int,input().split())) # # LEN = len(A) # Sparse_table = [A] # # for i in range(LEN.bit_length()-1): # j = 1<<i # B = [] # for k in range(len(Sparse_table[-1])-j): # B.append(min(Sparse_table[-1][k], Sparse_table[-1][k+j])) # Sparse_table.append(B) # # def query(l,r): # [l,r)におけるminを求める. # i=(r-l).bit_length()-1 # 何番目のSparse_tableを見るか. # # return min(Sparse_table[i][l],Sparse_table[i][r-(1<<i)]) # (1<<i)個あれば[l, r)が埋まるので, それを使ってminを求める. # # LMAX=[A[0]] # for i in range(1,n): # LMAX.append(max(LMAX[-1],A[i])) # # RMAX=A[-1] # # for i in range(n-1,-1,-1): # RMAX=max(RMAX,A[i]) # # x=bisect.bisect(LMAX,RMAX) # #print(RMAX,x) # print(RMAX,x,i) # if x==0: # continue # # v=min(x,i-1) # if v<=0: # continue # # if LMAX[v-1]==query(v,i)==RMAX: # print("YES") # print(v,i-v,n-i) # break # # v-=1 # if v<=0: # continue # if LMAX[v-1]==query(v,i)==RMAX: # print("YES") # print(v,i-v,n-i) # break # else: # print("NO") # # # # # # # # # # t = int(input()) # # for _ in range(t): # # x = int(input()) # mini = 10**18 # n = ceil((-1 + sqrt(1+8*x))/2) # for i in range(-100,1): # z = x+-1*i # z1 = (abs(i)*(abs(i)+1))//2 # z+=z1 # # print(z) # n = ceil((-1 + sqrt(1+8*z))/2) # # y = (n*(n+1))//2 # # print(n,y,z,i) # mini = min(n+y-z,mini) # print(n+y-z,i) # # # print(mini) # # # # n,m = map(int,input().split()) # l = [] # hash = defaultdict(int) # for i in range(n): # la = list(map(int,input().split()))[1:] # l.append(set(la)) # # for i in la: # # hash[i]+=1 # # for i in range(n): # # for j in range(n): # if i!=j: # # if len(l[i].intersection(l[j])) == 0: # for k in range(n): # # # else: # break # # # # # # # practicing segment_trees # t = int(input()) # # for _ in range(t): # n = int(input()) # l = [] # for i in range(n): # a,b = map(int,input().split()) # l.append([a,b]) # # l.sort() # n,m = map(int,input().split()) # l = list(map(int,input().split())) # # hash = defaultdict(int) # for i in range(1,2**n,2): # count = 0 # z1 = bin(l[i]|l[i-1])[2:] # z1+='0'*(17-len(z1)) + z1 # for k in range(len(z1)): # if z1[k] == '1': # hash[k]+=1 # for i in range(m): # a,b = map(int,input().split()) # a-=1 # init = a # if a%2 == 0: # a+=1 # z1 = bin(l[a]|l[a-1])[2:] # z1+='0'*(17-len(z1)) + z1 # for k in range(len(z1)): # if z1[k] == '1': # hash[k]-=1 # l[init] = b # a = init # if a%2 == 0: # a+=1 # z1 = bin(l[a]|l[a-1])[2:] # z1+='0'*(17-len(z1)) + z1 # for k in range(len(z1)): # if z1[k] == '1': # hash[k]+=1 # ans = '' # for k in range(17): # if n%2 == 0: # if hash[k]%2 == 0: # ans+='0' # else: # ans+='1' # else: # if hash[k]%2 == 0: # if hash[k] # # # def bfs1(p): level = [0]*(n+1) boo = [False]*(n+1) queue = [p] boo[p] = True maxi = 0 # node = -1 while queue: z = queue.pop(0) for i in hash[z]: if not boo[i]: boo[i] = True queue.append(i) level[i] = level[z]+1 if level[i]>maxi: maxi = level[i] # node = i / return maxi def bfs(p): level = [0]*(n+1) # boo = [False]*(n+1) queue = [p] boo[p] = True maxi = 0 node = p yo = [] while queue: z = queue.pop(0) yo.append(z) for i in hash[z]: if not boo[i]: boo[i] = True queue.append(i) level[i] = level[z]+1 if level[i]>maxi: maxi = level[i] node = i z = bfs1(node) return z,node,yo # t = int(input()) # # for _ in range(t): # # n = int(input()) # l1 = list(map(int,input().split())) # seti = set(i for i in range(1,2*n+1)) # l2 = [] # for i in seti: # if i not in l1: # l2.append(i) # l2.sort() # l1.sort() # print(l1,l2) # ans = [0] # count = 0 # for i in range(n): # z = bisect_right(l2,l1[i]) # k = ans[-1] + 1 # if z>=k: # ans.append(k) # count+=1 # else: # ans.append(ans[-1]) # print(count) x = int(input()) if x == 1: print(1) exit() if x == 2 or x == 4 or x == 5: print(3) exit() dp = [0]*(1000) dp[1] = 1 dp[2] = 0 dp[3] = 4 for i in range(5,102,2): y1 = 4+2*4*(ceil((i//2)/2)-1) z1 = ceil(i/2) if z1%2 !=0: y1+=4 # print(x1,y1,i) tot = 0 for j in range(i-2,-1,-2): tot+=dp[j] dp[i] = y1 z = y1 + tot if 2<=x<=z: print(i) break ```
7,831
Provide tags and a correct Python 3 solution for this coding contest problem. Consider some square matrix A with side n consisting of zeros and ones. There are n rows numbered from 1 to n from top to bottom and n columns numbered from 1 to n from left to right in this matrix. We'll denote the element of the matrix which is located at the intersection of the i-row and the j-th column as Ai, j. Let's call matrix A clear if no two cells containing ones have a common side. Let's call matrix A symmetrical if it matches the matrices formed from it by a horizontal and/or a vertical reflection. Formally, for each pair (i, j) (1 ≤ i, j ≤ n) both of the following conditions must be met: Ai, j = An - i + 1, j and Ai, j = Ai, n - j + 1. Let's define the sharpness of matrix A as the number of ones in it. Given integer x, your task is to find the smallest positive integer n such that there exists a clear symmetrical matrix A with side n and sharpness x. Input The only line contains a single integer x (1 ≤ x ≤ 100) — the required sharpness of the matrix. Output Print a single number — the sought value of n. Examples Input 4 Output 3 Input 9 Output 5 Note The figure below shows the matrices that correspond to the samples: <image> Tags: constructive algorithms, dp, math Correct Solution: ``` import math x = int(input()) if x == 3: print(5) exit() avaiable = [1] smallest = [1] for i in range(3,16,2): avaiable.append(math.ceil(i/2)**2+math.floor(i/2)**2) smallest.append(i) for j in avaiable: if(j >= x): print(smallest[avaiable.index(j)]) break ```
7,832
Provide tags and a correct Python 3 solution for this coding contest problem. Consider some square matrix A with side n consisting of zeros and ones. There are n rows numbered from 1 to n from top to bottom and n columns numbered from 1 to n from left to right in this matrix. We'll denote the element of the matrix which is located at the intersection of the i-row and the j-th column as Ai, j. Let's call matrix A clear if no two cells containing ones have a common side. Let's call matrix A symmetrical if it matches the matrices formed from it by a horizontal and/or a vertical reflection. Formally, for each pair (i, j) (1 ≤ i, j ≤ n) both of the following conditions must be met: Ai, j = An - i + 1, j and Ai, j = Ai, n - j + 1. Let's define the sharpness of matrix A as the number of ones in it. Given integer x, your task is to find the smallest positive integer n such that there exists a clear symmetrical matrix A with side n and sharpness x. Input The only line contains a single integer x (1 ≤ x ≤ 100) — the required sharpness of the matrix. Output Print a single number — the sought value of n. Examples Input 4 Output 3 Input 9 Output 5 Note The figure below shows the matrices that correspond to the samples: <image> Tags: constructive algorithms, dp, math Correct Solution: ``` pos = [1,5,13,25,41,61,85,113] num = [1,3,5,7,9,11,13,15] while True: try: x = int(input()) if x== 3: print(5) continue i = 0 while pos[i] < x: i+=1 print(num[i]) except: break ```
7,833
Provide tags and a correct Python 3 solution for this coding contest problem. Consider some square matrix A with side n consisting of zeros and ones. There are n rows numbered from 1 to n from top to bottom and n columns numbered from 1 to n from left to right in this matrix. We'll denote the element of the matrix which is located at the intersection of the i-row and the j-th column as Ai, j. Let's call matrix A clear if no two cells containing ones have a common side. Let's call matrix A symmetrical if it matches the matrices formed from it by a horizontal and/or a vertical reflection. Formally, for each pair (i, j) (1 ≤ i, j ≤ n) both of the following conditions must be met: Ai, j = An - i + 1, j and Ai, j = Ai, n - j + 1. Let's define the sharpness of matrix A as the number of ones in it. Given integer x, your task is to find the smallest positive integer n such that there exists a clear symmetrical matrix A with side n and sharpness x. Input The only line contains a single integer x (1 ≤ x ≤ 100) — the required sharpness of the matrix. Output Print a single number — the sought value of n. Examples Input 4 Output 3 Input 9 Output 5 Note The figure below shows the matrices that correspond to the samples: <image> Tags: constructive algorithms, dp, math Correct Solution: ``` x = int(input()) arr = [] for i in range(1, 10000, 2): arr.append((i//2) * (i // 2) + (i //2+ 1) * (i // 2 + 1)) counter = 0 ind = 1 while arr[counter] < x: counter += 1 ind += 2 if (x == 2): print(3) elif (x == 3): print(5) else: print(ind) ```
7,834
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Consider some square matrix A with side n consisting of zeros and ones. There are n rows numbered from 1 to n from top to bottom and n columns numbered from 1 to n from left to right in this matrix. We'll denote the element of the matrix which is located at the intersection of the i-row and the j-th column as Ai, j. Let's call matrix A clear if no two cells containing ones have a common side. Let's call matrix A symmetrical if it matches the matrices formed from it by a horizontal and/or a vertical reflection. Formally, for each pair (i, j) (1 ≤ i, j ≤ n) both of the following conditions must be met: Ai, j = An - i + 1, j and Ai, j = Ai, n - j + 1. Let's define the sharpness of matrix A as the number of ones in it. Given integer x, your task is to find the smallest positive integer n such that there exists a clear symmetrical matrix A with side n and sharpness x. Input The only line contains a single integer x (1 ≤ x ≤ 100) — the required sharpness of the matrix. Output Print a single number — the sought value of n. Examples Input 4 Output 3 Input 9 Output 5 Note The figure below shows the matrices that correspond to the samples: <image> Submitted Solution: ``` #!/usr/bin/python3.5 x = int(input()) if x == 1: print(1) quit() elif x == 2: print(3) quit() elif x == 3: print(5) quit() else: if x % 2 == 0: k = x * 2 else: k = x * 2 - 1 for n in range(1, 16, 2): if n ** 2 >= k: print(n) break ``` Yes
7,835
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Consider some square matrix A with side n consisting of zeros and ones. There are n rows numbered from 1 to n from top to bottom and n columns numbered from 1 to n from left to right in this matrix. We'll denote the element of the matrix which is located at the intersection of the i-row and the j-th column as Ai, j. Let's call matrix A clear if no two cells containing ones have a common side. Let's call matrix A symmetrical if it matches the matrices formed from it by a horizontal and/or a vertical reflection. Formally, for each pair (i, j) (1 ≤ i, j ≤ n) both of the following conditions must be met: Ai, j = An - i + 1, j and Ai, j = Ai, n - j + 1. Let's define the sharpness of matrix A as the number of ones in it. Given integer x, your task is to find the smallest positive integer n such that there exists a clear symmetrical matrix A with side n and sharpness x. Input The only line contains a single integer x (1 ≤ x ≤ 100) — the required sharpness of the matrix. Output Print a single number — the sought value of n. Examples Input 4 Output 3 Input 9 Output 5 Note The figure below shows the matrices that correspond to the samples: <image> Submitted Solution: ``` x = int(input()) if x == 3: print(5) exit(0) for i in range(1, 20, 2): if i * i // 2 + 1 >= x: print(i) exit(0) ``` Yes
7,836
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Consider some square matrix A with side n consisting of zeros and ones. There are n rows numbered from 1 to n from top to bottom and n columns numbered from 1 to n from left to right in this matrix. We'll denote the element of the matrix which is located at the intersection of the i-row and the j-th column as Ai, j. Let's call matrix A clear if no two cells containing ones have a common side. Let's call matrix A symmetrical if it matches the matrices formed from it by a horizontal and/or a vertical reflection. Formally, for each pair (i, j) (1 ≤ i, j ≤ n) both of the following conditions must be met: Ai, j = An - i + 1, j and Ai, j = Ai, n - j + 1. Let's define the sharpness of matrix A as the number of ones in it. Given integer x, your task is to find the smallest positive integer n such that there exists a clear symmetrical matrix A with side n and sharpness x. Input The only line contains a single integer x (1 ≤ x ≤ 100) — the required sharpness of the matrix. Output Print a single number — the sought value of n. Examples Input 4 Output 3 Input 9 Output 5 Note The figure below shows the matrices that correspond to the samples: <image> Submitted Solution: ``` x = int(input()) if x == 1: print(1) elif x == 2: print(3) elif x == 3: print(5) else: if x % 2 == 0: k = x * 2 else: k = x * 2 - 1 for n in range(1, 16, 2): if n ** 2 >= k: print(n) break ``` Yes
7,837
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Consider some square matrix A with side n consisting of zeros and ones. There are n rows numbered from 1 to n from top to bottom and n columns numbered from 1 to n from left to right in this matrix. We'll denote the element of the matrix which is located at the intersection of the i-row and the j-th column as Ai, j. Let's call matrix A clear if no two cells containing ones have a common side. Let's call matrix A symmetrical if it matches the matrices formed from it by a horizontal and/or a vertical reflection. Formally, for each pair (i, j) (1 ≤ i, j ≤ n) both of the following conditions must be met: Ai, j = An - i + 1, j and Ai, j = Ai, n - j + 1. Let's define the sharpness of matrix A as the number of ones in it. Given integer x, your task is to find the smallest positive integer n such that there exists a clear symmetrical matrix A with side n and sharpness x. Input The only line contains a single integer x (1 ≤ x ≤ 100) — the required sharpness of the matrix. Output Print a single number — the sought value of n. Examples Input 4 Output 3 Input 9 Output 5 Note The figure below shows the matrices that correspond to the samples: <image> Submitted Solution: ``` n=int(input()) if n==1:i=1 elif n!=3and n<6:i=3 else: i=5 while i*i//2+1<n:i+=2 print(i) # Made By Mostafa_Khaled ``` Yes
7,838
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Consider some square matrix A with side n consisting of zeros and ones. There are n rows numbered from 1 to n from top to bottom and n columns numbered from 1 to n from left to right in this matrix. We'll denote the element of the matrix which is located at the intersection of the i-row and the j-th column as Ai, j. Let's call matrix A clear if no two cells containing ones have a common side. Let's call matrix A symmetrical if it matches the matrices formed from it by a horizontal and/or a vertical reflection. Formally, for each pair (i, j) (1 ≤ i, j ≤ n) both of the following conditions must be met: Ai, j = An - i + 1, j and Ai, j = Ai, n - j + 1. Let's define the sharpness of matrix A as the number of ones in it. Given integer x, your task is to find the smallest positive integer n such that there exists a clear symmetrical matrix A with side n and sharpness x. Input The only line contains a single integer x (1 ≤ x ≤ 100) — the required sharpness of the matrix. Output Print a single number — the sought value of n. Examples Input 4 Output 3 Input 9 Output 5 Note The figure below shows the matrices that correspond to the samples: <image> Submitted Solution: ``` import sys import math MAXNUM = math.inf MINNUM = -1 * math.inf ASCIILOWER = 97 ASCIIUPPER = 65 def getInt(): return int(sys.stdin.readline().rstrip()) def getInts(): return map(int, sys.stdin.readline().rstrip().split(" ")) def getString(): return sys.stdin.readline().rstrip() def printOutput(ans): sys.stdout.write() pass def solve(num): if num == 1: return 1 for i in range(3, 102, 2): big = ((i + 1) // 2) ** 2 small = (i // 2) ** 2 if big + small > num: return i def readinput(): num = getInt() print(solve(num)) readinput() ``` No
7,839
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Consider some square matrix A with side n consisting of zeros and ones. There are n rows numbered from 1 to n from top to bottom and n columns numbered from 1 to n from left to right in this matrix. We'll denote the element of the matrix which is located at the intersection of the i-row and the j-th column as Ai, j. Let's call matrix A clear if no two cells containing ones have a common side. Let's call matrix A symmetrical if it matches the matrices formed from it by a horizontal and/or a vertical reflection. Formally, for each pair (i, j) (1 ≤ i, j ≤ n) both of the following conditions must be met: Ai, j = An - i + 1, j and Ai, j = Ai, n - j + 1. Let's define the sharpness of matrix A as the number of ones in it. Given integer x, your task is to find the smallest positive integer n such that there exists a clear symmetrical matrix A with side n and sharpness x. Input The only line contains a single integer x (1 ≤ x ≤ 100) — the required sharpness of the matrix. Output Print a single number — the sought value of n. Examples Input 4 Output 3 Input 9 Output 5 Note The figure below shows the matrices that correspond to the samples: <image> Submitted Solution: ``` x = int(input()) arr = [] for i in range(1, 300, 2): arr.append((i//2) * (i // 2) + (i //2+ 1) + (i // 2 + 1)) counter = 0 ind = 1 while arr[counter] < x: counter+=1 ind += 2 if (x == 2): print(3) elif (x == 3): print(5) else: print(ind) ``` No
7,840
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Consider some square matrix A with side n consisting of zeros and ones. There are n rows numbered from 1 to n from top to bottom and n columns numbered from 1 to n from left to right in this matrix. We'll denote the element of the matrix which is located at the intersection of the i-row and the j-th column as Ai, j. Let's call matrix A clear if no two cells containing ones have a common side. Let's call matrix A symmetrical if it matches the matrices formed from it by a horizontal and/or a vertical reflection. Formally, for each pair (i, j) (1 ≤ i, j ≤ n) both of the following conditions must be met: Ai, j = An - i + 1, j and Ai, j = Ai, n - j + 1. Let's define the sharpness of matrix A as the number of ones in it. Given integer x, your task is to find the smallest positive integer n such that there exists a clear symmetrical matrix A with side n and sharpness x. Input The only line contains a single integer x (1 ≤ x ≤ 100) — the required sharpness of the matrix. Output Print a single number — the sought value of n. Examples Input 4 Output 3 Input 9 Output 5 Note The figure below shows the matrices that correspond to the samples: <image> Submitted Solution: ``` # your code goes here def cnt(x): ret = (x+1)//2 ret = ret+ret ret = ret+ret+1 a = 0 sum = 0 for i in range(0, x): sum = sum + (x+a)//2 a = 1-a return ret+4*sum N = int(input()) for i in range(0, 100): #print(cnt(i)) if cnt(i) >= N: print(i+i+1) break ``` No
7,841
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Consider some square matrix A with side n consisting of zeros and ones. There are n rows numbered from 1 to n from top to bottom and n columns numbered from 1 to n from left to right in this matrix. We'll denote the element of the matrix which is located at the intersection of the i-row and the j-th column as Ai, j. Let's call matrix A clear if no two cells containing ones have a common side. Let's call matrix A symmetrical if it matches the matrices formed from it by a horizontal and/or a vertical reflection. Formally, for each pair (i, j) (1 ≤ i, j ≤ n) both of the following conditions must be met: Ai, j = An - i + 1, j and Ai, j = Ai, n - j + 1. Let's define the sharpness of matrix A as the number of ones in it. Given integer x, your task is to find the smallest positive integer n such that there exists a clear symmetrical matrix A with side n and sharpness x. Input The only line contains a single integer x (1 ≤ x ≤ 100) — the required sharpness of the matrix. Output Print a single number — the sought value of n. Examples Input 4 Output 3 Input 9 Output 5 Note The figure below shows the matrices that correspond to the samples: <image> Submitted Solution: ``` def Solve(n): if(n%2==1): return (n//2)*n+(n//2+1) x=(n-2)//2 if(x%2==1): return Solve(x)*4 else: return (x//2)*x*4 L=[0,1,0] for i in range(3,1000): L.append(Solve(i)) x=int(input()) if(x==2): print(5) else: for i in range(1,1000): if(x<=L[i] and i%2==1 and ((i-1)//2)%2==1): print(i) break if(x<=L[i] and i%2==1 and (L[i]-x)!=1): print(i) break if(x<=L[i] and i%2==0 and (L[i]-x)%4==0): print(i) break ``` No
7,842
Provide tags and a correct Python 3 solution for this coding contest problem. Consider the following equation: <image> where sign [a] represents the integer part of number a. Let's find all integer z (z > 0), for which this equation is unsolvable in positive integers. The phrase "unsolvable in positive integers" means that there are no such positive integers x and y (x, y > 0), for which the given above equation holds. Let's write out all such z in the increasing order: z1, z2, z3, and so on (zi < zi + 1). Your task is: given the number n, find the number zn. Input The first line contains a single integer n (1 ≤ n ≤ 40). Output Print a single integer — the number zn modulo 1000000007 (109 + 7). It is guaranteed that the answer exists. Examples Input 1 Output 1 Input 2 Output 3 Input 3 Output 15 Tags: math, number theory Correct Solution: ``` from bisect import bisect_left as bl from bisect import bisect_right as br import heapq import math from collections import * from functools import reduce,cmp_to_key import sys input = sys.stdin.readline # M = mod = 998244353 def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))) # def inv_mod(n):return pow(n, mod - 2, mod) def li():return [int(i) for i in input().rstrip('\n').split()] def st():return input().rstrip('\n') def val():return int(input().rstrip('\n')) def li2():return [i for i in input().rstrip('\n').split(' ')] def li3():return [int(i) for i in input().rstrip('\n')] l = [2,3,5,7,13,17,19,31,61,89,107,127,521,607,1279,2203,2281,3217,4253,4423,9689,9941,11213,19937,21701,23209,44497,86243,110503,132049,216091,756839,859433,1257787,1398269,2976221,3021377,6972593,13466917,20996011,24036583] n = val() curr = l[n-1]-1 print((pow(2,curr)-1)%(10**9 + 7)) ```
7,843
Provide tags and a correct Python 3 solution for this coding contest problem. Consider the following equation: <image> where sign [a] represents the integer part of number a. Let's find all integer z (z > 0), for which this equation is unsolvable in positive integers. The phrase "unsolvable in positive integers" means that there are no such positive integers x and y (x, y > 0), for which the given above equation holds. Let's write out all such z in the increasing order: z1, z2, z3, and so on (zi < zi + 1). Your task is: given the number n, find the number zn. Input The first line contains a single integer n (1 ≤ n ≤ 40). Output Print a single integer — the number zn modulo 1000000007 (109 + 7). It is guaranteed that the answer exists. Examples Input 1 Output 1 Input 2 Output 3 Input 3 Output 15 Tags: math, number theory Correct Solution: ``` # I've proven, that z takes form of 2 ** (k - 1) - 1, # where 2 ** k - 1 is prime, which are called 'Mersenne primes'. p = [2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127,\ 521, 607, 1279, 2203, 2281, 3217, 4253, 4423, 9689,\ 9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503,\ 132049, 216091, 756839, 859433, 1257787, 1398269,\ 2976221, 3021377, 6972593, 13466917, 20996011] n = int(input()) MOD = 10 ** 9 + 7 print((pow(2, p[n - 1] - 1, MOD) - 1) % MOD) ```
7,844
Provide tags and a correct Python 3 solution for this coding contest problem. Consider the following equation: <image> where sign [a] represents the integer part of number a. Let's find all integer z (z > 0), for which this equation is unsolvable in positive integers. The phrase "unsolvable in positive integers" means that there are no such positive integers x and y (x, y > 0), for which the given above equation holds. Let's write out all such z in the increasing order: z1, z2, z3, and so on (zi < zi + 1). Your task is: given the number n, find the number zn. Input The first line contains a single integer n (1 ≤ n ≤ 40). Output Print a single integer — the number zn modulo 1000000007 (109 + 7). It is guaranteed that the answer exists. Examples Input 1 Output 1 Input 2 Output 3 Input 3 Output 15 Tags: math, number theory Correct Solution: ``` print([0,1,3,15,63,4095,65535,262143,73741816,536396503,140130950,487761805,319908070,106681874,373391776,317758023,191994803,416292236,110940209,599412198,383601260,910358878,532737550,348927936,923450985,470083777,642578561,428308066,485739298,419990027,287292016,202484167,389339971,848994100,273206869,853092282,411696552,876153853,90046024,828945523,697988359][int(input())]) ```
7,845
Provide tags and a correct Python 3 solution for this coding contest problem. Consider the following equation: <image> where sign [a] represents the integer part of number a. Let's find all integer z (z > 0), for which this equation is unsolvable in positive integers. The phrase "unsolvable in positive integers" means that there are no such positive integers x and y (x, y > 0), for which the given above equation holds. Let's write out all such z in the increasing order: z1, z2, z3, and so on (zi < zi + 1). Your task is: given the number n, find the number zn. Input The first line contains a single integer n (1 ≤ n ≤ 40). Output Print a single integer — the number zn modulo 1000000007 (109 + 7). It is guaranteed that the answer exists. Examples Input 1 Output 1 Input 2 Output 3 Input 3 Output 15 Tags: math, number theory Correct Solution: ``` n=int(input()) p=[2,3,5,7,13,17,19,31,61,89,107,127,521,607,1279,2203,2281,3217,4253,4423,9689,9941,11213,19937,21701,23209,44497,86243,110503,132049,216091,756839,859433,1257787,1398269,2976221,3021377,6972593,13466917,20996011] res=1 for i in range(p[n-1]-1): res*=2 res%=1000000007 print(res-1) ```
7,846
Provide tags and a correct Python 3 solution for this coding contest problem. Consider the following equation: <image> where sign [a] represents the integer part of number a. Let's find all integer z (z > 0), for which this equation is unsolvable in positive integers. The phrase "unsolvable in positive integers" means that there are no such positive integers x and y (x, y > 0), for which the given above equation holds. Let's write out all such z in the increasing order: z1, z2, z3, and so on (zi < zi + 1). Your task is: given the number n, find the number zn. Input The first line contains a single integer n (1 ≤ n ≤ 40). Output Print a single integer — the number zn modulo 1000000007 (109 + 7). It is guaranteed that the answer exists. Examples Input 1 Output 1 Input 2 Output 3 Input 3 Output 15 Tags: math, number theory Correct Solution: ``` mercenes = [2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203, 2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503, 132049, 216091, 756839, 859433, 1257787, 1398269, 2976221, 3021377, 6972593, 13466917, 20996011, 24036583, 25964951, 30402457, 32582657, 37156667] print((2**(mercenes[int(input())-1]-1)-1)%1000000007) ```
7,847
Provide tags and a correct Python 3 solution for this coding contest problem. Consider the following equation: <image> where sign [a] represents the integer part of number a. Let's find all integer z (z > 0), for which this equation is unsolvable in positive integers. The phrase "unsolvable in positive integers" means that there are no such positive integers x and y (x, y > 0), for which the given above equation holds. Let's write out all such z in the increasing order: z1, z2, z3, and so on (zi < zi + 1). Your task is: given the number n, find the number zn. Input The first line contains a single integer n (1 ≤ n ≤ 40). Output Print a single integer — the number zn modulo 1000000007 (109 + 7). It is guaranteed that the answer exists. Examples Input 1 Output 1 Input 2 Output 3 Input 3 Output 15 Tags: math, number theory Correct Solution: ``` mod = 10**9+7 a = [2,3,5,7,13,17,19,31,61,89,107,127,521,607,1279,2203,2281,3217,4253,4423,9689,9941,11213,19937,21701,23209,44497,86243,110503,132049,216091,756839,859433,1257787,1398269,2976221,3021377,6972593,13466917,20996011] n = int(input()) print(pow(2,a[n-1]-1,mod)-1) ```
7,848
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Consider the following equation: <image> where sign [a] represents the integer part of number a. Let's find all integer z (z > 0), for which this equation is unsolvable in positive integers. The phrase "unsolvable in positive integers" means that there are no such positive integers x and y (x, y > 0), for which the given above equation holds. Let's write out all such z in the increasing order: z1, z2, z3, and so on (zi < zi + 1). Your task is: given the number n, find the number zn. Input The first line contains a single integer n (1 ≤ n ≤ 40). Output Print a single integer — the number zn modulo 1000000007 (109 + 7). It is guaranteed that the answer exists. Examples Input 1 Output 1 Input 2 Output 3 Input 3 Output 15 Submitted Solution: ``` a = [1, 2, 4, 6, 12, 16, 18, 30, 60, 88, 106, 126, 520, 606, 1278, 2202, 2280, 3216, 4252, 4422, 9688, 9940, 11212, 19936, 21700, 23208, 44496, 86242, 110502, 132048, 216090, 756838, 859432, 1257786, 1398268, 2976220, 3021376, 6972592, 13466916, 20996010, 24036582, 25964950, 30402456, 32582656] x = int(input()); print(2**a[x - 1] - 1) ``` No
7,849
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Consider the following equation: <image> where sign [a] represents the integer part of number a. Let's find all integer z (z > 0), for which this equation is unsolvable in positive integers. The phrase "unsolvable in positive integers" means that there are no such positive integers x and y (x, y > 0), for which the given above equation holds. Let's write out all such z in the increasing order: z1, z2, z3, and so on (zi < zi + 1). Your task is: given the number n, find the number zn. Input The first line contains a single integer n (1 ≤ n ≤ 40). Output Print a single integer — the number zn modulo 1000000007 (109 + 7). It is guaranteed that the answer exists. Examples Input 1 Output 1 Input 2 Output 3 Input 3 Output 15 Submitted Solution: ``` n=int(input()) p=[2,3,5,7,13,17,19,31,61,89,107,127,521,607,1279,2203,2281,3217,4253,4423,9689,9941,11213,19937,21701,23209,44497,86243,110503,132049,216091,756839,859433,1257787,1398269,2976221,3021377,13466917,20996011] res=1 for i in range(p[n-1]-1): res*=2 res%=1000000007 print(res-1) ``` No
7,850
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Consider the following equation: <image> where sign [a] represents the integer part of number a. Let's find all integer z (z > 0), for which this equation is unsolvable in positive integers. The phrase "unsolvable in positive integers" means that there are no such positive integers x and y (x, y > 0), for which the given above equation holds. Let's write out all such z in the increasing order: z1, z2, z3, and so on (zi < zi + 1). Your task is: given the number n, find the number zn. Input The first line contains a single integer n (1 ≤ n ≤ 40). Output Print a single integer — the number zn modulo 1000000007 (109 + 7). It is guaranteed that the answer exists. Examples Input 1 Output 1 Input 2 Output 3 Input 3 Output 15 Submitted Solution: ``` n = int(input()) k = 1 ans = 1 for j in range(n): i = j+1 prev_ans = ans%1000000007 k+=2 ans = prev_ans*k print(prev_ans) ``` No
7,851
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Consider the following equation: <image> where sign [a] represents the integer part of number a. Let's find all integer z (z > 0), for which this equation is unsolvable in positive integers. The phrase "unsolvable in positive integers" means that there are no such positive integers x and y (x, y > 0), for which the given above equation holds. Let's write out all such z in the increasing order: z1, z2, z3, and so on (zi < zi + 1). Your task is: given the number n, find the number zn. Input The first line contains a single integer n (1 ≤ n ≤ 40). Output Print a single integer — the number zn modulo 1000000007 (109 + 7). It is guaranteed that the answer exists. Examples Input 1 Output 1 Input 2 Output 3 Input 3 Output 15 Submitted Solution: ``` n=int(input()) p=[2,3,5,7,13,17,19,31,61,89,107,127,521,607,1279,2203,2281,3217,4253,4423,9689,9941,11213,19937,21701,23209,44497,86243,110503,132049,216091,756839,859433,1257787,1398269,2976221,3021377,6972593,13466917,20996011] print(len(p)) res=1 for i in range(p[n-1]-1): res*=2 res%=1000000007 print(res-1) ``` No
7,852
Provide tags and a correct Python 3 solution for this coding contest problem. You are given the following points with integer coordinates on the plane: M0, A0, A1, ..., An - 1, where n is odd number. Now we define the following infinite sequence of points Mi: Mi is symmetric to Mi - 1 according <image> (for every natural number i). Here point B is symmetric to A according M, if M is the center of the line segment AB. Given index j find the point Mj. Input On the first line you will be given an integer n (1 ≤ n ≤ 105), which will be odd, and j (1 ≤ j ≤ 1018), where j is the index of the desired point. The next line contains two space separated integers, the coordinates of M0. After that n lines follow, where the i-th line contain the space separated integer coordinates of the point Ai - 1. The absolute values of all input coordinates will not be greater then 1000. Output On a single line output the coordinates of Mj, space separated. Examples Input 3 4 0 0 1 1 2 3 -5 3 Output 14 0 Input 3 1 5 5 1000 1000 -1000 1000 3 100 Output 1995 1995 Tags: geometry, implementation, math Correct Solution: ``` import sys def read(): tokens = sys.stdin.readline().strip().split() return int(tokens[0]), int(tokens[1]) n,m=read() p,q=read() x=[] y=[] r=1 for i in range(0,n*2): if (i<n): tx,ty=read() x.append(tx) y.append(ty) else: x.append(x[i-n]) y.append(y[i-n]) m%=n*2 for i in range(0,m): p=2*x[i]-p q=2*y[i]-q print (p,q) ''' (x,y) (ax,ay) (ax*2-x,ay*2-y) (x,y,1)(-1 0 0 0 -1 0 ax*2 ay*2 1) ''' ```
7,853
Provide tags and a correct Python 3 solution for this coding contest problem. You are given the following points with integer coordinates on the plane: M0, A0, A1, ..., An - 1, where n is odd number. Now we define the following infinite sequence of points Mi: Mi is symmetric to Mi - 1 according <image> (for every natural number i). Here point B is symmetric to A according M, if M is the center of the line segment AB. Given index j find the point Mj. Input On the first line you will be given an integer n (1 ≤ n ≤ 105), which will be odd, and j (1 ≤ j ≤ 1018), where j is the index of the desired point. The next line contains two space separated integers, the coordinates of M0. After that n lines follow, where the i-th line contain the space separated integer coordinates of the point Ai - 1. The absolute values of all input coordinates will not be greater then 1000. Output On a single line output the coordinates of Mj, space separated. Examples Input 3 4 0 0 1 1 2 3 -5 3 Output 14 0 Input 3 1 5 5 1000 1000 -1000 1000 3 100 Output 1995 1995 Tags: geometry, implementation, math Correct Solution: ``` n, k = map(int, input().split()) ax = [] ay = [] mx, my = map(int, input().split()) for i in range(n): x, y = map(int, input().split()) ax.append(x) ay.append(y) k %= 2*n for i in range(k): mx = 2*ax[i % n] - mx my = 2*ay[i % n] - my print(mx, " ", my) ```
7,854
Provide tags and a correct Python 3 solution for this coding contest problem. You are given the following points with integer coordinates on the plane: M0, A0, A1, ..., An - 1, where n is odd number. Now we define the following infinite sequence of points Mi: Mi is symmetric to Mi - 1 according <image> (for every natural number i). Here point B is symmetric to A according M, if M is the center of the line segment AB. Given index j find the point Mj. Input On the first line you will be given an integer n (1 ≤ n ≤ 105), which will be odd, and j (1 ≤ j ≤ 1018), where j is the index of the desired point. The next line contains two space separated integers, the coordinates of M0. After that n lines follow, where the i-th line contain the space separated integer coordinates of the point Ai - 1. The absolute values of all input coordinates will not be greater then 1000. Output On a single line output the coordinates of Mj, space separated. Examples Input 3 4 0 0 1 1 2 3 -5 3 Output 14 0 Input 3 1 5 5 1000 1000 -1000 1000 3 100 Output 1995 1995 Tags: geometry, implementation, math Correct Solution: ``` n, j = map(int, input().split()) x, y = map(int, input().split()) dx, dy = n * [ None ], n * [ None ] for i in range(n): dx[i], dy[i] = map(lambda s: 2 * int(s), input().split()) j %= 2 * n pos = 0 if j % 2 == 0: sign = -1 else: sign = 1 x, y = -x, -y for i in range(j): x += sign * dx[pos] y += sign * dy[pos] sign = -sign pos += 1 if pos == n: pos = 0 print(x, y) # Made By Mostafa_Khaled ```
7,855
Provide tags and a correct Python 3 solution for this coding contest problem. You are given the following points with integer coordinates on the plane: M0, A0, A1, ..., An - 1, where n is odd number. Now we define the following infinite sequence of points Mi: Mi is symmetric to Mi - 1 according <image> (for every natural number i). Here point B is symmetric to A according M, if M is the center of the line segment AB. Given index j find the point Mj. Input On the first line you will be given an integer n (1 ≤ n ≤ 105), which will be odd, and j (1 ≤ j ≤ 1018), where j is the index of the desired point. The next line contains two space separated integers, the coordinates of M0. After that n lines follow, where the i-th line contain the space separated integer coordinates of the point Ai - 1. The absolute values of all input coordinates will not be greater then 1000. Output On a single line output the coordinates of Mj, space separated. Examples Input 3 4 0 0 1 1 2 3 -5 3 Output 14 0 Input 3 1 5 5 1000 1000 -1000 1000 3 100 Output 1995 1995 Tags: geometry, implementation, math Correct Solution: ``` import sys def read(): tokens = sys.stdin.readline().strip().split() return int(tokens[0]), int(tokens[1]) n, j = read() m0_x, m0_y = read() ax, ay = [], [] for i in range(n): ax_, ay_ = read() ax.append(ax_) ay.append(ay_) mult = j // n j = (j % n) if mult % 2 == 0 else (n + (j % n)) px, py = -m0_x, -m0_y for i in range(j): if i % 2 == 0: px += ax[i % n] * 2 py += ay[i % n] * 2 else: px -= ax[i % n] * 2 py -= ay[i % n] * 2 if j % 2 == 0: px, py = -px, -py print(px, py) ```
7,856
Provide tags and a correct Python 3 solution for this coding contest problem. You are given the following points with integer coordinates on the plane: M0, A0, A1, ..., An - 1, where n is odd number. Now we define the following infinite sequence of points Mi: Mi is symmetric to Mi - 1 according <image> (for every natural number i). Here point B is symmetric to A according M, if M is the center of the line segment AB. Given index j find the point Mj. Input On the first line you will be given an integer n (1 ≤ n ≤ 105), which will be odd, and j (1 ≤ j ≤ 1018), where j is the index of the desired point. The next line contains two space separated integers, the coordinates of M0. After that n lines follow, where the i-th line contain the space separated integer coordinates of the point Ai - 1. The absolute values of all input coordinates will not be greater then 1000. Output On a single line output the coordinates of Mj, space separated. Examples Input 3 4 0 0 1 1 2 3 -5 3 Output 14 0 Input 3 1 5 5 1000 1000 -1000 1000 3 100 Output 1995 1995 Tags: geometry, implementation, math Correct Solution: ``` #codeforces 24c sequence of points, math """import sys sys.stdin=open("24c.in",mode='r',encoding='utf-8') """ def readGen(transform): while (True): n=0 tmp=input().split() m=len(tmp) while (n<m): yield(transform(tmp[n])) n+=1 readint=readGen(int) n,j=next(readint),next(readint) j%=2*n x0,y0=next(readint),next(readint) a=tuple((next(readint),next(readint)) for i in range(n)) #a=[[next(readint),next(readint)] for i in range(n)] for i in range(1,j+1): x0=2*a[(i-1)%n][0]-x0 y0=2*a[(i-1)%n][1]-y0 print(x0,y0) #sys.stdin.close() ```
7,857
Provide tags and a correct Python 3 solution for this coding contest problem. You are given the following points with integer coordinates on the plane: M0, A0, A1, ..., An - 1, where n is odd number. Now we define the following infinite sequence of points Mi: Mi is symmetric to Mi - 1 according <image> (for every natural number i). Here point B is symmetric to A according M, if M is the center of the line segment AB. Given index j find the point Mj. Input On the first line you will be given an integer n (1 ≤ n ≤ 105), which will be odd, and j (1 ≤ j ≤ 1018), where j is the index of the desired point. The next line contains two space separated integers, the coordinates of M0. After that n lines follow, where the i-th line contain the space separated integer coordinates of the point Ai - 1. The absolute values of all input coordinates will not be greater then 1000. Output On a single line output the coordinates of Mj, space separated. Examples Input 3 4 0 0 1 1 2 3 -5 3 Output 14 0 Input 3 1 5 5 1000 1000 -1000 1000 3 100 Output 1995 1995 Tags: geometry, implementation, math Correct Solution: ``` n, j = map(int, input().split()) m = list(map(int, input().split())) points = [] for _ in range(n): points += [tuple(map(int, input().split()))] trans = [0, 0] points = points + points for i in range(0, len(points), 2): trans[0] += - 2 * points[i][0] + 2 * points[i + 1][0] trans[1] += - 2 * points[i][1] + 2 * points[i + 1][1] m = [m[0] + trans[0] * (j // (2 * n)), m[1] + trans[1] * (j // (2 * n))] j %= (2 * n) for i in range(j): m = [2 * points[i][0] - m[0], 2 * points[i][1] - m[1]] print(m[0], m[1]) ```
7,858
Provide tags and a correct Python 3 solution for this coding contest problem. You are given the following points with integer coordinates on the plane: M0, A0, A1, ..., An - 1, where n is odd number. Now we define the following infinite sequence of points Mi: Mi is symmetric to Mi - 1 according <image> (for every natural number i). Here point B is symmetric to A according M, if M is the center of the line segment AB. Given index j find the point Mj. Input On the first line you will be given an integer n (1 ≤ n ≤ 105), which will be odd, and j (1 ≤ j ≤ 1018), where j is the index of the desired point. The next line contains two space separated integers, the coordinates of M0. After that n lines follow, where the i-th line contain the space separated integer coordinates of the point Ai - 1. The absolute values of all input coordinates will not be greater then 1000. Output On a single line output the coordinates of Mj, space separated. Examples Input 3 4 0 0 1 1 2 3 -5 3 Output 14 0 Input 3 1 5 5 1000 1000 -1000 1000 3 100 Output 1995 1995 Tags: geometry, implementation, math Correct Solution: ``` # ========= /\ /| |====/| # | / \ | | / | # | /____\ | | / | # | / \ | | / | # ========= / \ ===== |/====| # code # MOD = 998244353 # def pow(base , exp): # if exp == -1: # return pow(base , MOD - 2) # res = 1 # base %= MOD # while exp > 0: # if exp % 2: # res = (res * base) % MOD # exp //= 2 # base = (base * base) % MOD # res %= MOD # return res def main(): n , j = map(int , input().split()) j = j % (2 * n) mx , my = map(int , input().split()) pntx = [] pnty = [] for i in range(n): a,b = map(int , input().split()) pntx.append(a) pnty.append(b) for i in range(j): k = i % n mx = 2 * pntx[k] - mx my = 2 * pnty[k] - my print(mx , my) return if __name__ == "__main__": main() ```
7,859
Provide tags and a correct Python 3 solution for this coding contest problem. You are given the following points with integer coordinates on the plane: M0, A0, A1, ..., An - 1, where n is odd number. Now we define the following infinite sequence of points Mi: Mi is symmetric to Mi - 1 according <image> (for every natural number i). Here point B is symmetric to A according M, if M is the center of the line segment AB. Given index j find the point Mj. Input On the first line you will be given an integer n (1 ≤ n ≤ 105), which will be odd, and j (1 ≤ j ≤ 1018), where j is the index of the desired point. The next line contains two space separated integers, the coordinates of M0. After that n lines follow, where the i-th line contain the space separated integer coordinates of the point Ai - 1. The absolute values of all input coordinates will not be greater then 1000. Output On a single line output the coordinates of Mj, space separated. Examples Input 3 4 0 0 1 1 2 3 -5 3 Output 14 0 Input 3 1 5 5 1000 1000 -1000 1000 3 100 Output 1995 1995 Tags: geometry, implementation, math Correct Solution: ``` n, j = map(int, input().split()) x, y = map(int, input().split()) dx, dy = n * [ None ], n * [ None ] for i in range(n): dx[i], dy[i] = map(lambda s: 2 * int(s), input().split()) j %= 2 * n pos = 0 if j % 2 == 0: sign = -1 else: sign = 1 x, y = -x, -y for i in range(j): x += sign * dx[pos] y += sign * dy[pos] sign = -sign pos += 1 if pos == n: pos = 0 print(x, y) ```
7,860
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given the following points with integer coordinates on the plane: M0, A0, A1, ..., An - 1, where n is odd number. Now we define the following infinite sequence of points Mi: Mi is symmetric to Mi - 1 according <image> (for every natural number i). Here point B is symmetric to A according M, if M is the center of the line segment AB. Given index j find the point Mj. Input On the first line you will be given an integer n (1 ≤ n ≤ 105), which will be odd, and j (1 ≤ j ≤ 1018), where j is the index of the desired point. The next line contains two space separated integers, the coordinates of M0. After that n lines follow, where the i-th line contain the space separated integer coordinates of the point Ai - 1. The absolute values of all input coordinates will not be greater then 1000. Output On a single line output the coordinates of Mj, space separated. Examples Input 3 4 0 0 1 1 2 3 -5 3 Output 14 0 Input 3 1 5 5 1000 1000 -1000 1000 3 100 Output 1995 1995 Submitted Solution: ``` def read(): return map(int, input().split()) n, j = read() mx, my = read() cycles = j // n rest = j - cycles * n tx = ty = 0 rx = ry = 0 for i in range(n): cx, cy = read() tx = 2 * cx - tx ty = 2 * cy - ty if i < rest: rx = 2 * cx - rx ry = 2 * cy - ry resx = resy = 0 if n % 2 == 0: resx = tx * cycles + mx resy = ty * cycles + my else: if cycles % 2 == 0: resx, resy = mx, my else: resx = tx - mx resy = ty - my if rest % 2 == 0: resx += rx resy += ry else: resx = rx - resx resy = ry - resy print (resx, resy) ``` Yes
7,861
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given the following points with integer coordinates on the plane: M0, A0, A1, ..., An - 1, where n is odd number. Now we define the following infinite sequence of points Mi: Mi is symmetric to Mi - 1 according <image> (for every natural number i). Here point B is symmetric to A according M, if M is the center of the line segment AB. Given index j find the point Mj. Input On the first line you will be given an integer n (1 ≤ n ≤ 105), which will be odd, and j (1 ≤ j ≤ 1018), where j is the index of the desired point. The next line contains two space separated integers, the coordinates of M0. After that n lines follow, where the i-th line contain the space separated integer coordinates of the point Ai - 1. The absolute values of all input coordinates will not be greater then 1000. Output On a single line output the coordinates of Mj, space separated. Examples Input 3 4 0 0 1 1 2 3 -5 3 Output 14 0 Input 3 1 5 5 1000 1000 -1000 1000 3 100 Output 1995 1995 Submitted Solution: ``` def mul(a,b): c=[[0,0,0],[0,0,0],[0,0,0]] for i in range(0,3): for j in range(0,3): c[i][j]=0 for k in range(0,3): c[i][j]+=a[i][k]*b[k][j] return c str=input().split() n=int(str[0]) m=int(str[1]) str=input().split() p=int(str[0]) q=int(str[1]) r=1 matrix=[] square=[[-1,0,0],[0,-1,0],[0,0,1]] one=[[1,0,0],[0,1,0],[0,0,1]] all=one for i in range(0,n): str=input().split() now=square now[2][0]=int(str[0])*2 now[2][1]=int(str[1])*2 #print(now[2][0],now[2][1]) matrix.append((tuple(now[0]),tuple(now[1]),tuple(now[2]))) '''print (matrix[i]) if i: for u in range(0,3): print (matrix[i-1][u][0],matrix[i-1][u][1],matrix[i-1][u][2]) print ('???')''' all=mul(all,now) tmp=m//n ans=one while tmp>0: if tmp and 1: ans=mul(ans,all) all=mul(all,all) tmp=tmp//2 now=ans p,q,r=p*now[0][0]+q*now[1][0]+r*now[2][0],q*now[1][1]+r*now[2][1],r #print (p,q) tmp=m%n '''for i in range(0,n): now=matrix[i] for u in range(0,3): print (now[u][0],now[u][1],now[u][2]) print ('!!!')''' for i in range(0,tmp): #print (i) now=matrix[i] '''for u in range(0,3): for v in range(0,3): print(now[u][v])''' p,q,r=p*now[0][0]+q*now[1][0]+r*now[2][0],p*now[0][1]+q*now[1][1]+r*now[2][1],p*now[0][2]+q*now[1][2]+r*now[2][2] print (p,q) ''' (x,y) (ax,ay) (ax*2-x,ay*2-y) (x,y,1)(-1 0 0 0 -1 0 ax*2 ay*2 1) ''' ``` No
7,862
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Lenny had an n × m matrix of positive integers. He loved the matrix so much, because each row of the matrix was sorted in non-decreasing order. For the same reason he calls such matrices of integers lovely. One day when Lenny was at school his little brother was playing with Lenny's matrix in his room. He erased some of the entries of the matrix and changed the order of some of its columns. When Lenny got back home he was very upset. Now Lenny wants to recover his matrix. Help him to find an order for the columns of the matrix so that it's possible to fill in the erased entries of the matrix to achieve a lovely matrix again. Note, that you can fill the erased entries of the matrix with any integers. Input The first line of the input contains two positive integers n and m (1 ≤ n·m ≤ 105). Each of the next n lines contains m space-separated integers representing the matrix. An integer -1 shows an erased entry of the matrix. All other integers (each of them is between 0 and 109 inclusive) represent filled entries. Output If there exists no possible reordering of the columns print -1. Otherwise the output should contain m integers p1, p2, ..., pm showing the sought permutation of columns. So, the first column of the lovely matrix will be p1-th column of the initial matrix, the second column of the lovely matrix will be p2-th column of the initial matrix and so on. Examples Input 3 3 1 -1 -1 1 2 1 2 -1 1 Output 3 1 2 Input 2 3 1 2 2 2 5 4 Output 1 3 2 Input 2 3 1 2 3 3 2 1 Output -1 Submitted Solution: ``` n, m = map(int, input().split()) b = [map(int, input().split()) for _ in range(n)] c = [n - x.count(-1) for x in zip(*b)] d = [] for r in b: t = {} for i, x in enumerate(r): if x != -1: if x not in t: t[x] = set() t[x].add(i) d.append([x for i, x in sorted(t.items())][:: -1]) p = [i for i, x in enumerate(c) if not x] for v in d: if v: for x in v[-1]: c[x] -= 1 if not c[x]: p.append(x) r = [] while p: x = p.pop() r.append(x + 1) for i, v in enumerate(d): if v: v[-1].discard(x) if not v[-1]: d[i].pop() if d[i]: for y in d[i][-1]: c[y] -= 1 if not c[y]: p.append(y) print(-1 if len(r) == m else ' '.join(map(str, r))) ``` No
7,863
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Lenny had an n × m matrix of positive integers. He loved the matrix so much, because each row of the matrix was sorted in non-decreasing order. For the same reason he calls such matrices of integers lovely. One day when Lenny was at school his little brother was playing with Lenny's matrix in his room. He erased some of the entries of the matrix and changed the order of some of its columns. When Lenny got back home he was very upset. Now Lenny wants to recover his matrix. Help him to find an order for the columns of the matrix so that it's possible to fill in the erased entries of the matrix to achieve a lovely matrix again. Note, that you can fill the erased entries of the matrix with any integers. Input The first line of the input contains two positive integers n and m (1 ≤ n·m ≤ 105). Each of the next n lines contains m space-separated integers representing the matrix. An integer -1 shows an erased entry of the matrix. All other integers (each of them is between 0 and 109 inclusive) represent filled entries. Output If there exists no possible reordering of the columns print -1. Otherwise the output should contain m integers p1, p2, ..., pm showing the sought permutation of columns. So, the first column of the lovely matrix will be p1-th column of the initial matrix, the second column of the lovely matrix will be p2-th column of the initial matrix and so on. Examples Input 3 3 1 -1 -1 1 2 1 2 -1 1 Output 3 1 2 Input 2 3 1 2 2 2 5 4 Output 1 3 2 Input 2 3 1 2 3 3 2 1 Output -1 Submitted Solution: ``` n, m = map(int, input().split()) b = [map(int, input().split()) for _ in range(n)] c = [n - x.count(-1) for x in zip(*b)] d = [] for r in b: t = {} for i, x in enumerate(r): if x != -1: if x not in t: t[x] = set() t[x].add(i) d.append([x for i, x in sorted(t.items())][:: -1]) p = [i for i, x in enumerate(c) if not x] for v in d: if v: for x in v[-1]: c[x] -= 1 if not c[x]: p.append(x) r = [] while p: x = p.pop() r.append(x + 1) for i, v in enumerate(d): if v: v[-1].discard(x) if not v[-1]: d[i].pop() if d[i]: for y in d[i][-1]: c[y] -= 1 if not c[y]: p.append(y) print([-1, ' '.join(map(str, r))][len(r) == m]) ``` No
7,864
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Lenny had an n × m matrix of positive integers. He loved the matrix so much, because each row of the matrix was sorted in non-decreasing order. For the same reason he calls such matrices of integers lovely. One day when Lenny was at school his little brother was playing with Lenny's matrix in his room. He erased some of the entries of the matrix and changed the order of some of its columns. When Lenny got back home he was very upset. Now Lenny wants to recover his matrix. Help him to find an order for the columns of the matrix so that it's possible to fill in the erased entries of the matrix to achieve a lovely matrix again. Note, that you can fill the erased entries of the matrix with any integers. Input The first line of the input contains two positive integers n and m (1 ≤ n·m ≤ 105). Each of the next n lines contains m space-separated integers representing the matrix. An integer -1 shows an erased entry of the matrix. All other integers (each of them is between 0 and 109 inclusive) represent filled entries. Output If there exists no possible reordering of the columns print -1. Otherwise the output should contain m integers p1, p2, ..., pm showing the sought permutation of columns. So, the first column of the lovely matrix will be p1-th column of the initial matrix, the second column of the lovely matrix will be p2-th column of the initial matrix and so on. Examples Input 3 3 1 -1 -1 1 2 1 2 -1 1 Output 3 1 2 Input 2 3 1 2 2 2 5 4 Output 1 3 2 Input 2 3 1 2 3 3 2 1 Output -1 Submitted Solution: ``` print("I AK IOI") ``` No
7,865
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Lenny had an n × m matrix of positive integers. He loved the matrix so much, because each row of the matrix was sorted in non-decreasing order. For the same reason he calls such matrices of integers lovely. One day when Lenny was at school his little brother was playing with Lenny's matrix in his room. He erased some of the entries of the matrix and changed the order of some of its columns. When Lenny got back home he was very upset. Now Lenny wants to recover his matrix. Help him to find an order for the columns of the matrix so that it's possible to fill in the erased entries of the matrix to achieve a lovely matrix again. Note, that you can fill the erased entries of the matrix with any integers. Input The first line of the input contains two positive integers n and m (1 ≤ n·m ≤ 105). Each of the next n lines contains m space-separated integers representing the matrix. An integer -1 shows an erased entry of the matrix. All other integers (each of them is between 0 and 109 inclusive) represent filled entries. Output If there exists no possible reordering of the columns print -1. Otherwise the output should contain m integers p1, p2, ..., pm showing the sought permutation of columns. So, the first column of the lovely matrix will be p1-th column of the initial matrix, the second column of the lovely matrix will be p2-th column of the initial matrix and so on. Examples Input 3 3 1 -1 -1 1 2 1 2 -1 1 Output 3 1 2 Input 2 3 1 2 2 2 5 4 Output 1 3 2 Input 2 3 1 2 3 3 2 1 Output -1 Submitted Solution: ``` n, m = map(int, input().split()) b = [] c = [] for _ in range(n): a = [map(int, input().split())] b += a c.append(n-a.count(-1)) c = [n - x.count(-1) for x in zip(*b)] d = [] for r in b: t = {} for i, x in enumerate(r): if x != -1: if x not in t: t[x] = set() t[x].add(i) d.append([x for i, x in sorted(t.items())][:: -1]) p = [i for i, x in enumerate(c) if not x] for v in d: if v: for x in v[-1]: c[x] -= 1 if not c[x]: p.append(x) r = [] while p: x = p.pop() r.append(x + 1) for i, v in enumerate(d): if v: v[-1].discard(x) if not v[-1]: d[i].pop() if d[i]: for y in d[i][-1]: c[y] -= 1 if not c[y]: p.append(y) if len(r) == m: print(-1) else: print(' '.join(map(str, r))) ``` No
7,866
Provide tags and a correct Python 3 solution for this coding contest problem. There is a straight snowy road, divided into n blocks. The blocks are numbered from 1 to n from left to right. If one moves from the i-th block to the (i + 1)-th block, he will leave a right footprint on the i-th block. Similarly, if one moves from the i-th block to the (i - 1)-th block, he will leave a left footprint on the i-th block. If there already is a footprint on the i-th block, the new footprint will cover the old one. <image> At the beginning, there were no footprints. Then polar bear Alice starts from the s-th block, makes a sequence of moves and ends in the t-th block. It is known that Alice never moves outside of the road. You are given the description of Alice's footprints. Your task is to find a pair of possible values of s, t by looking at the footprints. Input The first line of the input contains integer n (3 ≤ n ≤ 1000). The second line contains the description of the road — the string that consists of n characters. Each character will be either "." (a block without footprint), or "L" (a block with a left footprint), "R" (a block with a right footprint). It's guaranteed that the given string contains at least one character not equal to ".". Also, the first and the last character will always be ".". It's guaranteed that a solution exists. Output Print two space-separated integers — the values of s and t. If there are several possible solutions you can print any of them. Examples Input 9 ..RRLL... Output 3 4 Input 11 .RRRLLLLL.. Output 7 5 Note The first test sample is the one in the picture. Tags: greedy, implementation Correct Solution: ``` n=int(input()) s=input() se=set(s) if "L" not in s:print(s.index("R")+1,n+1-s[::-1].index("R")) elif "R" not in s:print(n-s[::-1].index("L"),s.index("L")) else: print(s.index("R")+1,s.index("L")) ```
7,867
Provide tags and a correct Python 3 solution for this coding contest problem. There is a straight snowy road, divided into n blocks. The blocks are numbered from 1 to n from left to right. If one moves from the i-th block to the (i + 1)-th block, he will leave a right footprint on the i-th block. Similarly, if one moves from the i-th block to the (i - 1)-th block, he will leave a left footprint on the i-th block. If there already is a footprint on the i-th block, the new footprint will cover the old one. <image> At the beginning, there were no footprints. Then polar bear Alice starts from the s-th block, makes a sequence of moves and ends in the t-th block. It is known that Alice never moves outside of the road. You are given the description of Alice's footprints. Your task is to find a pair of possible values of s, t by looking at the footprints. Input The first line of the input contains integer n (3 ≤ n ≤ 1000). The second line contains the description of the road — the string that consists of n characters. Each character will be either "." (a block without footprint), or "L" (a block with a left footprint), "R" (a block with a right footprint). It's guaranteed that the given string contains at least one character not equal to ".". Also, the first and the last character will always be ".". It's guaranteed that a solution exists. Output Print two space-separated integers — the values of s and t. If there are several possible solutions you can print any of them. Examples Input 9 ..RRLL... Output 3 4 Input 11 .RRRLLLLL.. Output 7 5 Note The first test sample is the one in the picture. Tags: greedy, implementation Correct Solution: ``` n = int(input()) footprints = input() firstR = n+1 lastR = 0 firstL = n+1 lastL=0 for i in range(n): if(footprints[i]=='.'): continue if(footprints[i]=='R'): firstR = min(firstR,i+1) lastR = max(lastR,i+1) else: firstL = min(firstL,i+1) lastL=max(lastL,i+1) if(firstR!=n+1): s = firstR else : s = lastL print(s,end=" ") if(firstL!=n+1): t = firstL-1 else : t = lastR+1; print(t) ```
7,868
Provide tags and a correct Python 3 solution for this coding contest problem. There is a straight snowy road, divided into n blocks. The blocks are numbered from 1 to n from left to right. If one moves from the i-th block to the (i + 1)-th block, he will leave a right footprint on the i-th block. Similarly, if one moves from the i-th block to the (i - 1)-th block, he will leave a left footprint on the i-th block. If there already is a footprint on the i-th block, the new footprint will cover the old one. <image> At the beginning, there were no footprints. Then polar bear Alice starts from the s-th block, makes a sequence of moves and ends in the t-th block. It is known that Alice never moves outside of the road. You are given the description of Alice's footprints. Your task is to find a pair of possible values of s, t by looking at the footprints. Input The first line of the input contains integer n (3 ≤ n ≤ 1000). The second line contains the description of the road — the string that consists of n characters. Each character will be either "." (a block without footprint), or "L" (a block with a left footprint), "R" (a block with a right footprint). It's guaranteed that the given string contains at least one character not equal to ".". Also, the first and the last character will always be ".". It's guaranteed that a solution exists. Output Print two space-separated integers — the values of s and t. If there are several possible solutions you can print any of them. Examples Input 9 ..RRLL... Output 3 4 Input 11 .RRRLLLLL.. Output 7 5 Note The first test sample is the one in the picture. Tags: greedy, implementation Correct Solution: ``` n = int(input()) s = str(input()) a, b = 0, 0 if 'R' in s and 'L' in s: a = s.find('R') b = s.rfind('R') elif 'R' in s: a = s.find('R') b = s.rfind('R') + 1 else: a = s.rfind('L') b = s.find('L')-1 print(a+1, b+1) ```
7,869
Provide tags and a correct Python 3 solution for this coding contest problem. There is a straight snowy road, divided into n blocks. The blocks are numbered from 1 to n from left to right. If one moves from the i-th block to the (i + 1)-th block, he will leave a right footprint on the i-th block. Similarly, if one moves from the i-th block to the (i - 1)-th block, he will leave a left footprint on the i-th block. If there already is a footprint on the i-th block, the new footprint will cover the old one. <image> At the beginning, there were no footprints. Then polar bear Alice starts from the s-th block, makes a sequence of moves and ends in the t-th block. It is known that Alice never moves outside of the road. You are given the description of Alice's footprints. Your task is to find a pair of possible values of s, t by looking at the footprints. Input The first line of the input contains integer n (3 ≤ n ≤ 1000). The second line contains the description of the road — the string that consists of n characters. Each character will be either "." (a block without footprint), or "L" (a block with a left footprint), "R" (a block with a right footprint). It's guaranteed that the given string contains at least one character not equal to ".". Also, the first and the last character will always be ".". It's guaranteed that a solution exists. Output Print two space-separated integers — the values of s and t. If there are several possible solutions you can print any of them. Examples Input 9 ..RRLL... Output 3 4 Input 11 .RRRLLLLL.. Output 7 5 Note The first test sample is the one in the picture. Tags: greedy, implementation Correct Solution: ``` from sys import stdin def footprints(steps): if steps.count('R') == 0: return len(steps) - steps[-1::-1].find('L'), steps.find('L') elif steps.count('L') == 0: return steps.find('R') + 1, len(steps) - steps[-1::-1].find('R') + 1 else: return steps.find('R') + 1, steps.find('L') if __name__ == '__main__': n = int(stdin.readline()) steps = stdin.readline().rstrip() print(" ".join(map(str, footprints(steps)))) ```
7,870
Provide tags and a correct Python 3 solution for this coding contest problem. There is a straight snowy road, divided into n blocks. The blocks are numbered from 1 to n from left to right. If one moves from the i-th block to the (i + 1)-th block, he will leave a right footprint on the i-th block. Similarly, if one moves from the i-th block to the (i - 1)-th block, he will leave a left footprint on the i-th block. If there already is a footprint on the i-th block, the new footprint will cover the old one. <image> At the beginning, there were no footprints. Then polar bear Alice starts from the s-th block, makes a sequence of moves and ends in the t-th block. It is known that Alice never moves outside of the road. You are given the description of Alice's footprints. Your task is to find a pair of possible values of s, t by looking at the footprints. Input The first line of the input contains integer n (3 ≤ n ≤ 1000). The second line contains the description of the road — the string that consists of n characters. Each character will be either "." (a block without footprint), or "L" (a block with a left footprint), "R" (a block with a right footprint). It's guaranteed that the given string contains at least one character not equal to ".". Also, the first and the last character will always be ".". It's guaranteed that a solution exists. Output Print two space-separated integers — the values of s and t. If there are several possible solutions you can print any of them. Examples Input 9 ..RRLL... Output 3 4 Input 11 .RRRLLLLL.. Output 7 5 Note The first test sample is the one in the picture. Tags: greedy, implementation Correct Solution: ``` arg = int(input()) s2=input() start = -1 ending = -1 flag9 = 0 if "R" in s2: for n in range(0, arg): if s2[n]=="R" and flag9 == 0: start = n + 1 flag9 = 1 if s2[n]== "R" and s2[n+1] == "L": ending = n + 1 elif s2[n] == "R": ending = n + 2 else: for n in range(0, arg): if s2[n]=="L" and flag9 == 0: ending = n flag9 = 1 if s2[n]== "L" and s2[n+1]==".": start = n + 1 print(start, ending) ```
7,871
Provide tags and a correct Python 3 solution for this coding contest problem. There is a straight snowy road, divided into n blocks. The blocks are numbered from 1 to n from left to right. If one moves from the i-th block to the (i + 1)-th block, he will leave a right footprint on the i-th block. Similarly, if one moves from the i-th block to the (i - 1)-th block, he will leave a left footprint on the i-th block. If there already is a footprint on the i-th block, the new footprint will cover the old one. <image> At the beginning, there were no footprints. Then polar bear Alice starts from the s-th block, makes a sequence of moves and ends in the t-th block. It is known that Alice never moves outside of the road. You are given the description of Alice's footprints. Your task is to find a pair of possible values of s, t by looking at the footprints. Input The first line of the input contains integer n (3 ≤ n ≤ 1000). The second line contains the description of the road — the string that consists of n characters. Each character will be either "." (a block without footprint), or "L" (a block with a left footprint), "R" (a block with a right footprint). It's guaranteed that the given string contains at least one character not equal to ".". Also, the first and the last character will always be ".". It's guaranteed that a solution exists. Output Print two space-separated integers — the values of s and t. If there are several possible solutions you can print any of them. Examples Input 9 ..RRLL... Output 3 4 Input 11 .RRRLLLLL.. Output 7 5 Note The first test sample is the one in the picture. Tags: greedy, implementation Correct Solution: ``` n=int(input()) x=input() a=list(set(x)) if 'R' in a and 'L' not in a: s=x.index('R') t=x.rindex('R')+1 elif 'L' in a and 'R' not in a: s=x.rindex('L') t=x.index('L')-1 else: s=x.index('R') t=x.rindex('R') print(s+1,t+1) ```
7,872
Provide tags and a correct Python 3 solution for this coding contest problem. There is a straight snowy road, divided into n blocks. The blocks are numbered from 1 to n from left to right. If one moves from the i-th block to the (i + 1)-th block, he will leave a right footprint on the i-th block. Similarly, if one moves from the i-th block to the (i - 1)-th block, he will leave a left footprint on the i-th block. If there already is a footprint on the i-th block, the new footprint will cover the old one. <image> At the beginning, there were no footprints. Then polar bear Alice starts from the s-th block, makes a sequence of moves and ends in the t-th block. It is known that Alice never moves outside of the road. You are given the description of Alice's footprints. Your task is to find a pair of possible values of s, t by looking at the footprints. Input The first line of the input contains integer n (3 ≤ n ≤ 1000). The second line contains the description of the road — the string that consists of n characters. Each character will be either "." (a block without footprint), or "L" (a block with a left footprint), "R" (a block with a right footprint). It's guaranteed that the given string contains at least one character not equal to ".". Also, the first and the last character will always be ".". It's guaranteed that a solution exists. Output Print two space-separated integers — the values of s and t. If there are several possible solutions you can print any of them. Examples Input 9 ..RRLL... Output 3 4 Input 11 .RRRLLLLL.. Output 7 5 Note The first test sample is the one in the picture. Tags: greedy, implementation Correct Solution: ``` n = int(input()) ft = input() r = ft.count('R') l = ft.count('L') if r==0: t = ft.index('L') for i in range(t,n-1): if ft[i+1]=='.': s=i+1 break print(s,t) elif l==0: s = ft.index('R') for i in range(s,n-1): if ft[i+1]=='.': t=i+1 break print(s+1,t+1) else: r = ft.index('R') l = ft.index('L') print(r+1,l) ```
7,873
Provide tags and a correct Python 3 solution for this coding contest problem. There is a straight snowy road, divided into n blocks. The blocks are numbered from 1 to n from left to right. If one moves from the i-th block to the (i + 1)-th block, he will leave a right footprint on the i-th block. Similarly, if one moves from the i-th block to the (i - 1)-th block, he will leave a left footprint on the i-th block. If there already is a footprint on the i-th block, the new footprint will cover the old one. <image> At the beginning, there were no footprints. Then polar bear Alice starts from the s-th block, makes a sequence of moves and ends in the t-th block. It is known that Alice never moves outside of the road. You are given the description of Alice's footprints. Your task is to find a pair of possible values of s, t by looking at the footprints. Input The first line of the input contains integer n (3 ≤ n ≤ 1000). The second line contains the description of the road — the string that consists of n characters. Each character will be either "." (a block without footprint), or "L" (a block with a left footprint), "R" (a block with a right footprint). It's guaranteed that the given string contains at least one character not equal to ".". Also, the first and the last character will always be ".". It's guaranteed that a solution exists. Output Print two space-separated integers — the values of s and t. If there are several possible solutions you can print any of them. Examples Input 9 ..RRLL... Output 3 4 Input 11 .RRRLLLLL.. Output 7 5 Note The first test sample is the one in the picture. Tags: greedy, implementation Correct Solution: ``` #!/usr/bin/env python import os import re import sys from bisect import bisect, bisect_left, insort, insort_left from collections import Counter, defaultdict, deque from copy import deepcopy from decimal import Decimal from fractions import gcd from io import BytesIO, IOBase from itertools import ( accumulate, combinations, combinations_with_replacement, groupby, permutations, product) from math import ( acos, asin, atan, ceil, cos, degrees, factorial, hypot, log2, pi, radians, sin, sqrt, tan) from operator import itemgetter, mul from string import ascii_lowercase, ascii_uppercase, digits def inp(): return(int(input())) def inlist(): return(list(map(int, input().split()))) def instr(): s = input() return(list(s[:len(s)])) def invr(): return(map(int, input().split())) def main(): n = inp() a = input() rpLeft = a.find("R") + 1 rpRight = a.rfind("R") + 1 lpLeft = a.find("L") + 1 lpRight = a.rfind("L") + 1 if rpRight > 0 and lpLeft > 0: print(rpLeft, rpRight) elif lpLeft == 0: print(rpLeft, rpRight + 1) elif lpLeft > 0: print(lpRight, lpLeft-1) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) def input(): return sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": main() ```
7,874
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a straight snowy road, divided into n blocks. The blocks are numbered from 1 to n from left to right. If one moves from the i-th block to the (i + 1)-th block, he will leave a right footprint on the i-th block. Similarly, if one moves from the i-th block to the (i - 1)-th block, he will leave a left footprint on the i-th block. If there already is a footprint on the i-th block, the new footprint will cover the old one. <image> At the beginning, there were no footprints. Then polar bear Alice starts from the s-th block, makes a sequence of moves and ends in the t-th block. It is known that Alice never moves outside of the road. You are given the description of Alice's footprints. Your task is to find a pair of possible values of s, t by looking at the footprints. Input The first line of the input contains integer n (3 ≤ n ≤ 1000). The second line contains the description of the road — the string that consists of n characters. Each character will be either "." (a block without footprint), or "L" (a block with a left footprint), "R" (a block with a right footprint). It's guaranteed that the given string contains at least one character not equal to ".". Also, the first and the last character will always be ".". It's guaranteed that a solution exists. Output Print two space-separated integers — the values of s and t. If there are several possible solutions you can print any of them. Examples Input 9 ..RRLL... Output 3 4 Input 11 .RRRLLLLL.. Output 7 5 Note The first test sample is the one in the picture. Submitted Solution: ``` # # Author: eloyhz # Date: Sep/07/2020 # if __name__ == '__main__': n = int(input()) road = input() s = t = None for i in range(n - 1): if road[i] == 'R' and road[i + 1] == 'L': s = i + 1 t = i + 1 break if s == t == None: right = True if road.count('R') > 0: s = road.find('R') + 1 else: right = False s = road.find('L') + 1 for t in range(s, n): if road[t] == '.': break if not right: s, t = t, s t -= 1 else: t += 1 print(s, t) ``` Yes
7,875
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a straight snowy road, divided into n blocks. The blocks are numbered from 1 to n from left to right. If one moves from the i-th block to the (i + 1)-th block, he will leave a right footprint on the i-th block. Similarly, if one moves from the i-th block to the (i - 1)-th block, he will leave a left footprint on the i-th block. If there already is a footprint on the i-th block, the new footprint will cover the old one. <image> At the beginning, there were no footprints. Then polar bear Alice starts from the s-th block, makes a sequence of moves and ends in the t-th block. It is known that Alice never moves outside of the road. You are given the description of Alice's footprints. Your task is to find a pair of possible values of s, t by looking at the footprints. Input The first line of the input contains integer n (3 ≤ n ≤ 1000). The second line contains the description of the road — the string that consists of n characters. Each character will be either "." (a block without footprint), or "L" (a block with a left footprint), "R" (a block with a right footprint). It's guaranteed that the given string contains at least one character not equal to ".". Also, the first and the last character will always be ".". It's guaranteed that a solution exists. Output Print two space-separated integers — the values of s and t. If there are several possible solutions you can print any of them. Examples Input 9 ..RRLL... Output 3 4 Input 11 .RRRLLLLL.. Output 7 5 Note The first test sample is the one in the picture. Submitted Solution: ``` n = int(input()) a = input() f = n-a.count('.') m = a.count('L') q0 = 0 flag = 1 for i in range(n): if(m==0): if(a[i]=='.' and a[i-1]=='R' and i>0): q1 = i+1 break if(a[i]=='.'): continue else: if(a[i]=='L'): q1 = i if(flag and q0 == 0): q0 = i+1 break if(flag): q0 = i+1 flag-=1 print(q0,q1) ``` Yes
7,876
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a straight snowy road, divided into n blocks. The blocks are numbered from 1 to n from left to right. If one moves from the i-th block to the (i + 1)-th block, he will leave a right footprint on the i-th block. Similarly, if one moves from the i-th block to the (i - 1)-th block, he will leave a left footprint on the i-th block. If there already is a footprint on the i-th block, the new footprint will cover the old one. <image> At the beginning, there were no footprints. Then polar bear Alice starts from the s-th block, makes a sequence of moves and ends in the t-th block. It is known that Alice never moves outside of the road. You are given the description of Alice's footprints. Your task is to find a pair of possible values of s, t by looking at the footprints. Input The first line of the input contains integer n (3 ≤ n ≤ 1000). The second line contains the description of the road — the string that consists of n characters. Each character will be either "." (a block without footprint), or "L" (a block with a left footprint), "R" (a block with a right footprint). It's guaranteed that the given string contains at least one character not equal to ".". Also, the first and the last character will always be ".". It's guaranteed that a solution exists. Output Print two space-separated integers — the values of s and t. If there are several possible solutions you can print any of them. Examples Input 9 ..RRLL... Output 3 4 Input 11 .RRRLLLLL.. Output 7 5 Note The first test sample is the one in the picture. Submitted Solution: ``` n = int(input()) k = input() start = 0 count1 = 0 count2 = 0 countl = 0 countr = 0 end = 0 for i in range(n): if k[i] == 'R' and count1 == 0: start = i count1+=1 if k[i] == 'R': countr+=1 endr = i if k[i] == 'L' : countl+=1 endl = i if k[i] == 'L' and count2 == 0: end = i count2+=1 if countl > 1 and countr>1: print(start+1,end) elif countr>1 and countl<=1: print(start+1,endr + 2) elif countr<=1 and countl>1: print(endl+1,end) else: for i in range(n): if k[i] == 'L': print(i+1,i) break if k[i] == 'R': print(i+1,i+2) break ``` Yes
7,877
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a straight snowy road, divided into n blocks. The blocks are numbered from 1 to n from left to right. If one moves from the i-th block to the (i + 1)-th block, he will leave a right footprint on the i-th block. Similarly, if one moves from the i-th block to the (i - 1)-th block, he will leave a left footprint on the i-th block. If there already is a footprint on the i-th block, the new footprint will cover the old one. <image> At the beginning, there were no footprints. Then polar bear Alice starts from the s-th block, makes a sequence of moves and ends in the t-th block. It is known that Alice never moves outside of the road. You are given the description of Alice's footprints. Your task is to find a pair of possible values of s, t by looking at the footprints. Input The first line of the input contains integer n (3 ≤ n ≤ 1000). The second line contains the description of the road — the string that consists of n characters. Each character will be either "." (a block without footprint), or "L" (a block with a left footprint), "R" (a block with a right footprint). It's guaranteed that the given string contains at least one character not equal to ".". Also, the first and the last character will always be ".". It's guaranteed that a solution exists. Output Print two space-separated integers — the values of s and t. If there are several possible solutions you can print any of them. Examples Input 9 ..RRLL... Output 3 4 Input 11 .RRRLLLLL.. Output 7 5 Note The first test sample is the one in the picture. Submitted Solution: ``` n = int(input()) a = input() if 'R' in a and 'L' in a: t = a.count('R') x = a.index('R') print (x + 1,x + t) else: if 'R' in a and ('L' not in a): t = a.count('R') x = a.index('R') print(x + 1, x + t + 1) else: t = a.count('L') x = a.index('L') print (x + t,x) ``` Yes
7,878
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a straight snowy road, divided into n blocks. The blocks are numbered from 1 to n from left to right. If one moves from the i-th block to the (i + 1)-th block, he will leave a right footprint on the i-th block. Similarly, if one moves from the i-th block to the (i - 1)-th block, he will leave a left footprint on the i-th block. If there already is a footprint on the i-th block, the new footprint will cover the old one. <image> At the beginning, there were no footprints. Then polar bear Alice starts from the s-th block, makes a sequence of moves and ends in the t-th block. It is known that Alice never moves outside of the road. You are given the description of Alice's footprints. Your task is to find a pair of possible values of s, t by looking at the footprints. Input The first line of the input contains integer n (3 ≤ n ≤ 1000). The second line contains the description of the road — the string that consists of n characters. Each character will be either "." (a block without footprint), or "L" (a block with a left footprint), "R" (a block with a right footprint). It's guaranteed that the given string contains at least one character not equal to ".". Also, the first and the last character will always be ".". It's guaranteed that a solution exists. Output Print two space-separated integers — the values of s and t. If there are several possible solutions you can print any of them. Examples Input 9 ..RRLL... Output 3 4 Input 11 .RRRLLLLL.. Output 7 5 Note The first test sample is the one in the picture. Submitted Solution: ``` a= int(input()) b= input() if 'R' not in b: c = len(b) - b[::-1].index('L') d = b.index('L') + 1 elif 'L' not in b: c = b.index('R') + 1 d = len(b) - b[::-1].index('R') else: c = b.index("R")+1 d = b.index('L') print(c , d) ``` No
7,879
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a straight snowy road, divided into n blocks. The blocks are numbered from 1 to n from left to right. If one moves from the i-th block to the (i + 1)-th block, he will leave a right footprint on the i-th block. Similarly, if one moves from the i-th block to the (i - 1)-th block, he will leave a left footprint on the i-th block. If there already is a footprint on the i-th block, the new footprint will cover the old one. <image> At the beginning, there were no footprints. Then polar bear Alice starts from the s-th block, makes a sequence of moves and ends in the t-th block. It is known that Alice never moves outside of the road. You are given the description of Alice's footprints. Your task is to find a pair of possible values of s, t by looking at the footprints. Input The first line of the input contains integer n (3 ≤ n ≤ 1000). The second line contains the description of the road — the string that consists of n characters. Each character will be either "." (a block without footprint), or "L" (a block with a left footprint), "R" (a block with a right footprint). It's guaranteed that the given string contains at least one character not equal to ".". Also, the first and the last character will always be ".". It's guaranteed that a solution exists. Output Print two space-separated integers — the values of s and t. If there are several possible solutions you can print any of them. Examples Input 9 ..RRLL... Output 3 4 Input 11 .RRRLLLLL.. Output 7 5 Note The first test sample is the one in the picture. Submitted Solution: ``` n = input() s = input() if(s.find('R')== -1) : i = s.rfind('L') j = s.find('L') elif(s.find('L') == -1) : i = s.find('R') j = s.rfind('R') else : i = s.rfind('R') j = s.find('L') print(i+1,j+1) ``` No
7,880
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a straight snowy road, divided into n blocks. The blocks are numbered from 1 to n from left to right. If one moves from the i-th block to the (i + 1)-th block, he will leave a right footprint on the i-th block. Similarly, if one moves from the i-th block to the (i - 1)-th block, he will leave a left footprint on the i-th block. If there already is a footprint on the i-th block, the new footprint will cover the old one. <image> At the beginning, there were no footprints. Then polar bear Alice starts from the s-th block, makes a sequence of moves and ends in the t-th block. It is known that Alice never moves outside of the road. You are given the description of Alice's footprints. Your task is to find a pair of possible values of s, t by looking at the footprints. Input The first line of the input contains integer n (3 ≤ n ≤ 1000). The second line contains the description of the road — the string that consists of n characters. Each character will be either "." (a block without footprint), or "L" (a block with a left footprint), "R" (a block with a right footprint). It's guaranteed that the given string contains at least one character not equal to ".". Also, the first and the last character will always be ".". It's guaranteed that a solution exists. Output Print two space-separated integers — the values of s and t. If there are several possible solutions you can print any of them. Examples Input 9 ..RRLL... Output 3 4 Input 11 .RRRLLLLL.. Output 7 5 Note The first test sample is the one in the picture. Submitted Solution: ``` x=int(input()) l=input() if l.count('R')+l.count('.')==len(l): print(l.find('R')+1,l.rfind('R')+2) elif l.count('L')+l.count('.')==len(l): print(l.rfind('L')+1,l.find('L')) else: print(l.find('R')+1,l.rfind('R')) ``` No
7,881
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a straight snowy road, divided into n blocks. The blocks are numbered from 1 to n from left to right. If one moves from the i-th block to the (i + 1)-th block, he will leave a right footprint on the i-th block. Similarly, if one moves from the i-th block to the (i - 1)-th block, he will leave a left footprint on the i-th block. If there already is a footprint on the i-th block, the new footprint will cover the old one. <image> At the beginning, there were no footprints. Then polar bear Alice starts from the s-th block, makes a sequence of moves and ends in the t-th block. It is known that Alice never moves outside of the road. You are given the description of Alice's footprints. Your task is to find a pair of possible values of s, t by looking at the footprints. Input The first line of the input contains integer n (3 ≤ n ≤ 1000). The second line contains the description of the road — the string that consists of n characters. Each character will be either "." (a block without footprint), or "L" (a block with a left footprint), "R" (a block with a right footprint). It's guaranteed that the given string contains at least one character not equal to ".". Also, the first and the last character will always be ".". It's guaranteed that a solution exists. Output Print two space-separated integers — the values of s and t. If there are several possible solutions you can print any of them. Examples Input 9 ..RRLL... Output 3 4 Input 11 .RRRLLLLL.. Output 7 5 Note The first test sample is the one in the picture. Submitted Solution: ``` import sys import itertools import math import collections from collections import Counter #input = sys.stdin.readline ######################### # imgur.com/Pkt7iIf.png # ######################### def sieve(n): prime = [True for i in range(n + 1)] p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p * 2, n + 1, p): prime[i] = False p += 1 prime[0] = prime[1] = False r = [p for p in range(n + 1) if prime[p]] return r def divs(n, start=1): r = [] for i in range(start, int(math.sqrt(n) + 1)): if (n % i == 0): if (n / i == i): r.append(i) else: r.extend([i, n // i]) return r def flin(d, x, default = -1): f = l = -1 for i in range(len(d)): if d[i] == x: if f == -1: f = i l = i if f == -1: return (default, default) else: return (f, l) def ceil(n, k): return n // k + (n % k != 0) def ii(): return int(input()) def mi(): return map(int, input().split()) def li(): return list(map(int, input().split())) def lcm(a, b): return abs(a * b) // math.gcd(a, b) def prr(a, sep=' '): print(sep.join(map(str, a))) def dd(): return collections.defaultdict(int) n = ii() s = input() fr, lr = flin(s, 'R') fl, ll = flin(s, 'L') if fr != -1 and fl != - 1: print(fr + 1, fl) elif fr == -1: print(ll + 1, fl) else: print(fr + 1, lr) ``` No
7,882
Provide tags and a correct Python 3 solution for this coding contest problem. There are n psychos standing in a line. Each psycho is assigned a unique integer from 1 to n. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might kill and get killed at the same step. You're given the initial arrangement of the psychos in the line. Calculate how many steps are needed to the moment of time such, that nobody kills his neighbor after that moment. Look notes to understand the statement more precise. Input The first line of input contains integer n denoting the number of psychos, (1 ≤ n ≤ 105). In the second line there will be a list of n space separated distinct integers each in range 1 to n, inclusive — ids of the psychos in the line from left to right. Output Print the number of steps, so that the line remains the same afterward. Examples Input 10 10 9 7 8 6 5 3 4 2 1 Output 2 Input 6 1 2 3 4 5 6 Output 0 Note In the first sample line of the psychos transforms as follows: [10 9 7 8 6 5 3 4 2 1] → [10 8 4] → [10]. So, there are two steps. Tags: data structures, implementation Correct Solution: ``` n = int(input()) aa = list(map(int,input().split())) live = [] ans=0 for i in range(n-1,-1,-1): c = 0 while len(live)!=0 and live[-1][0]<aa[i]: c = max(c+1,live[-1][1]) live.pop() if c>ans: ans =c live.append((aa[i],c)) print(ans) ```
7,883
Provide tags and a correct Python 3 solution for this coding contest problem. Valera is a lazy student. He has m clean bowls and k clean plates. Valera has made an eating plan for the next n days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat dishes of the first type from bowls and dishes of the second type from either bowls or plates. When Valera finishes eating, he leaves a dirty plate/bowl behind. His life philosophy doesn't let him eat from dirty kitchenware. So sometimes he needs to wash his plate/bowl before eating. Find the minimum number of times Valera will need to wash a plate/bowl, if he acts optimally. Input The first line of the input contains three integers n, m, k (1 ≤ n, m, k ≤ 1000) — the number of the planned days, the number of clean bowls and the number of clean plates. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 2). If ai equals one, then on day i Valera will eat a first type dish. If ai equals two, then on day i Valera will eat a second type dish. Output Print a single integer — the minimum number of times Valera will need to wash a plate/bowl. Examples Input 3 1 1 1 2 1 Output 1 Input 4 3 1 1 1 1 1 Output 1 Input 3 1 2 2 2 2 Output 0 Input 8 2 2 1 2 1 2 1 2 1 2 Output 4 Note In the first sample Valera will wash a bowl only on the third day, so the answer is one. In the second sample, Valera will have the first type of the dish during all four days, and since there are only three bowls, he will wash a bowl exactly once. In the third sample, Valera will have the second type of dish for all three days, and as they can be eaten from either a plate or a bowl, he will never need to wash a plate/bowl. Tags: greedy, implementation Correct Solution: ``` n,m,k=map(int,input().split()) a=list(map(int,input().split())) s=0 for i in range(n): if a[i]==1: if m!=0: m-=1 else: s+=1 else: if k!=0: k-=1 elif m!=0: m-=1 else: s+=1 print(s) ```
7,884
Provide tags and a correct Python 3 solution for this coding contest problem. Valera is a lazy student. He has m clean bowls and k clean plates. Valera has made an eating plan for the next n days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat dishes of the first type from bowls and dishes of the second type from either bowls or plates. When Valera finishes eating, he leaves a dirty plate/bowl behind. His life philosophy doesn't let him eat from dirty kitchenware. So sometimes he needs to wash his plate/bowl before eating. Find the minimum number of times Valera will need to wash a plate/bowl, if he acts optimally. Input The first line of the input contains three integers n, m, k (1 ≤ n, m, k ≤ 1000) — the number of the planned days, the number of clean bowls and the number of clean plates. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 2). If ai equals one, then on day i Valera will eat a first type dish. If ai equals two, then on day i Valera will eat a second type dish. Output Print a single integer — the minimum number of times Valera will need to wash a plate/bowl. Examples Input 3 1 1 1 2 1 Output 1 Input 4 3 1 1 1 1 1 Output 1 Input 3 1 2 2 2 2 Output 0 Input 8 2 2 1 2 1 2 1 2 1 2 Output 4 Note In the first sample Valera will wash a bowl only on the third day, so the answer is one. In the second sample, Valera will have the first type of the dish during all four days, and since there are only three bowls, he will wash a bowl exactly once. In the third sample, Valera will have the second type of dish for all three days, and as they can be eaten from either a plate or a bowl, he will never need to wash a plate/bowl. Tags: greedy, implementation Correct Solution: ``` n, m, k = list(map(int, input().split())) a = input().split() counter = 0 for i in range(n): if(a[i] == "1"): m -= 1 else: if(k != 0): k -= 1 else: m -= 1 if(m < 0): washM = abs(m) else: washM = 0 if(k < 0): washK = abs(k) else: washK = 0 counter = washM + washK print(counter) ```
7,885
Provide tags and a correct Python 3 solution for this coding contest problem. Valera is a lazy student. He has m clean bowls and k clean plates. Valera has made an eating plan for the next n days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat dishes of the first type from bowls and dishes of the second type from either bowls or plates. When Valera finishes eating, he leaves a dirty plate/bowl behind. His life philosophy doesn't let him eat from dirty kitchenware. So sometimes he needs to wash his plate/bowl before eating. Find the minimum number of times Valera will need to wash a plate/bowl, if he acts optimally. Input The first line of the input contains three integers n, m, k (1 ≤ n, m, k ≤ 1000) — the number of the planned days, the number of clean bowls and the number of clean plates. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 2). If ai equals one, then on day i Valera will eat a first type dish. If ai equals two, then on day i Valera will eat a second type dish. Output Print a single integer — the minimum number of times Valera will need to wash a plate/bowl. Examples Input 3 1 1 1 2 1 Output 1 Input 4 3 1 1 1 1 1 Output 1 Input 3 1 2 2 2 2 Output 0 Input 8 2 2 1 2 1 2 1 2 1 2 Output 4 Note In the first sample Valera will wash a bowl only on the third day, so the answer is one. In the second sample, Valera will have the first type of the dish during all four days, and since there are only three bowls, he will wash a bowl exactly once. In the third sample, Valera will have the second type of dish for all three days, and as they can be eaten from either a plate or a bowl, he will never need to wash a plate/bowl. Tags: greedy, implementation Correct Solution: ``` n, m, k = map(int, input().split()) a = [int(e) for e in input().split()] ans = 0 for i in a: if i == 2 and k > 0: k -= 1 elif m > 0: m -= 1 else: ans += 1 print(ans) ```
7,886
Provide tags and a correct Python 3 solution for this coding contest problem. Valera is a lazy student. He has m clean bowls and k clean plates. Valera has made an eating plan for the next n days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat dishes of the first type from bowls and dishes of the second type from either bowls or plates. When Valera finishes eating, he leaves a dirty plate/bowl behind. His life philosophy doesn't let him eat from dirty kitchenware. So sometimes he needs to wash his plate/bowl before eating. Find the minimum number of times Valera will need to wash a plate/bowl, if he acts optimally. Input The first line of the input contains three integers n, m, k (1 ≤ n, m, k ≤ 1000) — the number of the planned days, the number of clean bowls and the number of clean plates. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 2). If ai equals one, then on day i Valera will eat a first type dish. If ai equals two, then on day i Valera will eat a second type dish. Output Print a single integer — the minimum number of times Valera will need to wash a plate/bowl. Examples Input 3 1 1 1 2 1 Output 1 Input 4 3 1 1 1 1 1 Output 1 Input 3 1 2 2 2 2 Output 0 Input 8 2 2 1 2 1 2 1 2 1 2 Output 4 Note In the first sample Valera will wash a bowl only on the third day, so the answer is one. In the second sample, Valera will have the first type of the dish during all four days, and since there are only three bowls, he will wash a bowl exactly once. In the third sample, Valera will have the second type of dish for all three days, and as they can be eaten from either a plate or a bowl, he will never need to wash a plate/bowl. Tags: greedy, implementation Correct Solution: ``` s=input().split() n=int(s[0]) bowl=int(s[1]) plate=int(s[2]) s=input().split() a=0 b=0 for i in s: if i=='1': a+=1 if i=='2': b+=1 kq=0 if a>bowl: kq=a-bowl bowl=0 else: bowl=bowl-a if b>plate+bowl: kq+=b-(plate+bowl) print(kq) ```
7,887
Provide tags and a correct Python 3 solution for this coding contest problem. Valera is a lazy student. He has m clean bowls and k clean plates. Valera has made an eating plan for the next n days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat dishes of the first type from bowls and dishes of the second type from either bowls or plates. When Valera finishes eating, he leaves a dirty plate/bowl behind. His life philosophy doesn't let him eat from dirty kitchenware. So sometimes he needs to wash his plate/bowl before eating. Find the minimum number of times Valera will need to wash a plate/bowl, if he acts optimally. Input The first line of the input contains three integers n, m, k (1 ≤ n, m, k ≤ 1000) — the number of the planned days, the number of clean bowls and the number of clean plates. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 2). If ai equals one, then on day i Valera will eat a first type dish. If ai equals two, then on day i Valera will eat a second type dish. Output Print a single integer — the minimum number of times Valera will need to wash a plate/bowl. Examples Input 3 1 1 1 2 1 Output 1 Input 4 3 1 1 1 1 1 Output 1 Input 3 1 2 2 2 2 Output 0 Input 8 2 2 1 2 1 2 1 2 1 2 Output 4 Note In the first sample Valera will wash a bowl only on the third day, so the answer is one. In the second sample, Valera will have the first type of the dish during all four days, and since there are only three bowls, he will wash a bowl exactly once. In the third sample, Valera will have the second type of dish for all three days, and as they can be eaten from either a plate or a bowl, he will never need to wash a plate/bowl. Tags: greedy, implementation Correct Solution: ``` n, b, p = input().split() n = int(n) b = int(b) p = int(p) arr = input().split() for a in range(len(arr)): if arr[a] == "1" : b -= 1 else : p -= 1 if p < 0 : b -= abs(p) result = abs(b) if b > 0 : result = 0 print(result) ```
7,888
Provide tags and a correct Python 3 solution for this coding contest problem. Valera is a lazy student. He has m clean bowls and k clean plates. Valera has made an eating plan for the next n days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat dishes of the first type from bowls and dishes of the second type from either bowls or plates. When Valera finishes eating, he leaves a dirty plate/bowl behind. His life philosophy doesn't let him eat from dirty kitchenware. So sometimes he needs to wash his plate/bowl before eating. Find the minimum number of times Valera will need to wash a plate/bowl, if he acts optimally. Input The first line of the input contains three integers n, m, k (1 ≤ n, m, k ≤ 1000) — the number of the planned days, the number of clean bowls and the number of clean plates. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 2). If ai equals one, then on day i Valera will eat a first type dish. If ai equals two, then on day i Valera will eat a second type dish. Output Print a single integer — the minimum number of times Valera will need to wash a plate/bowl. Examples Input 3 1 1 1 2 1 Output 1 Input 4 3 1 1 1 1 1 Output 1 Input 3 1 2 2 2 2 Output 0 Input 8 2 2 1 2 1 2 1 2 1 2 Output 4 Note In the first sample Valera will wash a bowl only on the third day, so the answer is one. In the second sample, Valera will have the first type of the dish during all four days, and since there are only three bowls, he will wash a bowl exactly once. In the third sample, Valera will have the second type of dish for all three days, and as they can be eaten from either a plate or a bowl, he will never need to wash a plate/bowl. Tags: greedy, implementation Correct Solution: ``` ar = list(map(int,input().split(' '))) n = ar[0] m = ar[1] k = ar[2] array = list(map(int,input().split(' '))) for i in array: if i==1: m-=1 else: if k > 0: k -= 1 else: m -= 1 res = 0 res += -m if m<0 else 0 res += -k if k<0 else 0 print(res) ```
7,889
Provide tags and a correct Python 3 solution for this coding contest problem. Valera is a lazy student. He has m clean bowls and k clean plates. Valera has made an eating plan for the next n days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat dishes of the first type from bowls and dishes of the second type from either bowls or plates. When Valera finishes eating, he leaves a dirty plate/bowl behind. His life philosophy doesn't let him eat from dirty kitchenware. So sometimes he needs to wash his plate/bowl before eating. Find the minimum number of times Valera will need to wash a plate/bowl, if he acts optimally. Input The first line of the input contains three integers n, m, k (1 ≤ n, m, k ≤ 1000) — the number of the planned days, the number of clean bowls and the number of clean plates. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 2). If ai equals one, then on day i Valera will eat a first type dish. If ai equals two, then on day i Valera will eat a second type dish. Output Print a single integer — the minimum number of times Valera will need to wash a plate/bowl. Examples Input 3 1 1 1 2 1 Output 1 Input 4 3 1 1 1 1 1 Output 1 Input 3 1 2 2 2 2 Output 0 Input 8 2 2 1 2 1 2 1 2 1 2 Output 4 Note In the first sample Valera will wash a bowl only on the third day, so the answer is one. In the second sample, Valera will have the first type of the dish during all four days, and since there are only three bowls, he will wash a bowl exactly once. In the third sample, Valera will have the second type of dish for all three days, and as they can be eaten from either a plate or a bowl, he will never need to wash a plate/bowl. Tags: greedy, implementation Correct Solution: ``` n, m, k = map(int, input().split()) dishes= list(map(int, input().split())) answer=0 for i in dishes: if i==1: m = m-1 if m<0: answer = answer +1 if i==2: if k>0: k = k-1 elif m>0: m = m-1 else: answer = answer+1 print(answer) ```
7,890
Provide tags and a correct Python 3 solution for this coding contest problem. Valera is a lazy student. He has m clean bowls and k clean plates. Valera has made an eating plan for the next n days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat dishes of the first type from bowls and dishes of the second type from either bowls or plates. When Valera finishes eating, he leaves a dirty plate/bowl behind. His life philosophy doesn't let him eat from dirty kitchenware. So sometimes he needs to wash his plate/bowl before eating. Find the minimum number of times Valera will need to wash a plate/bowl, if he acts optimally. Input The first line of the input contains three integers n, m, k (1 ≤ n, m, k ≤ 1000) — the number of the planned days, the number of clean bowls and the number of clean plates. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 2). If ai equals one, then on day i Valera will eat a first type dish. If ai equals two, then on day i Valera will eat a second type dish. Output Print a single integer — the minimum number of times Valera will need to wash a plate/bowl. Examples Input 3 1 1 1 2 1 Output 1 Input 4 3 1 1 1 1 1 Output 1 Input 3 1 2 2 2 2 Output 0 Input 8 2 2 1 2 1 2 1 2 1 2 Output 4 Note In the first sample Valera will wash a bowl only on the third day, so the answer is one. In the second sample, Valera will have the first type of the dish during all four days, and since there are only three bowls, he will wash a bowl exactly once. In the third sample, Valera will have the second type of dish for all three days, and as they can be eaten from either a plate or a bowl, he will never need to wash a plate/bowl. Tags: greedy, implementation Correct Solution: ``` n,m,k=list(map(int,input().split())) t=list(map(int,input().split())) if 2 not in t: r=sum(t) if m>=r: print(0) else: print(abs(r-m)) elif 1 not in t: if m+k >= n: print(0) else: print(abs(m+k-n)) else: a=t.count(1) b=t.count(2) p=0 if m>= a: k+= m-a else: p+=a-m if k >= b: pass else: p+=b-k print(abs(p)) ```
7,891
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Valera is a lazy student. He has m clean bowls and k clean plates. Valera has made an eating plan for the next n days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat dishes of the first type from bowls and dishes of the second type from either bowls or plates. When Valera finishes eating, he leaves a dirty plate/bowl behind. His life philosophy doesn't let him eat from dirty kitchenware. So sometimes he needs to wash his plate/bowl before eating. Find the minimum number of times Valera will need to wash a plate/bowl, if he acts optimally. Input The first line of the input contains three integers n, m, k (1 ≤ n, m, k ≤ 1000) — the number of the planned days, the number of clean bowls and the number of clean plates. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 2). If ai equals one, then on day i Valera will eat a first type dish. If ai equals two, then on day i Valera will eat a second type dish. Output Print a single integer — the minimum number of times Valera will need to wash a plate/bowl. Examples Input 3 1 1 1 2 1 Output 1 Input 4 3 1 1 1 1 1 Output 1 Input 3 1 2 2 2 2 Output 0 Input 8 2 2 1 2 1 2 1 2 1 2 Output 4 Note In the first sample Valera will wash a bowl only on the third day, so the answer is one. In the second sample, Valera will have the first type of the dish during all four days, and since there are only three bowls, he will wash a bowl exactly once. In the third sample, Valera will have the second type of dish for all three days, and as they can be eaten from either a plate or a bowl, he will never need to wash a plate/bowl. Submitted Solution: ``` n, b, p = map(int, input().split()) meals = list(map(int, input().split())) x = meals.count(1) y = meals.count(2) b -= x if b >= 0: p += b p -= y count = 0 if b < 0: count+=b if p < 0: count+=p print(abs(count)) ``` Yes
7,892
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Valera is a lazy student. He has m clean bowls and k clean plates. Valera has made an eating plan for the next n days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat dishes of the first type from bowls and dishes of the second type from either bowls or plates. When Valera finishes eating, he leaves a dirty plate/bowl behind. His life philosophy doesn't let him eat from dirty kitchenware. So sometimes he needs to wash his plate/bowl before eating. Find the minimum number of times Valera will need to wash a plate/bowl, if he acts optimally. Input The first line of the input contains three integers n, m, k (1 ≤ n, m, k ≤ 1000) — the number of the planned days, the number of clean bowls and the number of clean plates. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 2). If ai equals one, then on day i Valera will eat a first type dish. If ai equals two, then on day i Valera will eat a second type dish. Output Print a single integer — the minimum number of times Valera will need to wash a plate/bowl. Examples Input 3 1 1 1 2 1 Output 1 Input 4 3 1 1 1 1 1 Output 1 Input 3 1 2 2 2 2 Output 0 Input 8 2 2 1 2 1 2 1 2 1 2 Output 4 Note In the first sample Valera will wash a bowl only on the third day, so the answer is one. In the second sample, Valera will have the first type of the dish during all four days, and since there are only three bowls, he will wash a bowl exactly once. In the third sample, Valera will have the second type of dish for all three days, and as they can be eaten from either a plate or a bowl, he will never need to wash a plate/bowl. Submitted Solution: ``` n, m, k = map(int, input().split()) A = list(map(int, input().split())) ans = 0 for a in A: if a == 1: if m > 0: m -= 1 else: ans += 1 elif a == 2: if k > 0: k -= 1 else: if m > 0: m -= 1 else: ans += 1 print(ans) ``` Yes
7,893
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Valera is a lazy student. He has m clean bowls and k clean plates. Valera has made an eating plan for the next n days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat dishes of the first type from bowls and dishes of the second type from either bowls or plates. When Valera finishes eating, he leaves a dirty plate/bowl behind. His life philosophy doesn't let him eat from dirty kitchenware. So sometimes he needs to wash his plate/bowl before eating. Find the minimum number of times Valera will need to wash a plate/bowl, if he acts optimally. Input The first line of the input contains three integers n, m, k (1 ≤ n, m, k ≤ 1000) — the number of the planned days, the number of clean bowls and the number of clean plates. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 2). If ai equals one, then on day i Valera will eat a first type dish. If ai equals two, then on day i Valera will eat a second type dish. Output Print a single integer — the minimum number of times Valera will need to wash a plate/bowl. Examples Input 3 1 1 1 2 1 Output 1 Input 4 3 1 1 1 1 1 Output 1 Input 3 1 2 2 2 2 Output 0 Input 8 2 2 1 2 1 2 1 2 1 2 Output 4 Note In the first sample Valera will wash a bowl only on the third day, so the answer is one. In the second sample, Valera will have the first type of the dish during all four days, and since there are only three bowls, he will wash a bowl exactly once. In the third sample, Valera will have the second type of dish for all three days, and as they can be eaten from either a plate or a bowl, he will never need to wash a plate/bowl. Submitted Solution: ``` n, m, k = map(int, input().split()) l_d = list(map(int, input().split())) t = 0 for d in l_d: if d == 2: if k > 0: k -= 1 else: if m > 0: m -= 1 else: t += 1 else: if m > 0: m -= 1 else: t += 1 print(t) ``` Yes
7,894
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Valera is a lazy student. He has m clean bowls and k clean plates. Valera has made an eating plan for the next n days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat dishes of the first type from bowls and dishes of the second type from either bowls or plates. When Valera finishes eating, he leaves a dirty plate/bowl behind. His life philosophy doesn't let him eat from dirty kitchenware. So sometimes he needs to wash his plate/bowl before eating. Find the minimum number of times Valera will need to wash a plate/bowl, if he acts optimally. Input The first line of the input contains three integers n, m, k (1 ≤ n, m, k ≤ 1000) — the number of the planned days, the number of clean bowls and the number of clean plates. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 2). If ai equals one, then on day i Valera will eat a first type dish. If ai equals two, then on day i Valera will eat a second type dish. Output Print a single integer — the minimum number of times Valera will need to wash a plate/bowl. Examples Input 3 1 1 1 2 1 Output 1 Input 4 3 1 1 1 1 1 Output 1 Input 3 1 2 2 2 2 Output 0 Input 8 2 2 1 2 1 2 1 2 1 2 Output 4 Note In the first sample Valera will wash a bowl only on the third day, so the answer is one. In the second sample, Valera will have the first type of the dish during all four days, and since there are only three bowls, he will wash a bowl exactly once. In the third sample, Valera will have the second type of dish for all three days, and as they can be eaten from either a plate or a bowl, he will never need to wash a plate/bowl. Submitted Solution: ``` n, m, k = map(int, input().split()) b1 = len([0 for i in input().split() if i == '1']) b2 = n - b1 print (max(0, b1 - m + max(0, b2 - k))) ``` Yes
7,895
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Valera is a lazy student. He has m clean bowls and k clean plates. Valera has made an eating plan for the next n days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat dishes of the first type from bowls and dishes of the second type from either bowls or plates. When Valera finishes eating, he leaves a dirty plate/bowl behind. His life philosophy doesn't let him eat from dirty kitchenware. So sometimes he needs to wash his plate/bowl before eating. Find the minimum number of times Valera will need to wash a plate/bowl, if he acts optimally. Input The first line of the input contains three integers n, m, k (1 ≤ n, m, k ≤ 1000) — the number of the planned days, the number of clean bowls and the number of clean plates. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 2). If ai equals one, then on day i Valera will eat a first type dish. If ai equals two, then on day i Valera will eat a second type dish. Output Print a single integer — the minimum number of times Valera will need to wash a plate/bowl. Examples Input 3 1 1 1 2 1 Output 1 Input 4 3 1 1 1 1 1 Output 1 Input 3 1 2 2 2 2 Output 0 Input 8 2 2 1 2 1 2 1 2 1 2 Output 4 Note In the first sample Valera will wash a bowl only on the third day, so the answer is one. In the second sample, Valera will have the first type of the dish during all four days, and since there are only three bowls, he will wash a bowl exactly once. In the third sample, Valera will have the second type of dish for all three days, and as they can be eaten from either a plate or a bowl, he will never need to wash a plate/bowl. Submitted Solution: ``` n,m,k = map(int, input().split()) mmax = m kmax = k ris = 0 types = list(map(int, input().split())) for p in types: if p == 2: if m != 0: m -= 1 elif k !=0: k -= 1 else: ris += 1 else: if m!=0: m -= 1 else: ris += 1 print(ris) ``` No
7,896
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Valera is a lazy student. He has m clean bowls and k clean plates. Valera has made an eating plan for the next n days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat dishes of the first type from bowls and dishes of the second type from either bowls or plates. When Valera finishes eating, he leaves a dirty plate/bowl behind. His life philosophy doesn't let him eat from dirty kitchenware. So sometimes he needs to wash his plate/bowl before eating. Find the minimum number of times Valera will need to wash a plate/bowl, if he acts optimally. Input The first line of the input contains three integers n, m, k (1 ≤ n, m, k ≤ 1000) — the number of the planned days, the number of clean bowls and the number of clean plates. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 2). If ai equals one, then on day i Valera will eat a first type dish. If ai equals two, then on day i Valera will eat a second type dish. Output Print a single integer — the minimum number of times Valera will need to wash a plate/bowl. Examples Input 3 1 1 1 2 1 Output 1 Input 4 3 1 1 1 1 1 Output 1 Input 3 1 2 2 2 2 Output 0 Input 8 2 2 1 2 1 2 1 2 1 2 Output 4 Note In the first sample Valera will wash a bowl only on the third day, so the answer is one. In the second sample, Valera will have the first type of the dish during all four days, and since there are only three bowls, he will wash a bowl exactly once. In the third sample, Valera will have the second type of dish for all three days, and as they can be eaten from either a plate or a bowl, he will never need to wash a plate/bowl. Submitted Solution: ``` def main(stdin): n, m, k = next(stdin).split() n, m, k = int(n), int(m), int(k) for a in next(stdin).split(): if int(a) == 1: m -= 1 if int(a) == 2: k -= 1 t = 0 if m < 0: t += m * (-1) if k < 0: t += k * (-1) print(t) if __name__ == '__main__': import sys main(sys.stdin) ``` No
7,897
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Valera is a lazy student. He has m clean bowls and k clean plates. Valera has made an eating plan for the next n days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat dishes of the first type from bowls and dishes of the second type from either bowls or plates. When Valera finishes eating, he leaves a dirty plate/bowl behind. His life philosophy doesn't let him eat from dirty kitchenware. So sometimes he needs to wash his plate/bowl before eating. Find the minimum number of times Valera will need to wash a plate/bowl, if he acts optimally. Input The first line of the input contains three integers n, m, k (1 ≤ n, m, k ≤ 1000) — the number of the planned days, the number of clean bowls and the number of clean plates. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 2). If ai equals one, then on day i Valera will eat a first type dish. If ai equals two, then on day i Valera will eat a second type dish. Output Print a single integer — the minimum number of times Valera will need to wash a plate/bowl. Examples Input 3 1 1 1 2 1 Output 1 Input 4 3 1 1 1 1 1 Output 1 Input 3 1 2 2 2 2 Output 0 Input 8 2 2 1 2 1 2 1 2 1 2 Output 4 Note In the first sample Valera will wash a bowl only on the third day, so the answer is one. In the second sample, Valera will have the first type of the dish during all four days, and since there are only three bowls, he will wash a bowl exactly once. In the third sample, Valera will have the second type of dish for all three days, and as they can be eaten from either a plate or a bowl, he will never need to wash a plate/bowl. Submitted Solution: ``` days, usual_cl, flat_cl = input().split() usual = 0 flat = 0 dish = input() dish_list = (dish.split()) for i in dish_list: if i == '1': usual+=1 else: flat+=1 usual = int(usual)-int(usual_cl) flat = int(flat)-int(flat_cl) if '1' and '2' in dish_list: print(flat+usual) else: if '1' in dish_list and not '2' in dish_list: print(usual) else: print(flat) ``` No
7,898
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Valera is a lazy student. He has m clean bowls and k clean plates. Valera has made an eating plan for the next n days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat dishes of the first type from bowls and dishes of the second type from either bowls or plates. When Valera finishes eating, he leaves a dirty plate/bowl behind. His life philosophy doesn't let him eat from dirty kitchenware. So sometimes he needs to wash his plate/bowl before eating. Find the minimum number of times Valera will need to wash a plate/bowl, if he acts optimally. Input The first line of the input contains three integers n, m, k (1 ≤ n, m, k ≤ 1000) — the number of the planned days, the number of clean bowls and the number of clean plates. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 2). If ai equals one, then on day i Valera will eat a first type dish. If ai equals two, then on day i Valera will eat a second type dish. Output Print a single integer — the minimum number of times Valera will need to wash a plate/bowl. Examples Input 3 1 1 1 2 1 Output 1 Input 4 3 1 1 1 1 1 Output 1 Input 3 1 2 2 2 2 Output 0 Input 8 2 2 1 2 1 2 1 2 1 2 Output 4 Note In the first sample Valera will wash a bowl only on the third day, so the answer is one. In the second sample, Valera will have the first type of the dish during all four days, and since there are only three bowls, he will wash a bowl exactly once. In the third sample, Valera will have the second type of dish for all three days, and as they can be eaten from either a plate or a bowl, he will never need to wash a plate/bowl. Submitted Solution: ``` inp = input().split(' ') dishes = input().split(' ') days = int(inp[0]) bowls = int(inp[1]) plates = int(inp[2]) shouldWash = 0 for i in dishes: days -= 1 if days < 0: break if i == '1': bowls -= 1 else: if plates <= 0: bowls -= 1 else: plates -= 1 if bowls < 0 or plates < 0: shouldWash += 1 print(shouldWash) ``` No
7,899