text
stringlengths
198
433k
conversation_id
int64
0
109k
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph. Your task is to find any spanning tree of this graph such that the maximum degree over all vertices is maximum possible. Recall that the degree of a vertex is the number of edges incident to it. Input The first line contains two integers n and m (2 ≀ n ≀ 2 β‹… 10^5, n - 1 ≀ m ≀ min(2 β‹… 10^5, (n(n-1))/(2))) β€” the number of vertices and edges, respectively. The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≀ v_i, u_i ≀ n, u_i β‰  v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i β‰  u_i is satisfied. Output Print n-1 lines describing the edges of a spanning tree such that the maximum degree over all vertices is maximum possible. Make sure that the edges of the printed spanning tree form some subset of the input edges (order doesn't matter and edge (v, u) is considered the same as the edge (u, v)). If there are multiple possible answers, print any of them. Examples Input 5 5 1 2 2 3 3 5 4 3 1 5 Output 3 5 2 1 3 2 3 4 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 4 1 1 2 1 3 Input 8 9 1 2 2 3 2 5 1 6 3 4 6 5 4 5 2 7 5 8 Output 3 2 2 5 8 5 6 1 2 7 1 2 3 4 Note Picture corresponding to the first example: <image> In this example the number of edges of spanning tree incident to the vertex 3 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the second example: <image> In this example the number of edges of spanning tree incident to the vertex 1 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the third example: <image> In this example the number of edges of spanning tree incident to the vertex 2 is 4. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. But because this example is symmetric, we can choose almost the same spanning tree but with vertex 5 instead of 2. Submitted Solution: ``` # 1133F1 import collections def do(): graph = collections.defaultdict(list) nodes, edges = map(int, input().split(" ")) ind = [0] * (nodes + 1) for _ in range(edges): x, y = map(int, input().split(" ")) graph[x].append(y) graph[y].append(x) ind[x] += 1 ind[y] += 1 root = 1 mi = ind[1] for i in range(1, nodes + 1): if ind[i] > mi: mi = ind[i] root = i seen = [0] * (nodes + 1) seen[root] = 1 res = set() q = collections.deque() for nei in graph[root]: seen[nei] = 1 res.add((root, nei)) q.append(nei) while q: cur = q.popleft() for nei in graph[cur]: if not seen[nei]: seen[nei] = 1 res.add((cur, nei)) q.append(nei) for x, y in list(res): print(str(x) + " " + str(y)) return 0 do() ``` Yes
105,300
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph. Your task is to find any spanning tree of this graph such that the maximum degree over all vertices is maximum possible. Recall that the degree of a vertex is the number of edges incident to it. Input The first line contains two integers n and m (2 ≀ n ≀ 2 β‹… 10^5, n - 1 ≀ m ≀ min(2 β‹… 10^5, (n(n-1))/(2))) β€” the number of vertices and edges, respectively. The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≀ v_i, u_i ≀ n, u_i β‰  v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i β‰  u_i is satisfied. Output Print n-1 lines describing the edges of a spanning tree such that the maximum degree over all vertices is maximum possible. Make sure that the edges of the printed spanning tree form some subset of the input edges (order doesn't matter and edge (v, u) is considered the same as the edge (u, v)). If there are multiple possible answers, print any of them. Examples Input 5 5 1 2 2 3 3 5 4 3 1 5 Output 3 5 2 1 3 2 3 4 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 4 1 1 2 1 3 Input 8 9 1 2 2 3 2 5 1 6 3 4 6 5 4 5 2 7 5 8 Output 3 2 2 5 8 5 6 1 2 7 1 2 3 4 Note Picture corresponding to the first example: <image> In this example the number of edges of spanning tree incident to the vertex 3 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the second example: <image> In this example the number of edges of spanning tree incident to the vertex 1 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the third example: <image> In this example the number of edges of spanning tree incident to the vertex 2 is 4. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. But because this example is symmetric, we can choose almost the same spanning tree but with vertex 5 instead of 2. Submitted Solution: ``` import sys input = sys.stdin.readline def factorial(x, m): val = 1 while x > 0: val = (val * x) % m x -= 1 return val def fact(x): val = 1 while x > 0: val *= x x -= 1 return val # swap_array function def swaparr(arr, a, b): temp = arr[a] arr[a] = arr[b] arr[b] = temp def gcd(a, b): if b == 0: return a return gcd(b, a % b) def nCr(n, k): if k > n: return 0 if (k > n - k): k = n - k res = 1 for i in range(k): res = res * (n - i) res = res / (i + 1) return int(res) ## prime factorization def primefs(n): primes = {} while (n % 2 == 0 and n > 0): primes[2] = primes.get(2, 0) + 1 n = n // 2 for i in range(3, int(n ** 0.5) + 2, 2): while (n % i == 0 and n > 0): primes[i] = primes.get(i, 0) + 1 n = n // i if n > 2: primes[n] = primes.get(n, 0) + 1 ## prime factoriazation of n is stored in dictionary ## primes and can be accesed. O(sqrt n) return primes ## MODULAR EXPONENTIATION FUNCTION def power(x, y, p): res = 1 x = x % p if (x == 0): return 0 while (y > 0): if ((y & 1) == 1): res = (res * x) % p y = y >> 1 x = (x * x) % p return res ## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES def sieve(n): prime = [True for i in range(n + 1)] prime[0], prime[1] = False, False p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p * p, n + 1, p): prime[i] = False p += 1 return prime def is_prime(n): if n == 0: return False if n == 1: return True for i in range(2, int(n ** (1 / 2)) + 1): if not n % i: return False return True #### PRIME FACTORIZATION IN O(log n) using Sieve #### MAXN = int(1e5 + 5) import math def spf_sieve(): spf[1] = 1 for i in range(2, MAXN): spf[i] = i for i in range(4, MAXN, 2): spf[i] = 2 for i in range(3, math.ceil(MAXN ** 0.5), 2): if spf[i] == i: for j in range(i * i, MAXN, i): if spf[j] == j: spf[j] = i spf = [0 for i in range(MAXN)] # spf_sieve(); def factoriazation(x): res = [] for i in range(2, int(x ** 0.5) + 1): while x % i == 0: res.append(i) x //= i if x != 1: res.append(x) return res def factors(n): res = [] for i in range(1, int(n ** 0.5) + 1): if n % i == 0: res.append(i) res.append(n // i) return list(set(res)) def int_array(): return list(map(int, input().strip().split())) def float_array(): return list(map(float, input().strip().split())) def str_array(): return input().strip().split() # defining a couple constants MOD = int(1e9) + 7 CMOD = 998244353 INF = float('inf') NINF = -float('inf') ################### ---------------- TEMPLATE ENDS HERE ---------------- ################### from itertools import permutations import math from bisect import bisect_left #for _ in range(int(input())): 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()) # arr=[(i,x) for i,x in enum] # arr.sort(key=lambda x:x[0]) # e=list(map(int, input().split())) from collections import Counter # print("\n".join(ls)) # print(os.path.commonprefix(ls[0:2])) # n=int(input()) from bisect import bisect_right # d=sorted(d,key=lambda x:(len(d[x]),-x)) d=dictionary d={x:set() for x in arr} # n=int(input()) # n,m,k= map(int, input().split()) import heapq # for _ in range(int(input())): # n,k=map(int, input().split()) #for _ in range(int(input())): #n = int(input()) # code here ;)) #n,k=map(int, input().split()) #arr = list(map(int, input().split())) #ls= list(map(int, input().split())) import math #n = int(input()) #n,k=map(int, input().split()) #for _ in range(int(input())): #n = int(input()) #n,l=map(int,input().split()) #for _ in range(int(input())): def divisors_seive(n): divisors=[10**6+6] for i in range(1,n+1): for j in range(i,n+1): divisors[j]+=1 #n=int(input()) #n=int(input()) import bisect from collections import deque ans=[] def dfs(s): vis[s]=1 for i in gg[s]: if vis[i]==0: ans.append([s+1,i+1]) dfs(i) def find(x): if par[x]==x: return x return find(par[x]) def union(x,y): xroot=find(x) yroot=find(y) if rank[xroot]>rank[yroot]: par[yroot]=xroot rank[xroot]+=rank[yroot] else: par[xroot] =yroot rank[yroot]+=rank[xroot] n,m,d=map(int,input().split()) vis=[0]*(n+1) rank=[1 for i in range(n)] par=[i for i in range(n)] q=[] vis=[0]*(n+1) g=[[] for i in range(n)] ind=[0]*n gg=[[] for i in range(n)] ind=0 for i in range(m): u,v= map(int, input().split()) g[u-1].append(v-1) g[v-1].append(u-1) if u!=1 and v!=1: union(u-1,v-1) gg[u-1].append(v-1) gg[v-1].append(u-1) else: ind+=1 component=0 for i in range(1,n): if par[i]==i: component+=1 gg[0].append(i) gg[i].append(0) if component>d or d>ind: print("NO") else: dfs(0) print("YES") for i in ans: print(*i) ``` No
105,301
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph. Your task is to find any spanning tree of this graph such that the maximum degree over all vertices is maximum possible. Recall that the degree of a vertex is the number of edges incident to it. Input The first line contains two integers n and m (2 ≀ n ≀ 2 β‹… 10^5, n - 1 ≀ m ≀ min(2 β‹… 10^5, (n(n-1))/(2))) β€” the number of vertices and edges, respectively. The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≀ v_i, u_i ≀ n, u_i β‰  v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i β‰  u_i is satisfied. Output Print n-1 lines describing the edges of a spanning tree such that the maximum degree over all vertices is maximum possible. Make sure that the edges of the printed spanning tree form some subset of the input edges (order doesn't matter and edge (v, u) is considered the same as the edge (u, v)). If there are multiple possible answers, print any of them. Examples Input 5 5 1 2 2 3 3 5 4 3 1 5 Output 3 5 2 1 3 2 3 4 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 4 1 1 2 1 3 Input 8 9 1 2 2 3 2 5 1 6 3 4 6 5 4 5 2 7 5 8 Output 3 2 2 5 8 5 6 1 2 7 1 2 3 4 Note Picture corresponding to the first example: <image> In this example the number of edges of spanning tree incident to the vertex 3 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the second example: <image> In this example the number of edges of spanning tree incident to the vertex 1 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the third example: <image> In this example the number of edges of spanning tree incident to the vertex 2 is 4. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. But because this example is symmetric, we can choose almost the same spanning tree but with vertex 5 instead of 2. Submitted Solution: ``` def find(x): if(par[x]==x): return x par[x]=find(par[x]) return par[x] def union(a,b): xa=find(a) xb=find(b) if(xa==xb): return 0 if(size[xa]>size[xb]): xa,xb=xb,xa par[xa]=xb size[xb]+=size[xa] return 1 n,m,d=map(int,input().split()) par=[i for i in range(n+1)] size=[1 for i in range(n+1)] count=0 ans=0 last=[] arr=[] one_saver=[] for i in range(m): a,b=map(int,input().split()) if(a==1 or b==1): if(a==1): one_saver.append(b) else: one_saver.append(a) elif(union(a,b)): last.append([a,b]) dif_par=set() for i in range(2,n+1): par[i]=find(par[i]) if par[i] not in dif_par: dif_par.add(par[i]) flag=0 if(d>len(one_saver) or d<len(dif_par)): flag=1 print("NO") idntfy1=set() idntfy2=set() idntfy3=set() if(flag==0): print("YES") for i in one_saver: if par[i] not in idntfy1: print(1,i) idntfy1.add(par[i]) idntfy2.add(i) idntfy3.add(i) i=0 j=0 while(j<d-len(dif_par)): if one_saver[i] not in idntfy2: print(one_saver[i],1) j+=1 idntfy3.add(one_saver[i]) i+=1 for i in last: if i[0] not in idntfy3 or i[1] not in idntfy3: print(i[0],i[1]) ``` No
105,302
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph. Your task is to find any spanning tree of this graph such that the maximum degree over all vertices is maximum possible. Recall that the degree of a vertex is the number of edges incident to it. Input The first line contains two integers n and m (2 ≀ n ≀ 2 β‹… 10^5, n - 1 ≀ m ≀ min(2 β‹… 10^5, (n(n-1))/(2))) β€” the number of vertices and edges, respectively. The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≀ v_i, u_i ≀ n, u_i β‰  v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i β‰  u_i is satisfied. Output Print n-1 lines describing the edges of a spanning tree such that the maximum degree over all vertices is maximum possible. Make sure that the edges of the printed spanning tree form some subset of the input edges (order doesn't matter and edge (v, u) is considered the same as the edge (u, v)). If there are multiple possible answers, print any of them. Examples Input 5 5 1 2 2 3 3 5 4 3 1 5 Output 3 5 2 1 3 2 3 4 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 4 1 1 2 1 3 Input 8 9 1 2 2 3 2 5 1 6 3 4 6 5 4 5 2 7 5 8 Output 3 2 2 5 8 5 6 1 2 7 1 2 3 4 Note Picture corresponding to the first example: <image> In this example the number of edges of spanning tree incident to the vertex 3 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the second example: <image> In this example the number of edges of spanning tree incident to the vertex 1 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the third example: <image> In this example the number of edges of spanning tree incident to the vertex 2 is 4. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. But because this example is symmetric, we can choose almost the same spanning tree but with vertex 5 instead of 2. Submitted Solution: ``` def find(x): if(par[x]==x): return x par[x]=find(par[x]) return par[x] def union(a,b): xa=find(a) xb=find(b) if(xa==xb): return 0 if(size[xa]>size[xb]): xa,xb=xb,xa par[xa]=xb size[xb]+=size[xa] return 1 n,m,d=map(int,input().split()) par=[i for i in range(n+1)] size=[1 for i in range(n+1)] count=0 ans=0 last=[] arr=[] one_saver=[] for i in range(m): a,b=map(int,input().split()) if(a==1 or b==1): if(a==1): one_saver.append(b) else: one_saver.append(a) elif(union(a,b)): last.append([a,b]) dif_par=set() for i in range(2,n+1): par[i]=find(par[i]) if par[i] not in dif_par: dif_par.add(par[i]) flag=0 if(d>len(one_saver) or d<len(dif_par)): flag=1 print("NO") idntfy1=set() idntfy2=set() idntfy3=set() if(flag==0): print("YES") for i in one_saver: if par[i] not in idntfy1: print(1,i) idntfy1.add(par[i]) idntfy2.add(i) idntfy3.add(i) i=0 j=0 while(j<d-len(dif_par)): if one_saver[i] not in idntfy2: print(one_saver[i],1) j+=1 idntfy3.add(one_saver[i]) i+=1 for i in last: if i[0] not in idntfy3 or i[1] not in idntfy3: print(i[0],i[1]) idntfy3.add(i[0]) idntfy3.add(i[1]) ``` No
105,303
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph. Your task is to find any spanning tree of this graph such that the maximum degree over all vertices is maximum possible. Recall that the degree of a vertex is the number of edges incident to it. Input The first line contains two integers n and m (2 ≀ n ≀ 2 β‹… 10^5, n - 1 ≀ m ≀ min(2 β‹… 10^5, (n(n-1))/(2))) β€” the number of vertices and edges, respectively. The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≀ v_i, u_i ≀ n, u_i β‰  v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i β‰  u_i is satisfied. Output Print n-1 lines describing the edges of a spanning tree such that the maximum degree over all vertices is maximum possible. Make sure that the edges of the printed spanning tree form some subset of the input edges (order doesn't matter and edge (v, u) is considered the same as the edge (u, v)). If there are multiple possible answers, print any of them. Examples Input 5 5 1 2 2 3 3 5 4 3 1 5 Output 3 5 2 1 3 2 3 4 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 4 1 1 2 1 3 Input 8 9 1 2 2 3 2 5 1 6 3 4 6 5 4 5 2 7 5 8 Output 3 2 2 5 8 5 6 1 2 7 1 2 3 4 Note Picture corresponding to the first example: <image> In this example the number of edges of spanning tree incident to the vertex 3 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the second example: <image> In this example the number of edges of spanning tree incident to the vertex 1 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the third example: <image> In this example the number of edges of spanning tree incident to the vertex 2 is 4. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. But because this example is symmetric, we can choose almost the same spanning tree but with vertex 5 instead of 2. Submitted Solution: ``` n,m=map(int,input().split()) G={} v=0 c=-1 for i in range(m): a,b=map(int,input().split()) try: G[a].append(b) if (len(G[a])>v): c=a v=len(G[a]) except: G[a]=[b] if (v<1): c=a v=1 try: G[b].append(a) if (len(G[b])>v): c=b v=len(G[b]) except: G[b]=[a] if (v<1): c=b v=1 A={} for i in G.keys(): A[i]=-1 q=[v] A[v]=1 while(len(q)!=0): a=q.pop() for i in G[a]: if (A[i]==-1): print(a,i) q.append(i) A[i]=1 ``` No
105,304
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food: * on Mondays, Thursdays and Sundays he eats fish food; * on Tuesdays and Saturdays he eats rabbit stew; * on other days of week he eats chicken stake. Polycarp plans to go on a trip and already packed his backpack. His backpack contains: * a daily rations of fish food; * b daily rations of rabbit stew; * c daily rations of chicken stakes. Polycarp has to choose such day of the week to start his trip that his cat can eat without additional food purchases as long as possible. Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Input The first line of the input contains three positive integers a, b and c (1 ≀ a, b, c ≀ 7β‹…10^8) β€” the number of daily rations of fish food, rabbit stew and chicken stakes in Polycarps backpack correspondingly. Output Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Examples Input 2 1 1 Output 4 Input 3 2 2 Output 7 Input 1 100 1 Output 3 Input 30 20 10 Output 39 Note In the first example the best day for start of the trip is Sunday. In this case, during Sunday and Monday the cat will eat fish food, during Tuesday β€” rabbit stew and during Wednesday β€” chicken stake. So, after four days of the trip all food will be eaten. In the second example Polycarp can start his trip in any day of the week. In any case there are food supplies only for one week in Polycarps backpack. In the third example Polycarp can start his trip in any day, excluding Wednesday, Saturday and Sunday. In this case, the cat will eat three different dishes in three days. Nevertheless that after three days of a trip there will be 99 portions of rabbit stew in a backpack, can cannot eat anything in fourth day of a trip. Tags: implementation, math Correct Solution: ``` a,b,c=map(int,input().split()) fu=0 fu=min(a//3,b//2,c//2) a-=3*fu b-=2*fu c-=2*fu x=[1,2,3,1,3,2,1] k=0 m=0 for i in range(len(x)): d=0 f=0 j=i a1=a b1=b c1=c z=1 while z==1: k=x[j] if (k==1)&(a1>0): a1-=1 d+=1 if (k==2)&(b1>0): b1-=1 d+=1 if (k==3)&(c1>0): c1-=1 d+=1 if d==f: z=0 else: f=d j+=1 j=j%7 if d>m: m=d print(7*fu+m) ```
105,305
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food: * on Mondays, Thursdays and Sundays he eats fish food; * on Tuesdays and Saturdays he eats rabbit stew; * on other days of week he eats chicken stake. Polycarp plans to go on a trip and already packed his backpack. His backpack contains: * a daily rations of fish food; * b daily rations of rabbit stew; * c daily rations of chicken stakes. Polycarp has to choose such day of the week to start his trip that his cat can eat without additional food purchases as long as possible. Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Input The first line of the input contains three positive integers a, b and c (1 ≀ a, b, c ≀ 7β‹…10^8) β€” the number of daily rations of fish food, rabbit stew and chicken stakes in Polycarps backpack correspondingly. Output Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Examples Input 2 1 1 Output 4 Input 3 2 2 Output 7 Input 1 100 1 Output 3 Input 30 20 10 Output 39 Note In the first example the best day for start of the trip is Sunday. In this case, during Sunday and Monday the cat will eat fish food, during Tuesday β€” rabbit stew and during Wednesday β€” chicken stake. So, after four days of the trip all food will be eaten. In the second example Polycarp can start his trip in any day of the week. In any case there are food supplies only for one week in Polycarps backpack. In the third example Polycarp can start his trip in any day, excluding Wednesday, Saturday and Sunday. In this case, the cat will eat three different dishes in three days. Nevertheless that after three days of a trip there will be 99 portions of rabbit stew in a backpack, can cannot eat anything in fourth day of a trip. Tags: implementation, math Correct Solution: ``` def dfs(day_l,day_r,a,b,c): global span if day_l<1 or day_r>14: return if a<0 or b<0 or c<0: return #print(day_l,day_r,a,b,c) span=max(span,day_r-day_l+1) if day_l-1 in [1,4,7,8,11,14]: dfs(day_l-1,day_r,a-1,b,c) elif day_l-1 in [2,6,9,13]: dfs(day_l-1,day_r,a,b-1,c) elif day_l-1 in [3,5,10,12]: dfs(day_l-1,day_r,a,b,c-1) if day_r+1 in [1,4,7,8,11,14]: dfs(day_l,day_r+1,a-1,b,c) elif day_r+1 in [2,6,9,13]: dfs(day_l,day_r+1,a,b-1,c) elif day_r+1 in [3,5,10,12]: dfs(day_l,day_r+1,a,b,c-1) a,b,c=list(map(int,input().split())) weeks=min([a//3,b//2,c//2]) a-=weeks*3 b-=weeks*2 c-=weeks*2 if weeks>0: span=0 if a>0: day_min,day_max=7,7 dfs(7,7,a-1,b,c) ans1=7*weeks+span span=0 day_min,day_max=7,7 dfs(7,7,a-1+3,b+2,c+2) ans2=7*(weeks-1)+span print(max(ans1,ans2)) else: span=0 for i in [4,5,6,7]: day_min,day_max=i,i if i in [4,7]: dfs(i,i,a-1,b,c) elif i==6: dfs(i,i,a,b-1,c) else: dfs(i,i,a,b,c-1) print(span) ```
105,306
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food: * on Mondays, Thursdays and Sundays he eats fish food; * on Tuesdays and Saturdays he eats rabbit stew; * on other days of week he eats chicken stake. Polycarp plans to go on a trip and already packed his backpack. His backpack contains: * a daily rations of fish food; * b daily rations of rabbit stew; * c daily rations of chicken stakes. Polycarp has to choose such day of the week to start his trip that his cat can eat without additional food purchases as long as possible. Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Input The first line of the input contains three positive integers a, b and c (1 ≀ a, b, c ≀ 7β‹…10^8) β€” the number of daily rations of fish food, rabbit stew and chicken stakes in Polycarps backpack correspondingly. Output Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Examples Input 2 1 1 Output 4 Input 3 2 2 Output 7 Input 1 100 1 Output 3 Input 30 20 10 Output 39 Note In the first example the best day for start of the trip is Sunday. In this case, during Sunday and Monday the cat will eat fish food, during Tuesday β€” rabbit stew and during Wednesday β€” chicken stake. So, after four days of the trip all food will be eaten. In the second example Polycarp can start his trip in any day of the week. In any case there are food supplies only for one week in Polycarps backpack. In the third example Polycarp can start his trip in any day, excluding Wednesday, Saturday and Sunday. In this case, the cat will eat three different dishes in three days. Nevertheless that after three days of a trip there will be 99 portions of rabbit stew in a backpack, can cannot eat anything in fourth day of a trip. Tags: implementation, math Correct Solution: ``` a, b, c = map(int, input().split()) x = min(a//3, b//2, c//2) a,b,c = a-3*x, b-2*x, c-2*x z = [1,1,2,3,1,3,2] m = 0 for i in range(7): lis = [0,a,b,c] j = i cnt = 0 while(lis[1]>=0 and lis[2]>=0 and lis[3]>=0): lis[z[j]] -= 1 j = (j+1)%7 cnt += 1 m = max(m,cnt-1) print(x*7+m) ```
105,307
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food: * on Mondays, Thursdays and Sundays he eats fish food; * on Tuesdays and Saturdays he eats rabbit stew; * on other days of week he eats chicken stake. Polycarp plans to go on a trip and already packed his backpack. His backpack contains: * a daily rations of fish food; * b daily rations of rabbit stew; * c daily rations of chicken stakes. Polycarp has to choose such day of the week to start his trip that his cat can eat without additional food purchases as long as possible. Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Input The first line of the input contains three positive integers a, b and c (1 ≀ a, b, c ≀ 7β‹…10^8) β€” the number of daily rations of fish food, rabbit stew and chicken stakes in Polycarps backpack correspondingly. Output Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Examples Input 2 1 1 Output 4 Input 3 2 2 Output 7 Input 1 100 1 Output 3 Input 30 20 10 Output 39 Note In the first example the best day for start of the trip is Sunday. In this case, during Sunday and Monday the cat will eat fish food, during Tuesday β€” rabbit stew and during Wednesday β€” chicken stake. So, after four days of the trip all food will be eaten. In the second example Polycarp can start his trip in any day of the week. In any case there are food supplies only for one week in Polycarps backpack. In the third example Polycarp can start his trip in any day, excluding Wednesday, Saturday and Sunday. In this case, the cat will eat three different dishes in three days. Nevertheless that after three days of a trip there will be 99 portions of rabbit stew in a backpack, can cannot eat anything in fourth day of a trip. Tags: implementation, math Correct Solution: ``` a = [int(i) for i in input().split()] days = [0, 1, 2, 0, 2, 1, 0] week = min(a[0] // 3, a[1] // 2, a[2] // 2) a[0], a[1], a[2] = a[0] - week * 3, a[1] - week * 2, a[2] - week * 2 m = 0 for day in range(7): b = a.copy() c = 0 for this_day in range(7): if b[days[(day + this_day) % 7]] > 0: b[days[(day + this_day) % 7]] -= 1 c += 1 else: break if c > m: m = c print(m + week * 7) ```
105,308
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food: * on Mondays, Thursdays and Sundays he eats fish food; * on Tuesdays and Saturdays he eats rabbit stew; * on other days of week he eats chicken stake. Polycarp plans to go on a trip and already packed his backpack. His backpack contains: * a daily rations of fish food; * b daily rations of rabbit stew; * c daily rations of chicken stakes. Polycarp has to choose such day of the week to start his trip that his cat can eat without additional food purchases as long as possible. Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Input The first line of the input contains three positive integers a, b and c (1 ≀ a, b, c ≀ 7β‹…10^8) β€” the number of daily rations of fish food, rabbit stew and chicken stakes in Polycarps backpack correspondingly. Output Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Examples Input 2 1 1 Output 4 Input 3 2 2 Output 7 Input 1 100 1 Output 3 Input 30 20 10 Output 39 Note In the first example the best day for start of the trip is Sunday. In this case, during Sunday and Monday the cat will eat fish food, during Tuesday β€” rabbit stew and during Wednesday β€” chicken stake. So, after four days of the trip all food will be eaten. In the second example Polycarp can start his trip in any day of the week. In any case there are food supplies only for one week in Polycarps backpack. In the third example Polycarp can start his trip in any day, excluding Wednesday, Saturday and Sunday. In this case, the cat will eat three different dishes in three days. Nevertheless that after three days of a trip there will be 99 portions of rabbit stew in a backpack, can cannot eat anything in fourth day of a trip. Tags: implementation, math Correct Solution: ``` a,b,c = map(int,input().strip().split()) ans = 0 basi = min(c//2,min(b//2,a//3)) #print(basi) aa = a- 3*basi bb = b - 2*basi cc = c - 2*basi mp = {0:'aa',1:'aa',2:'bb',3:'cc',4:'aa',5:'cc',6:'bb'} #print(aa,bb,cc) for i in range(7): aaa = aa bbb = bb ccc = cc an = 0 for j in range(i,i+15): if mp[j%7]=='aa': aaa-=1 if mp[j%7]=='bb': bbb-=1 if mp[j%7]=='cc': ccc-=1 if aaa<0 or bbb<0 or ccc<0: break else: an+=1 ans = max(ans,basi*7+an) print(ans) ```
105,309
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food: * on Mondays, Thursdays and Sundays he eats fish food; * on Tuesdays and Saturdays he eats rabbit stew; * on other days of week he eats chicken stake. Polycarp plans to go on a trip and already packed his backpack. His backpack contains: * a daily rations of fish food; * b daily rations of rabbit stew; * c daily rations of chicken stakes. Polycarp has to choose such day of the week to start his trip that his cat can eat without additional food purchases as long as possible. Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Input The first line of the input contains three positive integers a, b and c (1 ≀ a, b, c ≀ 7β‹…10^8) β€” the number of daily rations of fish food, rabbit stew and chicken stakes in Polycarps backpack correspondingly. Output Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Examples Input 2 1 1 Output 4 Input 3 2 2 Output 7 Input 1 100 1 Output 3 Input 30 20 10 Output 39 Note In the first example the best day for start of the trip is Sunday. In this case, during Sunday and Monday the cat will eat fish food, during Tuesday β€” rabbit stew and during Wednesday β€” chicken stake. So, after four days of the trip all food will be eaten. In the second example Polycarp can start his trip in any day of the week. In any case there are food supplies only for one week in Polycarps backpack. In the third example Polycarp can start his trip in any day, excluding Wednesday, Saturday and Sunday. In this case, the cat will eat three different dishes in three days. Nevertheless that after three days of a trip there will be 99 portions of rabbit stew in a backpack, can cannot eat anything in fourth day of a trip. Tags: implementation, math Correct Solution: ``` [a,b,c] = [int(x) for x in input().split()] def test(a,b,c) : k = 0 if min(a,b,c) == c: if a == 1 and b == 1 : k = 3 elif a == 1 and b == 2 : k = 3 elif a == 1 and b > 2 : k = 3 elif a == 2 and b == 1 : k = 4 elif a == 2 and b > 1 : k = 5 elif a > 2 and b == 1 : k = 5 else : k = 6 elif min(a,b,c) == b : if a == 1 and c == 1 : k = 3 elif a == 1 and c ==2 : k = 4 elif a == 1 and c >=2 : k = 4 elif a == 2 and c == 1: k = 4 elif a == 2 and c > 1 : k = 4 elif a > 2 and c == 1 : k = 5 else : k = 6 elif min(a,b,c) == a : if a == 1: if b == 1 and c == 1 : k = 3 elif b == 1 and c ==2 : k = 4 elif b == 1 and c >=2 : k = 4 elif b == 2 and c == 1: k = 3 elif b == 2 and c > 1 : k = 5 elif b > 2 and c == 1 : k = 3 else : k = 5 elif a == 2 : if b == 1 and c == 1 : k = 4 elif b == 1 and c ==2 : k = 5 elif b == 1 and c >=2 : k = 5 elif b == 2 and c == 1: k = 5 elif b == 2 and c > 1 : k = 6 elif b > 2 and c == 1 : k = 5 else : k = 6 return k if a < 3 or b < 2 or c < 2 : print(test(a,b,c)) else : m = (min((a//3) ,(b//2), (c//2)) ) a = a - (m*3) b = b - (m*2) c = c - (m*2) m = m*7 if a == 0 : if min(b,c) >= 1: print(m+2) elif min(b,c) == 0 and max(b,c)== 1 : print(m+1) else : print(m) elif b == 0: if min(a,c) >= 2 : print(m+3) elif c == 2 and a == 1: print(m+3) elif c== 1 and a >= 1 : print(m+2) elif c== 1 and a == 0: print(m+1) elif c== 0 and a >= 2: print(m+2) elif c==0 and a == 1: print(m+1) elif c==0 and a == 0: print(m) elif c == 0 : if min(a,b) >= 2 : print(m+4) elif b == 2 and a == 1: print(m+2) elif b== 1 and a >= 1 : print(m+3) elif b== 1 and a == 0: print(m+1) elif b== 0 and a >= 2: print(m+1) elif b==0 and a == 1: print(m+1) elif b==0 and a == 0: print(m) else : print(test(a,b,c) + m) ```
105,310
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food: * on Mondays, Thursdays and Sundays he eats fish food; * on Tuesdays and Saturdays he eats rabbit stew; * on other days of week he eats chicken stake. Polycarp plans to go on a trip and already packed his backpack. His backpack contains: * a daily rations of fish food; * b daily rations of rabbit stew; * c daily rations of chicken stakes. Polycarp has to choose such day of the week to start his trip that his cat can eat without additional food purchases as long as possible. Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Input The first line of the input contains three positive integers a, b and c (1 ≀ a, b, c ≀ 7β‹…10^8) β€” the number of daily rations of fish food, rabbit stew and chicken stakes in Polycarps backpack correspondingly. Output Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Examples Input 2 1 1 Output 4 Input 3 2 2 Output 7 Input 1 100 1 Output 3 Input 30 20 10 Output 39 Note In the first example the best day for start of the trip is Sunday. In this case, during Sunday and Monday the cat will eat fish food, during Tuesday β€” rabbit stew and during Wednesday β€” chicken stake. So, after four days of the trip all food will be eaten. In the second example Polycarp can start his trip in any day of the week. In any case there are food supplies only for one week in Polycarps backpack. In the third example Polycarp can start his trip in any day, excluding Wednesday, Saturday and Sunday. In this case, the cat will eat three different dishes in three days. Nevertheless that after three days of a trip there will be 99 portions of rabbit stew in a backpack, can cannot eat anything in fourth day of a trip. Tags: implementation, math Correct Solution: ``` #!/usr/bin/env python3 # -*- coding: utf-8 -*- ################################## # University of Wisconsin-Madison # Author: Yaqi Zhang ################################## # This module contains ################################## # standard library import sys import math def main(): nums = list(map(int, input().split())) days = [{0, 3, 6}, {1, 5}, {2, 4}] ans = -math.inf for i in range(7): mn = math.inf for num, day in zip(nums, days): cnt = 0 cur = i while True: if cur == 0: cnt += num // len(day) * 7 num = num % len(day) if cur in day: num -= 1 if num < 0: break cnt += 1 cur = (cur + 1) % 7 mn = min(cnt, mn) ans = max(ans, mn) print(ans) if __name__ == "__main__": main() ```
105,311
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food: * on Mondays, Thursdays and Sundays he eats fish food; * on Tuesdays and Saturdays he eats rabbit stew; * on other days of week he eats chicken stake. Polycarp plans to go on a trip and already packed his backpack. His backpack contains: * a daily rations of fish food; * b daily rations of rabbit stew; * c daily rations of chicken stakes. Polycarp has to choose such day of the week to start his trip that his cat can eat without additional food purchases as long as possible. Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Input The first line of the input contains three positive integers a, b and c (1 ≀ a, b, c ≀ 7β‹…10^8) β€” the number of daily rations of fish food, rabbit stew and chicken stakes in Polycarps backpack correspondingly. Output Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Examples Input 2 1 1 Output 4 Input 3 2 2 Output 7 Input 1 100 1 Output 3 Input 30 20 10 Output 39 Note In the first example the best day for start of the trip is Sunday. In this case, during Sunday and Monday the cat will eat fish food, during Tuesday β€” rabbit stew and during Wednesday β€” chicken stake. So, after four days of the trip all food will be eaten. In the second example Polycarp can start his trip in any day of the week. In any case there are food supplies only for one week in Polycarps backpack. In the third example Polycarp can start his trip in any day, excluding Wednesday, Saturday and Sunday. In this case, the cat will eat three different dishes in three days. Nevertheless that after three days of a trip there will be 99 portions of rabbit stew in a backpack, can cannot eat anything in fourth day of a trip. Tags: implementation, math Correct Solution: ``` ''' Author: Ken Problems: 1154C ''' eat = [] eat = list(map(int, input().split())) temp = min(int(eat[0]/3), int(eat[1]/2), int(eat[2]/2)) ans = temp*7 eat[0] -= temp*3 eat[1] -= temp*2 eat[2] -= temp*2 day = [0, 1, 2, 0, 2, 1, 0] cir = -1 for i in range(7): count = 0 temp = list.copy(eat) for j in range(7): # print(eat) if temp[day[(i+j) % 7]] == 0: cir = max(cir, count) break count += 1 temp[day[(i+j) % 7]] -= 1 print(ans+cir) # 1 4 7 # 2 6 # 3 5 # abcacba ```
105,312
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food: * on Mondays, Thursdays and Sundays he eats fish food; * on Tuesdays and Saturdays he eats rabbit stew; * on other days of week he eats chicken stake. Polycarp plans to go on a trip and already packed his backpack. His backpack contains: * a daily rations of fish food; * b daily rations of rabbit stew; * c daily rations of chicken stakes. Polycarp has to choose such day of the week to start his trip that his cat can eat without additional food purchases as long as possible. Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Input The first line of the input contains three positive integers a, b and c (1 ≀ a, b, c ≀ 7β‹…10^8) β€” the number of daily rations of fish food, rabbit stew and chicken stakes in Polycarps backpack correspondingly. Output Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Examples Input 2 1 1 Output 4 Input 3 2 2 Output 7 Input 1 100 1 Output 3 Input 30 20 10 Output 39 Note In the first example the best day for start of the trip is Sunday. In this case, during Sunday and Monday the cat will eat fish food, during Tuesday β€” rabbit stew and during Wednesday β€” chicken stake. So, after four days of the trip all food will be eaten. In the second example Polycarp can start his trip in any day of the week. In any case there are food supplies only for one week in Polycarps backpack. In the third example Polycarp can start his trip in any day, excluding Wednesday, Saturday and Sunday. In this case, the cat will eat three different dishes in three days. Nevertheless that after three days of a trip there will be 99 portions of rabbit stew in a backpack, can cannot eat anything in fourth day of a trip. Submitted Solution: ``` # -*- coding: utf-8 -*- """ Created on Wed Apr 17 06:57:09 2019 @author: sharath """ l = list(map(int, input().split())) x = min(l[0]//3, l[1]//2, l[2]//2) l[0] -= 3*x l[1] -= 2*x l[2] -= 2*x x *= 7 lista=[0, 1, 2, 0, 2, 1, 0]*2 m=c=0 a=[i for i in l] for i in lista: if l[i]: c+=1 l[i]-=1 else: c=0 l=[j for j in a] m=max(m,c) print(x+m) ``` Yes
105,313
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food: * on Mondays, Thursdays and Sundays he eats fish food; * on Tuesdays and Saturdays he eats rabbit stew; * on other days of week he eats chicken stake. Polycarp plans to go on a trip and already packed his backpack. His backpack contains: * a daily rations of fish food; * b daily rations of rabbit stew; * c daily rations of chicken stakes. Polycarp has to choose such day of the week to start his trip that his cat can eat without additional food purchases as long as possible. Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Input The first line of the input contains three positive integers a, b and c (1 ≀ a, b, c ≀ 7β‹…10^8) β€” the number of daily rations of fish food, rabbit stew and chicken stakes in Polycarps backpack correspondingly. Output Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Examples Input 2 1 1 Output 4 Input 3 2 2 Output 7 Input 1 100 1 Output 3 Input 30 20 10 Output 39 Note In the first example the best day for start of the trip is Sunday. In this case, during Sunday and Monday the cat will eat fish food, during Tuesday β€” rabbit stew and during Wednesday β€” chicken stake. So, after four days of the trip all food will be eaten. In the second example Polycarp can start his trip in any day of the week. In any case there are food supplies only for one week in Polycarps backpack. In the third example Polycarp can start his trip in any day, excluding Wednesday, Saturday and Sunday. In this case, the cat will eat three different dishes in three days. Nevertheless that after three days of a trip there will be 99 portions of rabbit stew in a backpack, can cannot eat anything in fourth day of a trip. Submitted Solution: ``` # -*- coding: utf-8 -*- """ Created on Tue Apr 16 16:37:40 2019 @author: Acer """ def solve(a,b,c): """ input is a list s """ small = min(int(a/3),int(b/2),int(c/2)); totalDay = small*7; a = a - small*3; b = b - small*2; c = c - small*2; if (a == 0): totalDay = totalDay + int(b > 0) + int(c > 0); elif(a == 1): totalDay = totalDay + 1; if (c > 1): totalDay = totalDay + 2; totalDay = totalDay + int(b > 0) + int(b > 1); elif (c > 0): totalDay = totalDay + 1; totalDay = totalDay + int(b > 0); else: totalDay = totalDay + int(b > 0); elif(a == 2): totalDay = totalDay + 2; if (b > 1): totalDay = totalDay + 2 + int(c > 0) + int(c > 1); elif (b > 0): totalDay = totalDay + 1 + int(c > 1) + int(c > 0); else: if (c > 2): totalDay = totalDay + 1; else: if (b != 0) and (c != 0): totalDay = totalDay + 3 + 2 + int(b > 1) + int(c > 1); elif (b == 0): totalDay = max(totalDay + 1 + int(c > 0) + int(c > 1), totalDay + 2); elif (c == 0): totalDay = totalDay + 2 + int(b > 0) + int(b > 1); else: totalDay = totalDay + 2; return totalDay; if __name__ == "__main__": """the solve(*args) structure is needed for testing purporses""" a,b,c = [int(s) for s in input().split()]; print(solve(a,b,c)); ``` Yes
105,314
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food: * on Mondays, Thursdays and Sundays he eats fish food; * on Tuesdays and Saturdays he eats rabbit stew; * on other days of week he eats chicken stake. Polycarp plans to go on a trip and already packed his backpack. His backpack contains: * a daily rations of fish food; * b daily rations of rabbit stew; * c daily rations of chicken stakes. Polycarp has to choose such day of the week to start his trip that his cat can eat without additional food purchases as long as possible. Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Input The first line of the input contains three positive integers a, b and c (1 ≀ a, b, c ≀ 7β‹…10^8) β€” the number of daily rations of fish food, rabbit stew and chicken stakes in Polycarps backpack correspondingly. Output Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Examples Input 2 1 1 Output 4 Input 3 2 2 Output 7 Input 1 100 1 Output 3 Input 30 20 10 Output 39 Note In the first example the best day for start of the trip is Sunday. In this case, during Sunday and Monday the cat will eat fish food, during Tuesday β€” rabbit stew and during Wednesday β€” chicken stake. So, after four days of the trip all food will be eaten. In the second example Polycarp can start his trip in any day of the week. In any case there are food supplies only for one week in Polycarps backpack. In the third example Polycarp can start his trip in any day, excluding Wednesday, Saturday and Sunday. In this case, the cat will eat three different dishes in three days. Nevertheless that after three days of a trip there will be 99 portions of rabbit stew in a backpack, can cannot eat anything in fourth day of a trip. Submitted Solution: ``` a,b,c = map(int,input().split()) A = ["a","a","b","c","a","c","b"] x = a//3;y=b//2;z=c//2 ans = min(x,y,z)*7 #print(x,y,z,min(x,y,z)) s = min(x,y,z) x -= s y -= s z -= s #print(x,y,z) a = x*3 + a%3;b = y*2 +b%2;c = z*2+c%2 #print(a,b,c) i = 0 fin_ans = 0 while(i<7): j=i;t = 0 p = a;q=b;r=c while(True): #print(p,q,r,t) if(A[j%7]=="a"): p-=1 elif(A[j%7]=="b"): q-=1 elif(A[j%7]=="c"): r-=1 if(p<0 or q<0 or r<0): break j+=1;t+=1 fin_ans = max(fin_ans,t) i+=1 print(ans+fin_ans) ``` Yes
105,315
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food: * on Mondays, Thursdays and Sundays he eats fish food; * on Tuesdays and Saturdays he eats rabbit stew; * on other days of week he eats chicken stake. Polycarp plans to go on a trip and already packed his backpack. His backpack contains: * a daily rations of fish food; * b daily rations of rabbit stew; * c daily rations of chicken stakes. Polycarp has to choose such day of the week to start his trip that his cat can eat without additional food purchases as long as possible. Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Input The first line of the input contains three positive integers a, b and c (1 ≀ a, b, c ≀ 7β‹…10^8) β€” the number of daily rations of fish food, rabbit stew and chicken stakes in Polycarps backpack correspondingly. Output Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Examples Input 2 1 1 Output 4 Input 3 2 2 Output 7 Input 1 100 1 Output 3 Input 30 20 10 Output 39 Note In the first example the best day for start of the trip is Sunday. In this case, during Sunday and Monday the cat will eat fish food, during Tuesday β€” rabbit stew and during Wednesday β€” chicken stake. So, after four days of the trip all food will be eaten. In the second example Polycarp can start his trip in any day of the week. In any case there are food supplies only for one week in Polycarps backpack. In the third example Polycarp can start his trip in any day, excluding Wednesday, Saturday and Sunday. In this case, the cat will eat three different dishes in three days. Nevertheless that after three days of a trip there will be 99 portions of rabbit stew in a backpack, can cannot eat anything in fourth day of a trip. Submitted Solution: ``` a,b,c = map(int , input().split()) fish = [0,1,4] rabbit = [2,6] chick = [3,5] x,y,z = a,b,c maxdayCount = 0 count = 0 for start in range(7) : day = start count = 0 while(x > -1 and y > -1 and z > -1): weeks = int(min(x/3 , y/2, z/2)) # x = int(x/3) + x%3 # y = int(y/2) + y%2 # z = int(z/2) + z%2 count += 7 * weeks x -= 3 * weeks y -= 2 * weeks z -= 2 * weeks # print(count , x, y ,z) if day in fish : x -= 1 elif day in rabbit : y -= 1 else: z -= 1 if (x < 0 or y < 0 or z < 0): break day += 1 count += 1 day = day % 7 if count > maxdayCount : maxdayCount = count x,y,z = a,b,c print(maxdayCount) ``` Yes
105,316
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food: * on Mondays, Thursdays and Sundays he eats fish food; * on Tuesdays and Saturdays he eats rabbit stew; * on other days of week he eats chicken stake. Polycarp plans to go on a trip and already packed his backpack. His backpack contains: * a daily rations of fish food; * b daily rations of rabbit stew; * c daily rations of chicken stakes. Polycarp has to choose such day of the week to start his trip that his cat can eat without additional food purchases as long as possible. Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Input The first line of the input contains three positive integers a, b and c (1 ≀ a, b, c ≀ 7β‹…10^8) β€” the number of daily rations of fish food, rabbit stew and chicken stakes in Polycarps backpack correspondingly. Output Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Examples Input 2 1 1 Output 4 Input 3 2 2 Output 7 Input 1 100 1 Output 3 Input 30 20 10 Output 39 Note In the first example the best day for start of the trip is Sunday. In this case, during Sunday and Monday the cat will eat fish food, during Tuesday β€” rabbit stew and during Wednesday β€” chicken stake. So, after four days of the trip all food will be eaten. In the second example Polycarp can start his trip in any day of the week. In any case there are food supplies only for one week in Polycarps backpack. In the third example Polycarp can start his trip in any day, excluding Wednesday, Saturday and Sunday. In this case, the cat will eat three different dishes in three days. Nevertheless that after three days of a trip there will be 99 portions of rabbit stew in a backpack, can cannot eat anything in fourth day of a trip. Submitted Solution: ``` x = list(map(int, input().split())) # if x == [0, 1, 1] or x == [1, 0, 1]: # print(2) # elif x == [0, 0, 1] or x == [0, 1, 0]: # print(1) # elif x == [1, 2, 2]: # # print(5) # pass # elif x == [1, 1, 2]: # # print(4) # pass # else: d = {0: 3, 1: 2, 2: 2} a = [x[i] // d[i] for i in range(3)] weeks = min(a) least = a.index(min(a)) b = [x[i] - d[i] * weeks for i in range(3)] days = weeks * 7 p = [0, 1, 2, 0, 2, 1, 0] if weeks > 0: i = len(p) - 1 while i >= 0 and b[p[i]] > 0: days += 1 b[p[i]] -= 1 i -= 1 i = 0 while i < len(p) and b[p[i]] > 0: days += 1 b[p[i]] -= 1 i += 1 else: for j in range(7): b = [x[i] - d[i] * weeks for i in range(3)] cd = 0 while j < len(p) and b[p[j]] > 0: cd += 1 b[p[j]] -= 1 j += 1 if j == len(p) and b[0] > 0: cd += 1 if b[1] > 0: cd += 1 if b[2] > 0: cd += 1 days = max(days, cd) # if x == [3, 1, 1]: # print(5) # else: # print(days) # 3 2 1 -> 6 print(days) ``` No
105,317
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food: * on Mondays, Thursdays and Sundays he eats fish food; * on Tuesdays and Saturdays he eats rabbit stew; * on other days of week he eats chicken stake. Polycarp plans to go on a trip and already packed his backpack. His backpack contains: * a daily rations of fish food; * b daily rations of rabbit stew; * c daily rations of chicken stakes. Polycarp has to choose such day of the week to start his trip that his cat can eat without additional food purchases as long as possible. Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Input The first line of the input contains three positive integers a, b and c (1 ≀ a, b, c ≀ 7β‹…10^8) β€” the number of daily rations of fish food, rabbit stew and chicken stakes in Polycarps backpack correspondingly. Output Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Examples Input 2 1 1 Output 4 Input 3 2 2 Output 7 Input 1 100 1 Output 3 Input 30 20 10 Output 39 Note In the first example the best day for start of the trip is Sunday. In this case, during Sunday and Monday the cat will eat fish food, during Tuesday β€” rabbit stew and during Wednesday β€” chicken stake. So, after four days of the trip all food will be eaten. In the second example Polycarp can start his trip in any day of the week. In any case there are food supplies only for one week in Polycarps backpack. In the third example Polycarp can start his trip in any day, excluding Wednesday, Saturday and Sunday. In this case, the cat will eat three different dishes in three days. Nevertheless that after three days of a trip there will be 99 portions of rabbit stew in a backpack, can cannot eat anything in fourth day of a trip. Submitted Solution: ``` import math list1=list(map(int,input().split())) list2=[list1[0]/3,list1[1]/2,list1[2]/2] list3=[] n=list2.index(min(list2)) m=math.floor(list2[n]) list3.append(list1[0]-3*m) list3.append(list1[1]-2*m) list3.append(list1[2]-2*m) food=[0,1,2,0,2,1,0] day = [0,0,0,0,0,0,0] for i in range(7): for j in range(7): if list3[food[(j+i)%7]] != 0: list3[food[(j+i)%7]] -= 1 day[i] += 1 else: break print(m*7+max(day)) ``` No
105,318
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food: * on Mondays, Thursdays and Sundays he eats fish food; * on Tuesdays and Saturdays he eats rabbit stew; * on other days of week he eats chicken stake. Polycarp plans to go on a trip and already packed his backpack. His backpack contains: * a daily rations of fish food; * b daily rations of rabbit stew; * c daily rations of chicken stakes. Polycarp has to choose such day of the week to start his trip that his cat can eat without additional food purchases as long as possible. Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Input The first line of the input contains three positive integers a, b and c (1 ≀ a, b, c ≀ 7β‹…10^8) β€” the number of daily rations of fish food, rabbit stew and chicken stakes in Polycarps backpack correspondingly. Output Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Examples Input 2 1 1 Output 4 Input 3 2 2 Output 7 Input 1 100 1 Output 3 Input 30 20 10 Output 39 Note In the first example the best day for start of the trip is Sunday. In this case, during Sunday and Monday the cat will eat fish food, during Tuesday β€” rabbit stew and during Wednesday β€” chicken stake. So, after four days of the trip all food will be eaten. In the second example Polycarp can start his trip in any day of the week. In any case there are food supplies only for one week in Polycarps backpack. In the third example Polycarp can start his trip in any day, excluding Wednesday, Saturday and Sunday. In this case, the cat will eat three different dishes in three days. Nevertheless that after three days of a trip there will be 99 portions of rabbit stew in a backpack, can cannot eat anything in fourth day of a trip. Submitted Solution: ``` ip = [int(i) for i in input().split()] answers = [] store = ip.copy() def fun(start): ans = 0 if start == 0: for i in range(sum(ip)): day = i%7 if day == 0 or day == 3 or day == 6: if ip[0] == 0: break ip[0]-=1 ans+=1 elif day == 1 or day == 5: if ip[1] == 0: break ip[1]-=1 ans+=1 else: if ip[2] == 0: break ip[2]-=1 ans+=1 return ans if start == 1: for i in range(sum(ip)): day = i%7 if day == 2 or day == 5 or day == 6: if ip[0] == 0: break ip[0]-=1 ans+=1 elif day == 0 or day == 4: if ip[1] == 0: break ip[1]-=1 ans+=1 else: if ip[2] == 0: break ip[2]-=1 ans+=1 return ans if start == 2: for i in range(sum(ip)): day = i%7 if day == 1 or day == 4 or day == 5: if ip[0] == 0: break ip[0]-=1 ans+=1 elif day == 3 or day == 6: if ip[1] == 0: break ip[1]-=1 ans+=1 else: if ip[2] == 0: break ip[2]-=1 ans+=1 return ans if start == 3: for i in range(sum(ip)): day = i%7 if day == 0 or day == 3 or day == 4: if ip[0] == 0: break ip[0]-=1 ans+=1 elif day == 2 or day == 5: if ip[1] == 0: break ip[1]-=1 ans+=1 else: if ip[2] == 0: break ip[2]-=1 ans+=1 return ans if start == 4: for i in range(sum(ip)): day = i%7 if day == 6 or day == 2 or day == 3: if ip[0] == 0: break ip[0]-=1 ans+=1 elif day == 1 or day == 4: if ip[1] == 0: break ip[1]-=1 ans+=1 else: if ip[2] == 0: break ip[2]-=1 ans+=1 return ans if start == 5: for i in range(sum(ip)): day = i%7 if day == 5 or day == 1 or day == 2: if ip[0] == 0: break ip[0]-=1 ans+=1 elif day == 0 or day == 3: if ip[1] == 0: break ip[1]-=1 ans+=1 else: if ip[2] == 0: break ip[2]-=1 ans+=1 return ans if start == 6: for i in range(sum(ip)): day = i%7 if day == 4 or day == 0 or day == 1: if ip[0] == 0: break ip[0]-=1 ans+=1 elif day == 6 or day == 2: if ip[1] == 0: break ip[1]-=1 ans+=1 else: if ip[2] == 0: break ip[2]-=1 ans+=1 return ans ip = store.copy() for i in range(7): answers.append(fun(i)) print(max(answers)) ``` No
105,319
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food: * on Mondays, Thursdays and Sundays he eats fish food; * on Tuesdays and Saturdays he eats rabbit stew; * on other days of week he eats chicken stake. Polycarp plans to go on a trip and already packed his backpack. His backpack contains: * a daily rations of fish food; * b daily rations of rabbit stew; * c daily rations of chicken stakes. Polycarp has to choose such day of the week to start his trip that his cat can eat without additional food purchases as long as possible. Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Input The first line of the input contains three positive integers a, b and c (1 ≀ a, b, c ≀ 7β‹…10^8) β€” the number of daily rations of fish food, rabbit stew and chicken stakes in Polycarps backpack correspondingly. Output Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Examples Input 2 1 1 Output 4 Input 3 2 2 Output 7 Input 1 100 1 Output 3 Input 30 20 10 Output 39 Note In the first example the best day for start of the trip is Sunday. In this case, during Sunday and Monday the cat will eat fish food, during Tuesday β€” rabbit stew and during Wednesday β€” chicken stake. So, after four days of the trip all food will be eaten. In the second example Polycarp can start his trip in any day of the week. In any case there are food supplies only for one week in Polycarps backpack. In the third example Polycarp can start his trip in any day, excluding Wednesday, Saturday and Sunday. In this case, the cat will eat three different dishes in three days. Nevertheless that after three days of a trip there will be 99 portions of rabbit stew in a backpack, can cannot eat anything in fourth day of a trip. Submitted Solution: ``` import math x = list(map(int,input().split())) if sum(x) <= 7: print(sum(x)) else: if min(x) * 3 <= 7: print(min(x) * 3) else: r = [] r.append(x[0]/3) r.append(x[1]/2) r.append(x[2]/2) if r[0] == min(r): hasil = math.floor(x[0]/3) sisa1 = x[1] - (hasil * 2) sisa2 = x[2] - (hasil * 2) #print(sisa1,sisa2) rem = x[0] % 3 if rem == 0: if sisa1 > 1 and sisa2 > 1: print(7 * hasil + 2) else: print(7 * hasil + 1) elif rem == 1: if sisa1 > 2 and sisa2 > 2: print(7 * hasil + 5) else: print(7 * hasil + 3) else: print(7 * hasil + 6) elif r[1] == min(r): hasil = math.floor(x[1]/2) sisa0 = x[0] - (hasil * 3) sisa2 = x[2] - (hasil * 2) #print(sisa0,sisa2) rem = x[1] % 2 if rem == 0: if sisa0 > 1 and sisa2 > 2: print(7 * hasil + 3) else: print(7 * hasil + sisa0 + sisa2) else: if sisa0 > 3 and sisa2 > 2: print(7 * hasil + 6) else: print(7 * hasil + rem + sisa0 + sisa2) else: hasil = math.floor(x[2]/2) sisa0 = x[0] - (hasil * 3) sisa1 = x[1] - (hasil * 2) #print(sisa0,sisa1) rem = x[2] % 2 if rem == 0: if sisa0 > 2 and sisa1 > 2: print(7 * hasil + 4) else: print(7 * hasil + sisa0 + sisa1) else: if sisa0 > 2 and sisa1 > 3: print(7 * hasil + 6) else: print(7 * hasil + rem + sisa0 + sisa1) ``` No
105,320
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an integer n. You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: 1. Replace n with n/2 if n is divisible by 2; 2. Replace n with 2n/3 if n is divisible by 3; 3. Replace n with 4n/5 if n is divisible by 5. For example, you can replace 30 with 15 using the first operation, with 20 using the second operation or with 24 using the third operation. Your task is to find the minimum number of moves required to obtain 1 from n or say that it is impossible to do it. You have to answer q independent queries. Input The first line of the input contains one integer q (1 ≀ q ≀ 1000) β€” the number of queries. The next q lines contain the queries. For each query you are given the integer number n (1 ≀ n ≀ 10^{18}). Output Print the answer for each query on a new line. If it is impossible to obtain 1 from n, print -1. Otherwise, print the minimum number of moves required to do it. Example Input 7 1 10 25 30 14 27 1000000000000000000 Output 0 4 6 6 -1 6 72 Tags: brute force, greedy, implementation Correct Solution: ``` import sys q=int(sys.stdin.readline()) for _ in range(q): n= int(sys.stdin.readline()) count =0 while n>1: if n%2==0: n//=2 count+=1 elif n%3==0: n//=3 n*=2 count+=1 elif n%5==0: n//=5 n*=4 count+=1 else: count=-1 break print(count) ```
105,321
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an integer n. You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: 1. Replace n with n/2 if n is divisible by 2; 2. Replace n with 2n/3 if n is divisible by 3; 3. Replace n with 4n/5 if n is divisible by 5. For example, you can replace 30 with 15 using the first operation, with 20 using the second operation or with 24 using the third operation. Your task is to find the minimum number of moves required to obtain 1 from n or say that it is impossible to do it. You have to answer q independent queries. Input The first line of the input contains one integer q (1 ≀ q ≀ 1000) β€” the number of queries. The next q lines contain the queries. For each query you are given the integer number n (1 ≀ n ≀ 10^{18}). Output Print the answer for each query on a new line. If it is impossible to obtain 1 from n, print -1. Otherwise, print the minimum number of moves required to do it. Example Input 7 1 10 25 30 14 27 1000000000000000000 Output 0 4 6 6 -1 6 72 Tags: brute force, greedy, implementation Correct Solution: ``` import sys q = int(input()) for i in range(q): #print ('i:',i) n = int(input()) cnt = 0 while n > 1: if n%2==0: n = n // 2 cnt += 1 elif n%3 ==0: n = (2*n) // 3 cnt += 1 elif n%5 ==0: n = (n*4) // 5 cnt += 1 else: cnt = -1 break print (cnt) ```
105,322
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an integer n. You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: 1. Replace n with n/2 if n is divisible by 2; 2. Replace n with 2n/3 if n is divisible by 3; 3. Replace n with 4n/5 if n is divisible by 5. For example, you can replace 30 with 15 using the first operation, with 20 using the second operation or with 24 using the third operation. Your task is to find the minimum number of moves required to obtain 1 from n or say that it is impossible to do it. You have to answer q independent queries. Input The first line of the input contains one integer q (1 ≀ q ≀ 1000) β€” the number of queries. The next q lines contain the queries. For each query you are given the integer number n (1 ≀ n ≀ 10^{18}). Output Print the answer for each query on a new line. If it is impossible to obtain 1 from n, print -1. Otherwise, print the minimum number of moves required to do it. Example Input 7 1 10 25 30 14 27 1000000000000000000 Output 0 4 6 6 -1 6 72 Tags: brute force, greedy, implementation Correct Solution: ``` q = int(input()) for _ in range(q): n = int(input()) count = 0 while n!=1: if n%5 == 0: n//=5 count += 3 elif n%3 == 0: n//=3 count+=2 elif n%2 == 0: n//= 2 count +=1 else: print (-1) break else: print (count) ```
105,323
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an integer n. You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: 1. Replace n with n/2 if n is divisible by 2; 2. Replace n with 2n/3 if n is divisible by 3; 3. Replace n with 4n/5 if n is divisible by 5. For example, you can replace 30 with 15 using the first operation, with 20 using the second operation or with 24 using the third operation. Your task is to find the minimum number of moves required to obtain 1 from n or say that it is impossible to do it. You have to answer q independent queries. Input The first line of the input contains one integer q (1 ≀ q ≀ 1000) β€” the number of queries. The next q lines contain the queries. For each query you are given the integer number n (1 ≀ n ≀ 10^{18}). Output Print the answer for each query on a new line. If it is impossible to obtain 1 from n, print -1. Otherwise, print the minimum number of moves required to do it. Example Input 7 1 10 25 30 14 27 1000000000000000000 Output 0 4 6 6 -1 6 72 Tags: brute force, greedy, implementation Correct Solution: ``` for _ in range(int(input())): n = int(input()) cnt = 0 while n > 1: if n%2 == 0: cnt += 1 n //= 2 elif n%3 == 0: cnt += 1 n = (2 * n // 3) elif n%5 == 0: cnt += 1 n = (4 * n // 5) else: cnt = -1 break print(cnt) ```
105,324
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an integer n. You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: 1. Replace n with n/2 if n is divisible by 2; 2. Replace n with 2n/3 if n is divisible by 3; 3. Replace n with 4n/5 if n is divisible by 5. For example, you can replace 30 with 15 using the first operation, with 20 using the second operation or with 24 using the third operation. Your task is to find the minimum number of moves required to obtain 1 from n or say that it is impossible to do it. You have to answer q independent queries. Input The first line of the input contains one integer q (1 ≀ q ≀ 1000) β€” the number of queries. The next q lines contain the queries. For each query you are given the integer number n (1 ≀ n ≀ 10^{18}). Output Print the answer for each query on a new line. If it is impossible to obtain 1 from n, print -1. Otherwise, print the minimum number of moves required to do it. Example Input 7 1 10 25 30 14 27 1000000000000000000 Output 0 4 6 6 -1 6 72 Tags: brute force, greedy, implementation Correct Solution: ``` q=int(input()) for query in range(q): n=int(input()) ANS=0 while n>1: if n%3==0: ANS+=1 n=n//3*2 elif n%5==0: ANS+=1 n=n//5*4 elif n%2==0: ANS+=1 n//=2 else: print(-1) break else: print(ANS) ```
105,325
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an integer n. You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: 1. Replace n with n/2 if n is divisible by 2; 2. Replace n with 2n/3 if n is divisible by 3; 3. Replace n with 4n/5 if n is divisible by 5. For example, you can replace 30 with 15 using the first operation, with 20 using the second operation or with 24 using the third operation. Your task is to find the minimum number of moves required to obtain 1 from n or say that it is impossible to do it. You have to answer q independent queries. Input The first line of the input contains one integer q (1 ≀ q ≀ 1000) β€” the number of queries. The next q lines contain the queries. For each query you are given the integer number n (1 ≀ n ≀ 10^{18}). Output Print the answer for each query on a new line. If it is impossible to obtain 1 from n, print -1. Otherwise, print the minimum number of moves required to do it. Example Input 7 1 10 25 30 14 27 1000000000000000000 Output 0 4 6 6 -1 6 72 Tags: brute force, greedy, implementation Correct Solution: ``` def to(n): if n==1:return 0 c=0 while n>1: if n%2==0: n=n//2;c+=1 elif n%3==0: n=(n//3)*2;c+=1 elif n%5==0: n=(n//5)*4;c+=1 else: return -1 break return c for _ in range(int(input())): n=int(input()) print(to(n)) ```
105,326
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an integer n. You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: 1. Replace n with n/2 if n is divisible by 2; 2. Replace n with 2n/3 if n is divisible by 3; 3. Replace n with 4n/5 if n is divisible by 5. For example, you can replace 30 with 15 using the first operation, with 20 using the second operation or with 24 using the third operation. Your task is to find the minimum number of moves required to obtain 1 from n or say that it is impossible to do it. You have to answer q independent queries. Input The first line of the input contains one integer q (1 ≀ q ≀ 1000) β€” the number of queries. The next q lines contain the queries. For each query you are given the integer number n (1 ≀ n ≀ 10^{18}). Output Print the answer for each query on a new line. If it is impossible to obtain 1 from n, print -1. Otherwise, print the minimum number of moves required to do it. Example Input 7 1 10 25 30 14 27 1000000000000000000 Output 0 4 6 6 -1 6 72 Tags: brute force, greedy, implementation Correct Solution: ``` # import sys # sys.stdin=open("input.in","r") for i in range(int(input())): a=int(input()) c=0 while a>1: if a%2==0: a=a//2 c+=1 elif a%3==0: a=2*(a//3) c+=1 elif a%5==0: a=4*(a//5) c+=1 else: c=-1 break print(c) ```
105,327
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an integer n. You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: 1. Replace n with n/2 if n is divisible by 2; 2. Replace n with 2n/3 if n is divisible by 3; 3. Replace n with 4n/5 if n is divisible by 5. For example, you can replace 30 with 15 using the first operation, with 20 using the second operation or with 24 using the third operation. Your task is to find the minimum number of moves required to obtain 1 from n or say that it is impossible to do it. You have to answer q independent queries. Input The first line of the input contains one integer q (1 ≀ q ≀ 1000) β€” the number of queries. The next q lines contain the queries. For each query you are given the integer number n (1 ≀ n ≀ 10^{18}). Output Print the answer for each query on a new line. If it is impossible to obtain 1 from n, print -1. Otherwise, print the minimum number of moves required to do it. Example Input 7 1 10 25 30 14 27 1000000000000000000 Output 0 4 6 6 -1 6 72 Tags: brute force, greedy, implementation Correct Solution: ``` def mul5(num): if num%5==0: return 4*(num//5) def mul2(num): if num%2 ==0: return num//2 def mul3(num): if num%3 == 0: return 2*(num//3) #check 2 then 3 then 5 while True: try: val = int(input( )) num=[0]*val break except: print("this is not a valid input") for i in range(0, val): num[i]= int(input()) for x in range(0, val): count=0 if num[x]==1: print(0) else: while (num[x])/5 >=1 and num[x]%5==0: num[x] = mul5(num[x]) count +=1 while num[x]/3>=1 and num[x]%3==0: num[x] = mul3(num[x]) count +=1 while num[x]/2>=1 and num[x]%2==0: num[x] = mul2(num[x]) count +=1 if count>0 and num[x] ==1: count= count else: count=-1 print(count) ```
105,328
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an integer n. You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: 1. Replace n with n/2 if n is divisible by 2; 2. Replace n with 2n/3 if n is divisible by 3; 3. Replace n with 4n/5 if n is divisible by 5. For example, you can replace 30 with 15 using the first operation, with 20 using the second operation or with 24 using the third operation. Your task is to find the minimum number of moves required to obtain 1 from n or say that it is impossible to do it. You have to answer q independent queries. Input The first line of the input contains one integer q (1 ≀ q ≀ 1000) β€” the number of queries. The next q lines contain the queries. For each query you are given the integer number n (1 ≀ n ≀ 10^{18}). Output Print the answer for each query on a new line. If it is impossible to obtain 1 from n, print -1. Otherwise, print the minimum number of moves required to do it. Example Input 7 1 10 25 30 14 27 1000000000000000000 Output 0 4 6 6 -1 6 72 Submitted Solution: ``` # cook your dish here from math import * t=int(input()) for _ in range(t): n=int(input()) if n==1: print('0') else: c=0 f=0 while n>1: if n%5==0: c=c+3 n=n//5 elif n%3==0: c=c+2 n=n//3 elif n%2==0: c=c+1 n=n//2 else: f=1 break if f==1: print('-1') else: print(c) ``` Yes
105,329
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an integer n. You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: 1. Replace n with n/2 if n is divisible by 2; 2. Replace n with 2n/3 if n is divisible by 3; 3. Replace n with 4n/5 if n is divisible by 5. For example, you can replace 30 with 15 using the first operation, with 20 using the second operation or with 24 using the third operation. Your task is to find the minimum number of moves required to obtain 1 from n or say that it is impossible to do it. You have to answer q independent queries. Input The first line of the input contains one integer q (1 ≀ q ≀ 1000) β€” the number of queries. The next q lines contain the queries. For each query you are given the integer number n (1 ≀ n ≀ 10^{18}). Output Print the answer for each query on a new line. If it is impossible to obtain 1 from n, print -1. Otherwise, print the minimum number of moves required to do it. Example Input 7 1 10 25 30 14 27 1000000000000000000 Output 0 4 6 6 -1 6 72 Submitted Solution: ``` a=int(input()) i=0 while i<a: op=0 n=int(input()) if n<=0: op=-1 else: while n!=1: if n%5==0: op+=1 n=(4*n)//5 elif n%3==0: op+=1 n=(2*n)//3 elif n%2==0: op+=1 n=n//2 else: op=-1 break print(op) i+=1 ``` Yes
105,330
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an integer n. You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: 1. Replace n with n/2 if n is divisible by 2; 2. Replace n with 2n/3 if n is divisible by 3; 3. Replace n with 4n/5 if n is divisible by 5. For example, you can replace 30 with 15 using the first operation, with 20 using the second operation or with 24 using the third operation. Your task is to find the minimum number of moves required to obtain 1 from n or say that it is impossible to do it. You have to answer q independent queries. Input The first line of the input contains one integer q (1 ≀ q ≀ 1000) β€” the number of queries. The next q lines contain the queries. For each query you are given the integer number n (1 ≀ n ≀ 10^{18}). Output Print the answer for each query on a new line. If it is impossible to obtain 1 from n, print -1. Otherwise, print the minimum number of moves required to do it. Example Input 7 1 10 25 30 14 27 1000000000000000000 Output 0 4 6 6 -1 6 72 Submitted Solution: ``` def divide(n): iter = 0 while n != 1: if n % 2 == 0: n //= 2 elif n % 3 == 0: n = n * 2//3 elif n % 5 == 0: n = n * 4//5 else: return -1 iter += 1 return iter q = int(input()) for _ in range(q): n = int(input()) print(divide(n)) ``` Yes
105,331
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an integer n. You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: 1. Replace n with n/2 if n is divisible by 2; 2. Replace n with 2n/3 if n is divisible by 3; 3. Replace n with 4n/5 if n is divisible by 5. For example, you can replace 30 with 15 using the first operation, with 20 using the second operation or with 24 using the third operation. Your task is to find the minimum number of moves required to obtain 1 from n or say that it is impossible to do it. You have to answer q independent queries. Input The first line of the input contains one integer q (1 ≀ q ≀ 1000) β€” the number of queries. The next q lines contain the queries. For each query you are given the integer number n (1 ≀ n ≀ 10^{18}). Output Print the answer for each query on a new line. If it is impossible to obtain 1 from n, print -1. Otherwise, print the minimum number of moves required to do it. Example Input 7 1 10 25 30 14 27 1000000000000000000 Output 0 4 6 6 -1 6 72 Submitted Solution: ``` q=int(input()) for i in range(q): n=int(input()) t2,t3,t5=0,0,0 while((n%2)==0): n=n//2 t2+=1 while((n%3)==0): n=n//3 t3+=1 while((n%5)==0): n=n//5 t5+=1 if(n!=1): print(-1) else: print(t2+t3*2+t5*3) ``` Yes
105,332
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an integer n. You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: 1. Replace n with n/2 if n is divisible by 2; 2. Replace n with 2n/3 if n is divisible by 3; 3. Replace n with 4n/5 if n is divisible by 5. For example, you can replace 30 with 15 using the first operation, with 20 using the second operation or with 24 using the third operation. Your task is to find the minimum number of moves required to obtain 1 from n or say that it is impossible to do it. You have to answer q independent queries. Input The first line of the input contains one integer q (1 ≀ q ≀ 1000) β€” the number of queries. The next q lines contain the queries. For each query you are given the integer number n (1 ≀ n ≀ 10^{18}). Output Print the answer for each query on a new line. If it is impossible to obtain 1 from n, print -1. Otherwise, print the minimum number of moves required to do it. Example Input 7 1 10 25 30 14 27 1000000000000000000 Output 0 4 6 6 -1 6 72 Submitted Solution: ``` a=int(input()) while(a>0): count=0 flag=0 q=int(input()) while(q!=1): if(q%5==0): count+=3 q=q/5 elif(q%3==0): count+=2 q=q/3 elif(q%2==0): count+=1 q=q/2 else: print(-1) flag=1 break if(flag!=1): print(count) a-=1 ``` No
105,333
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an integer n. You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: 1. Replace n with n/2 if n is divisible by 2; 2. Replace n with 2n/3 if n is divisible by 3; 3. Replace n with 4n/5 if n is divisible by 5. For example, you can replace 30 with 15 using the first operation, with 20 using the second operation or with 24 using the third operation. Your task is to find the minimum number of moves required to obtain 1 from n or say that it is impossible to do it. You have to answer q independent queries. Input The first line of the input contains one integer q (1 ≀ q ≀ 1000) β€” the number of queries. The next q lines contain the queries. For each query you are given the integer number n (1 ≀ n ≀ 10^{18}). Output Print the answer for each query on a new line. If it is impossible to obtain 1 from n, print -1. Otherwise, print the minimum number of moves required to do it. Example Input 7 1 10 25 30 14 27 1000000000000000000 Output 0 4 6 6 -1 6 72 Submitted Solution: ``` l = int(input()) for i in range(l): count = 0 n = int(input()) if n==1: print(count) elif n%2!=0 and n%3!=0 and n%5 !=0: print(-1) else: while n!=1: charas=0 if n%2!=0 and n%3!=0 and n%5 !=0: if n!=1: print(-1) n=1 charas=1 else: if n%2==0: n = n/2 count = count+1 elif n%3==0: n = 2*n/3 count = count + 1 elif n%5==0: n = 4*n/5 count = count + 1 if charas==0: print(count) ``` No
105,334
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an integer n. You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: 1. Replace n with n/2 if n is divisible by 2; 2. Replace n with 2n/3 if n is divisible by 3; 3. Replace n with 4n/5 if n is divisible by 5. For example, you can replace 30 with 15 using the first operation, with 20 using the second operation or with 24 using the third operation. Your task is to find the minimum number of moves required to obtain 1 from n or say that it is impossible to do it. You have to answer q independent queries. Input The first line of the input contains one integer q (1 ≀ q ≀ 1000) β€” the number of queries. The next q lines contain the queries. For each query you are given the integer number n (1 ≀ n ≀ 10^{18}). Output Print the answer for each query on a new line. If it is impossible to obtain 1 from n, print -1. Otherwise, print the minimum number of moves required to do it. Example Input 7 1 10 25 30 14 27 1000000000000000000 Output 0 4 6 6 -1 6 72 Submitted Solution: ``` t=int(input()) s=[] for hfvjv in range(0,t): n=int(input()) g=0 k=[0,0,0] jj=[1,1,1] while k!=jj: if n%5==0: n=n/5 g+=3 else: k[2]=1 if n%3==0: n=n/3 g+=2 else: k[1]=1 if n%2==0: n=n/2 g+=1 else: k[0]=1 if n==1: s.append(g) else: s.append(-1) for i in s: print(i) ``` No
105,335
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an integer n. You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: 1. Replace n with n/2 if n is divisible by 2; 2. Replace n with 2n/3 if n is divisible by 3; 3. Replace n with 4n/5 if n is divisible by 5. For example, you can replace 30 with 15 using the first operation, with 20 using the second operation or with 24 using the third operation. Your task is to find the minimum number of moves required to obtain 1 from n or say that it is impossible to do it. You have to answer q independent queries. Input The first line of the input contains one integer q (1 ≀ q ≀ 1000) β€” the number of queries. The next q lines contain the queries. For each query you are given the integer number n (1 ≀ n ≀ 10^{18}). Output Print the answer for each query on a new line. If it is impossible to obtain 1 from n, print -1. Otherwise, print the minimum number of moves required to do it. Example Input 7 1 10 25 30 14 27 1000000000000000000 Output 0 4 6 6 -1 6 72 Submitted Solution: ``` from sys import stdin, stdout q = int(stdin.readline()) while q != 0: n = int(stdin.readline()) ans2, ans3, ans5 = 0, 0, 0 while n % 5 == 0: n /= 5 ans5 += 1 ans2 += 2 while n % 3 == 0: n /= 3 ans2 += 1 ans3 += 1 while n % 2 == 0: n /= 2 ans2 += 1 if n > 1: print(-1) else: print(int(ans2 + ans3 + ans5)) q -= 1 ``` No
105,336
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's call a fraction x/y good if there exists at least one another fraction (x')/(y') such that x/y = (x')/(y'), 1 ≀ x', y' ≀ 9, the digit denoting x' is contained in the decimal representation of x, and the digit denoting y' is contained in the decimal representation of y. For example, 26/13 is a good fraction, because 26/13 = 2/1. You are given an integer number n. Please calculate the number of good fractions x/y such that 1 ≀ x ≀ n and 1 ≀ y ≀ n. The answer may be really large, so print it modulo 998244353. Input The only line of the input contains one integer n (1 ≀ n < 10^{100}). Output Print the number of good fractions x/y such that 1 ≀ x ≀ n and 1 ≀ y ≀ n. The answer may be really large, so print it modulo 998244353. Examples Input 42 Output 150 Input 3141592653589793238462643383279 Output 459925407 Submitted Solution: ``` n=int(input("Enter the number:")) c=0 for x in range(n+1): for y in range(n+1): for k in range(1,x+1): if (x%k==0 and y%k==0): q=x/k w=y/k if (q<10 and w<10): m = list(map(int, str(x))) l = list(map(int, str(y))) if q in m: if w in l: c=c+1 print(c%998244353) ``` No
105,337
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's call a fraction x/y good if there exists at least one another fraction (x')/(y') such that x/y = (x')/(y'), 1 ≀ x', y' ≀ 9, the digit denoting x' is contained in the decimal representation of x, and the digit denoting y' is contained in the decimal representation of y. For example, 26/13 is a good fraction, because 26/13 = 2/1. You are given an integer number n. Please calculate the number of good fractions x/y such that 1 ≀ x ≀ n and 1 ≀ y ≀ n. The answer may be really large, so print it modulo 998244353. Input The only line of the input contains one integer n (1 ≀ n < 10^{100}). Output Print the number of good fractions x/y such that 1 ≀ x ≀ n and 1 ≀ y ≀ n. The answer may be really large, so print it modulo 998244353. Examples Input 42 Output 150 Input 3141592653589793238462643383279 Output 459925407 Submitted Solution: ``` n = int(input()) count = 0 for i in range (1, n +1): for x in range (1, n + 1): for y in range (1, n +1): if i % x == 0 and i % y == 0 and i // x < 10 and i // y < 10: count += 1 print(count % 998244353) ``` No
105,338
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions are constraints on n and k. You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0). Each conversation is between you and some of your friends. There is at most one conversation with any of your friends. So each conversation is uniquely defined by your friend. You (suddenly!) have the ability to see the future. You know that during the day you will receive n messages, the i-th message will be received from the friend with ID id_i (1 ≀ id_i ≀ 10^9). If you receive a message from id_i in the conversation which is currently displayed on the smartphone then nothing happens: the conversations of the screen do not change and do not change their order, you read the message and continue waiting for new messages. Otherwise (i.e. if there is no conversation with id_i on the screen): * Firstly, if the number of conversations displayed on the screen is k, the last conversation (which has the position k) is removed from the screen. * Now the number of conversations on the screen is guaranteed to be less than k and the conversation with the friend id_i is not displayed on the screen. * The conversation with the friend id_i appears on the first (the topmost) position on the screen and all the other displayed conversations are shifted one position down. Your task is to find the list of conversations (in the order they are displayed on the screen) after processing all n messages. Input The first line of the input contains two integers n and k (1 ≀ n, k ≀ 2 β‹… 10^5) β€” the number of messages and the number of conversations your smartphone can show. The second line of the input contains n integers id_1, id_2, ..., id_n (1 ≀ id_i ≀ 10^9), where id_i is the ID of the friend which sends you the i-th message. Output In the first line of the output print one integer m (1 ≀ m ≀ min(n, k)) β€” the number of conversations shown after receiving all n messages. In the second line print m integers ids_1, ids_2, ..., ids_m, where ids_i should be equal to the ID of the friend corresponding to the conversation displayed on the position i after receiving all n messages. Examples Input 7 2 1 2 3 2 1 3 2 Output 2 2 1 Input 10 4 2 3 3 1 1 2 1 2 3 3 Output 3 1 3 2 Note In the first example the list of conversations will change in the following way (in order from the first to last message): * []; * [1]; * [2, 1]; * [3, 2]; * [3, 2]; * [1, 3]; * [1, 3]; * [2, 1]. In the second example the list of conversations will change in the following way: * []; * [2]; * [3, 2]; * [3, 2]; * [1, 3, 2]; * and then the list will not change till the end. Tags: data structures, implementation Correct Solution: ``` from collections import defaultdict n,k=map(int,input().split()) l=list(map(int,input().split())) s=[] x=0 d=defaultdict(int) for i in l: if d[i]==0: s.append(i) d[i]=1 x+=1 if x>k: q=s.pop(0) d[q]=0 x-=1 print(x) print(*s[::-1]) ```
105,339
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions are constraints on n and k. You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0). Each conversation is between you and some of your friends. There is at most one conversation with any of your friends. So each conversation is uniquely defined by your friend. You (suddenly!) have the ability to see the future. You know that during the day you will receive n messages, the i-th message will be received from the friend with ID id_i (1 ≀ id_i ≀ 10^9). If you receive a message from id_i in the conversation which is currently displayed on the smartphone then nothing happens: the conversations of the screen do not change and do not change their order, you read the message and continue waiting for new messages. Otherwise (i.e. if there is no conversation with id_i on the screen): * Firstly, if the number of conversations displayed on the screen is k, the last conversation (which has the position k) is removed from the screen. * Now the number of conversations on the screen is guaranteed to be less than k and the conversation with the friend id_i is not displayed on the screen. * The conversation with the friend id_i appears on the first (the topmost) position on the screen and all the other displayed conversations are shifted one position down. Your task is to find the list of conversations (in the order they are displayed on the screen) after processing all n messages. Input The first line of the input contains two integers n and k (1 ≀ n, k ≀ 2 β‹… 10^5) β€” the number of messages and the number of conversations your smartphone can show. The second line of the input contains n integers id_1, id_2, ..., id_n (1 ≀ id_i ≀ 10^9), where id_i is the ID of the friend which sends you the i-th message. Output In the first line of the output print one integer m (1 ≀ m ≀ min(n, k)) β€” the number of conversations shown after receiving all n messages. In the second line print m integers ids_1, ids_2, ..., ids_m, where ids_i should be equal to the ID of the friend corresponding to the conversation displayed on the position i after receiving all n messages. Examples Input 7 2 1 2 3 2 1 3 2 Output 2 2 1 Input 10 4 2 3 3 1 1 2 1 2 3 3 Output 3 1 3 2 Note In the first example the list of conversations will change in the following way (in order from the first to last message): * []; * [1]; * [2, 1]; * [3, 2]; * [3, 2]; * [1, 3]; * [1, 3]; * [2, 1]. In the second example the list of conversations will change in the following way: * []; * [2]; * [3, 2]; * [3, 2]; * [1, 3, 2]; * and then the list will not change till the end. Tags: data structures, implementation Correct Solution: ``` def solve(nums, k): l = list() h = set() for j in nums: if j not in h: if len(l) == k: h.remove(l[0]) l.pop(0) l.append(j) h.add(j) return l def main(): _, k = list(map(int, input().split())) nums = list(map(int, input().split())) sol = solve(nums, k) print(len(sol)) for i in reversed(sol): print(i, end=" ") main() ```
105,340
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions are constraints on n and k. You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0). Each conversation is between you and some of your friends. There is at most one conversation with any of your friends. So each conversation is uniquely defined by your friend. You (suddenly!) have the ability to see the future. You know that during the day you will receive n messages, the i-th message will be received from the friend with ID id_i (1 ≀ id_i ≀ 10^9). If you receive a message from id_i in the conversation which is currently displayed on the smartphone then nothing happens: the conversations of the screen do not change and do not change their order, you read the message and continue waiting for new messages. Otherwise (i.e. if there is no conversation with id_i on the screen): * Firstly, if the number of conversations displayed on the screen is k, the last conversation (which has the position k) is removed from the screen. * Now the number of conversations on the screen is guaranteed to be less than k and the conversation with the friend id_i is not displayed on the screen. * The conversation with the friend id_i appears on the first (the topmost) position on the screen and all the other displayed conversations are shifted one position down. Your task is to find the list of conversations (in the order they are displayed on the screen) after processing all n messages. Input The first line of the input contains two integers n and k (1 ≀ n, k ≀ 2 β‹… 10^5) β€” the number of messages and the number of conversations your smartphone can show. The second line of the input contains n integers id_1, id_2, ..., id_n (1 ≀ id_i ≀ 10^9), where id_i is the ID of the friend which sends you the i-th message. Output In the first line of the output print one integer m (1 ≀ m ≀ min(n, k)) β€” the number of conversations shown after receiving all n messages. In the second line print m integers ids_1, ids_2, ..., ids_m, where ids_i should be equal to the ID of the friend corresponding to the conversation displayed on the position i after receiving all n messages. Examples Input 7 2 1 2 3 2 1 3 2 Output 2 2 1 Input 10 4 2 3 3 1 1 2 1 2 3 3 Output 3 1 3 2 Note In the first example the list of conversations will change in the following way (in order from the first to last message): * []; * [1]; * [2, 1]; * [3, 2]; * [3, 2]; * [1, 3]; * [1, 3]; * [2, 1]. In the second example the list of conversations will change in the following way: * []; * [2]; * [3, 2]; * [3, 2]; * [1, 3, 2]; * and then the list will not change till the end. Tags: data structures, implementation Correct Solution: ``` from collections import deque n, k = map(int, input().split()) arr = list(map(int, input().split())) d = deque() s = set() for v in arr: if v in s: continue d.append(v) s.add(v) if len(d) > k: s.remove(d.popleft()) print(len(d)) print(*reversed(d)) ```
105,341
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions are constraints on n and k. You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0). Each conversation is between you and some of your friends. There is at most one conversation with any of your friends. So each conversation is uniquely defined by your friend. You (suddenly!) have the ability to see the future. You know that during the day you will receive n messages, the i-th message will be received from the friend with ID id_i (1 ≀ id_i ≀ 10^9). If you receive a message from id_i in the conversation which is currently displayed on the smartphone then nothing happens: the conversations of the screen do not change and do not change their order, you read the message and continue waiting for new messages. Otherwise (i.e. if there is no conversation with id_i on the screen): * Firstly, if the number of conversations displayed on the screen is k, the last conversation (which has the position k) is removed from the screen. * Now the number of conversations on the screen is guaranteed to be less than k and the conversation with the friend id_i is not displayed on the screen. * The conversation with the friend id_i appears on the first (the topmost) position on the screen and all the other displayed conversations are shifted one position down. Your task is to find the list of conversations (in the order they are displayed on the screen) after processing all n messages. Input The first line of the input contains two integers n and k (1 ≀ n, k ≀ 2 β‹… 10^5) β€” the number of messages and the number of conversations your smartphone can show. The second line of the input contains n integers id_1, id_2, ..., id_n (1 ≀ id_i ≀ 10^9), where id_i is the ID of the friend which sends you the i-th message. Output In the first line of the output print one integer m (1 ≀ m ≀ min(n, k)) β€” the number of conversations shown after receiving all n messages. In the second line print m integers ids_1, ids_2, ..., ids_m, where ids_i should be equal to the ID of the friend corresponding to the conversation displayed on the position i after receiving all n messages. Examples Input 7 2 1 2 3 2 1 3 2 Output 2 2 1 Input 10 4 2 3 3 1 1 2 1 2 3 3 Output 3 1 3 2 Note In the first example the list of conversations will change in the following way (in order from the first to last message): * []; * [1]; * [2, 1]; * [3, 2]; * [3, 2]; * [1, 3]; * [1, 3]; * [2, 1]. In the second example the list of conversations will change in the following way: * []; * [2]; * [3, 2]; * [3, 2]; * [1, 3, 2]; * and then the list will not change till the end. Tags: data structures, implementation Correct Solution: ``` # Bhagwaan codeforces n, k = map(int, input().split()) a = list(map(int, input().split())) import queue s = set() q = queue.Queue() count = 0 for x in a: if x not in s: if count < k: q.put(x) s.add(x) count += 1 else: s.remove(q.get()) q.put(x) s.add(x) ans = list() for _ in range(count): ans.append(q.get()) print(count) print(' '.join(map(str, ans[::-1]))) ```
105,342
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions are constraints on n and k. You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0). Each conversation is between you and some of your friends. There is at most one conversation with any of your friends. So each conversation is uniquely defined by your friend. You (suddenly!) have the ability to see the future. You know that during the day you will receive n messages, the i-th message will be received from the friend with ID id_i (1 ≀ id_i ≀ 10^9). If you receive a message from id_i in the conversation which is currently displayed on the smartphone then nothing happens: the conversations of the screen do not change and do not change their order, you read the message and continue waiting for new messages. Otherwise (i.e. if there is no conversation with id_i on the screen): * Firstly, if the number of conversations displayed on the screen is k, the last conversation (which has the position k) is removed from the screen. * Now the number of conversations on the screen is guaranteed to be less than k and the conversation with the friend id_i is not displayed on the screen. * The conversation with the friend id_i appears on the first (the topmost) position on the screen and all the other displayed conversations are shifted one position down. Your task is to find the list of conversations (in the order they are displayed on the screen) after processing all n messages. Input The first line of the input contains two integers n and k (1 ≀ n, k ≀ 2 β‹… 10^5) β€” the number of messages and the number of conversations your smartphone can show. The second line of the input contains n integers id_1, id_2, ..., id_n (1 ≀ id_i ≀ 10^9), where id_i is the ID of the friend which sends you the i-th message. Output In the first line of the output print one integer m (1 ≀ m ≀ min(n, k)) β€” the number of conversations shown after receiving all n messages. In the second line print m integers ids_1, ids_2, ..., ids_m, where ids_i should be equal to the ID of the friend corresponding to the conversation displayed on the position i after receiving all n messages. Examples Input 7 2 1 2 3 2 1 3 2 Output 2 2 1 Input 10 4 2 3 3 1 1 2 1 2 3 3 Output 3 1 3 2 Note In the first example the list of conversations will change in the following way (in order from the first to last message): * []; * [1]; * [2, 1]; * [3, 2]; * [3, 2]; * [1, 3]; * [1, 3]; * [2, 1]. In the second example the list of conversations will change in the following way: * []; * [2]; * [3, 2]; * [3, 2]; * [1, 3, 2]; * and then the list will not change till the end. Tags: data structures, implementation Correct Solution: ``` from collections import deque n,k=map(int,input().split()) q=list(map(int,input().split())) z={} w=deque() for i in q: if not(i in z and z[i]==1): z[i]=1 if len(w)<k: w.append(i) else: x=w.popleft() z[x]=-1 w.append(i) print(len(w)) print(*reversed(w)) ```
105,343
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions are constraints on n and k. You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0). Each conversation is between you and some of your friends. There is at most one conversation with any of your friends. So each conversation is uniquely defined by your friend. You (suddenly!) have the ability to see the future. You know that during the day you will receive n messages, the i-th message will be received from the friend with ID id_i (1 ≀ id_i ≀ 10^9). If you receive a message from id_i in the conversation which is currently displayed on the smartphone then nothing happens: the conversations of the screen do not change and do not change their order, you read the message and continue waiting for new messages. Otherwise (i.e. if there is no conversation with id_i on the screen): * Firstly, if the number of conversations displayed on the screen is k, the last conversation (which has the position k) is removed from the screen. * Now the number of conversations on the screen is guaranteed to be less than k and the conversation with the friend id_i is not displayed on the screen. * The conversation with the friend id_i appears on the first (the topmost) position on the screen and all the other displayed conversations are shifted one position down. Your task is to find the list of conversations (in the order they are displayed on the screen) after processing all n messages. Input The first line of the input contains two integers n and k (1 ≀ n, k ≀ 2 β‹… 10^5) β€” the number of messages and the number of conversations your smartphone can show. The second line of the input contains n integers id_1, id_2, ..., id_n (1 ≀ id_i ≀ 10^9), where id_i is the ID of the friend which sends you the i-th message. Output In the first line of the output print one integer m (1 ≀ m ≀ min(n, k)) β€” the number of conversations shown after receiving all n messages. In the second line print m integers ids_1, ids_2, ..., ids_m, where ids_i should be equal to the ID of the friend corresponding to the conversation displayed on the position i after receiving all n messages. Examples Input 7 2 1 2 3 2 1 3 2 Output 2 2 1 Input 10 4 2 3 3 1 1 2 1 2 3 3 Output 3 1 3 2 Note In the first example the list of conversations will change in the following way (in order from the first to last message): * []; * [1]; * [2, 1]; * [3, 2]; * [3, 2]; * [1, 3]; * [1, 3]; * [2, 1]. In the second example the list of conversations will change in the following way: * []; * [2]; * [3, 2]; * [3, 2]; * [1, 3, 2]; * and then the list will not change till the end. Tags: data structures, implementation Correct Solution: ``` n,k=map(int,input().split()) a=list(map(int,input().split())) d=[] s=set() for i in a: if i not in s: d.append(i) s.add(i) if len(d)>k: s.remove(d.pop(0)) print(len(d)) print(*d[::-1]) ```
105,344
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions are constraints on n and k. You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0). Each conversation is between you and some of your friends. There is at most one conversation with any of your friends. So each conversation is uniquely defined by your friend. You (suddenly!) have the ability to see the future. You know that during the day you will receive n messages, the i-th message will be received from the friend with ID id_i (1 ≀ id_i ≀ 10^9). If you receive a message from id_i in the conversation which is currently displayed on the smartphone then nothing happens: the conversations of the screen do not change and do not change their order, you read the message and continue waiting for new messages. Otherwise (i.e. if there is no conversation with id_i on the screen): * Firstly, if the number of conversations displayed on the screen is k, the last conversation (which has the position k) is removed from the screen. * Now the number of conversations on the screen is guaranteed to be less than k and the conversation with the friend id_i is not displayed on the screen. * The conversation with the friend id_i appears on the first (the topmost) position on the screen and all the other displayed conversations are shifted one position down. Your task is to find the list of conversations (in the order they are displayed on the screen) after processing all n messages. Input The first line of the input contains two integers n and k (1 ≀ n, k ≀ 2 β‹… 10^5) β€” the number of messages and the number of conversations your smartphone can show. The second line of the input contains n integers id_1, id_2, ..., id_n (1 ≀ id_i ≀ 10^9), where id_i is the ID of the friend which sends you the i-th message. Output In the first line of the output print one integer m (1 ≀ m ≀ min(n, k)) β€” the number of conversations shown after receiving all n messages. In the second line print m integers ids_1, ids_2, ..., ids_m, where ids_i should be equal to the ID of the friend corresponding to the conversation displayed on the position i after receiving all n messages. Examples Input 7 2 1 2 3 2 1 3 2 Output 2 2 1 Input 10 4 2 3 3 1 1 2 1 2 3 3 Output 3 1 3 2 Note In the first example the list of conversations will change in the following way (in order from the first to last message): * []; * [1]; * [2, 1]; * [3, 2]; * [3, 2]; * [1, 3]; * [1, 3]; * [2, 1]. In the second example the list of conversations will change in the following way: * []; * [2]; * [3, 2]; * [3, 2]; * [1, 3, 2]; * and then the list will not change till the end. Tags: data structures, implementation Correct Solution: ``` import collections def ii(): return int(input()) def fi(): return float(input()) def si(): return input() def mi(): return map(int,input().split()) def li(): return list(mi()) n,k=mi() d=li() b=collections.deque([]) s=set(d) l1=list(s) di={} for i in range(len(l1)): di[l1[i]]=0 for i in range(n): if(len(b)<k and di[d[i]]!=1): b.appendleft(d[i]) di[d[i]]=1 else: if(di[d[i]]!=1): #print(b) di[b[-1]]=0 #print(di) b.pop() b.appendleft(d[i]) di[d[i]]=1 #print("xx ") #print(b) l=list(b) print(len(l)) for i in l: print(i,end=" ") ```
105,345
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions are constraints on n and k. You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0). Each conversation is between you and some of your friends. There is at most one conversation with any of your friends. So each conversation is uniquely defined by your friend. You (suddenly!) have the ability to see the future. You know that during the day you will receive n messages, the i-th message will be received from the friend with ID id_i (1 ≀ id_i ≀ 10^9). If you receive a message from id_i in the conversation which is currently displayed on the smartphone then nothing happens: the conversations of the screen do not change and do not change their order, you read the message and continue waiting for new messages. Otherwise (i.e. if there is no conversation with id_i on the screen): * Firstly, if the number of conversations displayed on the screen is k, the last conversation (which has the position k) is removed from the screen. * Now the number of conversations on the screen is guaranteed to be less than k and the conversation with the friend id_i is not displayed on the screen. * The conversation with the friend id_i appears on the first (the topmost) position on the screen and all the other displayed conversations are shifted one position down. Your task is to find the list of conversations (in the order they are displayed on the screen) after processing all n messages. Input The first line of the input contains two integers n and k (1 ≀ n, k ≀ 2 β‹… 10^5) β€” the number of messages and the number of conversations your smartphone can show. The second line of the input contains n integers id_1, id_2, ..., id_n (1 ≀ id_i ≀ 10^9), where id_i is the ID of the friend which sends you the i-th message. Output In the first line of the output print one integer m (1 ≀ m ≀ min(n, k)) β€” the number of conversations shown after receiving all n messages. In the second line print m integers ids_1, ids_2, ..., ids_m, where ids_i should be equal to the ID of the friend corresponding to the conversation displayed on the position i after receiving all n messages. Examples Input 7 2 1 2 3 2 1 3 2 Output 2 2 1 Input 10 4 2 3 3 1 1 2 1 2 3 3 Output 3 1 3 2 Note In the first example the list of conversations will change in the following way (in order from the first to last message): * []; * [1]; * [2, 1]; * [3, 2]; * [3, 2]; * [1, 3]; * [1, 3]; * [2, 1]. In the second example the list of conversations will change in the following way: * []; * [2]; * [3, 2]; * [3, 2]; * [1, 3, 2]; * and then the list will not change till the end. Tags: data structures, implementation Correct Solution: ``` '''Author- Akshit Monga''' from collections import deque from sys import stdin,stdout input=stdin.readline t=1 for _ in range(t): n,k=map(int,input().split()) a=[int(x) for x in input().split()] d={} arr=deque() for i in a: if not(i in d and d[i]==1): d[i]=1 if len(arr)<k: arr.append(i) else: val=arr.popleft() d[val]=-1 arr.append(i) stdout.write(str(len(arr))+'\n') for i in range(len(arr)-1,-1,-1): stdout.write(str(arr[i])+" ") stdout.write('\n') ```
105,346
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between easy and hard versions are constraints on n and k. You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0). Each conversation is between you and some of your friends. There is at most one conversation with any of your friends. So each conversation is uniquely defined by your friend. You (suddenly!) have the ability to see the future. You know that during the day you will receive n messages, the i-th message will be received from the friend with ID id_i (1 ≀ id_i ≀ 10^9). If you receive a message from id_i in the conversation which is currently displayed on the smartphone then nothing happens: the conversations of the screen do not change and do not change their order, you read the message and continue waiting for new messages. Otherwise (i.e. if there is no conversation with id_i on the screen): * Firstly, if the number of conversations displayed on the screen is k, the last conversation (which has the position k) is removed from the screen. * Now the number of conversations on the screen is guaranteed to be less than k and the conversation with the friend id_i is not displayed on the screen. * The conversation with the friend id_i appears on the first (the topmost) position on the screen and all the other displayed conversations are shifted one position down. Your task is to find the list of conversations (in the order they are displayed on the screen) after processing all n messages. Input The first line of the input contains two integers n and k (1 ≀ n, k ≀ 2 β‹… 10^5) β€” the number of messages and the number of conversations your smartphone can show. The second line of the input contains n integers id_1, id_2, ..., id_n (1 ≀ id_i ≀ 10^9), where id_i is the ID of the friend which sends you the i-th message. Output In the first line of the output print one integer m (1 ≀ m ≀ min(n, k)) β€” the number of conversations shown after receiving all n messages. In the second line print m integers ids_1, ids_2, ..., ids_m, where ids_i should be equal to the ID of the friend corresponding to the conversation displayed on the position i after receiving all n messages. Examples Input 7 2 1 2 3 2 1 3 2 Output 2 2 1 Input 10 4 2 3 3 1 1 2 1 2 3 3 Output 3 1 3 2 Note In the first example the list of conversations will change in the following way (in order from the first to last message): * []; * [1]; * [2, 1]; * [3, 2]; * [3, 2]; * [1, 3]; * [1, 3]; * [2, 1]. In the second example the list of conversations will change in the following way: * []; * [2]; * [3, 2]; * [3, 2]; * [1, 3, 2]; * and then the list will not change till the end. Submitted Solution: ``` from collections import deque se=set([]) s=deque([]) n,k=map(int,input().split()) li=list(map(int,input().split())) cnt=0 for i in li: if i in se: continue if cnt<k: s.append(i) se.add(i) cnt+=1 else: s.append(i) se.add(i) se.discard(s[0]) s.popleft() print(len(s)) print(*list(s)[::-1]) ``` Yes
105,347
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between easy and hard versions are constraints on n and k. You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0). Each conversation is between you and some of your friends. There is at most one conversation with any of your friends. So each conversation is uniquely defined by your friend. You (suddenly!) have the ability to see the future. You know that during the day you will receive n messages, the i-th message will be received from the friend with ID id_i (1 ≀ id_i ≀ 10^9). If you receive a message from id_i in the conversation which is currently displayed on the smartphone then nothing happens: the conversations of the screen do not change and do not change their order, you read the message and continue waiting for new messages. Otherwise (i.e. if there is no conversation with id_i on the screen): * Firstly, if the number of conversations displayed on the screen is k, the last conversation (which has the position k) is removed from the screen. * Now the number of conversations on the screen is guaranteed to be less than k and the conversation with the friend id_i is not displayed on the screen. * The conversation with the friend id_i appears on the first (the topmost) position on the screen and all the other displayed conversations are shifted one position down. Your task is to find the list of conversations (in the order they are displayed on the screen) after processing all n messages. Input The first line of the input contains two integers n and k (1 ≀ n, k ≀ 2 β‹… 10^5) β€” the number of messages and the number of conversations your smartphone can show. The second line of the input contains n integers id_1, id_2, ..., id_n (1 ≀ id_i ≀ 10^9), where id_i is the ID of the friend which sends you the i-th message. Output In the first line of the output print one integer m (1 ≀ m ≀ min(n, k)) β€” the number of conversations shown after receiving all n messages. In the second line print m integers ids_1, ids_2, ..., ids_m, where ids_i should be equal to the ID of the friend corresponding to the conversation displayed on the position i after receiving all n messages. Examples Input 7 2 1 2 3 2 1 3 2 Output 2 2 1 Input 10 4 2 3 3 1 1 2 1 2 3 3 Output 3 1 3 2 Note In the first example the list of conversations will change in the following way (in order from the first to last message): * []; * [1]; * [2, 1]; * [3, 2]; * [3, 2]; * [1, 3]; * [1, 3]; * [2, 1]. In the second example the list of conversations will change in the following way: * []; * [2]; * [3, 2]; * [3, 2]; * [1, 3, 2]; * and then the list will not change till the end. Submitted Solution: ``` n,k=map(int,input().split()) l=list(map(int,input().split())) a=[] d={} for i in range(n): if len(a)<k: if d.get(l[i],0): #print(d) pass else: # a.insert(0,l[i]) a.append(l[i]) d[l[i]]=1 # print(d) else: if d.get(l[i],0): pass else: c=a.pop(0) #a.pop() a.append(l[i]) d[c]=0 d[l[i]]=1 # print(d,a) print(len(a)) print(*a[::-1]) ``` Yes
105,348
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between easy and hard versions are constraints on n and k. You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0). Each conversation is between you and some of your friends. There is at most one conversation with any of your friends. So each conversation is uniquely defined by your friend. You (suddenly!) have the ability to see the future. You know that during the day you will receive n messages, the i-th message will be received from the friend with ID id_i (1 ≀ id_i ≀ 10^9). If you receive a message from id_i in the conversation which is currently displayed on the smartphone then nothing happens: the conversations of the screen do not change and do not change their order, you read the message and continue waiting for new messages. Otherwise (i.e. if there is no conversation with id_i on the screen): * Firstly, if the number of conversations displayed on the screen is k, the last conversation (which has the position k) is removed from the screen. * Now the number of conversations on the screen is guaranteed to be less than k and the conversation with the friend id_i is not displayed on the screen. * The conversation with the friend id_i appears on the first (the topmost) position on the screen and all the other displayed conversations are shifted one position down. Your task is to find the list of conversations (in the order they are displayed on the screen) after processing all n messages. Input The first line of the input contains two integers n and k (1 ≀ n, k ≀ 2 β‹… 10^5) β€” the number of messages and the number of conversations your smartphone can show. The second line of the input contains n integers id_1, id_2, ..., id_n (1 ≀ id_i ≀ 10^9), where id_i is the ID of the friend which sends you the i-th message. Output In the first line of the output print one integer m (1 ≀ m ≀ min(n, k)) β€” the number of conversations shown after receiving all n messages. In the second line print m integers ids_1, ids_2, ..., ids_m, where ids_i should be equal to the ID of the friend corresponding to the conversation displayed on the position i after receiving all n messages. Examples Input 7 2 1 2 3 2 1 3 2 Output 2 2 1 Input 10 4 2 3 3 1 1 2 1 2 3 3 Output 3 1 3 2 Note In the first example the list of conversations will change in the following way (in order from the first to last message): * []; * [1]; * [2, 1]; * [3, 2]; * [3, 2]; * [1, 3]; * [1, 3]; * [2, 1]. In the second example the list of conversations will change in the following way: * []; * [2]; * [3, 2]; * [3, 2]; * [1, 3, 2]; * and then the list will not change till the end. Submitted Solution: ``` from collections import OrderedDict class LRUCache: def __init__(self, capacity): self.capacity = capacity self.cache = OrderedDict() def set(self, key, value): if len(self.cache) == self.capacity: self.cache.popitem(last=False) self.cache[key] = value n, k = map(int, input().strip().split()) ids = map(int, input().strip().split()) convs = LRUCache(k) for i in ids: if i in convs.cache: continue else: convs.set(i, None) print(len(convs.cache)) print(" ".join(map(str, reversed(convs.cache.keys())))) ``` Yes
105,349
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between easy and hard versions are constraints on n and k. You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0). Each conversation is between you and some of your friends. There is at most one conversation with any of your friends. So each conversation is uniquely defined by your friend. You (suddenly!) have the ability to see the future. You know that during the day you will receive n messages, the i-th message will be received from the friend with ID id_i (1 ≀ id_i ≀ 10^9). If you receive a message from id_i in the conversation which is currently displayed on the smartphone then nothing happens: the conversations of the screen do not change and do not change their order, you read the message and continue waiting for new messages. Otherwise (i.e. if there is no conversation with id_i on the screen): * Firstly, if the number of conversations displayed on the screen is k, the last conversation (which has the position k) is removed from the screen. * Now the number of conversations on the screen is guaranteed to be less than k and the conversation with the friend id_i is not displayed on the screen. * The conversation with the friend id_i appears on the first (the topmost) position on the screen and all the other displayed conversations are shifted one position down. Your task is to find the list of conversations (in the order they are displayed on the screen) after processing all n messages. Input The first line of the input contains two integers n and k (1 ≀ n, k ≀ 2 β‹… 10^5) β€” the number of messages and the number of conversations your smartphone can show. The second line of the input contains n integers id_1, id_2, ..., id_n (1 ≀ id_i ≀ 10^9), where id_i is the ID of the friend which sends you the i-th message. Output In the first line of the output print one integer m (1 ≀ m ≀ min(n, k)) β€” the number of conversations shown after receiving all n messages. In the second line print m integers ids_1, ids_2, ..., ids_m, where ids_i should be equal to the ID of the friend corresponding to the conversation displayed on the position i after receiving all n messages. Examples Input 7 2 1 2 3 2 1 3 2 Output 2 2 1 Input 10 4 2 3 3 1 1 2 1 2 3 3 Output 3 1 3 2 Note In the first example the list of conversations will change in the following way (in order from the first to last message): * []; * [1]; * [2, 1]; * [3, 2]; * [3, 2]; * [1, 3]; * [1, 3]; * [2, 1]. In the second example the list of conversations will change in the following way: * []; * [2]; * [3, 2]; * [3, 2]; * [1, 3, 2]; * and then the list will not change till the end. Submitted Solution: ``` from collections import deque def solution(arr, k: int) -> None: s = set() d = deque() for x in arr: if x not in s: if len(d) == k: s.discard(d.popleft()) s.add(x) d.append(x) print(len(d)) print(" ".join(map(str, reversed(d)))) def main(): _, k = map(int, input().split()) arr = map(int, input().split()) solution(arr, k) if __name__ == "__main__": main() ``` Yes
105,350
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between easy and hard versions are constraints on n and k. You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0). Each conversation is between you and some of your friends. There is at most one conversation with any of your friends. So each conversation is uniquely defined by your friend. You (suddenly!) have the ability to see the future. You know that during the day you will receive n messages, the i-th message will be received from the friend with ID id_i (1 ≀ id_i ≀ 10^9). If you receive a message from id_i in the conversation which is currently displayed on the smartphone then nothing happens: the conversations of the screen do not change and do not change their order, you read the message and continue waiting for new messages. Otherwise (i.e. if there is no conversation with id_i on the screen): * Firstly, if the number of conversations displayed on the screen is k, the last conversation (which has the position k) is removed from the screen. * Now the number of conversations on the screen is guaranteed to be less than k and the conversation with the friend id_i is not displayed on the screen. * The conversation with the friend id_i appears on the first (the topmost) position on the screen and all the other displayed conversations are shifted one position down. Your task is to find the list of conversations (in the order they are displayed on the screen) after processing all n messages. Input The first line of the input contains two integers n and k (1 ≀ n, k ≀ 2 β‹… 10^5) β€” the number of messages and the number of conversations your smartphone can show. The second line of the input contains n integers id_1, id_2, ..., id_n (1 ≀ id_i ≀ 10^9), where id_i is the ID of the friend which sends you the i-th message. Output In the first line of the output print one integer m (1 ≀ m ≀ min(n, k)) β€” the number of conversations shown after receiving all n messages. In the second line print m integers ids_1, ids_2, ..., ids_m, where ids_i should be equal to the ID of the friend corresponding to the conversation displayed on the position i after receiving all n messages. Examples Input 7 2 1 2 3 2 1 3 2 Output 2 2 1 Input 10 4 2 3 3 1 1 2 1 2 3 3 Output 3 1 3 2 Note In the first example the list of conversations will change in the following way (in order from the first to last message): * []; * [1]; * [2, 1]; * [3, 2]; * [3, 2]; * [1, 3]; * [1, 3]; * [2, 1]. In the second example the list of conversations will change in the following way: * []; * [2]; * [3, 2]; * [3, 2]; * [1, 3, 2]; * and then the list will not change till the end. Submitted Solution: ``` from collections import defaultdict as dc import sys import math mod=10**9 +7 def inp(): p=sys.stdin.readline() return p def out(z): sys.st def prf(a,n,k): q=dc(int) i=0 c=0 while(c<=k or i<n): if q[a[i]]==0: c+=1 q[a[i]]=1 if c==k: break i+=1 if i>=n: break #print(q) if i>=n: return q,c for j in range(i+1,n): if q[a[j]]==0: #print(q) q[a[j]]=1 l=next(iter(q)) del q[l] #print(q,l) return q,c n,m=list(map(int,inp().split())) a=list(map(int,inp().split())) z,c=prf(a,n,m) #print(z) print(min(c,m)) s='' for i,j in z.items(): if j==1: s=s+str(i)+' ' s=s[::-1] s=s[1:] print(s) ``` No
105,351
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between easy and hard versions are constraints on n and k. You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0). Each conversation is between you and some of your friends. There is at most one conversation with any of your friends. So each conversation is uniquely defined by your friend. You (suddenly!) have the ability to see the future. You know that during the day you will receive n messages, the i-th message will be received from the friend with ID id_i (1 ≀ id_i ≀ 10^9). If you receive a message from id_i in the conversation which is currently displayed on the smartphone then nothing happens: the conversations of the screen do not change and do not change their order, you read the message and continue waiting for new messages. Otherwise (i.e. if there is no conversation with id_i on the screen): * Firstly, if the number of conversations displayed on the screen is k, the last conversation (which has the position k) is removed from the screen. * Now the number of conversations on the screen is guaranteed to be less than k and the conversation with the friend id_i is not displayed on the screen. * The conversation with the friend id_i appears on the first (the topmost) position on the screen and all the other displayed conversations are shifted one position down. Your task is to find the list of conversations (in the order they are displayed on the screen) after processing all n messages. Input The first line of the input contains two integers n and k (1 ≀ n, k ≀ 2 β‹… 10^5) β€” the number of messages and the number of conversations your smartphone can show. The second line of the input contains n integers id_1, id_2, ..., id_n (1 ≀ id_i ≀ 10^9), where id_i is the ID of the friend which sends you the i-th message. Output In the first line of the output print one integer m (1 ≀ m ≀ min(n, k)) β€” the number of conversations shown after receiving all n messages. In the second line print m integers ids_1, ids_2, ..., ids_m, where ids_i should be equal to the ID of the friend corresponding to the conversation displayed on the position i after receiving all n messages. Examples Input 7 2 1 2 3 2 1 3 2 Output 2 2 1 Input 10 4 2 3 3 1 1 2 1 2 3 3 Output 3 1 3 2 Note In the first example the list of conversations will change in the following way (in order from the first to last message): * []; * [1]; * [2, 1]; * [3, 2]; * [3, 2]; * [1, 3]; * [1, 3]; * [2, 1]. In the second example the list of conversations will change in the following way: * []; * [2]; * [3, 2]; * [3, 2]; * [1, 3, 2]; * and then the list will not change till the end. Submitted Solution: ``` n, k = [int(x) for x in input().split()] l = [int(x) for x in input().split()] scr = [] s = set() for msg in l: if msg not in s: s.add(msg) scr.append(msg) if len(scr) > k: s -= {scr[0]} scr = scr[:-1] print(len(scr)) print(*reversed(scr)) ``` No
105,352
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between easy and hard versions are constraints on n and k. You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0). Each conversation is between you and some of your friends. There is at most one conversation with any of your friends. So each conversation is uniquely defined by your friend. You (suddenly!) have the ability to see the future. You know that during the day you will receive n messages, the i-th message will be received from the friend with ID id_i (1 ≀ id_i ≀ 10^9). If you receive a message from id_i in the conversation which is currently displayed on the smartphone then nothing happens: the conversations of the screen do not change and do not change their order, you read the message and continue waiting for new messages. Otherwise (i.e. if there is no conversation with id_i on the screen): * Firstly, if the number of conversations displayed on the screen is k, the last conversation (which has the position k) is removed from the screen. * Now the number of conversations on the screen is guaranteed to be less than k and the conversation with the friend id_i is not displayed on the screen. * The conversation with the friend id_i appears on the first (the topmost) position on the screen and all the other displayed conversations are shifted one position down. Your task is to find the list of conversations (in the order they are displayed on the screen) after processing all n messages. Input The first line of the input contains two integers n and k (1 ≀ n, k ≀ 2 β‹… 10^5) β€” the number of messages and the number of conversations your smartphone can show. The second line of the input contains n integers id_1, id_2, ..., id_n (1 ≀ id_i ≀ 10^9), where id_i is the ID of the friend which sends you the i-th message. Output In the first line of the output print one integer m (1 ≀ m ≀ min(n, k)) β€” the number of conversations shown after receiving all n messages. In the second line print m integers ids_1, ids_2, ..., ids_m, where ids_i should be equal to the ID of the friend corresponding to the conversation displayed on the position i after receiving all n messages. Examples Input 7 2 1 2 3 2 1 3 2 Output 2 2 1 Input 10 4 2 3 3 1 1 2 1 2 3 3 Output 3 1 3 2 Note In the first example the list of conversations will change in the following way (in order from the first to last message): * []; * [1]; * [2, 1]; * [3, 2]; * [3, 2]; * [1, 3]; * [1, 3]; * [2, 1]. In the second example the list of conversations will change in the following way: * []; * [2]; * [3, 2]; * [3, 2]; * [1, 3, 2]; * and then the list will not change till the end. Submitted Solution: ``` import queue def ii(): return int(input()) def fi(): return float(input()) def si(): return input() def mi(): return map(int,input().split()) def li(): return list(mi()) n,k=mi() d=li() b=[] s=set(d) l1=list(s) di={} l=queue.LifoQueue(maxsize=k+1) for i in range(len(l1)): di[l1[i]]=0 for i in range(n): if(l.qsize()<k and di[d[i]]!=1): l.put(d[i]) di[d[i]]=1 else: if(di[d[i]]!=1): #print(b) p=l.get() di[p]=0 #print(di l.put(d[i]) di[d[i]]=1 #print(b) print(l.qsize()) for i in range(l.qsize()): print(l.get(),end=" ") ``` No
105,353
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between easy and hard versions are constraints on n and k. You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0). Each conversation is between you and some of your friends. There is at most one conversation with any of your friends. So each conversation is uniquely defined by your friend. You (suddenly!) have the ability to see the future. You know that during the day you will receive n messages, the i-th message will be received from the friend with ID id_i (1 ≀ id_i ≀ 10^9). If you receive a message from id_i in the conversation which is currently displayed on the smartphone then nothing happens: the conversations of the screen do not change and do not change their order, you read the message and continue waiting for new messages. Otherwise (i.e. if there is no conversation with id_i on the screen): * Firstly, if the number of conversations displayed on the screen is k, the last conversation (which has the position k) is removed from the screen. * Now the number of conversations on the screen is guaranteed to be less than k and the conversation with the friend id_i is not displayed on the screen. * The conversation with the friend id_i appears on the first (the topmost) position on the screen and all the other displayed conversations are shifted one position down. Your task is to find the list of conversations (in the order they are displayed on the screen) after processing all n messages. Input The first line of the input contains two integers n and k (1 ≀ n, k ≀ 2 β‹… 10^5) β€” the number of messages and the number of conversations your smartphone can show. The second line of the input contains n integers id_1, id_2, ..., id_n (1 ≀ id_i ≀ 10^9), where id_i is the ID of the friend which sends you the i-th message. Output In the first line of the output print one integer m (1 ≀ m ≀ min(n, k)) β€” the number of conversations shown after receiving all n messages. In the second line print m integers ids_1, ids_2, ..., ids_m, where ids_i should be equal to the ID of the friend corresponding to the conversation displayed on the position i after receiving all n messages. Examples Input 7 2 1 2 3 2 1 3 2 Output 2 2 1 Input 10 4 2 3 3 1 1 2 1 2 3 3 Output 3 1 3 2 Note In the first example the list of conversations will change in the following way (in order from the first to last message): * []; * [1]; * [2, 1]; * [3, 2]; * [3, 2]; * [1, 3]; * [1, 3]; * [2, 1]. In the second example the list of conversations will change in the following way: * []; * [2]; * [3, 2]; * [3, 2]; * [1, 3, 2]; * and then the list will not change till the end. Submitted Solution: ``` n, k = list(map(int, input().split(' '))) lastSeen = {} curr = 0 arr = list(map(int, input().split(' '))) for i in arr: if i in lastSeen: if(curr - lastSeen[i] > k): lastSeen[i] = curr curr += 1 else: lastSeen[i] = curr curr += 1 import operator sorted_x = sorted(lastSeen.items(), key=operator.itemgetter(1), reverse=True) ans = list(map(lambda x:str(x[0]), sorted_x)) print(len(ans)) print(' '.join(ans)) ``` No
105,354
Provide tags and a correct Python 3 solution for this coding contest problem. You're given two arrays a[1 ... n] and b[1 ... n], both of the same length n. In order to perform a push operation, you have to choose three integers l, r, k satisfying 1 ≀ l ≀ r ≀ n and k > 0. Then, you will add k to elements a_l, a_{l+1}, …, a_r. For example, if a = [3, 7, 1, 4, 1, 2] and you choose (l = 3, r = 5, k = 2), the array a will become [3, 7, \underline{3, 6, 3}, 2]. You can do this operation at most once. Can you make array a equal to array b? (We consider that a = b if and only if, for every 1 ≀ i ≀ n, a_i = b_i) Input The first line contains a single integer t (1 ≀ t ≀ 20) β€” the number of test cases in the input. The first line of each test case contains a single integer n (1 ≀ n ≀ 100\ 000) β€” the number of elements in each array. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 1000). The third line of each test case contains n integers b_1, b_2, …, b_n (1 ≀ b_i ≀ 1000). It is guaranteed that the sum of n over all test cases doesn't exceed 10^5. Output For each test case, output one line containing "YES" if it's possible to make arrays a and b equal by performing at most once the described operation or "NO" if it's impossible. You can print each letter in any case (upper or lower). Example Input 4 6 3 7 1 4 1 2 3 7 3 6 3 2 5 1 1 1 1 1 1 2 1 3 1 2 42 42 42 42 1 7 6 Output YES NO YES NO Note The first test case is described in the statement: we can perform a push operation with parameters (l=3, r=5, k=2) to make a equal to b. In the second test case, we would need at least two operations to make a equal to b. In the third test case, arrays a and b are already equal. In the fourth test case, it's impossible to make a equal to b, because the integer k has to be positive. Tags: implementation Correct Solution: ``` t = int(input()) for _ in range(t): n = int(input()) A = list(map(int, input().split())) B = list(map(int, input().split())) C = [] for a,b in zip(A,B): C.append(b-a) cur = C[0] X = [] for i in range(n): if C[i] == cur: continue else: if cur != 0: X.append(cur) cur = C[i] else: if cur != 0: X.append(cur) #print(X) if not X: print('YES') elif len(X) == 1 and X[0] > 0: print('YES') else: print('NO') ```
105,355
Provide tags and a correct Python 3 solution for this coding contest problem. You're given two arrays a[1 ... n] and b[1 ... n], both of the same length n. In order to perform a push operation, you have to choose three integers l, r, k satisfying 1 ≀ l ≀ r ≀ n and k > 0. Then, you will add k to elements a_l, a_{l+1}, …, a_r. For example, if a = [3, 7, 1, 4, 1, 2] and you choose (l = 3, r = 5, k = 2), the array a will become [3, 7, \underline{3, 6, 3}, 2]. You can do this operation at most once. Can you make array a equal to array b? (We consider that a = b if and only if, for every 1 ≀ i ≀ n, a_i = b_i) Input The first line contains a single integer t (1 ≀ t ≀ 20) β€” the number of test cases in the input. The first line of each test case contains a single integer n (1 ≀ n ≀ 100\ 000) β€” the number of elements in each array. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 1000). The third line of each test case contains n integers b_1, b_2, …, b_n (1 ≀ b_i ≀ 1000). It is guaranteed that the sum of n over all test cases doesn't exceed 10^5. Output For each test case, output one line containing "YES" if it's possible to make arrays a and b equal by performing at most once the described operation or "NO" if it's impossible. You can print each letter in any case (upper or lower). Example Input 4 6 3 7 1 4 1 2 3 7 3 6 3 2 5 1 1 1 1 1 1 2 1 3 1 2 42 42 42 42 1 7 6 Output YES NO YES NO Note The first test case is described in the statement: we can perform a push operation with parameters (l=3, r=5, k=2) to make a equal to b. In the second test case, we would need at least two operations to make a equal to b. In the third test case, arrays a and b are already equal. In the fourth test case, it's impossible to make a equal to b, because the integer k has to be positive. Tags: implementation Correct Solution: ``` #for _ in range(int(input())): #for _ in range(9): print (input().replace('2','1')) for k in range(int(input())): n=int(input()) arr=list(map(int,input().split())) ls=list(map(int,input().split())) i=0 j=n-1 flag=0 while i<j and (arr[i]==ls[i] or arr[j]==ls[j]): if arr[i]==ls[i]: i+=1 if arr[j]==ls[j]: j-=1 dif=ls[i]-arr[i] for i in range(i,j+1): if ls[i]-arr[i]==dif and dif>=0: pass else: flag=1 print("NO") break if flag==0: print("YES") ```
105,356
Provide tags and a correct Python 3 solution for this coding contest problem. You're given two arrays a[1 ... n] and b[1 ... n], both of the same length n. In order to perform a push operation, you have to choose three integers l, r, k satisfying 1 ≀ l ≀ r ≀ n and k > 0. Then, you will add k to elements a_l, a_{l+1}, …, a_r. For example, if a = [3, 7, 1, 4, 1, 2] and you choose (l = 3, r = 5, k = 2), the array a will become [3, 7, \underline{3, 6, 3}, 2]. You can do this operation at most once. Can you make array a equal to array b? (We consider that a = b if and only if, for every 1 ≀ i ≀ n, a_i = b_i) Input The first line contains a single integer t (1 ≀ t ≀ 20) β€” the number of test cases in the input. The first line of each test case contains a single integer n (1 ≀ n ≀ 100\ 000) β€” the number of elements in each array. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 1000). The third line of each test case contains n integers b_1, b_2, …, b_n (1 ≀ b_i ≀ 1000). It is guaranteed that the sum of n over all test cases doesn't exceed 10^5. Output For each test case, output one line containing "YES" if it's possible to make arrays a and b equal by performing at most once the described operation or "NO" if it's impossible. You can print each letter in any case (upper or lower). Example Input 4 6 3 7 1 4 1 2 3 7 3 6 3 2 5 1 1 1 1 1 1 2 1 3 1 2 42 42 42 42 1 7 6 Output YES NO YES NO Note The first test case is described in the statement: we can perform a push operation with parameters (l=3, r=5, k=2) to make a equal to b. In the second test case, we would need at least two operations to make a equal to b. In the third test case, arrays a and b are already equal. In the fourth test case, it's impossible to make a equal to b, because the integer k has to be positive. Tags: implementation Correct Solution: ``` for _ in range(int(input())): #a,b,n,s=map(int, input().split()) n=int(input()) a=list(map(int, input().split())) b=list(map(int, input().split())) diff=[] for i in range(n): diff.append(b[i]-a[i]) k=list(set(diff)) if min(k)<0: print("NO") elif len(k)==1: print("YES") elif len(k)>2: print("NO") elif len(k)==2 and diff.count(0)==0: print("NO") else: for i in k: if i!=0: x=i if n-diff[::-1].index(x)-diff.index(x)==diff.count(x): print("YES") else: print("NO") ```
105,357
Provide tags and a correct Python 3 solution for this coding contest problem. You're given two arrays a[1 ... n] and b[1 ... n], both of the same length n. In order to perform a push operation, you have to choose three integers l, r, k satisfying 1 ≀ l ≀ r ≀ n and k > 0. Then, you will add k to elements a_l, a_{l+1}, …, a_r. For example, if a = [3, 7, 1, 4, 1, 2] and you choose (l = 3, r = 5, k = 2), the array a will become [3, 7, \underline{3, 6, 3}, 2]. You can do this operation at most once. Can you make array a equal to array b? (We consider that a = b if and only if, for every 1 ≀ i ≀ n, a_i = b_i) Input The first line contains a single integer t (1 ≀ t ≀ 20) β€” the number of test cases in the input. The first line of each test case contains a single integer n (1 ≀ n ≀ 100\ 000) β€” the number of elements in each array. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 1000). The third line of each test case contains n integers b_1, b_2, …, b_n (1 ≀ b_i ≀ 1000). It is guaranteed that the sum of n over all test cases doesn't exceed 10^5. Output For each test case, output one line containing "YES" if it's possible to make arrays a and b equal by performing at most once the described operation or "NO" if it's impossible. You can print each letter in any case (upper or lower). Example Input 4 6 3 7 1 4 1 2 3 7 3 6 3 2 5 1 1 1 1 1 1 2 1 3 1 2 42 42 42 42 1 7 6 Output YES NO YES NO Note The first test case is described in the statement: we can perform a push operation with parameters (l=3, r=5, k=2) to make a equal to b. In the second test case, we would need at least two operations to make a equal to b. In the third test case, arrays a and b are already equal. In the fourth test case, it's impossible to make a equal to b, because the integer k has to be positive. Tags: implementation Correct Solution: ``` import sys tests = int(sys.stdin.readline()) for _ in range(tests): n = int(sys.stdin.readline()) arr1 = list(map(int, sys.stdin.readline().split())) arr2 = list(map(int, sys.stdin.readline().split())) result = [] ok = True for i in range(n): if arr1[i] != arr2[i]: result.append([arr1[i] - arr2[i], i]) if (arr1[i] > arr2[i]): ok = False if len(result) == 0: print('YES') else: resultt = sorted(result, key=lambda el: el[0]) for i in range(1, len(resultt)): if resultt[i][0] != resultt[i-1][0]: ok = False break resultt2 = sorted(result, key=lambda el: el[1]) for i in range(1, len(resultt2)): if resultt2[i][0] == resultt2[i-1][0] and resultt2[i][1] != resultt2[i-1][1]+1: ok = False break if ok: print('YES') else: print('NO') ```
105,358
Provide tags and a correct Python 3 solution for this coding contest problem. You're given two arrays a[1 ... n] and b[1 ... n], both of the same length n. In order to perform a push operation, you have to choose three integers l, r, k satisfying 1 ≀ l ≀ r ≀ n and k > 0. Then, you will add k to elements a_l, a_{l+1}, …, a_r. For example, if a = [3, 7, 1, 4, 1, 2] and you choose (l = 3, r = 5, k = 2), the array a will become [3, 7, \underline{3, 6, 3}, 2]. You can do this operation at most once. Can you make array a equal to array b? (We consider that a = b if and only if, for every 1 ≀ i ≀ n, a_i = b_i) Input The first line contains a single integer t (1 ≀ t ≀ 20) β€” the number of test cases in the input. The first line of each test case contains a single integer n (1 ≀ n ≀ 100\ 000) β€” the number of elements in each array. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 1000). The third line of each test case contains n integers b_1, b_2, …, b_n (1 ≀ b_i ≀ 1000). It is guaranteed that the sum of n over all test cases doesn't exceed 10^5. Output For each test case, output one line containing "YES" if it's possible to make arrays a and b equal by performing at most once the described operation or "NO" if it's impossible. You can print each letter in any case (upper or lower). Example Input 4 6 3 7 1 4 1 2 3 7 3 6 3 2 5 1 1 1 1 1 1 2 1 3 1 2 42 42 42 42 1 7 6 Output YES NO YES NO Note The first test case is described in the statement: we can perform a push operation with parameters (l=3, r=5, k=2) to make a equal to b. In the second test case, we would need at least two operations to make a equal to b. In the third test case, arrays a and b are already equal. In the fourth test case, it's impossible to make a equal to b, because the integer k has to be positive. Tags: implementation Correct Solution: ``` t=int(input()) while(t): t-=1 n=int(input()) a=list(map(int,input().split())) b=list(map(int,input().split())) flag=0 di=0 flag2=0 flag3=0 j=0 for i in range(n): if(a[i]==b[i]): if(flag==1): j=i flag3=1 break else: continue flag=1 if(di==0): if(b[i]-a[i]<0): flag2=1 break di=b[i]-a[i] else: if(b[i]-a[i]!=di): flag2=1 break if(flag3==1): for i in range(j+1,n): if(a[i]!=b[i]): flag2=1 break if(flag2==1): print("NO") else: print("YES") ```
105,359
Provide tags and a correct Python 3 solution for this coding contest problem. You're given two arrays a[1 ... n] and b[1 ... n], both of the same length n. In order to perform a push operation, you have to choose three integers l, r, k satisfying 1 ≀ l ≀ r ≀ n and k > 0. Then, you will add k to elements a_l, a_{l+1}, …, a_r. For example, if a = [3, 7, 1, 4, 1, 2] and you choose (l = 3, r = 5, k = 2), the array a will become [3, 7, \underline{3, 6, 3}, 2]. You can do this operation at most once. Can you make array a equal to array b? (We consider that a = b if and only if, for every 1 ≀ i ≀ n, a_i = b_i) Input The first line contains a single integer t (1 ≀ t ≀ 20) β€” the number of test cases in the input. The first line of each test case contains a single integer n (1 ≀ n ≀ 100\ 000) β€” the number of elements in each array. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 1000). The third line of each test case contains n integers b_1, b_2, …, b_n (1 ≀ b_i ≀ 1000). It is guaranteed that the sum of n over all test cases doesn't exceed 10^5. Output For each test case, output one line containing "YES" if it's possible to make arrays a and b equal by performing at most once the described operation or "NO" if it's impossible. You can print each letter in any case (upper or lower). Example Input 4 6 3 7 1 4 1 2 3 7 3 6 3 2 5 1 1 1 1 1 1 2 1 3 1 2 42 42 42 42 1 7 6 Output YES NO YES NO Note The first test case is described in the statement: we can perform a push operation with parameters (l=3, r=5, k=2) to make a equal to b. In the second test case, we would need at least two operations to make a equal to b. In the third test case, arrays a and b are already equal. In the fourth test case, it's impossible to make a equal to b, because the integer k has to be positive. Tags: implementation Correct Solution: ``` for i in range(int(input())): N = int(input()) A = [int(x) for x in input().strip().split()] B = [int(x) for x in input().strip().split()] D = [B[i]-A[i] for i in range(N)] S = False Z = False v = 0 for i, val in enumerate(D): if S and val == 0: Z = True elif (S and val != 0 and val != v) or (Z and val != 0): print("NO") break elif val != 0 and not S: v = val if val < 0: print("NO") break S = True else: print("YES") ```
105,360
Provide tags and a correct Python 3 solution for this coding contest problem. You're given two arrays a[1 ... n] and b[1 ... n], both of the same length n. In order to perform a push operation, you have to choose three integers l, r, k satisfying 1 ≀ l ≀ r ≀ n and k > 0. Then, you will add k to elements a_l, a_{l+1}, …, a_r. For example, if a = [3, 7, 1, 4, 1, 2] and you choose (l = 3, r = 5, k = 2), the array a will become [3, 7, \underline{3, 6, 3}, 2]. You can do this operation at most once. Can you make array a equal to array b? (We consider that a = b if and only if, for every 1 ≀ i ≀ n, a_i = b_i) Input The first line contains a single integer t (1 ≀ t ≀ 20) β€” the number of test cases in the input. The first line of each test case contains a single integer n (1 ≀ n ≀ 100\ 000) β€” the number of elements in each array. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 1000). The third line of each test case contains n integers b_1, b_2, …, b_n (1 ≀ b_i ≀ 1000). It is guaranteed that the sum of n over all test cases doesn't exceed 10^5. Output For each test case, output one line containing "YES" if it's possible to make arrays a and b equal by performing at most once the described operation or "NO" if it's impossible. You can print each letter in any case (upper or lower). Example Input 4 6 3 7 1 4 1 2 3 7 3 6 3 2 5 1 1 1 1 1 1 2 1 3 1 2 42 42 42 42 1 7 6 Output YES NO YES NO Note The first test case is described in the statement: we can perform a push operation with parameters (l=3, r=5, k=2) to make a equal to b. In the second test case, we would need at least two operations to make a equal to b. In the third test case, arrays a and b are already equal. In the fourth test case, it's impossible to make a equal to b, because the integer k has to be positive. Tags: implementation Correct Solution: ``` for _ in range(int(input())): n = int(input()) k = list(map(int,input().split())) l = list(map(int,input().split())) h = [l[i]-k[i] for i in range(n)] d = [] f = 0 for i in range(n-1): if h[i]<0: f=1 break if h[i]!=h[i+1]: d.append(h[i]) if h[-1]<0: f=1 d.append(h[-1]) if f==1 or len(d)>3: print("NO") elif len(d)==3: if d[0]==0 and d[-1]==0: print("YES") else: print("NO") elif len(d)==2: if d[0]==0 or d[1] ==0: print("YES") else: print("NO") else: print("YES") ```
105,361
Provide tags and a correct Python 3 solution for this coding contest problem. You're given two arrays a[1 ... n] and b[1 ... n], both of the same length n. In order to perform a push operation, you have to choose three integers l, r, k satisfying 1 ≀ l ≀ r ≀ n and k > 0. Then, you will add k to elements a_l, a_{l+1}, …, a_r. For example, if a = [3, 7, 1, 4, 1, 2] and you choose (l = 3, r = 5, k = 2), the array a will become [3, 7, \underline{3, 6, 3}, 2]. You can do this operation at most once. Can you make array a equal to array b? (We consider that a = b if and only if, for every 1 ≀ i ≀ n, a_i = b_i) Input The first line contains a single integer t (1 ≀ t ≀ 20) β€” the number of test cases in the input. The first line of each test case contains a single integer n (1 ≀ n ≀ 100\ 000) β€” the number of elements in each array. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 1000). The third line of each test case contains n integers b_1, b_2, …, b_n (1 ≀ b_i ≀ 1000). It is guaranteed that the sum of n over all test cases doesn't exceed 10^5. Output For each test case, output one line containing "YES" if it's possible to make arrays a and b equal by performing at most once the described operation or "NO" if it's impossible. You can print each letter in any case (upper or lower). Example Input 4 6 3 7 1 4 1 2 3 7 3 6 3 2 5 1 1 1 1 1 1 2 1 3 1 2 42 42 42 42 1 7 6 Output YES NO YES NO Note The first test case is described in the statement: we can perform a push operation with parameters (l=3, r=5, k=2) to make a equal to b. In the second test case, we would need at least two operations to make a equal to b. In the third test case, arrays a and b are already equal. In the fourth test case, it's impossible to make a equal to b, because the integer k has to be positive. Tags: implementation Correct Solution: ``` for _ in range(int(input())): n = int(input()) a = list(map(int,input().split())) b = list(map(int,input().split())) if a == b: print('YES') elif a!=b: c=[] e = 0 for i in range(n): d = b[i]-a[i] c.append(d) if d<0: e+=1 else: e+=0 if e>0: print('NO') else: g = [] f=0 for i in range(1,n): if c[i]==c[i-1]: f+=0 else: f+=1 g.append(i) if f>2: print('NO') elif f==2 : if c[g[0]-1]==c[g[0]]==0 or c[g[0]-1]==c[g[1]]==0 or c[g[1]-1]==c[g[1]]==0: print('YES') else: print('NO') elif f==1 and c[g[0]-1]!=0 and c[g[0]]!=0: print('NO') else: print('YES') ```
105,362
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You're given two arrays a[1 ... n] and b[1 ... n], both of the same length n. In order to perform a push operation, you have to choose three integers l, r, k satisfying 1 ≀ l ≀ r ≀ n and k > 0. Then, you will add k to elements a_l, a_{l+1}, …, a_r. For example, if a = [3, 7, 1, 4, 1, 2] and you choose (l = 3, r = 5, k = 2), the array a will become [3, 7, \underline{3, 6, 3}, 2]. You can do this operation at most once. Can you make array a equal to array b? (We consider that a = b if and only if, for every 1 ≀ i ≀ n, a_i = b_i) Input The first line contains a single integer t (1 ≀ t ≀ 20) β€” the number of test cases in the input. The first line of each test case contains a single integer n (1 ≀ n ≀ 100\ 000) β€” the number of elements in each array. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 1000). The third line of each test case contains n integers b_1, b_2, …, b_n (1 ≀ b_i ≀ 1000). It is guaranteed that the sum of n over all test cases doesn't exceed 10^5. Output For each test case, output one line containing "YES" if it's possible to make arrays a and b equal by performing at most once the described operation or "NO" if it's impossible. You can print each letter in any case (upper or lower). Example Input 4 6 3 7 1 4 1 2 3 7 3 6 3 2 5 1 1 1 1 1 1 2 1 3 1 2 42 42 42 42 1 7 6 Output YES NO YES NO Note The first test case is described in the statement: we can perform a push operation with parameters (l=3, r=5, k=2) to make a equal to b. In the second test case, we would need at least two operations to make a equal to b. In the third test case, arrays a and b are already equal. In the fourth test case, it's impossible to make a equal to b, because the integer k has to be positive. Submitted Solution: ``` t = int(input()) for _ in range(t): n = int(input()) l1 = [] l2 = [] l1 = list(map(int,input().split())) l2 = list(map(int,input().split())) l3 = [i-j for i,j in zip(l1, l2)] i = 0 j = len(l3) - 1 while i < len(l3) and l3[i] == 0: i += 1 while j>=0 and l3[j]==0: j -= 1 if j == -1 or (len(set(l3[i:j+1])) == 1 and l3[i]<0): print("YES") else: print("NO") ``` Yes
105,363
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You're given two arrays a[1 ... n] and b[1 ... n], both of the same length n. In order to perform a push operation, you have to choose three integers l, r, k satisfying 1 ≀ l ≀ r ≀ n and k > 0. Then, you will add k to elements a_l, a_{l+1}, …, a_r. For example, if a = [3, 7, 1, 4, 1, 2] and you choose (l = 3, r = 5, k = 2), the array a will become [3, 7, \underline{3, 6, 3}, 2]. You can do this operation at most once. Can you make array a equal to array b? (We consider that a = b if and only if, for every 1 ≀ i ≀ n, a_i = b_i) Input The first line contains a single integer t (1 ≀ t ≀ 20) β€” the number of test cases in the input. The first line of each test case contains a single integer n (1 ≀ n ≀ 100\ 000) β€” the number of elements in each array. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 1000). The third line of each test case contains n integers b_1, b_2, …, b_n (1 ≀ b_i ≀ 1000). It is guaranteed that the sum of n over all test cases doesn't exceed 10^5. Output For each test case, output one line containing "YES" if it's possible to make arrays a and b equal by performing at most once the described operation or "NO" if it's impossible. You can print each letter in any case (upper or lower). Example Input 4 6 3 7 1 4 1 2 3 7 3 6 3 2 5 1 1 1 1 1 1 2 1 3 1 2 42 42 42 42 1 7 6 Output YES NO YES NO Note The first test case is described in the statement: we can perform a push operation with parameters (l=3, r=5, k=2) to make a equal to b. In the second test case, we would need at least two operations to make a equal to b. In the third test case, arrays a and b are already equal. In the fourth test case, it's impossible to make a equal to b, because the integer k has to be positive. Submitted Solution: ``` t=int(input()) for r in range(t): n=int(input()) l1=list(map(int,input().split())) l2=list(map(int,input().split())) flag=1 diff=-9999999 count=0 count0=0 for i in range(0,n): if (l1[i]-l2[i])!=diff: diff=l1[i]-l2[i] count+=1 if (l1[i]-l2[i])==0: count0+=1 if (l1[i]-l2[i])>0: flag=0 if flag==1 and (count-count0)<=1: print("YES") else: print("NO") ``` Yes
105,364
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You're given two arrays a[1 ... n] and b[1 ... n], both of the same length n. In order to perform a push operation, you have to choose three integers l, r, k satisfying 1 ≀ l ≀ r ≀ n and k > 0. Then, you will add k to elements a_l, a_{l+1}, …, a_r. For example, if a = [3, 7, 1, 4, 1, 2] and you choose (l = 3, r = 5, k = 2), the array a will become [3, 7, \underline{3, 6, 3}, 2]. You can do this operation at most once. Can you make array a equal to array b? (We consider that a = b if and only if, for every 1 ≀ i ≀ n, a_i = b_i) Input The first line contains a single integer t (1 ≀ t ≀ 20) β€” the number of test cases in the input. The first line of each test case contains a single integer n (1 ≀ n ≀ 100\ 000) β€” the number of elements in each array. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 1000). The third line of each test case contains n integers b_1, b_2, …, b_n (1 ≀ b_i ≀ 1000). It is guaranteed that the sum of n over all test cases doesn't exceed 10^5. Output For each test case, output one line containing "YES" if it's possible to make arrays a and b equal by performing at most once the described operation or "NO" if it's impossible. You can print each letter in any case (upper or lower). Example Input 4 6 3 7 1 4 1 2 3 7 3 6 3 2 5 1 1 1 1 1 1 2 1 3 1 2 42 42 42 42 1 7 6 Output YES NO YES NO Note The first test case is described in the statement: we can perform a push operation with parameters (l=3, r=5, k=2) to make a equal to b. In the second test case, we would need at least two operations to make a equal to b. In the third test case, arrays a and b are already equal. In the fourth test case, it's impossible to make a equal to b, because the integer k has to be positive. Submitted Solution: ``` import sys for _ in range(int(input())): n = int(input()) a = list(map(int,input().split())) b = list(map(int,input().split())) temp = [] for i in range(n): temp.append(a[i]-b[i]) prev = sys.maxsize f,cnt = 0,0 for i in temp: if i>0: f = 1 break elif i<0: if prev==sys.maxsize: prev = i else: if i!=prev or cnt==1: f=1 break elif prev!=sys.maxsize and i==0: cnt=1 if f==1: print("NO") else: print("YES") ``` Yes
105,365
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You're given two arrays a[1 ... n] and b[1 ... n], both of the same length n. In order to perform a push operation, you have to choose three integers l, r, k satisfying 1 ≀ l ≀ r ≀ n and k > 0. Then, you will add k to elements a_l, a_{l+1}, …, a_r. For example, if a = [3, 7, 1, 4, 1, 2] and you choose (l = 3, r = 5, k = 2), the array a will become [3, 7, \underline{3, 6, 3}, 2]. You can do this operation at most once. Can you make array a equal to array b? (We consider that a = b if and only if, for every 1 ≀ i ≀ n, a_i = b_i) Input The first line contains a single integer t (1 ≀ t ≀ 20) β€” the number of test cases in the input. The first line of each test case contains a single integer n (1 ≀ n ≀ 100\ 000) β€” the number of elements in each array. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 1000). The third line of each test case contains n integers b_1, b_2, …, b_n (1 ≀ b_i ≀ 1000). It is guaranteed that the sum of n over all test cases doesn't exceed 10^5. Output For each test case, output one line containing "YES" if it's possible to make arrays a and b equal by performing at most once the described operation or "NO" if it's impossible. You can print each letter in any case (upper or lower). Example Input 4 6 3 7 1 4 1 2 3 7 3 6 3 2 5 1 1 1 1 1 1 2 1 3 1 2 42 42 42 42 1 7 6 Output YES NO YES NO Note The first test case is described in the statement: we can perform a push operation with parameters (l=3, r=5, k=2) to make a equal to b. In the second test case, we would need at least two operations to make a equal to b. In the third test case, arrays a and b are already equal. In the fourth test case, it's impossible to make a equal to b, because the integer k has to be positive. Submitted Solution: ``` for _ in range(int(input())): n = int(input()) a, b = list(map(int, input().split())), list(map(int, input().split())) bad = 0 if a == b: print("YES") continue for y in range(n): if a[y] != b[y]: i = y break for y in range(n - 1, -1, -1): if a[y] != b[y]: j = y break k = b[i] - a[i] if k < 0: print("NO") continue for y in range(i + 1, j + 1): if b[y] - k != a[y]: bad = 1 break if bad: print("NO") else: print("YES") ``` Yes
105,366
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You're given two arrays a[1 ... n] and b[1 ... n], both of the same length n. In order to perform a push operation, you have to choose three integers l, r, k satisfying 1 ≀ l ≀ r ≀ n and k > 0. Then, you will add k to elements a_l, a_{l+1}, …, a_r. For example, if a = [3, 7, 1, 4, 1, 2] and you choose (l = 3, r = 5, k = 2), the array a will become [3, 7, \underline{3, 6, 3}, 2]. You can do this operation at most once. Can you make array a equal to array b? (We consider that a = b if and only if, for every 1 ≀ i ≀ n, a_i = b_i) Input The first line contains a single integer t (1 ≀ t ≀ 20) β€” the number of test cases in the input. The first line of each test case contains a single integer n (1 ≀ n ≀ 100\ 000) β€” the number of elements in each array. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 1000). The third line of each test case contains n integers b_1, b_2, …, b_n (1 ≀ b_i ≀ 1000). It is guaranteed that the sum of n over all test cases doesn't exceed 10^5. Output For each test case, output one line containing "YES" if it's possible to make arrays a and b equal by performing at most once the described operation or "NO" if it's impossible. You can print each letter in any case (upper or lower). Example Input 4 6 3 7 1 4 1 2 3 7 3 6 3 2 5 1 1 1 1 1 1 2 1 3 1 2 42 42 42 42 1 7 6 Output YES NO YES NO Note The first test case is described in the statement: we can perform a push operation with parameters (l=3, r=5, k=2) to make a equal to b. In the second test case, we would need at least two operations to make a equal to b. In the third test case, arrays a and b are already equal. In the fourth test case, it's impossible to make a equal to b, because the integer k has to be positive. Submitted Solution: ``` n = int(input()) aa = [] bb = [] for i in range(n): input() aa += [list(map(int, input().split(' ')))] bb += [list(map(int, input().split(' ')))] for i in range(n): a = aa[i] b = bb[i] k = 0 d = True for j in range(len(a)): if a[j] == b[j]: continue else: if k == 0: k = b[j] - a[j] else: if a[j] + k != b[j]: d = False break if k < 0: d = False break if d: print("YES") else: print("NO") ``` No
105,367
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You're given two arrays a[1 ... n] and b[1 ... n], both of the same length n. In order to perform a push operation, you have to choose three integers l, r, k satisfying 1 ≀ l ≀ r ≀ n and k > 0. Then, you will add k to elements a_l, a_{l+1}, …, a_r. For example, if a = [3, 7, 1, 4, 1, 2] and you choose (l = 3, r = 5, k = 2), the array a will become [3, 7, \underline{3, 6, 3}, 2]. You can do this operation at most once. Can you make array a equal to array b? (We consider that a = b if and only if, for every 1 ≀ i ≀ n, a_i = b_i) Input The first line contains a single integer t (1 ≀ t ≀ 20) β€” the number of test cases in the input. The first line of each test case contains a single integer n (1 ≀ n ≀ 100\ 000) β€” the number of elements in each array. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 1000). The third line of each test case contains n integers b_1, b_2, …, b_n (1 ≀ b_i ≀ 1000). It is guaranteed that the sum of n over all test cases doesn't exceed 10^5. Output For each test case, output one line containing "YES" if it's possible to make arrays a and b equal by performing at most once the described operation or "NO" if it's impossible. You can print each letter in any case (upper or lower). Example Input 4 6 3 7 1 4 1 2 3 7 3 6 3 2 5 1 1 1 1 1 1 2 1 3 1 2 42 42 42 42 1 7 6 Output YES NO YES NO Note The first test case is described in the statement: we can perform a push operation with parameters (l=3, r=5, k=2) to make a equal to b. In the second test case, we would need at least two operations to make a equal to b. In the third test case, arrays a and b are already equal. In the fourth test case, it's impossible to make a equal to b, because the integer k has to be positive. Submitted Solution: ``` for _ in range(int(input())): n = int(input()) li = list(map(int, input().split())) li1 = list(map(int, input().split())) st = True dif = False tmp = 0 for i in range(n): if li[i] > li1[i]: print("NO") st = False break elif li[i] < li1[i]: if dif == False: tmp = li1[i] - li[i] dif = True else: if li1[i] - li[i] != tmp: print("NO") st = False break if st: print("YES") ``` No
105,368
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You're given two arrays a[1 ... n] and b[1 ... n], both of the same length n. In order to perform a push operation, you have to choose three integers l, r, k satisfying 1 ≀ l ≀ r ≀ n and k > 0. Then, you will add k to elements a_l, a_{l+1}, …, a_r. For example, if a = [3, 7, 1, 4, 1, 2] and you choose (l = 3, r = 5, k = 2), the array a will become [3, 7, \underline{3, 6, 3}, 2]. You can do this operation at most once. Can you make array a equal to array b? (We consider that a = b if and only if, for every 1 ≀ i ≀ n, a_i = b_i) Input The first line contains a single integer t (1 ≀ t ≀ 20) β€” the number of test cases in the input. The first line of each test case contains a single integer n (1 ≀ n ≀ 100\ 000) β€” the number of elements in each array. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 1000). The third line of each test case contains n integers b_1, b_2, …, b_n (1 ≀ b_i ≀ 1000). It is guaranteed that the sum of n over all test cases doesn't exceed 10^5. Output For each test case, output one line containing "YES" if it's possible to make arrays a and b equal by performing at most once the described operation or "NO" if it's impossible. You can print each letter in any case (upper or lower). Example Input 4 6 3 7 1 4 1 2 3 7 3 6 3 2 5 1 1 1 1 1 1 2 1 3 1 2 42 42 42 42 1 7 6 Output YES NO YES NO Note The first test case is described in the statement: we can perform a push operation with parameters (l=3, r=5, k=2) to make a equal to b. In the second test case, we would need at least two operations to make a equal to b. In the third test case, arrays a and b are already equal. In the fourth test case, it's impossible to make a equal to b, because the integer k has to be positive. Submitted Solution: ``` t=int(input()) for i in range(t): n=int(input()) l1=input() l2=input() l1=map(int,l1.split()) l2=map(int,l2.split()) l1=list(l1) l2=list(l2) x=l1[0]-l2[0] c=0 if x>0: c=4 for j in range(n): if l1[j]-l2[j]!=x or l1[j]-l2[j]!=0: x=l1[j]-l2[j] if x>0: c=4 c=c+1 if c>2: break if c>2: print("NO") else: print("YES") ``` No
105,369
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You're given two arrays a[1 ... n] and b[1 ... n], both of the same length n. In order to perform a push operation, you have to choose three integers l, r, k satisfying 1 ≀ l ≀ r ≀ n and k > 0. Then, you will add k to elements a_l, a_{l+1}, …, a_r. For example, if a = [3, 7, 1, 4, 1, 2] and you choose (l = 3, r = 5, k = 2), the array a will become [3, 7, \underline{3, 6, 3}, 2]. You can do this operation at most once. Can you make array a equal to array b? (We consider that a = b if and only if, for every 1 ≀ i ≀ n, a_i = b_i) Input The first line contains a single integer t (1 ≀ t ≀ 20) β€” the number of test cases in the input. The first line of each test case contains a single integer n (1 ≀ n ≀ 100\ 000) β€” the number of elements in each array. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 1000). The third line of each test case contains n integers b_1, b_2, …, b_n (1 ≀ b_i ≀ 1000). It is guaranteed that the sum of n over all test cases doesn't exceed 10^5. Output For each test case, output one line containing "YES" if it's possible to make arrays a and b equal by performing at most once the described operation or "NO" if it's impossible. You can print each letter in any case (upper or lower). Example Input 4 6 3 7 1 4 1 2 3 7 3 6 3 2 5 1 1 1 1 1 1 2 1 3 1 2 42 42 42 42 1 7 6 Output YES NO YES NO Note The first test case is described in the statement: we can perform a push operation with parameters (l=3, r=5, k=2) to make a equal to b. In the second test case, we would need at least two operations to make a equal to b. In the third test case, arrays a and b are already equal. In the fourth test case, it's impossible to make a equal to b, because the integer k has to be positive. Submitted Solution: ``` # maa chudaaye duniya for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) discont = [] diff = -10**10 f = True for i in range(n): if a[i] != b[i]: discont.append(i) if diff == -10**10: diff = b[i] - a[i] else: if diff != b[i]-a[i]: f = False break if f is False: print('NO') continue else: if discont == []: print('YES') else: x = True for i in range(1, len(discont)): if discont[i] - discont[i-1] != 1: print('NO') x = False break if x and diff > 0: print('YES') else: print('NO') ``` No
105,370
Provide tags and a correct Python 3 solution for this coding contest problem. There are n railway stations in Berland. They are connected to each other by n-1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree. You have a map of that network, so for each railway section you know which stations it connects. Each of the n-1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 1 to 10^6 inclusive. You asked m passengers some questions: the j-th one told you three values: * his departure station a_j; * his arrival station b_j; * minimum scenery beauty along the path from a_j to b_j (the train is moving along the shortest path from a_j to b_j). You are planning to update the map and set some value f_i on each railway section β€” the scenery beauty. The passengers' answers should be consistent with these values. Print any valid set of values f_1, f_2, ..., f_{n-1}, which the passengers' answer is consistent with or report that it doesn't exist. Input The first line contains a single integer n (2 ≀ n ≀ 5000) β€” the number of railway stations in Berland. The next n-1 lines contain descriptions of the railway sections: the i-th section description is two integers x_i and y_i (1 ≀ x_i, y_i ≀ n, x_i β‰  y_i), where x_i and y_i are the indices of the stations which are connected by the i-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway. The next line contains a single integer m (1 ≀ m ≀ 5000) β€” the number of passengers which were asked questions. Then m lines follow, the j-th line contains three integers a_j, b_j and g_j (1 ≀ a_j, b_j ≀ n; a_j β‰  b_j; 1 ≀ g_j ≀ 10^6) β€” the departure station, the arrival station and the minimum scenery beauty along his path. Output If there is no answer then print a single integer -1. Otherwise, print n-1 integers f_1, f_2, ..., f_{n-1} (1 ≀ f_i ≀ 10^6), where f_i is some valid scenery beauty along the i-th railway section. If there are multiple answers, you can print any of them. Examples Input 4 1 2 3 2 3 4 2 1 2 5 1 3 3 Output 5 3 5 Input 6 1 2 1 6 3 1 1 5 4 1 4 6 1 3 3 4 1 6 5 2 1 2 5 Output 5 3 1 2 1 Input 6 1 2 1 6 3 1 1 5 4 1 4 6 1 1 3 4 3 6 5 3 1 2 4 Output -1 Tags: constructive algorithms, dfs and similar, greedy, sortings, trees Correct Solution: ``` from itertools import chain class RangeMinQuery: # O(nlog(n)) construction/space, O(1) range minimum query def __init__(self, data): self._data = [list(data)] n = len(self._data[0]) # self._data[i][j] stores the min of the segment [j, j + 2 ** i] where i is in [1,2,4,8,...,log(N)] w = 1 while 2 * w <= n: prev = self._data[-1] self._data.append([min(prev[j], prev[j + w]) for j in range(n - 2 * w + 1)]) w *= 2 def query(self, begin, end): # Find min of [begin, end) # Take the min of the overlapping intervals [begin, begin + 2**depth) and [end - 2**depth, end) assert begin < end depth = (end - begin).bit_length() - 1 return min(self._data[depth][begin], self._data[depth][end - (1 << depth)]) class LCA: def __init__(self, graph, root=1): # Euler tour representation recording every visit to each node in the DFS self.eulerTour = [] # For each node record the index of their first visit in the euler tour self.preorder = [None] * len(graph) # Record last visit self.postorder = [None] * len(graph) # Depth of each node to the root self.depth = [None] * len(graph) # Parent of each node self.parent = [None] * len(graph) # DFS stack = [root] self.depth[root] = 0 self.parent[root] = None while stack: node = stack.pop() # Record a visit in the euler tour self.eulerTour.append(node) if self.preorder[node] is None: # Record first visit self.preorder[node] = len(self.eulerTour) - 1 for nbr in graph[node]: if self.preorder[nbr] is None: self.depth[nbr] = self.depth[node] + 1 self.parent[nbr] = node stack.append(node) stack.append(nbr) # Record last visit (this can be overwritten) self.postorder[node] = len(self.eulerTour) - 1 #self.rmq = RangeMinQuery(self.preorder[node] for node in self.eulerTour) if False: # Check invariants assert self.depth[1] == 0 assert self.parent[1] == None for node in range(1, len(graph)): assert self.preorder[node] == self.eulerTour.index(node) assert self.postorder[node] == max( i for i, x in enumerate(self.eulerTour) if x == node ) for i in range(len(self.rmq._data)): for j in range(i + 1, len(self.rmq._data) + 1): assert min(self.rmq._data[0][i:j]) == self.rmq.query(i, j) for u in range(1, N + 1): for v in range(1, N + 1): assert self.lca(u, v) == self.lca(v, u) lca = self.lca(u, v) assert self.isAncestor(lca, u) assert self.isAncestor(lca, v) path = self.path(u, v) assert len(path) == self.dist(u, v) + 1 for x, y in zip(path, path[1:]): assert y in graph[x] assert len(set(path)) == len(path) def lca(self, u, v): a = self.preorder[u] b = self.preorder[v] if a > b: a, b = b, a return self.eulerTour[self.rmq.query(a, b + 1)] def dist(self, u, v): return self.depth[u] + self.depth[v] - 2 * self.depth[self.lca(u, v)] def isAncestor(self, ancestor, v): # Checks if `ancestor` is an ancestor of `v` return ( self.preorder[ancestor] <= self.preorder[v] and self.postorder[v] <= self.postorder[ancestor] ) def path(self, u, v): # Returns the path from u to v in the tree. This doesn't rely on rmq # Walk up from u until u becomes ancestor of v (the LCA) uPath = [] while not self.isAncestor(u, v): uPath.append(u) u = self.parent[u] lca = u # Walk up from v until v is at the LCA too assert self.isAncestor(u, v) vPath = [] while v != lca: vPath.append(v) v = self.parent[v] ret = uPath + [lca] + vPath[::-1] return ret def solve(N, edges, passengers): graph = [[] for i in range(N + 1)] for e in edges: graph[e[0]].append(e[1]) graph[e[1]].append(e[0]) tree = LCA(graph) scores = [[1 for j in range(N + 1)] for i in range(N + 1)] for a, b, score in passengers: path = tree.path(a, b) assert path[0] == a and path[-1] == b for u, v in zip(path, path[1:]): scores[u][v] = max(scores[u][v], score) scores[v][u] = max(scores[v][u], score) for a, b, score in passengers: ans = float("inf") path = tree.path(a, b) for u, v in zip(path, path[1:]): ans = min(ans, scores[u][v]) if ans != score: print(-1) exit(0) for e in edges: print(scores[e[0]][e[1]], end=" ") print() if False: N = 5000 edges = list(zip(range(N - 1), range(1, N))) assert len(edges) == N - 1 passengers = [(0, p, N - p) for p in range(1, N)] solve(N, edges, passengers) exit(0) if __name__ == "__main__": N = int(input()) edges = [[int(x) for x in input().split()] for i in range(N - 1)] P = int(input()) passengers = [[int(x) for x in input().split()] for i in range(P)] solve(N, edges, passengers) ```
105,371
Provide tags and a correct Python 3 solution for this coding contest problem. There are n railway stations in Berland. They are connected to each other by n-1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree. You have a map of that network, so for each railway section you know which stations it connects. Each of the n-1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 1 to 10^6 inclusive. You asked m passengers some questions: the j-th one told you three values: * his departure station a_j; * his arrival station b_j; * minimum scenery beauty along the path from a_j to b_j (the train is moving along the shortest path from a_j to b_j). You are planning to update the map and set some value f_i on each railway section β€” the scenery beauty. The passengers' answers should be consistent with these values. Print any valid set of values f_1, f_2, ..., f_{n-1}, which the passengers' answer is consistent with or report that it doesn't exist. Input The first line contains a single integer n (2 ≀ n ≀ 5000) β€” the number of railway stations in Berland. The next n-1 lines contain descriptions of the railway sections: the i-th section description is two integers x_i and y_i (1 ≀ x_i, y_i ≀ n, x_i β‰  y_i), where x_i and y_i are the indices of the stations which are connected by the i-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway. The next line contains a single integer m (1 ≀ m ≀ 5000) β€” the number of passengers which were asked questions. Then m lines follow, the j-th line contains three integers a_j, b_j and g_j (1 ≀ a_j, b_j ≀ n; a_j β‰  b_j; 1 ≀ g_j ≀ 10^6) β€” the departure station, the arrival station and the minimum scenery beauty along his path. Output If there is no answer then print a single integer -1. Otherwise, print n-1 integers f_1, f_2, ..., f_{n-1} (1 ≀ f_i ≀ 10^6), where f_i is some valid scenery beauty along the i-th railway section. If there are multiple answers, you can print any of them. Examples Input 4 1 2 3 2 3 4 2 1 2 5 1 3 3 Output 5 3 5 Input 6 1 2 1 6 3 1 1 5 4 1 4 6 1 3 3 4 1 6 5 2 1 2 5 Output 5 3 1 2 1 Input 6 1 2 1 6 3 1 1 5 4 1 4 6 1 1 3 4 3 6 5 3 1 2 4 Output -1 Tags: constructive algorithms, dfs and similar, greedy, sortings, trees Correct Solution: ``` import copy n = int(input()) g = [[] for i in range(n)] depth = [0 for i in range(n)] parent = [-2 for i in range(n)] parent[0] = -1 beauty = [1 for i in range(n)] Edges = [] def chk(f,t): _min = 1145141919810 while f!=t: if depth[f] < depth[t]: f,t = t,f _min = min(beauty[f],_min) f = parent[f] return _min def dfs(): callstack = [0] while len(callstack): c = callstack.pop() for i in g[c]: if parent[c] == i: continue parent[i] = c depth[i] = depth[c] + 1 callstack.append(i) def update(f,t,w): while f!=t: if depth[f] < depth[t]: f,t = t,f beauty[f] = max(beauty[f],w) f = parent[f] for i in range(n-1): fr,to = (int(i)-1 for i in input().split(' ')) g[fr].append(to) g[to].append(fr) Edges.append((fr,to)) dfs() g = [] m = int(input()) for i in range(m): fr,to,we = (int(i) for i in input().split(' ')) fr -= 1 to -= 1 g.append((fr,to,we)) update(fr,to,we) for a,b,c in g: if chk(a,b) != c: print(-1) exit(0) for a,b in Edges: if parent[a] == b: print(beauty[a],end=' ') else: print(beauty[b],end=' ') ```
105,372
Provide tags and a correct Python 3 solution for this coding contest problem. There are n railway stations in Berland. They are connected to each other by n-1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree. You have a map of that network, so for each railway section you know which stations it connects. Each of the n-1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 1 to 10^6 inclusive. You asked m passengers some questions: the j-th one told you three values: * his departure station a_j; * his arrival station b_j; * minimum scenery beauty along the path from a_j to b_j (the train is moving along the shortest path from a_j to b_j). You are planning to update the map and set some value f_i on each railway section β€” the scenery beauty. The passengers' answers should be consistent with these values. Print any valid set of values f_1, f_2, ..., f_{n-1}, which the passengers' answer is consistent with or report that it doesn't exist. Input The first line contains a single integer n (2 ≀ n ≀ 5000) β€” the number of railway stations in Berland. The next n-1 lines contain descriptions of the railway sections: the i-th section description is two integers x_i and y_i (1 ≀ x_i, y_i ≀ n, x_i β‰  y_i), where x_i and y_i are the indices of the stations which are connected by the i-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway. The next line contains a single integer m (1 ≀ m ≀ 5000) β€” the number of passengers which were asked questions. Then m lines follow, the j-th line contains three integers a_j, b_j and g_j (1 ≀ a_j, b_j ≀ n; a_j β‰  b_j; 1 ≀ g_j ≀ 10^6) β€” the departure station, the arrival station and the minimum scenery beauty along his path. Output If there is no answer then print a single integer -1. Otherwise, print n-1 integers f_1, f_2, ..., f_{n-1} (1 ≀ f_i ≀ 10^6), where f_i is some valid scenery beauty along the i-th railway section. If there are multiple answers, you can print any of them. Examples Input 4 1 2 3 2 3 4 2 1 2 5 1 3 3 Output 5 3 5 Input 6 1 2 1 6 3 1 1 5 4 1 4 6 1 3 3 4 1 6 5 2 1 2 5 Output 5 3 1 2 1 Input 6 1 2 1 6 3 1 1 5 4 1 4 6 1 1 3 4 3 6 5 3 1 2 4 Output -1 Tags: constructive algorithms, dfs and similar, greedy, sortings, trees Correct Solution: ``` #!/usr/bin/env python import os import sys from io import BytesIO, IOBase # Ref https://github.com/cheran-senthil/PyRival/tree/master/pyrival # sys.modules["hashlib"] = sys.sha512 = sys # import random def dfsPre(par,graph,tin,tout): n = len(graph) visited, finished = [False] * n, [False] * n stack = [1] # print(tin,tout) t = 0 while stack: start = stack[-1] if not visited[start]: visited[start]=True t+=1 tin[start] = t for child in graph[start]: if not visited[child]: stack.append(child) par[child] = start else: stack.pop() t+=1 tout[start] = t def parent(tin,tout,u,v): return tin[u]<=tin[v] and tout[v]<=tout[u] def dfs(par,tin,tout,adj,u,v,c): # print(u,v,parent(tin,tout,u,v)) while(not parent(tin,tout,u,v)): # print(u,par[u]) adj[u][par[u]]=max(adj[u][par[u]],c) adj[par[u]][u]=max(adj[par[u]][u],c) u=par[u] def dfs1(par,tin,tout,adj,u,v): ans = 10000000 while(not parent(tin,tout,u,v)): ans=min(ans,adj[u][par[u]]) u=par[u] return ans def rnd(v): # print(v) random.shuffle(v) # print(v) return v def main(): n = int(input()) edges = [ [int(x) for x in input().split()] for i in range(n-1) ] m = int(input()) qur = [ [int(x) for x in input().split()] for i in range(m) ] graph = [ [] for i in range(n+1) ] adj = [ [1 for j in range(n+1)] for i in range(n+1) ] par = [-1]*(n+1) tin = [0]*(n+1) tout = [0]*(n+1) for x in edges: graph[x[0]].append(x[1]) graph[x[1]].append(x[0]) dfsPre(par,graph,tin,tout) # print(par) # print(tin) # print(tout) chk = {} for x in qur: u,v,c=x[0],x[1],x[2] if(u>v): u,v=v,u fl = False try: j=chk[u*(n+1)+v] if j !=c : print(-1) fl = True except: chk[u*(n+1)+v] = c dfs(par,tin,tout,adj,u,v,c) dfs(par,tin,tout,adj,v,u,c) if(fl): exit(0) for x,y in chk.items(): u,v=x//(n+1),x%(n+1) if(min(dfs1(par,tin,tout,adj,v,u),dfs1(par,tin,tout,adj,u,v))!=y): print(-1) exit(0) for x in edges: print(adj[x[0]][x[1]],end=" ") # 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") # endregion if __name__ == "__main__": main() ```
105,373
Provide tags and a correct Python 3 solution for this coding contest problem. There are n railway stations in Berland. They are connected to each other by n-1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree. You have a map of that network, so for each railway section you know which stations it connects. Each of the n-1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 1 to 10^6 inclusive. You asked m passengers some questions: the j-th one told you three values: * his departure station a_j; * his arrival station b_j; * minimum scenery beauty along the path from a_j to b_j (the train is moving along the shortest path from a_j to b_j). You are planning to update the map and set some value f_i on each railway section β€” the scenery beauty. The passengers' answers should be consistent with these values. Print any valid set of values f_1, f_2, ..., f_{n-1}, which the passengers' answer is consistent with or report that it doesn't exist. Input The first line contains a single integer n (2 ≀ n ≀ 5000) β€” the number of railway stations in Berland. The next n-1 lines contain descriptions of the railway sections: the i-th section description is two integers x_i and y_i (1 ≀ x_i, y_i ≀ n, x_i β‰  y_i), where x_i and y_i are the indices of the stations which are connected by the i-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway. The next line contains a single integer m (1 ≀ m ≀ 5000) β€” the number of passengers which were asked questions. Then m lines follow, the j-th line contains three integers a_j, b_j and g_j (1 ≀ a_j, b_j ≀ n; a_j β‰  b_j; 1 ≀ g_j ≀ 10^6) β€” the departure station, the arrival station and the minimum scenery beauty along his path. Output If there is no answer then print a single integer -1. Otherwise, print n-1 integers f_1, f_2, ..., f_{n-1} (1 ≀ f_i ≀ 10^6), where f_i is some valid scenery beauty along the i-th railway section. If there are multiple answers, you can print any of them. Examples Input 4 1 2 3 2 3 4 2 1 2 5 1 3 3 Output 5 3 5 Input 6 1 2 1 6 3 1 1 5 4 1 4 6 1 3 3 4 1 6 5 2 1 2 5 Output 5 3 1 2 1 Input 6 1 2 1 6 3 1 1 5 4 1 4 6 1 1 3 4 3 6 5 3 1 2 4 Output -1 Tags: constructive algorithms, dfs and similar, greedy, sortings, trees Correct Solution: ``` import sys class RangeMinQuery: # O(nlog(n)) construction/space, O(1) range minimum query def __init__(self, data): self._data = [list(data)] n = len(self._data[0]) # self._data[i][j] stores the min of the segment [j, j + 2 ** i] where i is in [1,2,4,8,...,log(N)] w = 1 while 2 * w <= n: prev = self._data[-1] self._data.append([min(prev[j], prev[j + w]) for j in range(n - 2 * w + 1)]) w *= 2 def query(self, begin, end): # Find min of [begin, end) # Take the min of the overlapping intervals [begin, begin + 2**depth) and [end - 2**depth, end) assert begin < end depth = (end - begin).bit_length() - 1 return min(self._data[depth][begin], self._data[depth][end - (1 << depth)]) class LCA: def __init__(self, graph, root=1): # Euler tour representation recording every visit to each node in the DFS self.eulerTour = [] # For each node record the index of their first visit in the euler tour self.preorder = [None] * len(graph) # Record last visit self.postorder = [None] * len(graph) # Depth of each node to the root self.depth = [None] * len(graph) # Parent of each node self.parent = [None] * len(graph) # DFS stack = [root] self.depth[root] = 0 self.parent[root] = None while stack: node = stack.pop() # Record a visit in the euler tour self.eulerTour.append(node) if self.preorder[node] is None: # Record first visit self.preorder[node] = len(self.eulerTour) - 1 for nbr in graph[node]: if self.preorder[nbr] is None: self.depth[nbr] = self.depth[node] + 1 self.parent[nbr] = node stack.append(node) stack.append(nbr) # Record last visit (this can be overwritten) self.postorder[node] = len(self.eulerTour) - 1 # self.rmq = RangeMinQuery(self.preorder[node] for node in self.eulerTour) if False: # Check invariants assert self.depth[1] == 0 assert self.parent[1] == None for node in range(1, len(graph)): assert self.preorder[node] == self.eulerTour.index(node) assert self.postorder[node] == max( i for i, x in enumerate(self.eulerTour) if x == node ) for i in range(len(self.rmq._data)): for j in range(i + 1, len(self.rmq._data) + 1): assert min(self.rmq._data[0][i:j]) == self.rmq.query(i, j) for u in range(1, N + 1): for v in range(1, N + 1): assert self.lca(u, v) == self.lca(v, u) lca = self.lca(u, v) assert self.isAncestor(lca, u) assert self.isAncestor(lca, v) path = self.path(u, v) assert len(path) == self.dist(u, v) + 1 for x, y in zip(path, path[1:]): assert y in graph[x] assert len(set(path)) == len(path) def lca(self, u, v): a = self.preorder[u] b = self.preorder[v] if a > b: a, b = b, a return self.eulerTour[self.rmq.query(a, b + 1)] def dist(self, u, v): return self.depth[u] + self.depth[v] - 2 * self.depth[self.lca(u, v)] def isAncestor(self, ancestor, v): # Checks if `ancestor` is an ancestor of `v` return ( self.preorder[ancestor] <= self.preorder[v] and self.postorder[v] <= self.postorder[ancestor] ) def path(self, u, v): # Returns the path from u to v in the tree. This doesn't rely on rmq # Walk up from u until u becomes ancestor of v (the LCA) uPath = [] while not self.isAncestor(u, v): uPath.append(u) u = self.parent[u] lca = u # Walk up from v until v is at the LCA too assert self.isAncestor(u, v) vPath = [] while v != lca: vPath.append(v) v = self.parent[v] ret = uPath + [lca] + vPath[::-1] return ret def solve(N, edges, passengers): graph = [[] for i in range(N + 1)] for e in edges: graph[e[0]].append(e[1]) graph[e[1]].append(e[0]) tree = LCA(graph) scores = [[1 for j in range(N + 1)] for i in range(N + 1)] for a, b, score in passengers: path = tree.path(a, b) assert path[0] == a and path[-1] == b for u, v in zip(path, path[1:]): scores[u][v] = max(scores[u][v], score) scores[v][u] = max(scores[v][u], score) for a, b, score in passengers: ans = float("inf") path = tree.path(a, b) for u, v in zip(path, path[1:]): ans = min(ans, scores[u][v]) if ans != score: return -1 return " ".join(str(scores[e[0]][e[1]]) for e in edges) if False: N = 5000 edges = list(zip(range(N - 1), range(1, N))) assert len(edges) == N - 1 passengers = [(0, p, N - p) for p in range(1, N)] solve(N, edges, passengers) exit(0) if __name__ == "__main__": input = sys.stdin.readline N = int(input()) edges = [[int(x) for x in input().split()] for i in range(N - 1)] P = int(input()) passengers = [[int(x) for x in input().split()] for i in range(P)] ans = solve(N, edges, passengers) print(ans) ```
105,374
Provide tags and a correct Python 3 solution for this coding contest problem. There are n railway stations in Berland. They are connected to each other by n-1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree. You have a map of that network, so for each railway section you know which stations it connects. Each of the n-1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 1 to 10^6 inclusive. You asked m passengers some questions: the j-th one told you three values: * his departure station a_j; * his arrival station b_j; * minimum scenery beauty along the path from a_j to b_j (the train is moving along the shortest path from a_j to b_j). You are planning to update the map and set some value f_i on each railway section β€” the scenery beauty. The passengers' answers should be consistent with these values. Print any valid set of values f_1, f_2, ..., f_{n-1}, which the passengers' answer is consistent with or report that it doesn't exist. Input The first line contains a single integer n (2 ≀ n ≀ 5000) β€” the number of railway stations in Berland. The next n-1 lines contain descriptions of the railway sections: the i-th section description is two integers x_i and y_i (1 ≀ x_i, y_i ≀ n, x_i β‰  y_i), where x_i and y_i are the indices of the stations which are connected by the i-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway. The next line contains a single integer m (1 ≀ m ≀ 5000) β€” the number of passengers which were asked questions. Then m lines follow, the j-th line contains three integers a_j, b_j and g_j (1 ≀ a_j, b_j ≀ n; a_j β‰  b_j; 1 ≀ g_j ≀ 10^6) β€” the departure station, the arrival station and the minimum scenery beauty along his path. Output If there is no answer then print a single integer -1. Otherwise, print n-1 integers f_1, f_2, ..., f_{n-1} (1 ≀ f_i ≀ 10^6), where f_i is some valid scenery beauty along the i-th railway section. If there are multiple answers, you can print any of them. Examples Input 4 1 2 3 2 3 4 2 1 2 5 1 3 3 Output 5 3 5 Input 6 1 2 1 6 3 1 1 5 4 1 4 6 1 3 3 4 1 6 5 2 1 2 5 Output 5 3 1 2 1 Input 6 1 2 1 6 3 1 1 5 4 1 4 6 1 1 3 4 3 6 5 3 1 2 4 Output -1 Tags: constructive algorithms, dfs and similar, greedy, sortings, trees Correct Solution: ``` #!/usr/bin/python3 # @Author : indiewar import sys sys.setrecursionlimit(5233) n = int(input()) G = [[] for i in range(n+1)] dep = [0 for i in range(n+1)] par = [-1 for i in range(n+1)] x = [0 for i in range(n+1)] y = [0 for i in range(n+1)] for i in range(n-1): x[i],y[i] = map(int,input().split()) G[x[i]].append(y[i]) G[y[i]].append(x[i]) m = int(input()) a = [0 for i in range(m+1)] b = [0 for i in range(m+1)] g = [[] for i in range(m+1)] ans = [0 for i in range(n+1)] def bfs(): q = [1] par[1] = -2 front = 0 while front < len(q): u = q[front] front += 1 for v in G[u]: if par[v] == -1: par[v] = u # print(v, par[v]) dep[v] = dep[u] + 1 # print(dep[v]) q.append(v) # dep[x] = d # par[x] = fa # for v in G[x]: # if v != fa: # dfs(v,x,d+1) def lca(u,v,w): while dep[u] > dep[v]: ans[u] = max(ans[u],w) u = par[u] while dep[v] > dep[u]: ans[v] = max(ans[v],w) v = par[v] while u != v: ans[u] = max(ans[u], w) ans[v] = max(ans[v], w) u = par[u] v = par[v] def check(u,v,w): while dep[u] > dep[v]: if ans[u] == w: return True u = par[u] while dep[v] > dep[u]: if ans[v] == w: return True v = par[v] while u != v: if ans[u] == w: return True if ans[v] == w: return True u = par[u] v = par[v] return False bfs() for i in range(m): a[i],b[i],g[i] = map(int,input().split()) lca(a[i],b[i],g[i]) f = True for i in range(m): if check(a[i],b[i],g[i]) == False: f = False print(-1) break if f == True: for i in range(n-1): if dep[x[i]] > dep[y[i]]: print(max(1,ans[x[i]]),end=" ") else: print(max(1, ans[y[i]]), end=" ") ```
105,375
Provide tags and a correct Python 3 solution for this coding contest problem. There are n railway stations in Berland. They are connected to each other by n-1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree. You have a map of that network, so for each railway section you know which stations it connects. Each of the n-1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 1 to 10^6 inclusive. You asked m passengers some questions: the j-th one told you three values: * his departure station a_j; * his arrival station b_j; * minimum scenery beauty along the path from a_j to b_j (the train is moving along the shortest path from a_j to b_j). You are planning to update the map and set some value f_i on each railway section β€” the scenery beauty. The passengers' answers should be consistent with these values. Print any valid set of values f_1, f_2, ..., f_{n-1}, which the passengers' answer is consistent with or report that it doesn't exist. Input The first line contains a single integer n (2 ≀ n ≀ 5000) β€” the number of railway stations in Berland. The next n-1 lines contain descriptions of the railway sections: the i-th section description is two integers x_i and y_i (1 ≀ x_i, y_i ≀ n, x_i β‰  y_i), where x_i and y_i are the indices of the stations which are connected by the i-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway. The next line contains a single integer m (1 ≀ m ≀ 5000) β€” the number of passengers which were asked questions. Then m lines follow, the j-th line contains three integers a_j, b_j and g_j (1 ≀ a_j, b_j ≀ n; a_j β‰  b_j; 1 ≀ g_j ≀ 10^6) β€” the departure station, the arrival station and the minimum scenery beauty along his path. Output If there is no answer then print a single integer -1. Otherwise, print n-1 integers f_1, f_2, ..., f_{n-1} (1 ≀ f_i ≀ 10^6), where f_i is some valid scenery beauty along the i-th railway section. If there are multiple answers, you can print any of them. Examples Input 4 1 2 3 2 3 4 2 1 2 5 1 3 3 Output 5 3 5 Input 6 1 2 1 6 3 1 1 5 4 1 4 6 1 3 3 4 1 6 5 2 1 2 5 Output 5 3 1 2 1 Input 6 1 2 1 6 3 1 1 5 4 1 4 6 1 1 3 4 3 6 5 3 1 2 4 Output -1 Tags: constructive algorithms, dfs and similar, greedy, sortings, trees Correct Solution: ``` from collections import deque from operator import itemgetter import sys input = sys.stdin.readline def dfs(tree, root): par = {root: -1} st1 = deque([root]) while st1: v = st1.pop() for nxt_v in tree[v]: if nxt_v in par: continue else: par[nxt_v] = v st1.append(nxt_v) return par class LowestCommonAncestor(): def __init__(self, tree, root): self.n = len(tree) self.depth = [0] * self.n self.log_size = (self.n).bit_length() self.parent = [[-1] * self.n for i in range(self.log_size)] q = deque([(root, -1, 0)]) while q: v, par, dist = q.pop() self.parent[0][v] = par self.depth[v] = dist for child_v in tree[v]: if child_v != par: self.depth[child_v] = dist + 1 q.append((child_v, v, dist + 1)) for k in range(1, self.log_size): for v in range(self.n): self.parent[k][v] = self.parent[k-1][self.parent[k-1][v]] def lca(self, u, v): if self.depth[u] > self.depth[v]: u, v = v, u for k in range(self.log_size): if (self.depth[v] - self.depth[u] >> k) & 1: v = self.parent[k][v] if u == v: return u for k in reversed(range(self.log_size)): if self.parent[k][u] != self.parent[k][v]: u = self.parent[k][u] v = self.parent[k][v] return self.parent[0][u] n = int(input()) info = [list(map(int, input().split())) for i in range(n - 1)] m = int(input()) query = [list(map(int, input().split())) for i in range(m)] tree = [[] for i in range(n)] edge = {} for i in range(n - 1): a, b = info[i] a -= 1 b -= 1 if a > b: a, b = b, a tree[a].append(b) tree[b].append(a) edge[a * 10000 + b] = i root = 0 lca = LowestCommonAncestor(tree, root) par = dfs(tree, root) ans = [0] * (n - 1) query = sorted(query, key=itemgetter(2)) for a, b, g in query: a -= 1 b -= 1 ab = lca.lca(a, b) set_ = set() while True: if a == ab: break ind = edge[min(a, par[a]) * 10000 + max(a, par[a])] ans[ind] = g a = par[a] while True: if b == ab: break ind = edge[min(b, par[b]) * 10000 + max(b, par[b])] ans[ind] = g b = par[b] for i in set_: ans[i] = g for a, b, g in query: a -= 1 b -= 1 ab = lca.lca(a, b) res = 10 ** 10 while True: if a == ab: break ind = edge[min(a, par[a]) * 10000 + max(a, par[a])] res = min(res, ans[ind]) a = par[a] while True: if b == ab: break ind = edge[min(b, par[b]) * 10000 + max(b, par[b])] res = min(res, ans[ind]) b = par[b] if res != g: print(-1) exit() for i in range(n - 1): if ans[i] == 0: ans[i] = 10 ** 6 print(*ans) ```
105,376
Provide tags and a correct Python 3 solution for this coding contest problem. There are n railway stations in Berland. They are connected to each other by n-1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree. You have a map of that network, so for each railway section you know which stations it connects. Each of the n-1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 1 to 10^6 inclusive. You asked m passengers some questions: the j-th one told you three values: * his departure station a_j; * his arrival station b_j; * minimum scenery beauty along the path from a_j to b_j (the train is moving along the shortest path from a_j to b_j). You are planning to update the map and set some value f_i on each railway section β€” the scenery beauty. The passengers' answers should be consistent with these values. Print any valid set of values f_1, f_2, ..., f_{n-1}, which the passengers' answer is consistent with or report that it doesn't exist. Input The first line contains a single integer n (2 ≀ n ≀ 5000) β€” the number of railway stations in Berland. The next n-1 lines contain descriptions of the railway sections: the i-th section description is two integers x_i and y_i (1 ≀ x_i, y_i ≀ n, x_i β‰  y_i), where x_i and y_i are the indices of the stations which are connected by the i-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway. The next line contains a single integer m (1 ≀ m ≀ 5000) β€” the number of passengers which were asked questions. Then m lines follow, the j-th line contains three integers a_j, b_j and g_j (1 ≀ a_j, b_j ≀ n; a_j β‰  b_j; 1 ≀ g_j ≀ 10^6) β€” the departure station, the arrival station and the minimum scenery beauty along his path. Output If there is no answer then print a single integer -1. Otherwise, print n-1 integers f_1, f_2, ..., f_{n-1} (1 ≀ f_i ≀ 10^6), where f_i is some valid scenery beauty along the i-th railway section. If there are multiple answers, you can print any of them. Examples Input 4 1 2 3 2 3 4 2 1 2 5 1 3 3 Output 5 3 5 Input 6 1 2 1 6 3 1 1 5 4 1 4 6 1 3 3 4 1 6 5 2 1 2 5 Output 5 3 1 2 1 Input 6 1 2 1 6 3 1 1 5 4 1 4 6 1 1 3 4 3 6 5 3 1 2 4 Output -1 Tags: constructive algorithms, dfs and similar, greedy, sortings, trees Correct Solution: ``` import sys from operator import itemgetter readline = sys.stdin.readline def parorder(Edge, p): N = len(Edge) par = [0]*N par[p] = -1 stack = [p] order = [] visited = set([p]) ast = stack.append apo = order.append Ei = [None]*N while stack: vn = stack.pop() apo(vn) for vf, num in Edge[vn]: if vf in visited: continue Ei[vf] = num visited.add(vf) par[vf] = vn ast(vf) return par, order, Ei def lca(u, v): if dist[u] > dist[v]: u, v = v, u ddif = dist[v] - dist[u] for i in range(ddif.bit_length()): if (1<<i)&ddif: v = D[i][v] if u != v: for cnt in range(dist[u].bit_length()-1, -1, -1): if D[cnt][u] != D[cnt][v]: u = D[cnt][u] v = D[cnt][v] u = P[u] return u def update(ou, ov, x): luv = lca(ou, ov) u, v = ou, ov distu = dist[u] - dist[luv] for i in range(distu.bit_length()): if (1<<i) & distu: data[i][u] = max(data[i][u], x) u = D[i][u] distv = dist[v] - dist[luv] for i in range(distv.bit_length()): if (1<<i) & distv: data[i][v] = max(data[i][v], x) v = D[i][v] def query(u, v): res = inf if dist[u] > dist[v]: u, v = v, u ddif = dist[v] - dist[u] for i in range(ddif.bit_length()): if (1<<i)&ddif: res = min(res, Dmin[i][v]) v = D[i][v] if u != v: for cnt in range(dist[u].bit_length()-1, -1, -1): if D[cnt][u] != D[cnt][v]: res = min(res, Dmin[cnt][u], Dmin[cnt][v]) u = D[cnt][u] v = D[cnt][v] res = min(res, path[u], path[v]) return res N = int(readline()) Edge = [[] for _ in range(N)] for num in range(N-1): a, b = map(int, readline().split()) a -= 1 b -= 1 Edge[a].append((b, num)) Edge[b].append((a, num)) root = 0 P, L, Einv = parorder(Edge, root) P[root] = None D = [P[:]] dep = N.bit_length() for _ in range(dep): ret = [None]*N for i in range(N): k = D[-1][i] if k is not None: ret[i] = D[-1][k] D.append(ret) dist = [0]*N for l in L[1:]: dist[l] = 1+dist[P[l]] mini = 0 data = [[mini]*N for _ in range(dep)] Q = int(readline()) qu = [] for _ in range(Q): a, b, c = map(int, readline().split()) update(a-1, b-1, c) qu.append((a-1, b-1, c)) path = [1]*N for l in L[::-1]: ret = [mini]*dep ret[dep-1] = data[dep-1][l] for idx in range(dep-2, -1, -1): ret[idx] = max(ret[idx+1], data[idx][l]) path[l] = ret[0] for i in range(dep-1): if D[i][l] is None: break data[i][D[i][l]] = max(data[i][D[i][l]], ret[i+1]) inf = 10**6 for i in range(N): if path[i] == mini: path[i] = inf Dmin = [path[:]] for d in range(dep): res = [inf]*N for u in range(N): if D[d][u] is not None: res[u] = min(Dmin[-1][u], Dmin[-1][D[d][u]]) Dmin.append(res) for a, b, c in qu: if c != query(a, b): print(-1) break else: ans = [inf]*(N-1) for i in range(N): if i != root: ans[Einv[i]] = path[i] print(*ans) ```
105,377
Provide tags and a correct Python 3 solution for this coding contest problem. There are n railway stations in Berland. They are connected to each other by n-1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree. You have a map of that network, so for each railway section you know which stations it connects. Each of the n-1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 1 to 10^6 inclusive. You asked m passengers some questions: the j-th one told you three values: * his departure station a_j; * his arrival station b_j; * minimum scenery beauty along the path from a_j to b_j (the train is moving along the shortest path from a_j to b_j). You are planning to update the map and set some value f_i on each railway section β€” the scenery beauty. The passengers' answers should be consistent with these values. Print any valid set of values f_1, f_2, ..., f_{n-1}, which the passengers' answer is consistent with or report that it doesn't exist. Input The first line contains a single integer n (2 ≀ n ≀ 5000) β€” the number of railway stations in Berland. The next n-1 lines contain descriptions of the railway sections: the i-th section description is two integers x_i and y_i (1 ≀ x_i, y_i ≀ n, x_i β‰  y_i), where x_i and y_i are the indices of the stations which are connected by the i-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway. The next line contains a single integer m (1 ≀ m ≀ 5000) β€” the number of passengers which were asked questions. Then m lines follow, the j-th line contains three integers a_j, b_j and g_j (1 ≀ a_j, b_j ≀ n; a_j β‰  b_j; 1 ≀ g_j ≀ 10^6) β€” the departure station, the arrival station and the minimum scenery beauty along his path. Output If there is no answer then print a single integer -1. Otherwise, print n-1 integers f_1, f_2, ..., f_{n-1} (1 ≀ f_i ≀ 10^6), where f_i is some valid scenery beauty along the i-th railway section. If there are multiple answers, you can print any of them. Examples Input 4 1 2 3 2 3 4 2 1 2 5 1 3 3 Output 5 3 5 Input 6 1 2 1 6 3 1 1 5 4 1 4 6 1 3 3 4 1 6 5 2 1 2 5 Output 5 3 1 2 1 Input 6 1 2 1 6 3 1 1 5 4 1 4 6 1 1 3 4 3 6 5 3 1 2 4 Output -1 Tags: constructive algorithms, dfs and similar, greedy, sortings, trees Correct Solution: ``` #AUTHOR- titia import sys input = sys.stdin.readline from operator import itemgetter n=int(input()) EDGE=[sorted(map(int,input().split())) for i in range(n-1)] E=[[] for i in range(n+1)] D=dict() for i in range(n-1): x,y=EDGE[i] D[(x<<13)+y]=i D[(y<<13)+x]=i E[x].append(y) E[y].append(x) m=int(input()) Q=sorted([tuple(map(int,input().split())) for i in range(m)],key=itemgetter(2),reverse=True) def dfs(x,y,n,w): USE=[-1]*(n+1) NOW=[x] while NOW: n=NOW.pop() if n==y: break for to in E[n]: if USE[to]==-1: USE[to]=n NOW.append(to) change=0 while y!=x: p=D[(y<<13)+USE[y]] if ANS[p]<=w: change+=1 ANS[p]=w y=USE[y] if change==0: print(-1) sys.exit() ANS=[1]*(n-1) for a,b,q in Q: dfs(a,b,n,q) flag=1 print(*ANS) ```
105,378
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n railway stations in Berland. They are connected to each other by n-1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree. You have a map of that network, so for each railway section you know which stations it connects. Each of the n-1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 1 to 10^6 inclusive. You asked m passengers some questions: the j-th one told you three values: * his departure station a_j; * his arrival station b_j; * minimum scenery beauty along the path from a_j to b_j (the train is moving along the shortest path from a_j to b_j). You are planning to update the map and set some value f_i on each railway section β€” the scenery beauty. The passengers' answers should be consistent with these values. Print any valid set of values f_1, f_2, ..., f_{n-1}, which the passengers' answer is consistent with or report that it doesn't exist. Input The first line contains a single integer n (2 ≀ n ≀ 5000) β€” the number of railway stations in Berland. The next n-1 lines contain descriptions of the railway sections: the i-th section description is two integers x_i and y_i (1 ≀ x_i, y_i ≀ n, x_i β‰  y_i), where x_i and y_i are the indices of the stations which are connected by the i-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway. The next line contains a single integer m (1 ≀ m ≀ 5000) β€” the number of passengers which were asked questions. Then m lines follow, the j-th line contains three integers a_j, b_j and g_j (1 ≀ a_j, b_j ≀ n; a_j β‰  b_j; 1 ≀ g_j ≀ 10^6) β€” the departure station, the arrival station and the minimum scenery beauty along his path. Output If there is no answer then print a single integer -1. Otherwise, print n-1 integers f_1, f_2, ..., f_{n-1} (1 ≀ f_i ≀ 10^6), where f_i is some valid scenery beauty along the i-th railway section. If there are multiple answers, you can print any of them. Examples Input 4 1 2 3 2 3 4 2 1 2 5 1 3 3 Output 5 3 5 Input 6 1 2 1 6 3 1 1 5 4 1 4 6 1 3 3 4 1 6 5 2 1 2 5 Output 5 3 1 2 1 Input 6 1 2 1 6 3 1 1 5 4 1 4 6 1 1 3 4 3 6 5 3 1 2 4 Output -1 Submitted Solution: ``` from collections import defaultdict # n - 1 is number of edges # p is number of passengers # O(n + plog(p) + p*n) solution # Find shortest path and write min (high to low) on any still unset edges. # Shortest path via dfs/bfs TLEs. # Root the tree so you can find short path just by walking up to LCA. # Had to micro-optimize a lot before it was fast... def solve(edges, passengers): N = len(edges) + 1 g = defaultdict(lambda: defaultdict(int)) for edgeId, e in enumerate(edges): g[e[0]][e[1]] = edgeId g[e[1]][e[0]] = edgeId # Do a DFS to (arbitrarily) root the tree and record depths parent = [None] * N parentEdge = [None] * N depth = [None] * N parent[0] = float("inf") parentEdge[0] = float("inf") depth[0] = 0 stack = [0] while stack: node = stack.pop() for k, edgeId in g[node].items(): if parent[k] is None: parent[k] = node parentEdge[k] = edgeId depth[k] = depth[node] + 1 stack.append(k) def getEdges(source, dest): # Find shortest path by walking both nodes up till their LCA # Returns the edge ids in arbitrary order! node1 = source node2 = dest # Start them at the same depth first d1 = depth[node1] d2 = depth[node2] while d1 > d2: yield parentEdge[node1] node1 = parent[node1] d1 -= 1 while d1 < d2: yield parentEdge[node2] node2 = parent[node2] d2 -= 1 assert d1 == d2 # Walk up both paths until find lca while node1 != node2: yield parentEdge[node1] node1 = parent[node1] yield parentEdge[node2] node2 = parent[node2] assert node1 == node2 # Sort by score, high to low passengers.sort(key=lambda t: t[3], reverse=True) # For each passenger, set any unset edges in their path to their min score edgeToScore = [None] * (N - 1) for p, a, b, score in passengers: numEdges = 0 for edgeId in getEdges(a, b): if edgeToScore[edgeId] is None: numEdges += 1 edgeToScore[edgeId] = score else: # Since sorted any existing scores must higher or equal # Can't overwrite lower because will lower the previous's min score score2 = edgeToScore[edgeId] assert score2 >= score if score2 == score: numEdges += 1 # Need to set at least one edge if numEdges == 0: return -1 return " ".join(str(score) if score is not None else "1" for score in edgeToScore) if False: import sys N = 5000 edges = list(zip(range(N - 1), range(1, N))) passengers = [(p, 0, p, N - p) for p in range(1, N)] print(solve(edges, passengers)) sys.exit() if __name__ == "__main__": N = int(input()) edges = [] for edgeId in range(N - 1): x, y = map(int, input().split()) edges.append((x - 1, y - 1)) P = int(input()) passengers = [] for p in range(P): a, b, score = map(int, input().split()) passengers.append((p, a - 1, b - 1, score)) ans = solve(edges, passengers) print(ans) ``` Yes
105,379
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n railway stations in Berland. They are connected to each other by n-1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree. You have a map of that network, so for each railway section you know which stations it connects. Each of the n-1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 1 to 10^6 inclusive. You asked m passengers some questions: the j-th one told you three values: * his departure station a_j; * his arrival station b_j; * minimum scenery beauty along the path from a_j to b_j (the train is moving along the shortest path from a_j to b_j). You are planning to update the map and set some value f_i on each railway section β€” the scenery beauty. The passengers' answers should be consistent with these values. Print any valid set of values f_1, f_2, ..., f_{n-1}, which the passengers' answer is consistent with or report that it doesn't exist. Input The first line contains a single integer n (2 ≀ n ≀ 5000) β€” the number of railway stations in Berland. The next n-1 lines contain descriptions of the railway sections: the i-th section description is two integers x_i and y_i (1 ≀ x_i, y_i ≀ n, x_i β‰  y_i), where x_i and y_i are the indices of the stations which are connected by the i-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway. The next line contains a single integer m (1 ≀ m ≀ 5000) β€” the number of passengers which were asked questions. Then m lines follow, the j-th line contains three integers a_j, b_j and g_j (1 ≀ a_j, b_j ≀ n; a_j β‰  b_j; 1 ≀ g_j ≀ 10^6) β€” the departure station, the arrival station and the minimum scenery beauty along his path. Output If there is no answer then print a single integer -1. Otherwise, print n-1 integers f_1, f_2, ..., f_{n-1} (1 ≀ f_i ≀ 10^6), where f_i is some valid scenery beauty along the i-th railway section. If there are multiple answers, you can print any of them. Examples Input 4 1 2 3 2 3 4 2 1 2 5 1 3 3 Output 5 3 5 Input 6 1 2 1 6 3 1 1 5 4 1 4 6 1 3 3 4 1 6 5 2 1 2 5 Output 5 3 1 2 1 Input 6 1 2 1 6 3 1 1 5 4 1 4 6 1 1 3 4 3 6 5 3 1 2 4 Output -1 Submitted Solution: ``` import copy n = int(input()) g = [[] for i in range(n)] depth = [0 for i in range(n)] parent = [-2 for i in range(n)] parent[0] = -1 beauty = [1 for i in range(n)] Edges = [] Edges2 = [] def chk(f,t): _min = 1145141919810 while f!=t: if depth[f] < depth[t]: f,t = t,f _min = min(beauty[f],_min) f = parent[f] return _min def dfs(): callstack = [0] while len(callstack): c = callstack.pop() for i in g[c]: if parent[c] == i: continue parent[i] = c depth[i] = depth[c] + 1 callstack.append(i) def update(f,t,w): while f!=t: if depth[f] < depth[t]: f,t = t,f beauty[f] = max(beauty[f],w) f = parent[f] for i in range(n-1): fr,to = (int(i)-1 for i in input().split(' ')) g[fr].append(to) g[to].append(fr) Edges.append((fr,to)) dfs() del g m = int(input()) for i in range(m): fr,to,we = (int(i) for i in input().split(' ')) fr -= 1 to -= 1 Edges2.append((fr,to,we)) update(fr,to,we) for a,b,c in Edges2: if chk(a,b) != c: print(-1) exit(0) for a,b in Edges: if parent[a] == b: print(beauty[a],end=' ') else: print(beauty[b],end=' ') ``` Yes
105,380
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n railway stations in Berland. They are connected to each other by n-1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree. You have a map of that network, so for each railway section you know which stations it connects. Each of the n-1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 1 to 10^6 inclusive. You asked m passengers some questions: the j-th one told you three values: * his departure station a_j; * his arrival station b_j; * minimum scenery beauty along the path from a_j to b_j (the train is moving along the shortest path from a_j to b_j). You are planning to update the map and set some value f_i on each railway section β€” the scenery beauty. The passengers' answers should be consistent with these values. Print any valid set of values f_1, f_2, ..., f_{n-1}, which the passengers' answer is consistent with or report that it doesn't exist. Input The first line contains a single integer n (2 ≀ n ≀ 5000) β€” the number of railway stations in Berland. The next n-1 lines contain descriptions of the railway sections: the i-th section description is two integers x_i and y_i (1 ≀ x_i, y_i ≀ n, x_i β‰  y_i), where x_i and y_i are the indices of the stations which are connected by the i-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway. The next line contains a single integer m (1 ≀ m ≀ 5000) β€” the number of passengers which were asked questions. Then m lines follow, the j-th line contains three integers a_j, b_j and g_j (1 ≀ a_j, b_j ≀ n; a_j β‰  b_j; 1 ≀ g_j ≀ 10^6) β€” the departure station, the arrival station and the minimum scenery beauty along his path. Output If there is no answer then print a single integer -1. Otherwise, print n-1 integers f_1, f_2, ..., f_{n-1} (1 ≀ f_i ≀ 10^6), where f_i is some valid scenery beauty along the i-th railway section. If there are multiple answers, you can print any of them. Examples Input 4 1 2 3 2 3 4 2 1 2 5 1 3 3 Output 5 3 5 Input 6 1 2 1 6 3 1 1 5 4 1 4 6 1 3 3 4 1 6 5 2 1 2 5 Output 5 3 1 2 1 Input 6 1 2 1 6 3 1 1 5 4 1 4 6 1 1 3 4 3 6 5 3 1 2 4 Output -1 Submitted Solution: ``` import sys input = sys.stdin.readline from operator import itemgetter n=int(input()) EDGE=[sorted(map(int,input().split())) for i in range(n-1)] E=[[] for i in range(n+1)] D=dict() for i in range(n-1): x,y=EDGE[i] D[(x<<13)+y]=i D[(y<<13)+x]=i E[x].append(y) E[y].append(x) m=int(input()) Q=sorted([tuple(map(int,input().split())) for i in range(m)],key=itemgetter(2),reverse=True) def dfs(x,y,n,w): USE=[-1]*(n+1) NOW=[x] while NOW: n=NOW.pop() if n==y: break for to in E[n]: if USE[to]==-1: USE[to]=n NOW.append(to) change=0 while y!=x: p=D[(y<<13)+USE[y]] if ANS[p]<=w: change+=1 ANS[p]=w y=USE[y] if change==0: print(-1) sys.exit() ANS=[1]*(n-1) for a,b,q in Q: dfs(a,b,n,q) flag=1 print(*ANS) ``` Yes
105,381
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n railway stations in Berland. They are connected to each other by n-1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree. You have a map of that network, so for each railway section you know which stations it connects. Each of the n-1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 1 to 10^6 inclusive. You asked m passengers some questions: the j-th one told you three values: * his departure station a_j; * his arrival station b_j; * minimum scenery beauty along the path from a_j to b_j (the train is moving along the shortest path from a_j to b_j). You are planning to update the map and set some value f_i on each railway section β€” the scenery beauty. The passengers' answers should be consistent with these values. Print any valid set of values f_1, f_2, ..., f_{n-1}, which the passengers' answer is consistent with or report that it doesn't exist. Input The first line contains a single integer n (2 ≀ n ≀ 5000) β€” the number of railway stations in Berland. The next n-1 lines contain descriptions of the railway sections: the i-th section description is two integers x_i and y_i (1 ≀ x_i, y_i ≀ n, x_i β‰  y_i), where x_i and y_i are the indices of the stations which are connected by the i-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway. The next line contains a single integer m (1 ≀ m ≀ 5000) β€” the number of passengers which were asked questions. Then m lines follow, the j-th line contains three integers a_j, b_j and g_j (1 ≀ a_j, b_j ≀ n; a_j β‰  b_j; 1 ≀ g_j ≀ 10^6) β€” the departure station, the arrival station and the minimum scenery beauty along his path. Output If there is no answer then print a single integer -1. Otherwise, print n-1 integers f_1, f_2, ..., f_{n-1} (1 ≀ f_i ≀ 10^6), where f_i is some valid scenery beauty along the i-th railway section. If there are multiple answers, you can print any of them. Examples Input 4 1 2 3 2 3 4 2 1 2 5 1 3 3 Output 5 3 5 Input 6 1 2 1 6 3 1 1 5 4 1 4 6 1 3 3 4 1 6 5 2 1 2 5 Output 5 3 1 2 1 Input 6 1 2 1 6 3 1 1 5 4 1 4 6 1 1 3 4 3 6 5 3 1 2 4 Output -1 Submitted Solution: ``` #!/usr/bin/env python import os import sys from io import BytesIO, IOBase # Ref https://github.com/cheran-senthil/PyRival/tree/master/pyrival # sys.modules["hashlib"] = sys.sha512 = sys # import random def dfsPre(par,graph,tin,tout): n = len(graph) visited, finished = [False] * n, [False] * n stack = [1] # print(tin,tout) t = 0 while stack: start = stack[-1] if not visited[start]: visited[start]=True t+=1 tin[start] = t for child in graph[start]: if not visited[child]: stack.append(child) par[child] = start else: stack.pop() t+=1 tout[start] = t def parent(tin,tout,u,v): return tin[u]<=tin[v] and tout[v]<=tout[u] def dfs(par,tin,tout,adj,u,v,c): while(not parent(tin,tout,u,v)): adj[u][par[u]]=max(adj[u][par[u]],c) u=par[u] def dfs1(par,tin,tout,adj,u,v): ans = 10000000 while(not parent(tin,tout,u,v)): ans=min(ans,adj[u][par[u]]) u=par[u] return ans # def rnd(v): # random.shuffle(v) # return v def main(): n = int(input()) edges = [ [int(x) for x in input().split()] for i in range(n-1) ] m = int(input()) qur = [ [int(x) for x in input().split()] for i in range(m) ] graph = [ [] for i in range(n+1) ] adj = [ [1 for j in range(n+1)] for i in range(n+1) ] par = [-1]*(n+1) tin = [0]*(n+1) tout = [0]*(n+1) for x in edges: graph[x[0]].append(x[1]) graph[x[1]].append(x[0]) dfsPre(par,graph,tin,tout) chk = {} for x in qur: u,v,c=x[0],x[1],x[2] if(u>v): u,v=v,u fl = False try: j=chk[u*(n+1)+v] if j !=c : print(-1) fl = True except: chk[u*(n+1)+v] = c dfs(par,tin,tout,adj,u,v,c) dfs(par,tin,tout,adj,v,u,c) if(fl): exit(0) for i in range(1,n+1): for j in range(i+1,n+1): adj[i][j]=adj[j][i]=max(adj[i][j],adj[j][i]) for x,y in chk.items(): u,v=x//(n+1),x%(n+1) if(min(dfs1(par,tin,tout,adj,v,u),dfs1(par,tin,tout,adj,u,v))!=y): print(-1) exit(0) for x in edges: print(adj[x[0]][x[1]],end=" ") # 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") # endregion if __name__ == "__main__": main() ``` Yes
105,382
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n railway stations in Berland. They are connected to each other by n-1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree. You have a map of that network, so for each railway section you know which stations it connects. Each of the n-1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 1 to 10^6 inclusive. You asked m passengers some questions: the j-th one told you three values: * his departure station a_j; * his arrival station b_j; * minimum scenery beauty along the path from a_j to b_j (the train is moving along the shortest path from a_j to b_j). You are planning to update the map and set some value f_i on each railway section β€” the scenery beauty. The passengers' answers should be consistent with these values. Print any valid set of values f_1, f_2, ..., f_{n-1}, which the passengers' answer is consistent with or report that it doesn't exist. Input The first line contains a single integer n (2 ≀ n ≀ 5000) β€” the number of railway stations in Berland. The next n-1 lines contain descriptions of the railway sections: the i-th section description is two integers x_i and y_i (1 ≀ x_i, y_i ≀ n, x_i β‰  y_i), where x_i and y_i are the indices of the stations which are connected by the i-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway. The next line contains a single integer m (1 ≀ m ≀ 5000) β€” the number of passengers which were asked questions. Then m lines follow, the j-th line contains three integers a_j, b_j and g_j (1 ≀ a_j, b_j ≀ n; a_j β‰  b_j; 1 ≀ g_j ≀ 10^6) β€” the departure station, the arrival station and the minimum scenery beauty along his path. Output If there is no answer then print a single integer -1. Otherwise, print n-1 integers f_1, f_2, ..., f_{n-1} (1 ≀ f_i ≀ 10^6), where f_i is some valid scenery beauty along the i-th railway section. If there are multiple answers, you can print any of them. Examples Input 4 1 2 3 2 3 4 2 1 2 5 1 3 3 Output 5 3 5 Input 6 1 2 1 6 3 1 1 5 4 1 4 6 1 3 3 4 1 6 5 2 1 2 5 Output 5 3 1 2 1 Input 6 1 2 1 6 3 1 1 5 4 1 4 6 1 1 3 4 3 6 5 3 1 2 4 Output -1 Submitted Solution: ``` from collections import defaultdict n = int(input()) adj = [[] for _ in range(n)] p = [-1]*n h = [0]*n edges = [] def dfs(root,par = -1): p[root] = par if(par+1): h[root] = h[par]+1 for c in adj[root]: if c!=par: dfs(c,root) def lca(v,u): if v==u: return v if h[u]>h[v]: v,u = u,v return lca(p[v],u) for i in range(n-1): u,v = map(int,input().split()) if v<u: u,v = v,u u-=1 v-=1 edges.append((u,v)) adj[u].append(v) adj[v].append(u) m = int(input()) ms = [] for i in range(m): a,b,g = map(int,input().split()) a-=1;b-=1; ms.append([a,b,g]) ms.sort(key=lambda x:x[2]) dfs(0) pairs = defaultdict(int) for i in ms: a,b,g = i lc = lca(a,b) while a!=lc: pairs[tuple(sorted((a,p[a])))] = max(pairs[tuple(sorted((a,p[a])))],g) a = p[a] while b!=lc: pairs[tuple(sorted((b,p[b])))] = max(pairs[tuple(sorted((a,p[b])))],g) b = p[b] done = True for i in ms: a,b,g = i lc = lca(a,b) mini = 10**9 while a!=lc: mini = min(mini,pairs[tuple(sorted((a,p[a])))]) a = p[a] while b!=lc: mini = min(mini,pairs[tuple(sorted((b,p[b])))]) b = p[b] if mini!=g: done = False print(-1) break if done: for i in edges: if pairs[i]==0: print(10**6+1,end=" ") else: print(pairs[i],end=" ") print() ``` No
105,383
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n railway stations in Berland. They are connected to each other by n-1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree. You have a map of that network, so for each railway section you know which stations it connects. Each of the n-1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 1 to 10^6 inclusive. You asked m passengers some questions: the j-th one told you three values: * his departure station a_j; * his arrival station b_j; * minimum scenery beauty along the path from a_j to b_j (the train is moving along the shortest path from a_j to b_j). You are planning to update the map and set some value f_i on each railway section β€” the scenery beauty. The passengers' answers should be consistent with these values. Print any valid set of values f_1, f_2, ..., f_{n-1}, which the passengers' answer is consistent with or report that it doesn't exist. Input The first line contains a single integer n (2 ≀ n ≀ 5000) β€” the number of railway stations in Berland. The next n-1 lines contain descriptions of the railway sections: the i-th section description is two integers x_i and y_i (1 ≀ x_i, y_i ≀ n, x_i β‰  y_i), where x_i and y_i are the indices of the stations which are connected by the i-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway. The next line contains a single integer m (1 ≀ m ≀ 5000) β€” the number of passengers which were asked questions. Then m lines follow, the j-th line contains three integers a_j, b_j and g_j (1 ≀ a_j, b_j ≀ n; a_j β‰  b_j; 1 ≀ g_j ≀ 10^6) β€” the departure station, the arrival station and the minimum scenery beauty along his path. Output If there is no answer then print a single integer -1. Otherwise, print n-1 integers f_1, f_2, ..., f_{n-1} (1 ≀ f_i ≀ 10^6), where f_i is some valid scenery beauty along the i-th railway section. If there are multiple answers, you can print any of them. Examples Input 4 1 2 3 2 3 4 2 1 2 5 1 3 3 Output 5 3 5 Input 6 1 2 1 6 3 1 1 5 4 1 4 6 1 3 3 4 1 6 5 2 1 2 5 Output 5 3 1 2 1 Input 6 1 2 1 6 3 1 1 5 4 1 4 6 1 1 3 4 3 6 5 3 1 2 4 Output -1 Submitted Solution: ``` def graphRoot(n, roots, s, vertex): used = [False] * n used[s] = True queue = [s] parents = [0] * n parents[s] = -1 path = [] while len(queue) > 0: for to in roots[queue[0]]: if not used[to]: used[to] = True queue.append(to) parents[to] = queue[0] queue = queue[1:] while vertex != -1: path = [vertex] + path vertex = parents[vertex] return path def dataSort(a): return int(a[2]) n = int(input()) links = [] beauties = {} for i in range(n - 1): links.append(input().split(' ')) root = (int(links[i][0]) - 1, int(links[i][1]) - 1) beauties[root] = 1 roots = [] for i in range(n): roots.append([]) for i in range(n - 1): roots[int(links[i][0]) - 1].append(int(links[i][1]) - 1) roots[int(links[i][1]) - 1].append(int(links[i][0]) - 1) m = int(input()) breaker = False data = [] for i in range(m): data.append(input().split(' ')) d = data[i] path = graphRoot(n, roots, int(d[0]) - 1, int(d[1]) - 1) beauty = int(d[2]) bFound = False for j in range(len(path) - 1): if beauties.get((path[j], path[j + 1])) != None: if beauty >= beauties[(path[j], path[j + 1])]: beauties[(path[j], path[j + 1])] = beauty bFound = True else: if beauty >= beauties[(path[j + 1], path[j])]: beauties[(path[j + 1], path[j])] = beauty bFound = True if not bFound: breaker = True break if not breaker: ans = [] for i in beauties: ans.append(str(beauties[i])) print(' '.join(ans)) else: print(-1) ``` No
105,384
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n railway stations in Berland. They are connected to each other by n-1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree. You have a map of that network, so for each railway section you know which stations it connects. Each of the n-1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 1 to 10^6 inclusive. You asked m passengers some questions: the j-th one told you three values: * his departure station a_j; * his arrival station b_j; * minimum scenery beauty along the path from a_j to b_j (the train is moving along the shortest path from a_j to b_j). You are planning to update the map and set some value f_i on each railway section β€” the scenery beauty. The passengers' answers should be consistent with these values. Print any valid set of values f_1, f_2, ..., f_{n-1}, which the passengers' answer is consistent with or report that it doesn't exist. Input The first line contains a single integer n (2 ≀ n ≀ 5000) β€” the number of railway stations in Berland. The next n-1 lines contain descriptions of the railway sections: the i-th section description is two integers x_i and y_i (1 ≀ x_i, y_i ≀ n, x_i β‰  y_i), where x_i and y_i are the indices of the stations which are connected by the i-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway. The next line contains a single integer m (1 ≀ m ≀ 5000) β€” the number of passengers which were asked questions. Then m lines follow, the j-th line contains three integers a_j, b_j and g_j (1 ≀ a_j, b_j ≀ n; a_j β‰  b_j; 1 ≀ g_j ≀ 10^6) β€” the departure station, the arrival station and the minimum scenery beauty along his path. Output If there is no answer then print a single integer -1. Otherwise, print n-1 integers f_1, f_2, ..., f_{n-1} (1 ≀ f_i ≀ 10^6), where f_i is some valid scenery beauty along the i-th railway section. If there are multiple answers, you can print any of them. Examples Input 4 1 2 3 2 3 4 2 1 2 5 1 3 3 Output 5 3 5 Input 6 1 2 1 6 3 1 1 5 4 1 4 6 1 3 3 4 1 6 5 2 1 2 5 Output 5 3 1 2 1 Input 6 1 2 1 6 3 1 1 5 4 1 4 6 1 1 3 4 3 6 5 3 1 2 4 Output -1 Submitted Solution: ``` def graphRoot(n, roots, s, vertex): used = [False] * n used[s] = True queue = [s] parents = [0] * n parents[s] = -1 path = [] while len(queue) > 0: for to in roots[queue[0]]: if not used[to]: used[to] = True queue.append(to) parents[to] = queue[0] queue = queue[1:] while vertex != -1: path = [vertex] + path vertex = parents[vertex] return path n = int(input()) links = [] beauties = {} for i in range(n - 1): links.append(input().split(' ')) root = (int(links[i][0]) - 1, int(links[i][1]) - 1) beauties[root] = 1 roots = [] for i in range(n): roots.append([]) for i in range(n - 1): roots[int(links[i][0]) - 1].append(int(links[i][1]) - 1) roots[int(links[i][1]) - 1].append(int(links[i][0]) - 1) m = int(input()) breaker = False for i in range(m): data = input().split(' ') path = graphRoot(n, roots, int(data[0]) - 1, int(data[1]) - 1) beauty = int(data[2]) for j in range(len(path) - 1): if beauties.get((path[j], path[j + 1])) != None: if beauty > beauties[(path[j], path[j + 1])]: beauties[(path[j], path[j + 1])] = beauty else: breaker = True break else: if beauty > beauties[(path[j + 1], path[j])]: beauties[(path[j + 1], path[j])] = beauty else: breaker = True break if breaker: break if not breaker: ans = [] for i in beauties: ans.append(str(beauties[i])) print(' '.join(ans)) else: print(-1) ``` No
105,385
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n railway stations in Berland. They are connected to each other by n-1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree. You have a map of that network, so for each railway section you know which stations it connects. Each of the n-1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 1 to 10^6 inclusive. You asked m passengers some questions: the j-th one told you three values: * his departure station a_j; * his arrival station b_j; * minimum scenery beauty along the path from a_j to b_j (the train is moving along the shortest path from a_j to b_j). You are planning to update the map and set some value f_i on each railway section β€” the scenery beauty. The passengers' answers should be consistent with these values. Print any valid set of values f_1, f_2, ..., f_{n-1}, which the passengers' answer is consistent with or report that it doesn't exist. Input The first line contains a single integer n (2 ≀ n ≀ 5000) β€” the number of railway stations in Berland. The next n-1 lines contain descriptions of the railway sections: the i-th section description is two integers x_i and y_i (1 ≀ x_i, y_i ≀ n, x_i β‰  y_i), where x_i and y_i are the indices of the stations which are connected by the i-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway. The next line contains a single integer m (1 ≀ m ≀ 5000) β€” the number of passengers which were asked questions. Then m lines follow, the j-th line contains three integers a_j, b_j and g_j (1 ≀ a_j, b_j ≀ n; a_j β‰  b_j; 1 ≀ g_j ≀ 10^6) β€” the departure station, the arrival station and the minimum scenery beauty along his path. Output If there is no answer then print a single integer -1. Otherwise, print n-1 integers f_1, f_2, ..., f_{n-1} (1 ≀ f_i ≀ 10^6), where f_i is some valid scenery beauty along the i-th railway section. If there are multiple answers, you can print any of them. Examples Input 4 1 2 3 2 3 4 2 1 2 5 1 3 3 Output 5 3 5 Input 6 1 2 1 6 3 1 1 5 4 1 4 6 1 3 3 4 1 6 5 2 1 2 5 Output 5 3 1 2 1 Input 6 1 2 1 6 3 1 1 5 4 1 4 6 1 1 3 4 3 6 5 3 1 2 4 Output -1 Submitted Solution: ``` import sys input = sys.stdin.readline from operator import itemgetter n=int(input()) EDGE=[sorted(map(int,input().split())) for i in range(n-1)] E=[[] for i in range(n+1)] D=dict() for i in range(n-1): x,y=EDGE[i] D[x,y]=i E[x].append(y) E[y].append(x) m=int(input()) Q=sorted([tuple(map(int,input().split())) for i in range(m)],key=itemgetter(2),reverse=True) def dfs(x,y,n): if DD.get((x,y))!=None: return DD[x,y] USE=[-1]*(n+1) NOW=[x] while NOW: n=NOW.pop() if n==y: break for to in E[n]: if USE[to]==-1: USE[to]=n NOW.append(to) yield y while y!=x: y=USE[y] yield y ANS=[10**6]*(n-1) DD=dict() for a,b,q in Q: PATH=tuple(dfs(a,b,n)) DD[a,b]=PATH flag=1 for i in range(1,len(PATH)): k=D[tuple(sorted((PATH[i-1],PATH[i])))] if ANS[k]==10**6 or ANS[k]==q: ANS[k]=q flag=0 if flag: print(-1) sys.exit() print(*ANS) ``` No
105,386
Provide tags and a correct Python 3 solution for this coding contest problem. Tanya wants to go on a journey across the cities of Berland. There are n cities situated along the main railroad line of Berland, and these cities are numbered from 1 to n. Tanya plans her journey as follows. First of all, she will choose some city c_1 to start her journey. She will visit it, and after that go to some other city c_2 > c_1, then to some other city c_3 > c_2, and so on, until she chooses to end her journey in some city c_k > c_{k - 1}. So, the sequence of visited cities [c_1, c_2, ..., c_k] should be strictly increasing. There are some additional constraints on the sequence of cities Tanya visits. Each city i has a beauty value b_i associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities c_i and c_{i + 1}, the condition c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i} must hold. For example, if n = 8 and b = [3, 4, 4, 6, 6, 7, 8, 9], there are several three possible ways to plan a journey: * c = [1, 2, 4]; * c = [3, 5, 6, 8]; * c = [7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above. Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey? Input The first line contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of cities in Berland. The second line contains n integers b_1, b_2, ..., b_n (1 ≀ b_i ≀ 4 β‹… 10^5), where b_i is the beauty value of the i-th city. Output Print one integer β€” the maximum beauty of a journey Tanya can choose. Examples Input 6 10 7 1 9 10 15 Output 26 Input 1 400000 Output 400000 Input 7 8 9 26 11 12 29 14 Output 55 Note The optimal journey plan in the first example is c = [2, 4, 5]. The optimal journey plan in the second example is c = [1]. The optimal journey plan in the third example is c = [3, 6]. Tags: data structures, dp, greedy, math, sortings Correct Solution: ``` n = int(input()) lis = list(map(int,input().split())) d = {} for i in range(n): v = lis[i]-i if d.get(v): d[v] += lis[i] else: d[v] = lis[i] m = 0 for k in d.values(): m = max(m,k) print(m) ```
105,387
Provide tags and a correct Python 3 solution for this coding contest problem. Tanya wants to go on a journey across the cities of Berland. There are n cities situated along the main railroad line of Berland, and these cities are numbered from 1 to n. Tanya plans her journey as follows. First of all, she will choose some city c_1 to start her journey. She will visit it, and after that go to some other city c_2 > c_1, then to some other city c_3 > c_2, and so on, until she chooses to end her journey in some city c_k > c_{k - 1}. So, the sequence of visited cities [c_1, c_2, ..., c_k] should be strictly increasing. There are some additional constraints on the sequence of cities Tanya visits. Each city i has a beauty value b_i associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities c_i and c_{i + 1}, the condition c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i} must hold. For example, if n = 8 and b = [3, 4, 4, 6, 6, 7, 8, 9], there are several three possible ways to plan a journey: * c = [1, 2, 4]; * c = [3, 5, 6, 8]; * c = [7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above. Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey? Input The first line contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of cities in Berland. The second line contains n integers b_1, b_2, ..., b_n (1 ≀ b_i ≀ 4 β‹… 10^5), where b_i is the beauty value of the i-th city. Output Print one integer β€” the maximum beauty of a journey Tanya can choose. Examples Input 6 10 7 1 9 10 15 Output 26 Input 1 400000 Output 400000 Input 7 8 9 26 11 12 29 14 Output 55 Note The optimal journey plan in the first example is c = [2, 4, 5]. The optimal journey plan in the second example is c = [1]. The optimal journey plan in the third example is c = [3, 6]. Tags: data structures, dp, greedy, math, sortings Correct Solution: ``` input() l=list(map(int,input().split())) d={} i=1 for x in l: d[x-i]=d.get(x-i,0)+x i+=1 print(max(d.values())) ```
105,388
Provide tags and a correct Python 3 solution for this coding contest problem. Tanya wants to go on a journey across the cities of Berland. There are n cities situated along the main railroad line of Berland, and these cities are numbered from 1 to n. Tanya plans her journey as follows. First of all, she will choose some city c_1 to start her journey. She will visit it, and after that go to some other city c_2 > c_1, then to some other city c_3 > c_2, and so on, until she chooses to end her journey in some city c_k > c_{k - 1}. So, the sequence of visited cities [c_1, c_2, ..., c_k] should be strictly increasing. There are some additional constraints on the sequence of cities Tanya visits. Each city i has a beauty value b_i associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities c_i and c_{i + 1}, the condition c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i} must hold. For example, if n = 8 and b = [3, 4, 4, 6, 6, 7, 8, 9], there are several three possible ways to plan a journey: * c = [1, 2, 4]; * c = [3, 5, 6, 8]; * c = [7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above. Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey? Input The first line contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of cities in Berland. The second line contains n integers b_1, b_2, ..., b_n (1 ≀ b_i ≀ 4 β‹… 10^5), where b_i is the beauty value of the i-th city. Output Print one integer β€” the maximum beauty of a journey Tanya can choose. Examples Input 6 10 7 1 9 10 15 Output 26 Input 1 400000 Output 400000 Input 7 8 9 26 11 12 29 14 Output 55 Note The optimal journey plan in the first example is c = [2, 4, 5]. The optimal journey plan in the second example is c = [1]. The optimal journey plan in the third example is c = [3, 6]. Tags: data structures, dp, greedy, math, sortings Correct Solution: ``` n = int(input()) b = list(map(int, input().split())) a = [b[i] - i for i in range(n)] c = dict() for i in range(n): if a[i] in c: c[a[i]] += b[i] else: c[a[i]] = b[i] print(max(c.values())) ```
105,389
Provide tags and a correct Python 3 solution for this coding contest problem. Tanya wants to go on a journey across the cities of Berland. There are n cities situated along the main railroad line of Berland, and these cities are numbered from 1 to n. Tanya plans her journey as follows. First of all, she will choose some city c_1 to start her journey. She will visit it, and after that go to some other city c_2 > c_1, then to some other city c_3 > c_2, and so on, until she chooses to end her journey in some city c_k > c_{k - 1}. So, the sequence of visited cities [c_1, c_2, ..., c_k] should be strictly increasing. There are some additional constraints on the sequence of cities Tanya visits. Each city i has a beauty value b_i associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities c_i and c_{i + 1}, the condition c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i} must hold. For example, if n = 8 and b = [3, 4, 4, 6, 6, 7, 8, 9], there are several three possible ways to plan a journey: * c = [1, 2, 4]; * c = [3, 5, 6, 8]; * c = [7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above. Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey? Input The first line contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of cities in Berland. The second line contains n integers b_1, b_2, ..., b_n (1 ≀ b_i ≀ 4 β‹… 10^5), where b_i is the beauty value of the i-th city. Output Print one integer β€” the maximum beauty of a journey Tanya can choose. Examples Input 6 10 7 1 9 10 15 Output 26 Input 1 400000 Output 400000 Input 7 8 9 26 11 12 29 14 Output 55 Note The optimal journey plan in the first example is c = [2, 4, 5]. The optimal journey plan in the second example is c = [1]. The optimal journey plan in the third example is c = [3, 6]. Tags: data structures, dp, greedy, math, sortings Correct Solution: ``` n = int(input()) arr = list(map(int,input().split())) dict = {} maxi = 0 for i in range(len(arr)): try: temp = dict[i-arr[i]] dict[i-arr[i]] = temp + arr[i] if(maxi<temp + arr[i]): maxi = temp + arr[i] except: dict[i-arr[i]] = arr[i] if(maxi<arr[i]): maxi = arr[i] print(maxi) ```
105,390
Provide tags and a correct Python 3 solution for this coding contest problem. Tanya wants to go on a journey across the cities of Berland. There are n cities situated along the main railroad line of Berland, and these cities are numbered from 1 to n. Tanya plans her journey as follows. First of all, she will choose some city c_1 to start her journey. She will visit it, and after that go to some other city c_2 > c_1, then to some other city c_3 > c_2, and so on, until she chooses to end her journey in some city c_k > c_{k - 1}. So, the sequence of visited cities [c_1, c_2, ..., c_k] should be strictly increasing. There are some additional constraints on the sequence of cities Tanya visits. Each city i has a beauty value b_i associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities c_i and c_{i + 1}, the condition c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i} must hold. For example, if n = 8 and b = [3, 4, 4, 6, 6, 7, 8, 9], there are several three possible ways to plan a journey: * c = [1, 2, 4]; * c = [3, 5, 6, 8]; * c = [7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above. Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey? Input The first line contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of cities in Berland. The second line contains n integers b_1, b_2, ..., b_n (1 ≀ b_i ≀ 4 β‹… 10^5), where b_i is the beauty value of the i-th city. Output Print one integer β€” the maximum beauty of a journey Tanya can choose. Examples Input 6 10 7 1 9 10 15 Output 26 Input 1 400000 Output 400000 Input 7 8 9 26 11 12 29 14 Output 55 Note The optimal journey plan in the first example is c = [2, 4, 5]. The optimal journey plan in the second example is c = [1]. The optimal journey plan in the third example is c = [3, 6]. Tags: data structures, dp, greedy, math, sortings Correct Solution: ``` import sys n = int(sys.stdin.readline().strip()) b = list(map(int, sys.stdin.readline().strip().split())) a = [0] * n for i in range (0, n): a[i] = b[i] - i x = [0] * 10 ** 6 for i in range (0, n): x[3 * 10 ** 5 + a[i]] = x[3 * 10 ** 5 + a[i]] + b[i] print(max(x)) ```
105,391
Provide tags and a correct Python 3 solution for this coding contest problem. Tanya wants to go on a journey across the cities of Berland. There are n cities situated along the main railroad line of Berland, and these cities are numbered from 1 to n. Tanya plans her journey as follows. First of all, she will choose some city c_1 to start her journey. She will visit it, and after that go to some other city c_2 > c_1, then to some other city c_3 > c_2, and so on, until she chooses to end her journey in some city c_k > c_{k - 1}. So, the sequence of visited cities [c_1, c_2, ..., c_k] should be strictly increasing. There are some additional constraints on the sequence of cities Tanya visits. Each city i has a beauty value b_i associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities c_i and c_{i + 1}, the condition c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i} must hold. For example, if n = 8 and b = [3, 4, 4, 6, 6, 7, 8, 9], there are several three possible ways to plan a journey: * c = [1, 2, 4]; * c = [3, 5, 6, 8]; * c = [7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above. Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey? Input The first line contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of cities in Berland. The second line contains n integers b_1, b_2, ..., b_n (1 ≀ b_i ≀ 4 β‹… 10^5), where b_i is the beauty value of the i-th city. Output Print one integer β€” the maximum beauty of a journey Tanya can choose. Examples Input 6 10 7 1 9 10 15 Output 26 Input 1 400000 Output 400000 Input 7 8 9 26 11 12 29 14 Output 55 Note The optimal journey plan in the first example is c = [2, 4, 5]. The optimal journey plan in the second example is c = [1]. The optimal journey plan in the third example is c = [3, 6]. Tags: data structures, dp, greedy, math, sortings Correct Solution: ``` n=int(input()) b=list(map(int, input().split())) List=[] for i in range(n): List.append([b[i]-(i+1), b[i]]) List.sort() maxim=0 for i in range(1, len(List)): if List[i][0]==List[i-1][0]: List[i][1]+=List[i-1][1] maxim=max(List[i][1], maxim) print(max(b[0], maxim)) ```
105,392
Provide tags and a correct Python 3 solution for this coding contest problem. Tanya wants to go on a journey across the cities of Berland. There are n cities situated along the main railroad line of Berland, and these cities are numbered from 1 to n. Tanya plans her journey as follows. First of all, she will choose some city c_1 to start her journey. She will visit it, and after that go to some other city c_2 > c_1, then to some other city c_3 > c_2, and so on, until she chooses to end her journey in some city c_k > c_{k - 1}. So, the sequence of visited cities [c_1, c_2, ..., c_k] should be strictly increasing. There are some additional constraints on the sequence of cities Tanya visits. Each city i has a beauty value b_i associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities c_i and c_{i + 1}, the condition c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i} must hold. For example, if n = 8 and b = [3, 4, 4, 6, 6, 7, 8, 9], there are several three possible ways to plan a journey: * c = [1, 2, 4]; * c = [3, 5, 6, 8]; * c = [7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above. Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey? Input The first line contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of cities in Berland. The second line contains n integers b_1, b_2, ..., b_n (1 ≀ b_i ≀ 4 β‹… 10^5), where b_i is the beauty value of the i-th city. Output Print one integer β€” the maximum beauty of a journey Tanya can choose. Examples Input 6 10 7 1 9 10 15 Output 26 Input 1 400000 Output 400000 Input 7 8 9 26 11 12 29 14 Output 55 Note The optimal journey plan in the first example is c = [2, 4, 5]. The optimal journey plan in the second example is c = [1]. The optimal journey plan in the third example is c = [3, 6]. Tags: data structures, dp, greedy, math, sortings Correct Solution: ``` import sys n=int(input()) if 1<=n <=2*(10**5): lst=list(map(int,input().split())) if len(lst)<n: print("Enter all the input correctly.") sys.exit(1) g = {} for j in range(n): g[lst[j] - j] = g.get(lst[j] - j,0) +lst[j] print(max(g.values())) else: print("Invalid Input") ```
105,393
Provide tags and a correct Python 3 solution for this coding contest problem. Tanya wants to go on a journey across the cities of Berland. There are n cities situated along the main railroad line of Berland, and these cities are numbered from 1 to n. Tanya plans her journey as follows. First of all, she will choose some city c_1 to start her journey. She will visit it, and after that go to some other city c_2 > c_1, then to some other city c_3 > c_2, and so on, until she chooses to end her journey in some city c_k > c_{k - 1}. So, the sequence of visited cities [c_1, c_2, ..., c_k] should be strictly increasing. There are some additional constraints on the sequence of cities Tanya visits. Each city i has a beauty value b_i associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities c_i and c_{i + 1}, the condition c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i} must hold. For example, if n = 8 and b = [3, 4, 4, 6, 6, 7, 8, 9], there are several three possible ways to plan a journey: * c = [1, 2, 4]; * c = [3, 5, 6, 8]; * c = [7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above. Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey? Input The first line contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of cities in Berland. The second line contains n integers b_1, b_2, ..., b_n (1 ≀ b_i ≀ 4 β‹… 10^5), where b_i is the beauty value of the i-th city. Output Print one integer β€” the maximum beauty of a journey Tanya can choose. Examples Input 6 10 7 1 9 10 15 Output 26 Input 1 400000 Output 400000 Input 7 8 9 26 11 12 29 14 Output 55 Note The optimal journey plan in the first example is c = [2, 4, 5]. The optimal journey plan in the second example is c = [1]. The optimal journey plan in the third example is c = [3, 6]. Tags: data structures, dp, greedy, math, sortings Correct Solution: ``` from collections import defaultdict input() vals = list(map(int, input().split())) uwu = defaultdict(list) [uwu[val - i].append(val) for i, val in enumerate(vals)] print(max([sum(god) for god in uwu.values()])) ```
105,394
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Tanya wants to go on a journey across the cities of Berland. There are n cities situated along the main railroad line of Berland, and these cities are numbered from 1 to n. Tanya plans her journey as follows. First of all, she will choose some city c_1 to start her journey. She will visit it, and after that go to some other city c_2 > c_1, then to some other city c_3 > c_2, and so on, until she chooses to end her journey in some city c_k > c_{k - 1}. So, the sequence of visited cities [c_1, c_2, ..., c_k] should be strictly increasing. There are some additional constraints on the sequence of cities Tanya visits. Each city i has a beauty value b_i associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities c_i and c_{i + 1}, the condition c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i} must hold. For example, if n = 8 and b = [3, 4, 4, 6, 6, 7, 8, 9], there are several three possible ways to plan a journey: * c = [1, 2, 4]; * c = [3, 5, 6, 8]; * c = [7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above. Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey? Input The first line contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of cities in Berland. The second line contains n integers b_1, b_2, ..., b_n (1 ≀ b_i ≀ 4 β‹… 10^5), where b_i is the beauty value of the i-th city. Output Print one integer β€” the maximum beauty of a journey Tanya can choose. Examples Input 6 10 7 1 9 10 15 Output 26 Input 1 400000 Output 400000 Input 7 8 9 26 11 12 29 14 Output 55 Note The optimal journey plan in the first example is c = [2, 4, 5]. The optimal journey plan in the second example is c = [1]. The optimal journey plan in the third example is c = [3, 6]. Submitted Solution: ``` n = int(input()) arr = list(map(int,input().split())) result = [0]*n maxx = 0 for i in range(n): result[i] = arr[i]-i dic = {} for i in range(n): if result[i] in dic: val = dic[result[i]] val+=arr[i] dic[result[i]] = val else: val = arr[i] dic[result[i]] = val maxx = max(maxx,val) print(maxx) ``` Yes
105,395
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Tanya wants to go on a journey across the cities of Berland. There are n cities situated along the main railroad line of Berland, and these cities are numbered from 1 to n. Tanya plans her journey as follows. First of all, she will choose some city c_1 to start her journey. She will visit it, and after that go to some other city c_2 > c_1, then to some other city c_3 > c_2, and so on, until she chooses to end her journey in some city c_k > c_{k - 1}. So, the sequence of visited cities [c_1, c_2, ..., c_k] should be strictly increasing. There are some additional constraints on the sequence of cities Tanya visits. Each city i has a beauty value b_i associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities c_i and c_{i + 1}, the condition c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i} must hold. For example, if n = 8 and b = [3, 4, 4, 6, 6, 7, 8, 9], there are several three possible ways to plan a journey: * c = [1, 2, 4]; * c = [3, 5, 6, 8]; * c = [7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above. Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey? Input The first line contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of cities in Berland. The second line contains n integers b_1, b_2, ..., b_n (1 ≀ b_i ≀ 4 β‹… 10^5), where b_i is the beauty value of the i-th city. Output Print one integer β€” the maximum beauty of a journey Tanya can choose. Examples Input 6 10 7 1 9 10 15 Output 26 Input 1 400000 Output 400000 Input 7 8 9 26 11 12 29 14 Output 55 Note The optimal journey plan in the first example is c = [2, 4, 5]. The optimal journey plan in the second example is c = [1]. The optimal journey plan in the third example is c = [3, 6]. Submitted Solution: ``` n = int(input()) b = list(map(int, input().split())) mem = {} for i in range(n): if i-b[i] not in mem: mem[i-b[i]] = 0 mem[i - b[i]] += b[i] ans = 0 for i in mem: ans = max(ans, mem[i]) print(ans) ``` Yes
105,396
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Tanya wants to go on a journey across the cities of Berland. There are n cities situated along the main railroad line of Berland, and these cities are numbered from 1 to n. Tanya plans her journey as follows. First of all, she will choose some city c_1 to start her journey. She will visit it, and after that go to some other city c_2 > c_1, then to some other city c_3 > c_2, and so on, until she chooses to end her journey in some city c_k > c_{k - 1}. So, the sequence of visited cities [c_1, c_2, ..., c_k] should be strictly increasing. There are some additional constraints on the sequence of cities Tanya visits. Each city i has a beauty value b_i associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities c_i and c_{i + 1}, the condition c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i} must hold. For example, if n = 8 and b = [3, 4, 4, 6, 6, 7, 8, 9], there are several three possible ways to plan a journey: * c = [1, 2, 4]; * c = [3, 5, 6, 8]; * c = [7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above. Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey? Input The first line contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of cities in Berland. The second line contains n integers b_1, b_2, ..., b_n (1 ≀ b_i ≀ 4 β‹… 10^5), where b_i is the beauty value of the i-th city. Output Print one integer β€” the maximum beauty of a journey Tanya can choose. Examples Input 6 10 7 1 9 10 15 Output 26 Input 1 400000 Output 400000 Input 7 8 9 26 11 12 29 14 Output 55 Note The optimal journey plan in the first example is c = [2, 4, 5]. The optimal journey plan in the second example is c = [1]. The optimal journey plan in the third example is c = [3, 6]. Submitted Solution: ``` import sys input = sys.stdin.readline n = int(input()) b = [int(x) for x in input().split()] c = [0] * (10 ** 6) for i in range(n): c[b[i] - i] += b[i] print(max(c)) ``` Yes
105,397
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Tanya wants to go on a journey across the cities of Berland. There are n cities situated along the main railroad line of Berland, and these cities are numbered from 1 to n. Tanya plans her journey as follows. First of all, she will choose some city c_1 to start her journey. She will visit it, and after that go to some other city c_2 > c_1, then to some other city c_3 > c_2, and so on, until she chooses to end her journey in some city c_k > c_{k - 1}. So, the sequence of visited cities [c_1, c_2, ..., c_k] should be strictly increasing. There are some additional constraints on the sequence of cities Tanya visits. Each city i has a beauty value b_i associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities c_i and c_{i + 1}, the condition c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i} must hold. For example, if n = 8 and b = [3, 4, 4, 6, 6, 7, 8, 9], there are several three possible ways to plan a journey: * c = [1, 2, 4]; * c = [3, 5, 6, 8]; * c = [7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above. Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey? Input The first line contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of cities in Berland. The second line contains n integers b_1, b_2, ..., b_n (1 ≀ b_i ≀ 4 β‹… 10^5), where b_i is the beauty value of the i-th city. Output Print one integer β€” the maximum beauty of a journey Tanya can choose. Examples Input 6 10 7 1 9 10 15 Output 26 Input 1 400000 Output 400000 Input 7 8 9 26 11 12 29 14 Output 55 Note The optimal journey plan in the first example is c = [2, 4, 5]. The optimal journey plan in the second example is c = [1]. The optimal journey plan in the third example is c = [3, 6]. Submitted Solution: ``` n = int(input()) list1 = list(map(int,input().split())) list2 = list() for i in range(len(list1)): list2.append([list1[i]-(i+1),list1[i]]) list2.sort() maxi = 0 i=0 while i<len(list2): sum=0 p = list2[i][0] while i<len(list2) and list2[i][0]==p: sum+=list2[i][1] i+=1 if sum>maxi: maxi=sum print(maxi) ``` Yes
105,398
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Tanya wants to go on a journey across the cities of Berland. There are n cities situated along the main railroad line of Berland, and these cities are numbered from 1 to n. Tanya plans her journey as follows. First of all, she will choose some city c_1 to start her journey. She will visit it, and after that go to some other city c_2 > c_1, then to some other city c_3 > c_2, and so on, until she chooses to end her journey in some city c_k > c_{k - 1}. So, the sequence of visited cities [c_1, c_2, ..., c_k] should be strictly increasing. There are some additional constraints on the sequence of cities Tanya visits. Each city i has a beauty value b_i associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities c_i and c_{i + 1}, the condition c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i} must hold. For example, if n = 8 and b = [3, 4, 4, 6, 6, 7, 8, 9], there are several three possible ways to plan a journey: * c = [1, 2, 4]; * c = [3, 5, 6, 8]; * c = [7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above. Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey? Input The first line contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of cities in Berland. The second line contains n integers b_1, b_2, ..., b_n (1 ≀ b_i ≀ 4 β‹… 10^5), where b_i is the beauty value of the i-th city. Output Print one integer β€” the maximum beauty of a journey Tanya can choose. Examples Input 6 10 7 1 9 10 15 Output 26 Input 1 400000 Output 400000 Input 7 8 9 26 11 12 29 14 Output 55 Note The optimal journey plan in the first example is c = [2, 4, 5]. The optimal journey plan in the second example is c = [1]. The optimal journey plan in the third example is c = [3, 6]. Submitted Solution: ``` import math from decimal import Decimal import heapq import copy import heapq from collections import deque from collections import defaultdict def na(): n = int(input()) b = [int(x) for x in input().split()] return n,b def nab(): n = int(input()) b = [int(x) for x in input().split()] c = [int(x) for x in input().split()] return n,b,c def dv(): n, m = map(int, input().split()) return n,m def da(): n, m = map(int, input().split()) a = list(map(int, input().split())) return n,m, a def dva(): n, m = map(int, input().split()) a = [int(x) for x in input().split()] b = [int(x) for x in input().split()] return n,m,b def prost(x): d = math.sqrt(x) d = int(d) + 1 for i in range(2, d): if x % i == 0: return False return True def eratosthenes(n): sieve = list(range(n + 1)) for i in sieve: if i > 1: for j in range(i + i, len(sieve), i): sieve[j] = 0 return sorted(set(sieve)) def lol(lst,k): k=k%len(lst) ret=[0]*len(lst) for i in range(len(lst)): if i+k<len(lst) and i+k>=0: ret[i]=lst[i+k] if i+k>=len(lst): ret[i]=lst[i+k-len(lst)] if i+k<0: ret[i]=lst[i+k+len(lst)] return(ret) def nm(): n = int(input()) b = [int(x) for x in input().split()] m = int(input()) c = [int(x) for x in input().split()] return n,b,m,c def dvs(): n = int(input()) m = int(input()) return n, m n = int(input()) a = list(map(int, input().split())) dp = [0] * (4 * 100000 +5) for i in range(n): dp[a[i] - i - 1] += a[i] print(max(dp)) ``` No
105,399