text
stringlengths
198
433k
conversation_id
int64
0
109k
Provide tags and a correct Python 3 solution for this coding contest problem. You are given three sticks with positive integer lengths of a, b, and c centimeters. You can increase length of some of them by some positive integer number of centimeters (different sticks can be increased by a different length), but in total by at most l centimeters. In particular, it is allowed not to increase the length of any stick. Determine the number of ways to increase the lengths of some sticks so that you can form from them a non-degenerate (that is, having a positive area) triangle. Two ways are considered different, if the length of some stick is increased by different number of centimeters in them. Input The single line contains 4 integers a, b, c, l (1 ≤ a, b, c ≤ 3·105, 0 ≤ l ≤ 3·105). Output Print a single integer — the number of ways to increase the sizes of the sticks by the total of at most l centimeters, so that you can make a non-degenerate triangle from it. Examples Input 1 1 1 2 Output 4 Input 1 2 3 1 Output 2 Input 10 2 1 7 Output 0 Note In the first sample test you can either not increase any stick or increase any two sticks by 1 centimeter. In the second sample test you can increase either the first or the second stick by one centimeter. Note that the triangle made from the initial sticks is degenerate and thus, doesn't meet the conditions. Tags: combinatorics, implementation, math Correct Solution: ``` ''' import sys sys.stdin = open("input.txt", "r") sys.stdout = open("output.txt", "w") ''' def Solve(a, b, c, l): delta = a - b - c if delta < 0: return 0 k = min(l, delta) + 1 return k * (k + 1) // 2 a, b, c, l = map(int, input().split()) ans = (l + 3) * (l + 2) * (l + 1) // 6 for d in range(l + 1): ans -= Solve(a + d, b, c, l - d) + Solve(b + d, a, c, l - d) + Solve(c + d, a, b, l - d) print(ans) ```
89,700
Provide tags and a correct Python 3 solution for this coding contest problem. You are given three sticks with positive integer lengths of a, b, and c centimeters. You can increase length of some of them by some positive integer number of centimeters (different sticks can be increased by a different length), but in total by at most l centimeters. In particular, it is allowed not to increase the length of any stick. Determine the number of ways to increase the lengths of some sticks so that you can form from them a non-degenerate (that is, having a positive area) triangle. Two ways are considered different, if the length of some stick is increased by different number of centimeters in them. Input The single line contains 4 integers a, b, c, l (1 ≤ a, b, c ≤ 3·105, 0 ≤ l ≤ 3·105). Output Print a single integer — the number of ways to increase the sizes of the sticks by the total of at most l centimeters, so that you can make a non-degenerate triangle from it. Examples Input 1 1 1 2 Output 4 Input 1 2 3 1 Output 2 Input 10 2 1 7 Output 0 Note In the first sample test you can either not increase any stick or increase any two sticks by 1 centimeter. In the second sample test you can increase either the first or the second stick by one centimeter. Note that the triangle made from the initial sticks is degenerate and thus, doesn't meet the conditions. Tags: combinatorics, implementation, math Correct Solution: ``` a, b, c, l = map(int, input().split()) ans = (l + 3) * (l + 2) * (l + 1) // 3 for z in (a, b, c): s = 2 * z - a - b - c for x in range(max(0, -s), l + 1): m = min(s + x, l - x) ans -= (m + 1) * (m + 2) print(ans // 2) ```
89,701
Provide tags and a correct Python 3 solution for this coding contest problem. You are given three sticks with positive integer lengths of a, b, and c centimeters. You can increase length of some of them by some positive integer number of centimeters (different sticks can be increased by a different length), but in total by at most l centimeters. In particular, it is allowed not to increase the length of any stick. Determine the number of ways to increase the lengths of some sticks so that you can form from them a non-degenerate (that is, having a positive area) triangle. Two ways are considered different, if the length of some stick is increased by different number of centimeters in them. Input The single line contains 4 integers a, b, c, l (1 ≤ a, b, c ≤ 3·105, 0 ≤ l ≤ 3·105). Output Print a single integer — the number of ways to increase the sizes of the sticks by the total of at most l centimeters, so that you can make a non-degenerate triangle from it. Examples Input 1 1 1 2 Output 4 Input 1 2 3 1 Output 2 Input 10 2 1 7 Output 0 Note In the first sample test you can either not increase any stick or increase any two sticks by 1 centimeter. In the second sample test you can increase either the first or the second stick by one centimeter. Note that the triangle made from the initial sticks is degenerate and thus, doesn't meet the conditions. Tags: combinatorics, implementation, math Correct Solution: ``` def solve(a, b, c): ans = 0 for da in range(max(0, b + c - a), l + 1): x = min(a - b - c + da, l - da) ans += (x + 1) * (x + 2) // 2 return ans a, b, c, l = map(int, input().split()) print((l + 1) * (l + 2) * (l + 3) // 6 - solve(a, b, c) - solve(b, a, c) - solve(c, a, b)) ```
89,702
Provide tags and a correct Python 3 solution for this coding contest problem. You are given three sticks with positive integer lengths of a, b, and c centimeters. You can increase length of some of them by some positive integer number of centimeters (different sticks can be increased by a different length), but in total by at most l centimeters. In particular, it is allowed not to increase the length of any stick. Determine the number of ways to increase the lengths of some sticks so that you can form from them a non-degenerate (that is, having a positive area) triangle. Two ways are considered different, if the length of some stick is increased by different number of centimeters in them. Input The single line contains 4 integers a, b, c, l (1 ≤ a, b, c ≤ 3·105, 0 ≤ l ≤ 3·105). Output Print a single integer — the number of ways to increase the sizes of the sticks by the total of at most l centimeters, so that you can make a non-degenerate triangle from it. Examples Input 1 1 1 2 Output 4 Input 1 2 3 1 Output 2 Input 10 2 1 7 Output 0 Note In the first sample test you can either not increase any stick or increase any two sticks by 1 centimeter. In the second sample test you can increase either the first or the second stick by one centimeter. Note that the triangle made from the initial sticks is degenerate and thus, doesn't meet the conditions. Tags: combinatorics, implementation, math Correct Solution: ``` p = list(map(int, input().split())) l = p.pop() n = (l + 1) * (l + 2) * (l + 3) // 6 s = sum(p) for q in p: t = 2 * q - s for d in range(l + 1): k = min(t + d, l - d) + 1 if k > 0: n -= k * k + k >> 1 print(n) ```
89,703
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given three sticks with positive integer lengths of a, b, and c centimeters. You can increase length of some of them by some positive integer number of centimeters (different sticks can be increased by a different length), but in total by at most l centimeters. In particular, it is allowed not to increase the length of any stick. Determine the number of ways to increase the lengths of some sticks so that you can form from them a non-degenerate (that is, having a positive area) triangle. Two ways are considered different, if the length of some stick is increased by different number of centimeters in them. Input The single line contains 4 integers a, b, c, l (1 ≤ a, b, c ≤ 3·105, 0 ≤ l ≤ 3·105). Output Print a single integer — the number of ways to increase the sizes of the sticks by the total of at most l centimeters, so that you can make a non-degenerate triangle from it. Examples Input 1 1 1 2 Output 4 Input 1 2 3 1 Output 2 Input 10 2 1 7 Output 0 Note In the first sample test you can either not increase any stick or increase any two sticks by 1 centimeter. In the second sample test you can increase either the first or the second stick by one centimeter. Note that the triangle made from the initial sticks is degenerate and thus, doesn't meet the conditions. Submitted Solution: ``` a, b, c, l = map(int, input().split()) ans = (l + 3) * (l + 2) * (l + 1) // 3 for z in (a, b, c): s = 2 * z - a - b - c for x in range(max(0, -s), l + 1): m = min(s + x, l - x) ans -= (m + 1) * (m + 2) print(ans // 2) # Made By Mostafa_Khaled ``` Yes
89,704
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given three sticks with positive integer lengths of a, b, and c centimeters. You can increase length of some of them by some positive integer number of centimeters (different sticks can be increased by a different length), but in total by at most l centimeters. In particular, it is allowed not to increase the length of any stick. Determine the number of ways to increase the lengths of some sticks so that you can form from them a non-degenerate (that is, having a positive area) triangle. Two ways are considered different, if the length of some stick is increased by different number of centimeters in them. Input The single line contains 4 integers a, b, c, l (1 ≤ a, b, c ≤ 3·105, 0 ≤ l ≤ 3·105). Output Print a single integer — the number of ways to increase the sizes of the sticks by the total of at most l centimeters, so that you can make a non-degenerate triangle from it. Examples Input 1 1 1 2 Output 4 Input 1 2 3 1 Output 2 Input 10 2 1 7 Output 0 Note In the first sample test you can either not increase any stick or increase any two sticks by 1 centimeter. In the second sample test you can increase either the first or the second stick by one centimeter. Note that the triangle made from the initial sticks is degenerate and thus, doesn't meet the conditions. Submitted Solution: ``` #in the name of god #Mr_Rubick a,b,c,l=map(int, input().split()) cnt=(l+3)*(l+2)*(l+1)//3 for i in (a,b,c): s=2*i-a-b-c for x in range(max(0,-s),l+1): m = min(s+x,l-x) cnt-=(m+1)*(m+2) print(cnt//2) ``` Yes
89,705
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given three sticks with positive integer lengths of a, b, and c centimeters. You can increase length of some of them by some positive integer number of centimeters (different sticks can be increased by a different length), but in total by at most l centimeters. In particular, it is allowed not to increase the length of any stick. Determine the number of ways to increase the lengths of some sticks so that you can form from them a non-degenerate (that is, having a positive area) triangle. Two ways are considered different, if the length of some stick is increased by different number of centimeters in them. Input The single line contains 4 integers a, b, c, l (1 ≤ a, b, c ≤ 3·105, 0 ≤ l ≤ 3·105). Output Print a single integer — the number of ways to increase the sizes of the sticks by the total of at most l centimeters, so that you can make a non-degenerate triangle from it. Examples Input 1 1 1 2 Output 4 Input 1 2 3 1 Output 2 Input 10 2 1 7 Output 0 Note In the first sample test you can either not increase any stick or increase any two sticks by 1 centimeter. In the second sample test you can increase either the first or the second stick by one centimeter. Note that the triangle made from the initial sticks is degenerate and thus, doesn't meet the conditions. Submitted Solution: ``` a, b, c, l = map(int, input().split()) ans = (l + 3) * (l + 2) // 2 * (l + 1) // 3 for z in (a, b, c): s = 2 * z - a - b - c for x in range(l + 1): m = min(s + x, l - x) if m >= 0: ans -= (m + 1) * (m + 2) >> 1 print(ans) ``` Yes
89,706
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given three sticks with positive integer lengths of a, b, and c centimeters. You can increase length of some of them by some positive integer number of centimeters (different sticks can be increased by a different length), but in total by at most l centimeters. In particular, it is allowed not to increase the length of any stick. Determine the number of ways to increase the lengths of some sticks so that you can form from them a non-degenerate (that is, having a positive area) triangle. Two ways are considered different, if the length of some stick is increased by different number of centimeters in them. Input The single line contains 4 integers a, b, c, l (1 ≤ a, b, c ≤ 3·105, 0 ≤ l ≤ 3·105). Output Print a single integer — the number of ways to increase the sizes of the sticks by the total of at most l centimeters, so that you can make a non-degenerate triangle from it. Examples Input 1 1 1 2 Output 4 Input 1 2 3 1 Output 2 Input 10 2 1 7 Output 0 Note In the first sample test you can either not increase any stick or increase any two sticks by 1 centimeter. In the second sample test you can increase either the first or the second stick by one centimeter. Note that the triangle made from the initial sticks is degenerate and thus, doesn't meet the conditions. Submitted Solution: ``` def f(a, b, c, l): k = min(l, a - b - c) return 0 if a < b + c else (k + 1) * (k + 2) // 2 solve = lambda i: f(a + i, b, c, l - i) + f(b + i, c, a, l - i) + f(c + i, a, b, l - i) a, b, c, l = map(int, input().split()) ans = (l + 1) * (l + 2) * (l + 3) // 6 - sum(solve(i) for i in range(l + 1)) print(ans) ``` Yes
89,707
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given three sticks with positive integer lengths of a, b, and c centimeters. You can increase length of some of them by some positive integer number of centimeters (different sticks can be increased by a different length), but in total by at most l centimeters. In particular, it is allowed not to increase the length of any stick. Determine the number of ways to increase the lengths of some sticks so that you can form from them a non-degenerate (that is, having a positive area) triangle. Two ways are considered different, if the length of some stick is increased by different number of centimeters in them. Input The single line contains 4 integers a, b, c, l (1 ≤ a, b, c ≤ 3·105, 0 ≤ l ≤ 3·105). Output Print a single integer — the number of ways to increase the sizes of the sticks by the total of at most l centimeters, so that you can make a non-degenerate triangle from it. Examples Input 1 1 1 2 Output 4 Input 1 2 3 1 Output 2 Input 10 2 1 7 Output 0 Note In the first sample test you can either not increase any stick or increase any two sticks by 1 centimeter. In the second sample test you can increase either the first or the second stick by one centimeter. Note that the triangle made from the initial sticks is degenerate and thus, doesn't meet the conditions. Submitted Solution: ``` a, b, c, l = map(int, input().split()) ans = (l + 3) * (l + 2) * (l + 1) // 3 for z in (a, b, c): s = 2 * z - a - b - c for x in range(max(0, -s), (l - s) // 2 + 1): m = s + x ans -= (m + 1) * (m + 2) for x in range((l - s) // 2 + 1, l + 1): m = l - x ans -= (m + 1) * (m + 2) print(ans // 2) ``` No
89,708
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given three sticks with positive integer lengths of a, b, and c centimeters. You can increase length of some of them by some positive integer number of centimeters (different sticks can be increased by a different length), but in total by at most l centimeters. In particular, it is allowed not to increase the length of any stick. Determine the number of ways to increase the lengths of some sticks so that you can form from them a non-degenerate (that is, having a positive area) triangle. Two ways are considered different, if the length of some stick is increased by different number of centimeters in them. Input The single line contains 4 integers a, b, c, l (1 ≤ a, b, c ≤ 3·105, 0 ≤ l ≤ 3·105). Output Print a single integer — the number of ways to increase the sizes of the sticks by the total of at most l centimeters, so that you can make a non-degenerate triangle from it. Examples Input 1 1 1 2 Output 4 Input 1 2 3 1 Output 2 Input 10 2 1 7 Output 0 Note In the first sample test you can either not increase any stick or increase any two sticks by 1 centimeter. In the second sample test you can increase either the first or the second stick by one centimeter. Note that the triangle made from the initial sticks is degenerate and thus, doesn't meet the conditions. Submitted Solution: ``` def f(a,b,c,l): if a<b+c: return 0 else: c=min(l,a-b-c) return (c+1)*(c+2)/2 a,b,c,l = map(int,input().split()) z=(l+1)*(l+2)*(l+3)/6 i=0 while i<=l: z-=f(a+i,b,c,l-i)+f(b+i,c,a,l-i)+f(c+i,a,b,l-i) i+=1 print(z) ``` No
89,709
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given three sticks with positive integer lengths of a, b, and c centimeters. You can increase length of some of them by some positive integer number of centimeters (different sticks can be increased by a different length), but in total by at most l centimeters. In particular, it is allowed not to increase the length of any stick. Determine the number of ways to increase the lengths of some sticks so that you can form from them a non-degenerate (that is, having a positive area) triangle. Two ways are considered different, if the length of some stick is increased by different number of centimeters in them. Input The single line contains 4 integers a, b, c, l (1 ≤ a, b, c ≤ 3·105, 0 ≤ l ≤ 3·105). Output Print a single integer — the number of ways to increase the sizes of the sticks by the total of at most l centimeters, so that you can make a non-degenerate triangle from it. Examples Input 1 1 1 2 Output 4 Input 1 2 3 1 Output 2 Input 10 2 1 7 Output 0 Note In the first sample test you can either not increase any stick or increase any two sticks by 1 centimeter. In the second sample test you can increase either the first or the second stick by one centimeter. Note that the triangle made from the initial sticks is degenerate and thus, doesn't meet the conditions. Submitted Solution: ``` a,b,c,l=map(int,input().split()) k=0 for i in range(l+1): a1=a+i for j in range(l-i+1): b1=b+j for k in range(l-i-j+1): c1=c+k if c1+b1>a1 and c1+a1>b1 and a1+b1>c1: k+=1 print(k) ``` No
89,710
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given three sticks with positive integer lengths of a, b, and c centimeters. You can increase length of some of them by some positive integer number of centimeters (different sticks can be increased by a different length), but in total by at most l centimeters. In particular, it is allowed not to increase the length of any stick. Determine the number of ways to increase the lengths of some sticks so that you can form from them a non-degenerate (that is, having a positive area) triangle. Two ways are considered different, if the length of some stick is increased by different number of centimeters in them. Input The single line contains 4 integers a, b, c, l (1 ≤ a, b, c ≤ 3·105, 0 ≤ l ≤ 3·105). Output Print a single integer — the number of ways to increase the sizes of the sticks by the total of at most l centimeters, so that you can make a non-degenerate triangle from it. Examples Input 1 1 1 2 Output 4 Input 1 2 3 1 Output 2 Input 10 2 1 7 Output 0 Note In the first sample test you can either not increase any stick or increase any two sticks by 1 centimeter. In the second sample test you can increase either the first or the second stick by one centimeter. Note that the triangle made from the initial sticks is degenerate and thus, doesn't meet the conditions. Submitted Solution: ``` from math import ceil a, b, c, l = list(map(int, input().split())) ans = 0 for i in range(l + 1): a1 = a + i lmin = max(a1 - (b + c) + 1, 0) lmax = l - i diffmax = a1 + b - c - 1 diffmin = b - c - a1 + 1 ans += max(0, (max(diffmax - diffmin + 1, 0)) * ((lmax + diffmin) // 2 - max(diffmax, ceil((lmin + diffmax) / 2)))) ans += (lmax - max(ceil((lmin + diffmax) / 2), ceil((lmax + diffmin) / 2))) * (max(0, lmax - lmin + 1)) #for lc in range(lmax + 1): # ans += max(-1, min(lmax - lc, lc - diffmin) - max(lc - diffmax, lmin-lc, 0)) + 1 print(ans) ``` No
89,711
Provide tags and a correct Python 3 solution for this coding contest problem. Ari the monster is not an ordinary monster. She is the hidden identity of Super M, the Byteforces’ superhero. Byteforces is a country that consists of n cities, connected by n - 1 bidirectional roads. Every road connects exactly two distinct cities, and the whole road system is designed in a way that one is able to go from any city to any other city using only the given roads. There are m cities being attacked by humans. So Ari... we meant Super M have to immediately go to each of the cities being attacked to scare those bad humans. Super M can pass from one city to another only using the given roads. Moreover, passing through one road takes her exactly one kron - the time unit used in Byteforces. <image> However, Super M is not on Byteforces now - she is attending a training camp located in a nearby country Codeforces. Fortunately, there is a special device in Codeforces that allows her to instantly teleport from Codeforces to any city of Byteforces. The way back is too long, so for the purpose of this problem teleportation is used exactly once. You are to help Super M, by calculating the city in which she should teleport at the beginning in order to end her job in the minimum time (measured in krons). Also, provide her with this time so she can plan her way back to Codeforces. Input The first line of the input contains two integers n and m (1 ≤ m ≤ n ≤ 123456) - the number of cities in Byteforces, and the number of cities being attacked respectively. Then follow n - 1 lines, describing the road system. Each line contains two city numbers ui and vi (1 ≤ ui, vi ≤ n) - the ends of the road i. The last line contains m distinct integers - numbers of cities being attacked. These numbers are given in no particular order. Output First print the number of the city Super M should teleport to. If there are many possible optimal answers, print the one with the lowest city number. Then print the minimum possible time needed to scare all humans in cities being attacked, measured in Krons. Note that the correct answer is always unique. Examples Input 7 2 1 2 1 3 1 4 3 5 3 6 3 7 2 7 Output 2 3 Input 6 4 1 2 2 3 2 4 4 5 4 6 2 4 5 6 Output 2 4 Note In the first sample, there are two possibilities to finish the Super M's job in 3 krons. They are: <image> and <image>. However, you should choose the first one as it starts in the city with the lower number. Tags: dfs and similar, dp, graphs, trees Correct Solution: ``` from collections import deque from sys import stdin from sys import exit #parsea una línea def parser(): return map(int, stdin.readline().split()) #Método usado para obtener los vértices por los que debe pasar Super M def DFS_Discriminiting(): visited=[False for x in range(n)] visited[numbers_of_attacked_cities[0]]=True stack=[] introduction_order=[] stack.append(numbers_of_attacked_cities[0]) while len(stack)>0: v=stack.pop() for u in adjacents_list[v]: if not visited[u]: pi[u]=v visited[u]=True if attacked_city[u]: count_attacked_cities_subtree[u]+=1 stack.append(u) introduction_order.append(u) for v in introduction_order[::-1]: count_attacked_cities_subtree[pi[v]]+=count_attacked_cities_subtree[v] if count_attacked_cities_subtree[v]==0: important_cities[v]=False #Método usado para calcular las alturas def DFS_Heigths(): visited=[False for x in range(n)] visited[numbers_of_attacked_cities[0]]=True stack=[] introduction_order=[] stack.append(numbers_of_attacked_cities[0]) while len(stack)>0: v=stack.pop() for u in adjacents_list[v]: if not visited[u]: visited[u]=True stack.append(u) introduction_order.append(u) for v in introduction_order[::-1]: if heights1[pi[v]] < heights1[v]+1: heights2[pi[v]]=heights1[pi[v]] heights1[pi[v]]=heights1[v]+1 elif heights2[pi[v]]<heights1[v]+1: heights2[pi[v]]=heights1[v]+1 #Método usado para calcular la primera y segunda distancia de la raíz def Distance_Root(s): for v in adjacents_list[s]: if heights1[v]+1>distances1[s]: distances2[s]=distances1[s] distances1[s]=heights1[v]+1 elif heights1[v]+1>distances2[s]: distances2[s]=heights1[v]+1 #Método usado para calcular la primera distancia y segunda distancia de cada vértice def DFS_Distances(): #visitados visited=[False for x in range(n)] visited[numbers_of_attacked_cities[0]]=True stack=[] stack.append(numbers_of_attacked_cities[0]) Distance_Root(numbers_of_attacked_cities[0]) while len(stack)>0: v=stack.pop() for u in adjacents_list[v]: if not visited[u]: visited[u]=True stack.append(u) determinate=False if heights1[u]+1==distances1[v]: if heights1[u]+1>distances2[v]: determinate=True distances1[u]=max(heights1[u],distances2[v]+1) if distances1[u]==heights1[u]: distances2[u]=max(distances2[v]+1,heights2[u]) else: distances2[u]=heights1[u] if not determinate: distances1[u]=distances1[v]+1 distances2[u]=heights1[u] #Método usado para calcular las distancias de un vétice al resto de los vértices def BFS(s): distance=[-1 for x in range(n)] distance[s]=0 q=deque() q.append(s) while len(q)>0: v=q.popleft() for u in adjacents_list[v]: if distance[u] == -1: distance[u]=distance[v]+1 q.append(u) return distance #Recibiendo los valores de n y m n,m=parser() #padres pi=[0 for x in range(n)] #ciudades atacadas en el subarbol count_attacked_cities_subtree=[0 for x in range(n)] #ciudad atacada o no atacada attacked_city=[False for x in range(n)] #ciudades_que_son atacadas o sirven para llegar a las mismas important_cities=[True for x in range(n)] #Armando el árbol que representa a Byteforces adjacents_list=[[] for x in range(n)] for i in range(n-1): v1,v2=parser() adjacents_list[v1-1].append(v2-1) adjacents_list[v2-1].append(v1-1) #número de ciudades atacadas numbers_of_attacked_cities=[x-1 for x in parser()] if m==1: print(numbers_of_attacked_cities[0]+1) print(0) exit() #marcando las ciudades atacadas for i in numbers_of_attacked_cities: attacked_city[i]=True #Obteniendo las ciudades que recorre Super M DFS_Discriminiting() #Creando el nuevo árbol que representa el recorrido de Super M adjacents_list=[[] for x in range(n)] #Armando el nuevo árbol y contando sus aristas count_edges=0 for v in range(n): if v==numbers_of_attacked_cities[0]: continue elif important_cities[v] and important_cities[pi[v]]: adjacents_list[v].append(pi[v]) adjacents_list[pi[v]].append(v) count_edges+=1 #alturas heights1=[0 for x in range(n)] heights2=[0 for x in range(n)] #Calculando las alturas DFS_Heigths() #distancias distances1=[0 for x in range(n)] distances2=[0 for x in range(n)] #Calculando las distancias DFS_Distances() #Hallando la mayor distancia de las primeras distancias min_distance=distances1[numbers_of_attacked_cities[0]] for i in range(n): if important_cities[i] and min_distance>distances1[i]: min_distance=distances1[i] #Hallando el centro center=[] for i in range(n): if distances1[i]==min_distance: center.append(i) posibles_begin_cities=[] #Hallando la ciudad por la cual comenzar for i in center: distances_center=BFS(i) max_distance=0 for j in range(n): if distances_center[j]>max_distance: max_distance=distances_center[j] for j in range(n): if distances_center[j]==max_distance: posibles_begin_cities.append(j) #Imprimiendo la respuesta print(min(posibles_begin_cities)+1) print(2*count_edges-(distances1[center[0]]+distances2[center[0]])) ```
89,712
Provide tags and a correct Python 3 solution for this coding contest problem. Ari the monster is not an ordinary monster. She is the hidden identity of Super M, the Byteforces’ superhero. Byteforces is a country that consists of n cities, connected by n - 1 bidirectional roads. Every road connects exactly two distinct cities, and the whole road system is designed in a way that one is able to go from any city to any other city using only the given roads. There are m cities being attacked by humans. So Ari... we meant Super M have to immediately go to each of the cities being attacked to scare those bad humans. Super M can pass from one city to another only using the given roads. Moreover, passing through one road takes her exactly one kron - the time unit used in Byteforces. <image> However, Super M is not on Byteforces now - she is attending a training camp located in a nearby country Codeforces. Fortunately, there is a special device in Codeforces that allows her to instantly teleport from Codeforces to any city of Byteforces. The way back is too long, so for the purpose of this problem teleportation is used exactly once. You are to help Super M, by calculating the city in which she should teleport at the beginning in order to end her job in the minimum time (measured in krons). Also, provide her with this time so she can plan her way back to Codeforces. Input The first line of the input contains two integers n and m (1 ≤ m ≤ n ≤ 123456) - the number of cities in Byteforces, and the number of cities being attacked respectively. Then follow n - 1 lines, describing the road system. Each line contains two city numbers ui and vi (1 ≤ ui, vi ≤ n) - the ends of the road i. The last line contains m distinct integers - numbers of cities being attacked. These numbers are given in no particular order. Output First print the number of the city Super M should teleport to. If there are many possible optimal answers, print the one with the lowest city number. Then print the minimum possible time needed to scare all humans in cities being attacked, measured in Krons. Note that the correct answer is always unique. Examples Input 7 2 1 2 1 3 1 4 3 5 3 6 3 7 2 7 Output 2 3 Input 6 4 1 2 2 3 2 4 4 5 4 6 2 4 5 6 Output 2 4 Note In the first sample, there are two possibilities to finish the Super M's job in 3 krons. They are: <image> and <image>. However, you should choose the first one as it starts in the city with the lower number. Tags: dfs and similar, dp, graphs, trees Correct Solution: ``` from collections import deque n,m = [int(x) for x in input().split()] adj = [[] for x in range(n+1)] for _ in range(1,n): a,b = [int(x) for x in input().split()] adj[a].append(b) adj[b].append(a) chaos = [int(x) for x in input().split()] s = chaos[0] chaos = set(chaos) cc = [0]*(n+1) st = deque() st.append((s,-1)) while len(st): u,e = st.pop() if u<0: if e>=0: cc[e] += cc[-u] continue if u in chaos: cc[u] +=1 st.append((-u,e)) for v in adj[u]: if v!=e: st.append((v,u)) #dfs(s,-1) adj = [list(filter(lambda v:cc[v]>0,u)) for u in adj] a = (s,0) st = deque() st.append((a[0],-1,0)) while len(st): u,e,h = st.pop() if h>a[1]: a = (u,h) elif h==a[1] and u<a[0]: a = (u,h) for v in adj[u]: if v!=e: st.append((v,u,h+1)) b = a a = (a[0],0) st = deque() st.append((a[0],-1,0)) while len(st): u,e,h = st.pop() if h>a[1]: a = (u,h) elif h==a[1] and u<a[0]: a = (u,h) for v in adj[u]: if v!=e: st.append((v,u,h+1)) print(min(a[0],b[0])) print(2*(n-cc.count(0))-a[1]) ```
89,713
Provide tags and a correct Python 3 solution for this coding contest problem. Ari the monster is not an ordinary monster. She is the hidden identity of Super M, the Byteforces’ superhero. Byteforces is a country that consists of n cities, connected by n - 1 bidirectional roads. Every road connects exactly two distinct cities, and the whole road system is designed in a way that one is able to go from any city to any other city using only the given roads. There are m cities being attacked by humans. So Ari... we meant Super M have to immediately go to each of the cities being attacked to scare those bad humans. Super M can pass from one city to another only using the given roads. Moreover, passing through one road takes her exactly one kron - the time unit used in Byteforces. <image> However, Super M is not on Byteforces now - she is attending a training camp located in a nearby country Codeforces. Fortunately, there is a special device in Codeforces that allows her to instantly teleport from Codeforces to any city of Byteforces. The way back is too long, so for the purpose of this problem teleportation is used exactly once. You are to help Super M, by calculating the city in which she should teleport at the beginning in order to end her job in the minimum time (measured in krons). Also, provide her with this time so she can plan her way back to Codeforces. Input The first line of the input contains two integers n and m (1 ≤ m ≤ n ≤ 123456) - the number of cities in Byteforces, and the number of cities being attacked respectively. Then follow n - 1 lines, describing the road system. Each line contains two city numbers ui and vi (1 ≤ ui, vi ≤ n) - the ends of the road i. The last line contains m distinct integers - numbers of cities being attacked. These numbers are given in no particular order. Output First print the number of the city Super M should teleport to. If there are many possible optimal answers, print the one with the lowest city number. Then print the minimum possible time needed to scare all humans in cities being attacked, measured in Krons. Note that the correct answer is always unique. Examples Input 7 2 1 2 1 3 1 4 3 5 3 6 3 7 2 7 Output 2 3 Input 6 4 1 2 2 3 2 4 4 5 4 6 2 4 5 6 Output 2 4 Note In the first sample, there are two possibilities to finish the Super M's job in 3 krons. They are: <image> and <image>. However, you should choose the first one as it starts in the city with the lower number. Tags: dfs and similar, dp, graphs, trees Correct Solution: ``` from heapq import * INF = float('inf') n, m = map(int, input().split()) adj = [[] for _ in range(n+1)] wg= ng = [0 for _ in range(n+1)] for _ in range(n-1): a, b = map(int, input().split()) adj[a].append(b) adj[b].append(a) aaa = set(map(int, input().split())) if len(aaa) == 1:print(min(aaa));print(0);exit() rm = [] for i in range(n+1): ng[i] = len(adj[i]) if i not in aaa and ng[i] == 1: rm.append(i) for a in aaa: ng[a] = 0 def remove_node(index): while adj[index]: nx = adj[index].pop() adj[nx].remove(index) ng[nx] -= 1 if ng[nx] == 1: rm.append(nx) ng[index] = 0 while rm: remove_node(rm.pop()) state = [0 for _ in range(n+1)] que = [(min(aaa), None)] res = 0 for _ in range(2): deep = [0 for _ in range(n + 1)] while que: res += 1 root, proot = que.pop() for nx in adj[root]: if proot == nx: continue if _: state[nx] = root deep[nx] = deep[root] + 1 que.append((nx, root)) if _: break start = max(1,deep.index(max(deep))) que = [(start, None)] end = max(1, deep.index(max(deep))) i = end path = 1 while i != start: path += 1 i = state[i] print(min(start,end)) print(res -1 -path) ```
89,714
Provide tags and a correct Python 3 solution for this coding contest problem. Ari the monster is not an ordinary monster. She is the hidden identity of Super M, the Byteforces’ superhero. Byteforces is a country that consists of n cities, connected by n - 1 bidirectional roads. Every road connects exactly two distinct cities, and the whole road system is designed in a way that one is able to go from any city to any other city using only the given roads. There are m cities being attacked by humans. So Ari... we meant Super M have to immediately go to each of the cities being attacked to scare those bad humans. Super M can pass from one city to another only using the given roads. Moreover, passing through one road takes her exactly one kron - the time unit used in Byteforces. <image> However, Super M is not on Byteforces now - she is attending a training camp located in a nearby country Codeforces. Fortunately, there is a special device in Codeforces that allows her to instantly teleport from Codeforces to any city of Byteforces. The way back is too long, so for the purpose of this problem teleportation is used exactly once. You are to help Super M, by calculating the city in which she should teleport at the beginning in order to end her job in the minimum time (measured in krons). Also, provide her with this time so she can plan her way back to Codeforces. Input The first line of the input contains two integers n and m (1 ≤ m ≤ n ≤ 123456) - the number of cities in Byteforces, and the number of cities being attacked respectively. Then follow n - 1 lines, describing the road system. Each line contains two city numbers ui and vi (1 ≤ ui, vi ≤ n) - the ends of the road i. The last line contains m distinct integers - numbers of cities being attacked. These numbers are given in no particular order. Output First print the number of the city Super M should teleport to. If there are many possible optimal answers, print the one with the lowest city number. Then print the minimum possible time needed to scare all humans in cities being attacked, measured in Krons. Note that the correct answer is always unique. Examples Input 7 2 1 2 1 3 1 4 3 5 3 6 3 7 2 7 Output 2 3 Input 6 4 1 2 2 3 2 4 4 5 4 6 2 4 5 6 Output 2 4 Note In the first sample, there are two possibilities to finish the Super M's job in 3 krons. They are: <image> and <image>. However, you should choose the first one as it starts in the city with the lower number. Tags: dfs and similar, dp, graphs, trees Correct Solution: ``` from collections import deque from sys import stdin from sys import exit #parser def parser(): return map(int, stdin.readline().split()) def DFS_Discriminiting(): #visitados visited=[False for x in range(n)] visited[numbers_of_attacked_cities[0]]=True stack=[] intrudoction_order=[] stack.append(numbers_of_attacked_cities[0]) while len(stack)>0: v=stack.pop() for u in adjacents_list[v]: if not visited[u]: pi[u]=v visited[u]=True if attacked_city[u]: count_attacked_cities_subtree[u]+=1 stack.append(u) intrudoction_order.append(u) for v in intrudoction_order[::-1]: count_attacked_cities_subtree[pi[v]]+=count_attacked_cities_subtree[v] if count_attacked_cities_subtree[v]==0: important_cities[v]=False def DFS_Heigths(): #visitados visited=[False for x in range(n)] visited[numbers_of_attacked_cities[0]]=True stack=[] intrudoction_order=[] stack.append(numbers_of_attacked_cities[0]) while len(stack)>0: v=stack.pop() for u in adjacents_list[v]: if not visited[u]: pi[u]=v visited[u]=True stack.append(u) intrudoction_order.append(u) for v in intrudoction_order[::-1]: if heights1[pi[v]] < heights1[v]+1: heights2[pi[v]]=heights1[pi[v]] heights1[pi[v]]=heights1[v]+1 elif heights2[pi[v]]<heights1[v]+1: heights2[pi[v]]=heights1[v]+1 def Distance_Root(s): for v in adjacents_list[s]: if heights1[v]+1>distances1[s]: distances2[s]=distances1[s] distances1[s]=heights1[v]+1 elif heights1[v]+1>distances2[s]: distances2[s]=heights1[v]+1 def DFS_Distances(): #visitados visited=[False for x in range(n)] visited[numbers_of_attacked_cities[0]]=True stack=[] stack.append(numbers_of_attacked_cities[0]) Distance_Root(numbers_of_attacked_cities[0]) while len(stack)>0: v=stack.pop() for u in adjacents_list[v]: if not visited[u]: pi[u]=v visited[u]=True determinate=False stack.append(u) if heights1[u]+1==distances1[v]: if heights1[u]+1>distances2[v]: determinate=True distances1[u]=max(heights1[u],distances2[v]+1) if distances1[u]==heights1[u]: distances2[u]=max(distances2[v]+1,heights2[u]) else: distances2[u]=heights1[u] if not determinate: distances1[u]=distances1[v]+1 distances2[u]=heights1[u] def BFS(s): distance=[-1 for x in range(n)] distance[s]=0 q=deque() q.append(s) while len(q)>0: v=q.popleft() for u in adjacents_list[v]: if distance[u] == -1: distance[u]=distance[v]+1 q.append(u) return distance n,m=parser() #Creando los arrays necesarios para la ejecucion de DFS #padres pi=[0 for x in range(n)] #ciudades atacadas en el subarbol count_attacked_cities_subtree=[0 for x in range(n)] #ciudad atacada o no atacada attacked_city=[False for x in range(n)] #ciudades_que_son atacadas o sirven para llegar a las mismas important_cities=[True for x in range(n)] adjacents_list=[[] for x in range(n)] for i in range(n-1): v1,v2=parser() adjacents_list[v1-1].append(v2-1) adjacents_list[v2-1].append(v1-1) #numero de ciudades atacadas numbers_of_attacked_cities=[x-1 for x in parser()] if m==1: print(numbers_of_attacked_cities[0]+1) print(0) exit() #marcando las ciudades atacadas for i in numbers_of_attacked_cities: attacked_city[i]=True DFS_Discriminiting() adjacents_list=[[] for x in range(n)] count_edges=0 for v in range(n): if v==numbers_of_attacked_cities[0]: continue elif important_cities[v] and important_cities[pi[v]]: adjacents_list[v].append(pi[v]) adjacents_list[pi[v]].append(v) count_edges+=1 #padres pi=[0 for x in range(n)] #alturas heights1=[0 for x in range(n)] heights2=[0 for x in range(n)] DFS_Heigths() #distances distances1=[0 for x in range(n)] distances2=[0 for x in range(n)] DFS_Distances() lower=distances1[numbers_of_attacked_cities[0]] for i in range(n): if important_cities[i] and lower>distances1[i]: lower=distances1[i] centers=[] for i in range(n): if distances1[i]==lower: centers.append(i) posibles_begin_cities=[] for i in centers: distances_center=BFS(i) max_distance=0 for j in range(n): if distances_center[j]>max_distance: max_distance=distances_center[j] for j in range(n): if distances_center[j]==max_distance: posibles_begin_cities.append(j) print(min(posibles_begin_cities)+1) print(2*count_edges-(distances1[centers[0]]+distances2[centers[0]])) ```
89,715
Provide tags and a correct Python 3 solution for this coding contest problem. Ari the monster is not an ordinary monster. She is the hidden identity of Super M, the Byteforces’ superhero. Byteforces is a country that consists of n cities, connected by n - 1 bidirectional roads. Every road connects exactly two distinct cities, and the whole road system is designed in a way that one is able to go from any city to any other city using only the given roads. There are m cities being attacked by humans. So Ari... we meant Super M have to immediately go to each of the cities being attacked to scare those bad humans. Super M can pass from one city to another only using the given roads. Moreover, passing through one road takes her exactly one kron - the time unit used in Byteforces. <image> However, Super M is not on Byteforces now - she is attending a training camp located in a nearby country Codeforces. Fortunately, there is a special device in Codeforces that allows her to instantly teleport from Codeforces to any city of Byteforces. The way back is too long, so for the purpose of this problem teleportation is used exactly once. You are to help Super M, by calculating the city in which she should teleport at the beginning in order to end her job in the minimum time (measured in krons). Also, provide her with this time so she can plan her way back to Codeforces. Input The first line of the input contains two integers n and m (1 ≤ m ≤ n ≤ 123456) - the number of cities in Byteforces, and the number of cities being attacked respectively. Then follow n - 1 lines, describing the road system. Each line contains two city numbers ui and vi (1 ≤ ui, vi ≤ n) - the ends of the road i. The last line contains m distinct integers - numbers of cities being attacked. These numbers are given in no particular order. Output First print the number of the city Super M should teleport to. If there are many possible optimal answers, print the one with the lowest city number. Then print the minimum possible time needed to scare all humans in cities being attacked, measured in Krons. Note that the correct answer is always unique. Examples Input 7 2 1 2 1 3 1 4 3 5 3 6 3 7 2 7 Output 2 3 Input 6 4 1 2 2 3 2 4 4 5 4 6 2 4 5 6 Output 2 4 Note In the first sample, there are two possibilities to finish the Super M's job in 3 krons. They are: <image> and <image>. However, you should choose the first one as it starts in the city with the lower number. Tags: dfs and similar, dp, graphs, trees Correct Solution: ``` import sys d = list(map(int, sys.stdin.read().split())) n, m = d[0], d[1] k = 2 * n class T: def __init__(t, i): t.p = set() t.h = t.d = 0 t.k = i def g(k, h): print(k, h) exit() t = [T(i) for i in range(n + 1)] for i in d[k:]: t[i].d = 1 for a, b in zip(d[2:k:2], d[3:k:2]): t[a].p.add(t[b]) t[b].p.add(t[a]) u = [x for x in t if len(x.p) == 1] v = [] while u: x = u.pop() if x.d: v.append(x) elif x.p: y = x.p.pop() y.p.remove(x) if len(y.p) == 1: u.append(y) if len(v) == 1: g(v[0].k, 0) if len(t) == 2: g(t[1].k, 0) for x in v: x.h = 1 s = 1 while 1: s += 2 x = v.pop() y = x.p.pop() if len(y.p) == 1 and x in y.p: g(min(x.k, y.k), s - x.h - y.h) h = x.h + 1 if h > y.h: y.h, y.k = h, x.k elif h == y.h: y.k = min(x.k, y.k) y.p.remove(x) if len(y.p) == 1: u.append(y) if not v: v, u = u, v ```
89,716
Provide tags and a correct Python 3 solution for this coding contest problem. Ari the monster is not an ordinary monster. She is the hidden identity of Super M, the Byteforces’ superhero. Byteforces is a country that consists of n cities, connected by n - 1 bidirectional roads. Every road connects exactly two distinct cities, and the whole road system is designed in a way that one is able to go from any city to any other city using only the given roads. There are m cities being attacked by humans. So Ari... we meant Super M have to immediately go to each of the cities being attacked to scare those bad humans. Super M can pass from one city to another only using the given roads. Moreover, passing through one road takes her exactly one kron - the time unit used in Byteforces. <image> However, Super M is not on Byteforces now - she is attending a training camp located in a nearby country Codeforces. Fortunately, there is a special device in Codeforces that allows her to instantly teleport from Codeforces to any city of Byteforces. The way back is too long, so for the purpose of this problem teleportation is used exactly once. You are to help Super M, by calculating the city in which she should teleport at the beginning in order to end her job in the minimum time (measured in krons). Also, provide her with this time so she can plan her way back to Codeforces. Input The first line of the input contains two integers n and m (1 ≤ m ≤ n ≤ 123456) - the number of cities in Byteforces, and the number of cities being attacked respectively. Then follow n - 1 lines, describing the road system. Each line contains two city numbers ui and vi (1 ≤ ui, vi ≤ n) - the ends of the road i. The last line contains m distinct integers - numbers of cities being attacked. These numbers are given in no particular order. Output First print the number of the city Super M should teleport to. If there are many possible optimal answers, print the one with the lowest city number. Then print the minimum possible time needed to scare all humans in cities being attacked, measured in Krons. Note that the correct answer is always unique. Examples Input 7 2 1 2 1 3 1 4 3 5 3 6 3 7 2 7 Output 2 3 Input 6 4 1 2 2 3 2 4 4 5 4 6 2 4 5 6 Output 2 4 Note In the first sample, there are two possibilities to finish the Super M's job in 3 krons. They are: <image> and <image>. However, you should choose the first one as it starts in the city with the lower number. Tags: dfs and similar, dp, graphs, trees Correct Solution: ``` from collections import deque from sys import exit #parser def parser(): return [int(x) for x in input().split()] def DFS_Discriminiting(): #visitados visited=[False for x in range(n)] visited[numbers_of_attacked_cities[0]]=True stack=[] intrudoction_order=[] stack.append(numbers_of_attacked_cities[0]) while len(stack)>0: v=stack.pop() for u in adjacents_list[v]: if not visited[u]: pi[u]=v visited[u]=True if attacked_city[u]: count_attacked_cities_subtree[u]+=1 stack.append(u) intrudoction_order.append(u) for v in intrudoction_order[::-1]: count_attacked_cities_subtree[pi[v]]+=count_attacked_cities_subtree[v] if count_attacked_cities_subtree[v]==0: important_cities[v]=False def DFS_Heigths(): #visitados visited=[False for x in range(n)] visited[numbers_of_attacked_cities[0]]=True stack=[] intrudoction_order=[] stack.append(numbers_of_attacked_cities[0]) while len(stack)>0: v=stack.pop() for u in adjacents_list[v]: if not visited[u]: pi[u]=v visited[u]=True stack.append(u) intrudoction_order.append(u) for v in intrudoction_order[::-1]: if heights1[pi[v]] < heights1[v]+1: heights2[pi[v]]=heights1[pi[v]] heights1[pi[v]]=heights1[v]+1 elif heights2[pi[v]]<heights1[v]+1: heights2[pi[v]]=heights1[v]+1 def Distance_Root(s): for v in adjacents_list[s]: if heights1[v]+1>distances1[s]: distances2[s]=distances1[s] distances1[s]=heights1[v]+1 elif heights1[v]+1>distances2[s]: distances2[s]=heights1[v]+1 def DFS_Distances(): #visitados visited=[False for x in range(n)] visited[numbers_of_attacked_cities[0]]=True stack=[] stack.append(numbers_of_attacked_cities[0]) Distance_Root(numbers_of_attacked_cities[0]) while len(stack)>0: v=stack.pop() for u in adjacents_list[v]: if not visited[u]: pi[u]=v visited[u]=True determinate=False stack.append(u) if heights1[u]+1==distances1[v]: if heights1[u]+1>distances2[v]: determinate=True distances1[u]=max(heights1[u],distances2[v]+1) if distances1[u]==heights1[u]: distances2[u]=max(distances2[v]+1,heights2[u]) else: distances2[u]=heights1[u] if not determinate: distances1[u]=distances1[v]+1 distances2[u]=heights1[u] def BFS(s): distance=[-1 for x in range(n)] distance[s]=0 q=deque() q.append(s) while len(q)>0: v=q.popleft() for u in adjacents_list[v]: if distance[u] == -1: distance[u]=distance[v]+1 q.append(u) return distance n,m=parser() #Creando los arrays necesarios para la ejecucion de DFS #padres pi=[0 for x in range(n)] #ciudades atacadas en el subarbol count_attacked_cities_subtree=[0 for x in range(n)] #ciudad atacada o no atacada attacked_city=[False for x in range(n)] #ciudades_que_son atacadas o sirven para llegar a las mismas important_cities=[True for x in range(n)] adjacents_list=[[] for x in range(n)] for i in range(n-1): edge=parser() adjacents_list[edge[0]-1].append(edge[1]-1) adjacents_list[edge[1]-1].append(edge[0]-1) #numero de ciudades atacadas numbers_of_attacked_cities=[] for i in parser(): numbers_of_attacked_cities.append(i-1) if m==1: print(numbers_of_attacked_cities[0]+1) print(0) exit() #marcando las ciudades atacadas for i in numbers_of_attacked_cities: attacked_city[i]=True DFS_Discriminiting() adjacents_list=[[] for x in range(n)] count_edges=0 for v in range(n): if v==numbers_of_attacked_cities[0]: continue elif important_cities[v] and important_cities[pi[v]]: adjacents_list[v].append(pi[v]) adjacents_list[pi[v]].append(v) count_edges+=1 #padres pi=[0 for x in range(n)] #alturas heights1=[0 for x in range(n)] heights2=[0 for x in range(n)] DFS_Heigths() #distances distances1=[0 for x in range(n)] distances2=[0 for x in range(n)] DFS_Distances() lower=distances1[numbers_of_attacked_cities[0]] for i in range(n): if important_cities[i] and lower>distances1[i]: lower=distances1[i] centers=[] for i in range(n): if distances1[i]==lower: centers.append(i) posibles_begin_cities=[] for i in centers: distances_center=BFS(i) max_distance=0 for j in range(n): if distances_center[j]>max_distance: max_distance=distances_center[j] for j in range(n): if distances_center[j]==max_distance: posibles_begin_cities.append(j) print(min(posibles_begin_cities)+1) print(2*count_edges-(distances1[centers[0]]+distances2[centers[0]])) ```
89,717
Provide tags and a correct Python 3 solution for this coding contest problem. Ari the monster is not an ordinary monster. She is the hidden identity of Super M, the Byteforces’ superhero. Byteforces is a country that consists of n cities, connected by n - 1 bidirectional roads. Every road connects exactly two distinct cities, and the whole road system is designed in a way that one is able to go from any city to any other city using only the given roads. There are m cities being attacked by humans. So Ari... we meant Super M have to immediately go to each of the cities being attacked to scare those bad humans. Super M can pass from one city to another only using the given roads. Moreover, passing through one road takes her exactly one kron - the time unit used in Byteforces. <image> However, Super M is not on Byteforces now - she is attending a training camp located in a nearby country Codeforces. Fortunately, there is a special device in Codeforces that allows her to instantly teleport from Codeforces to any city of Byteforces. The way back is too long, so for the purpose of this problem teleportation is used exactly once. You are to help Super M, by calculating the city in which she should teleport at the beginning in order to end her job in the minimum time (measured in krons). Also, provide her with this time so she can plan her way back to Codeforces. Input The first line of the input contains two integers n and m (1 ≤ m ≤ n ≤ 123456) - the number of cities in Byteforces, and the number of cities being attacked respectively. Then follow n - 1 lines, describing the road system. Each line contains two city numbers ui and vi (1 ≤ ui, vi ≤ n) - the ends of the road i. The last line contains m distinct integers - numbers of cities being attacked. These numbers are given in no particular order. Output First print the number of the city Super M should teleport to. If there are many possible optimal answers, print the one with the lowest city number. Then print the minimum possible time needed to scare all humans in cities being attacked, measured in Krons. Note that the correct answer is always unique. Examples Input 7 2 1 2 1 3 1 4 3 5 3 6 3 7 2 7 Output 2 3 Input 6 4 1 2 2 3 2 4 4 5 4 6 2 4 5 6 Output 2 4 Note In the first sample, there are two possibilities to finish the Super M's job in 3 krons. They are: <image> and <image>. However, you should choose the first one as it starts in the city with the lower number. Tags: dfs and similar, dp, graphs, trees Correct Solution: ``` def f(k, h): print(k, h) exit() def g(p): i = p.pop() return i, t[i] import sys d = list(map(int, sys.stdin.read().split())) n, m = d[0], d[1] if n == 1: f(1, 0) k = 2 * n t = [[0, set(), i, 0] for i in range(n + 1)] for i in d[k:]: t[i][0] = 1 for a, b in zip(d[2:k:2], d[3:k:2]): t[a][1].add(b) t[b][1].add(a) p = ([], []) for x in t: if len(x[1]) == 1: p[x[0]].append(x[2]) k = s = 1 while p[0]: i, x = g(p[0]) j, y = g(x[1]) y[1].remove(i) if len(y[1]) == 1: p[y[0]].append(j) if len(p[k]) == 1: f(p[k][0], 0) for i in p[k]: t[i][3] = 1 while 1: s += 2 i, x = g(p[k]) j, y = g(x[1]) if len(y[1]) == 1: f(min(x[2], y[2]), s - x[3] - y[3]) x[3] += 1 if x[3] > y[3]: y[2:] = x[2:] elif x[3] == y[3]: y[2] = min(x[2], y[2]) y[1].remove(i) if len(y[1]) == 1: p[1 - k].append(j) if not p[k]: k = 1 - k ```
89,718
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ari the monster is not an ordinary monster. She is the hidden identity of Super M, the Byteforces’ superhero. Byteforces is a country that consists of n cities, connected by n - 1 bidirectional roads. Every road connects exactly two distinct cities, and the whole road system is designed in a way that one is able to go from any city to any other city using only the given roads. There are m cities being attacked by humans. So Ari... we meant Super M have to immediately go to each of the cities being attacked to scare those bad humans. Super M can pass from one city to another only using the given roads. Moreover, passing through one road takes her exactly one kron - the time unit used in Byteforces. <image> However, Super M is not on Byteforces now - she is attending a training camp located in a nearby country Codeforces. Fortunately, there is a special device in Codeforces that allows her to instantly teleport from Codeforces to any city of Byteforces. The way back is too long, so for the purpose of this problem teleportation is used exactly once. You are to help Super M, by calculating the city in which she should teleport at the beginning in order to end her job in the minimum time (measured in krons). Also, provide her with this time so she can plan her way back to Codeforces. Input The first line of the input contains two integers n and m (1 ≤ m ≤ n ≤ 123456) - the number of cities in Byteforces, and the number of cities being attacked respectively. Then follow n - 1 lines, describing the road system. Each line contains two city numbers ui and vi (1 ≤ ui, vi ≤ n) - the ends of the road i. The last line contains m distinct integers - numbers of cities being attacked. These numbers are given in no particular order. Output First print the number of the city Super M should teleport to. If there are many possible optimal answers, print the one with the lowest city number. Then print the minimum possible time needed to scare all humans in cities being attacked, measured in Krons. Note that the correct answer is always unique. Examples Input 7 2 1 2 1 3 1 4 3 5 3 6 3 7 2 7 Output 2 3 Input 6 4 1 2 2 3 2 4 4 5 4 6 2 4 5 6 Output 2 4 Note In the first sample, there are two possibilities to finish the Super M's job in 3 krons. They are: <image> and <image>. However, you should choose the first one as it starts in the city with the lower number. Submitted Solution: ``` def tolist(graph): res = [[] for i in range(n + 1)] for l in graph: res[l[0]].append(l[1]) res[l[1]].append(l[0]) return res # ������� ��� rebuild # ������� ��� ����� �� ������ ����� - �� ������� def dfs(s): global graph global regraph global checked good = False if bads[s]: good = True checked[s] = 1 for fr in graph[s]: if not checked[fr]: f = dfs(fr) if f: regraph[s].append(fr) regraph[fr].append(s) good = True return good def dfs2(s, k): global pathto global checked k += 1 pathto[s] = k checked[s] = 1 for fr in regraph[s]: if not checked[fr]: dfs2(fr, k) n, m = tuple(map(int, input().split())) pathto = [0] * (n + 1) graph = [] regraph = [[] for i in range(n + 1)] checked = [0] * (n + 1) for i in range(n - 1): graph.append(list(map(int, input().split()))) graph = tolist(graph) #bads = [2, 5, 7, 9] #graph[1] = [4] #graph[2] = [3, 4] #graph[3] = [2] #graph[4] = [1, 2, 5, 10] #graph[5] = [4, 6, 7] #graph[6] = [5] #graph[7] = [5] #graph[8] = [10] #graph[9] = [10] #graph[10] = [4, 8, 9] ba = list(map(int, input().split())) bads = [0] * (n + 1) for bad in ba: bads[bad] = 1 a = max(ba) dfs(a) checked = [0] * (n + 1) dfs2(a, -1) s = pathto.index(max(pathto)) checked = [0] * (n + 1) dfs2(s, -1) res = max(pathto) m = -1 # ����� ����� for i in range(n + 1): if regraph[i] : m += 1 result = m * 2 - res print(s) print(result) ``` No
89,719
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ari the monster is not an ordinary monster. She is the hidden identity of Super M, the Byteforces’ superhero. Byteforces is a country that consists of n cities, connected by n - 1 bidirectional roads. Every road connects exactly two distinct cities, and the whole road system is designed in a way that one is able to go from any city to any other city using only the given roads. There are m cities being attacked by humans. So Ari... we meant Super M have to immediately go to each of the cities being attacked to scare those bad humans. Super M can pass from one city to another only using the given roads. Moreover, passing through one road takes her exactly one kron - the time unit used in Byteforces. <image> However, Super M is not on Byteforces now - she is attending a training camp located in a nearby country Codeforces. Fortunately, there is a special device in Codeforces that allows her to instantly teleport from Codeforces to any city of Byteforces. The way back is too long, so for the purpose of this problem teleportation is used exactly once. You are to help Super M, by calculating the city in which she should teleport at the beginning in order to end her job in the minimum time (measured in krons). Also, provide her with this time so she can plan her way back to Codeforces. Input The first line of the input contains two integers n and m (1 ≤ m ≤ n ≤ 123456) - the number of cities in Byteforces, and the number of cities being attacked respectively. Then follow n - 1 lines, describing the road system. Each line contains two city numbers ui and vi (1 ≤ ui, vi ≤ n) - the ends of the road i. The last line contains m distinct integers - numbers of cities being attacked. These numbers are given in no particular order. Output First print the number of the city Super M should teleport to. If there are many possible optimal answers, print the one with the lowest city number. Then print the minimum possible time needed to scare all humans in cities being attacked, measured in Krons. Note that the correct answer is always unique. Examples Input 7 2 1 2 1 3 1 4 3 5 3 6 3 7 2 7 Output 2 3 Input 6 4 1 2 2 3 2 4 4 5 4 6 2 4 5 6 Output 2 4 Note In the first sample, there are two possibilities to finish the Super M's job in 3 krons. They are: <image> and <image>. However, you should choose the first one as it starts in the city with the lower number. Submitted Solution: ``` import sys d = list(map(int, sys.stdin.read().split())) n, m = d[0], d[1] k = 2 * n class T: def __init__(t, i): t.p, t.q = set(), set() t.h = t.l = 0 t.k = i t = [T(i) for i in range(n + 1)] for i in d[k:]: t[i].l = 1 for a, b in zip(d[2:k:2], d[3:k:2]): t[a].p.add(t[b]) t[b].p.add(t[a]) u = [x for x in t if len(x.p) == 1] v = [] while u: x = u.pop() if x.l: v.append(x) elif x.p: y = x.p.pop() y.p.remove(x) if len(y.p) == 1: u.append(y) for x in v: x.h = 1 for x in t: x.q = x.p.copy() while v: x = v.pop() y = x.p.pop() h = x.h + 1 if h > y.h: y.h, y.k = h, x.k elif h == y.h: y.k = min(x.k, y.k) y.p.remove(x) h = k = 0 s = -1 for x in t: if x.q: s += 2 for y in x.q: if x.k != y.k and x.h + y.h > h: h = x.h + y.h k = min(x.k, y.k) print(k, s - h) ``` No
89,720
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ari the monster is not an ordinary monster. She is the hidden identity of Super M, the Byteforces’ superhero. Byteforces is a country that consists of n cities, connected by n - 1 bidirectional roads. Every road connects exactly two distinct cities, and the whole road system is designed in a way that one is able to go from any city to any other city using only the given roads. There are m cities being attacked by humans. So Ari... we meant Super M have to immediately go to each of the cities being attacked to scare those bad humans. Super M can pass from one city to another only using the given roads. Moreover, passing through one road takes her exactly one kron - the time unit used in Byteforces. <image> However, Super M is not on Byteforces now - she is attending a training camp located in a nearby country Codeforces. Fortunately, there is a special device in Codeforces that allows her to instantly teleport from Codeforces to any city of Byteforces. The way back is too long, so for the purpose of this problem teleportation is used exactly once. You are to help Super M, by calculating the city in which she should teleport at the beginning in order to end her job in the minimum time (measured in krons). Also, provide her with this time so she can plan her way back to Codeforces. Input The first line of the input contains two integers n and m (1 ≤ m ≤ n ≤ 123456) - the number of cities in Byteforces, and the number of cities being attacked respectively. Then follow n - 1 lines, describing the road system. Each line contains two city numbers ui and vi (1 ≤ ui, vi ≤ n) - the ends of the road i. The last line contains m distinct integers - numbers of cities being attacked. These numbers are given in no particular order. Output First print the number of the city Super M should teleport to. If there are many possible optimal answers, print the one with the lowest city number. Then print the minimum possible time needed to scare all humans in cities being attacked, measured in Krons. Note that the correct answer is always unique. Examples Input 7 2 1 2 1 3 1 4 3 5 3 6 3 7 2 7 Output 2 3 Input 6 4 1 2 2 3 2 4 4 5 4 6 2 4 5 6 Output 2 4 Note In the first sample, there are two possibilities to finish the Super M's job in 3 krons. They are: <image> and <image>. However, you should choose the first one as it starts in the city with the lower number. Submitted Solution: ``` from heapq import * INF = float('inf') n, m = map(int, input().split()) adj = [[] for _ in range(n+1)] wg = [0 for _ in range(n+1)] for _ in range(n-1): a, b = map(int, input().split()) adj[a].append(b) adj[b].append(a) aaa = set(map(int, input().split())) def remove_node(index): while adj[index]: nx = adj[index].pop() adj[nx].remove(index) def dfs(root, p=None): wtab = [(0, root)] for nx in adj[root].copy(): if p == nx: continue w, index = dfs(nx, root) if w or index: heappush(wtab, (w-1, index)) if len(wtab) == 1 and root not in aaa: remove_node(root) return 0, 0 return heappop(wtab) start = dfs(min(aaa))[1] end = dfs(start)[1] if start > end: start, end = end, start def pathfinder(root, p=None): if root == end: path.append(root) return True for nx in adj[root]: if nx == p: continue if pathfinder(nx, root): path.append(root) return True return False path = [] pathfinder(start) path.reverse() def weight(root, p=None): w = 1 for nx in adj[root]: if nx == p: continue if nx in path: continue w += weight(nx, root) return w for p in path: wg[p] = weight(p) s = 0 for p in path: s += 1 if p == 1 else 2 * wg[p] - 1 print(start) print(s-1) ``` No
89,721
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ari the monster is not an ordinary monster. She is the hidden identity of Super M, the Byteforces’ superhero. Byteforces is a country that consists of n cities, connected by n - 1 bidirectional roads. Every road connects exactly two distinct cities, and the whole road system is designed in a way that one is able to go from any city to any other city using only the given roads. There are m cities being attacked by humans. So Ari... we meant Super M have to immediately go to each of the cities being attacked to scare those bad humans. Super M can pass from one city to another only using the given roads. Moreover, passing through one road takes her exactly one kron - the time unit used in Byteforces. <image> However, Super M is not on Byteforces now - she is attending a training camp located in a nearby country Codeforces. Fortunately, there is a special device in Codeforces that allows her to instantly teleport from Codeforces to any city of Byteforces. The way back is too long, so for the purpose of this problem teleportation is used exactly once. You are to help Super M, by calculating the city in which she should teleport at the beginning in order to end her job in the minimum time (measured in krons). Also, provide her with this time so she can plan her way back to Codeforces. Input The first line of the input contains two integers n and m (1 ≤ m ≤ n ≤ 123456) - the number of cities in Byteforces, and the number of cities being attacked respectively. Then follow n - 1 lines, describing the road system. Each line contains two city numbers ui and vi (1 ≤ ui, vi ≤ n) - the ends of the road i. The last line contains m distinct integers - numbers of cities being attacked. These numbers are given in no particular order. Output First print the number of the city Super M should teleport to. If there are many possible optimal answers, print the one with the lowest city number. Then print the minimum possible time needed to scare all humans in cities being attacked, measured in Krons. Note that the correct answer is always unique. Examples Input 7 2 1 2 1 3 1 4 3 5 3 6 3 7 2 7 Output 2 3 Input 6 4 1 2 2 3 2 4 4 5 4 6 2 4 5 6 Output 2 4 Note In the first sample, there are two possibilities to finish the Super M's job in 3 krons. They are: <image> and <image>. However, you should choose the first one as it starts in the city with the lower number. Submitted Solution: ``` import sys def dfs(v, h): v.color = True s = 0 for g in v.nodes: if not g.color: s += dfs(g, h + 1) if v.a: s += h v.color = False return s class Node: def __init__(self, id_): self.id = id_ self.nodes = [] self.a = False self.color = False #sys.stdin = open('input.txt') goals = [] towns = [] n, m = map(int, input().split()) for i in range(n): towns.append(Node(i + 1)) goals.append(False) i = 0 while i < n - 1: u, v = map(int, input().split()) towns[u - 1].nodes.append(towns[v - 1]) towns[v - 1].nodes.append(towns[u - 1]) i += 1 st = input().split() for t in st: towns[int(t) - 1].a = True min_p = 123457 min_id = 123457 for v in towns: if len(v.nodes) == 1: res = dfs(v, 0) if res < min_p: min_p = res min_id = v.id print(min_id, min_p, sep='\n') ``` No
89,722
Provide tags and a correct Python 3 solution for this coding contest problem. It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not enough time to assign tanks into teams and the whole game will collapse! There are exactly n distinct countries in the world and the i-th country added ai tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains at most one digit '1'. However, due to complaints from players, some number of tanks of one country was removed from the game, hence the number of tanks of this country may not remain beautiful. Your task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case. Input The first line of the input contains the number of countries n (1 ≤ n ≤ 100 000). The second line contains n non-negative integers ai without leading zeroes — the number of tanks of the i-th country. It is guaranteed that the second line contains at least n - 1 beautiful numbers and the total length of all these number's representations doesn't exceed 100 000. Output Print a single number without leading zeroes — the product of the number of tanks presented by each country. Examples Input 3 5 10 1 Output 50 Input 4 1 1 10 11 Output 110 Input 5 0 3 1 100 1 Output 0 Note In sample 1 numbers 10 and 1 are beautiful, number 5 is not not. In sample 2 number 11 is not beautiful (contains two '1's), all others are beautiful. In sample 3 number 3 is not beautiful, all others are beautiful. Tags: implementation, math Correct Solution: ``` def is_beautiful(s): if s[0] == '1' and s.count('0') == len(s)-1: return True return False def main(): n = int(input()) tmp = input().split() nb = '1' cnt = 0 if '0' in tmp: print('0') return; for num in tmp: if not is_beautiful(num): nb = num else: cnt += len(num)-1 print(nb + '0' * cnt) return; main() ```
89,723
Provide tags and a correct Python 3 solution for this coding contest problem. It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not enough time to assign tanks into teams and the whole game will collapse! There are exactly n distinct countries in the world and the i-th country added ai tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains at most one digit '1'. However, due to complaints from players, some number of tanks of one country was removed from the game, hence the number of tanks of this country may not remain beautiful. Your task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case. Input The first line of the input contains the number of countries n (1 ≤ n ≤ 100 000). The second line contains n non-negative integers ai without leading zeroes — the number of tanks of the i-th country. It is guaranteed that the second line contains at least n - 1 beautiful numbers and the total length of all these number's representations doesn't exceed 100 000. Output Print a single number without leading zeroes — the product of the number of tanks presented by each country. Examples Input 3 5 10 1 Output 50 Input 4 1 1 10 11 Output 110 Input 5 0 3 1 100 1 Output 0 Note In sample 1 numbers 10 and 1 are beautiful, number 5 is not not. In sample 2 number 11 is not beautiful (contains two '1's), all others are beautiful. In sample 3 number 3 is not beautiful, all others are beautiful. Tags: implementation, math Correct Solution: ``` n = int(input()) h = list(map(str, input().rstrip().split())) ans = '_' nuls = 0 for i in range(len(h)): if h[i][0] == '0': ans = '0' break else: cnt = 0 for j in range(len(h[i])): if (h[i][j] == '0'): cnt += 1 if (cnt == len(h[i]) - 1 and h[i][0] == '1'): nuls += cnt else: ans = h[i] if (ans == '0'): print(ans) else: if (ans == '_'): ans = '1' for i in range(nuls): ans += '0' print(ans) ```
89,724
Provide tags and a correct Python 3 solution for this coding contest problem. It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not enough time to assign tanks into teams and the whole game will collapse! There are exactly n distinct countries in the world and the i-th country added ai tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains at most one digit '1'. However, due to complaints from players, some number of tanks of one country was removed from the game, hence the number of tanks of this country may not remain beautiful. Your task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case. Input The first line of the input contains the number of countries n (1 ≤ n ≤ 100 000). The second line contains n non-negative integers ai without leading zeroes — the number of tanks of the i-th country. It is guaranteed that the second line contains at least n - 1 beautiful numbers and the total length of all these number's representations doesn't exceed 100 000. Output Print a single number without leading zeroes — the product of the number of tanks presented by each country. Examples Input 3 5 10 1 Output 50 Input 4 1 1 10 11 Output 110 Input 5 0 3 1 100 1 Output 0 Note In sample 1 numbers 10 and 1 are beautiful, number 5 is not not. In sample 2 number 11 is not beautiful (contains two '1's), all others are beautiful. In sample 3 number 3 is not beautiful, all others are beautiful. Tags: implementation, math Correct Solution: ``` n=int(input()) li=[x for x in input().split()] cnt=0 note='1' for ele in li: if ele=='0': print(0) break elif ele.count("0")+ele.count("1")==len(ele) and ele.count("1")==1: cnt+=ele.count("0") else: note=ele else: print(note+'0'*cnt) ```
89,725
Provide tags and a correct Python 3 solution for this coding contest problem. It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not enough time to assign tanks into teams and the whole game will collapse! There are exactly n distinct countries in the world and the i-th country added ai tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains at most one digit '1'. However, due to complaints from players, some number of tanks of one country was removed from the game, hence the number of tanks of this country may not remain beautiful. Your task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case. Input The first line of the input contains the number of countries n (1 ≤ n ≤ 100 000). The second line contains n non-negative integers ai without leading zeroes — the number of tanks of the i-th country. It is guaranteed that the second line contains at least n - 1 beautiful numbers and the total length of all these number's representations doesn't exceed 100 000. Output Print a single number without leading zeroes — the product of the number of tanks presented by each country. Examples Input 3 5 10 1 Output 50 Input 4 1 1 10 11 Output 110 Input 5 0 3 1 100 1 Output 0 Note In sample 1 numbers 10 and 1 are beautiful, number 5 is not not. In sample 2 number 11 is not beautiful (contains two '1's), all others are beautiful. In sample 3 number 3 is not beautiful, all others are beautiful. Tags: implementation, math Correct Solution: ``` n = int(input()) strings = input().split(" "); res = "1" adding = 0 for i in range(n) : NotGod = False if len(strings[i]) ==1 : if ( strings[i] != "1" ) : res = strings[i] else : if strings[i][0] != "1" : NotGod = True z = 1 while z < len(strings[i]) : if ( strings[i][z] != "0" ) : NotGod = True break z += 1 if NotGod : res = strings[i] else : adding += len(strings[i]) - 1 if res == "0" : print(0) exit() temp = res + "0"*adding print ( temp ) ```
89,726
Provide tags and a correct Python 3 solution for this coding contest problem. It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not enough time to assign tanks into teams and the whole game will collapse! There are exactly n distinct countries in the world and the i-th country added ai tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains at most one digit '1'. However, due to complaints from players, some number of tanks of one country was removed from the game, hence the number of tanks of this country may not remain beautiful. Your task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case. Input The first line of the input contains the number of countries n (1 ≤ n ≤ 100 000). The second line contains n non-negative integers ai without leading zeroes — the number of tanks of the i-th country. It is guaranteed that the second line contains at least n - 1 beautiful numbers and the total length of all these number's representations doesn't exceed 100 000. Output Print a single number without leading zeroes — the product of the number of tanks presented by each country. Examples Input 3 5 10 1 Output 50 Input 4 1 1 10 11 Output 110 Input 5 0 3 1 100 1 Output 0 Note In sample 1 numbers 10 and 1 are beautiful, number 5 is not not. In sample 2 number 11 is not beautiful (contains two '1's), all others are beautiful. In sample 3 number 3 is not beautiful, all others are beautiful. Tags: implementation, math Correct Solution: ``` #!/usr/bin/env python3 def check_number(a): is_ugly_number = False count = 0 first_digit = True for ch in a: if first_digit and ch != '1' or not first_digit and ch != '0': return True, a elif not first_digit: count += 1 first_digit = False return False, count n = int(input()) ugly_number = 1 count = 0 for a in input().split(): if a == '0': print( '0' ) exit() is_ugly_number, count_or_number = check_number(a) if is_ugly_number: ugly_number = count_or_number else: count += count_or_number print(ugly_number, end = '') print('0' * count) ```
89,727
Provide tags and a correct Python 3 solution for this coding contest problem. It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not enough time to assign tanks into teams and the whole game will collapse! There are exactly n distinct countries in the world and the i-th country added ai tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains at most one digit '1'. However, due to complaints from players, some number of tanks of one country was removed from the game, hence the number of tanks of this country may not remain beautiful. Your task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case. Input The first line of the input contains the number of countries n (1 ≤ n ≤ 100 000). The second line contains n non-negative integers ai without leading zeroes — the number of tanks of the i-th country. It is guaranteed that the second line contains at least n - 1 beautiful numbers and the total length of all these number's representations doesn't exceed 100 000. Output Print a single number without leading zeroes — the product of the number of tanks presented by each country. Examples Input 3 5 10 1 Output 50 Input 4 1 1 10 11 Output 110 Input 5 0 3 1 100 1 Output 0 Note In sample 1 numbers 10 and 1 are beautiful, number 5 is not not. In sample 2 number 11 is not beautiful (contains two '1's), all others are beautiful. In sample 3 number 3 is not beautiful, all others are beautiful. Tags: implementation, math Correct Solution: ``` n = int(input()) arr = input().split() zeros = 0 a = 0 for i in arr: x = i.count('0') y = i.count('1') if (i == '1'): continue elif (i == '0'): print(0) exit(0) elif (y == 1 and x == len(i) - 1 ): zeros += x else: a = i #print(a) if (a): ans = a + ('0' * zeros) print(ans) else: ans = '1' + ('0' * zeros) print(ans) ```
89,728
Provide tags and a correct Python 3 solution for this coding contest problem. It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not enough time to assign tanks into teams and the whole game will collapse! There are exactly n distinct countries in the world and the i-th country added ai tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains at most one digit '1'. However, due to complaints from players, some number of tanks of one country was removed from the game, hence the number of tanks of this country may not remain beautiful. Your task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case. Input The first line of the input contains the number of countries n (1 ≤ n ≤ 100 000). The second line contains n non-negative integers ai without leading zeroes — the number of tanks of the i-th country. It is guaranteed that the second line contains at least n - 1 beautiful numbers and the total length of all these number's representations doesn't exceed 100 000. Output Print a single number without leading zeroes — the product of the number of tanks presented by each country. Examples Input 3 5 10 1 Output 50 Input 4 1 1 10 11 Output 110 Input 5 0 3 1 100 1 Output 0 Note In sample 1 numbers 10 and 1 are beautiful, number 5 is not not. In sample 2 number 11 is not beautiful (contains two '1's), all others are beautiful. In sample 3 number 3 is not beautiful, all others are beautiful. Tags: implementation, math Correct Solution: ``` def main(): n = int(input()) zo = set('10') strings = input().split() zer_num = 0 start = '1' for s in strings: if s == '0': print (0) return elif (len(set(s) - zo) > 0) or ('1' in (s[1:])): start = s else: zer_num += len(s) - 1 print(start + '0' * zer_num) main() ```
89,729
Provide tags and a correct Python 3 solution for this coding contest problem. It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not enough time to assign tanks into teams and the whole game will collapse! There are exactly n distinct countries in the world and the i-th country added ai tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains at most one digit '1'. However, due to complaints from players, some number of tanks of one country was removed from the game, hence the number of tanks of this country may not remain beautiful. Your task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case. Input The first line of the input contains the number of countries n (1 ≤ n ≤ 100 000). The second line contains n non-negative integers ai without leading zeroes — the number of tanks of the i-th country. It is guaranteed that the second line contains at least n - 1 beautiful numbers and the total length of all these number's representations doesn't exceed 100 000. Output Print a single number without leading zeroes — the product of the number of tanks presented by each country. Examples Input 3 5 10 1 Output 50 Input 4 1 1 10 11 Output 110 Input 5 0 3 1 100 1 Output 0 Note In sample 1 numbers 10 and 1 are beautiful, number 5 is not not. In sample 2 number 11 is not beautiful (contains two '1's), all others are beautiful. In sample 3 number 3 is not beautiful, all others are beautiful. Tags: implementation, math Correct Solution: ``` import sys z=int(input()) v=0 nm='1' for i in input().split(): if i == '0': print(0) sys.exit(0) c1=i.count('1') c0=i.count('0') if len(i)!=c1+c0 or c1>1: nm=i else: v+=c0 print (nm+'0'*v) ```
89,730
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not enough time to assign tanks into teams and the whole game will collapse! There are exactly n distinct countries in the world and the i-th country added ai tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains at most one digit '1'. However, due to complaints from players, some number of tanks of one country was removed from the game, hence the number of tanks of this country may not remain beautiful. Your task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case. Input The first line of the input contains the number of countries n (1 ≤ n ≤ 100 000). The second line contains n non-negative integers ai without leading zeroes — the number of tanks of the i-th country. It is guaranteed that the second line contains at least n - 1 beautiful numbers and the total length of all these number's representations doesn't exceed 100 000. Output Print a single number without leading zeroes — the product of the number of tanks presented by each country. Examples Input 3 5 10 1 Output 50 Input 4 1 1 10 11 Output 110 Input 5 0 3 1 100 1 Output 0 Note In sample 1 numbers 10 and 1 are beautiful, number 5 is not not. In sample 2 number 11 is not beautiful (contains two '1's), all others are beautiful. In sample 3 number 3 is not beautiful, all others are beautiful. Submitted Solution: ``` n = int(input()) a = list(input().split()) cnt0 = 0 deb = '1' for x in a: if x=='0': print(0) exit() if x[0] == '1' and x.count('0') == len(x) - 1: cnt0 += len(x)-1 else: deb = x debb = ('0'*cnt0) debb = deb + debb print(debb) ``` Yes
89,731
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not enough time to assign tanks into teams and the whole game will collapse! There are exactly n distinct countries in the world and the i-th country added ai tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains at most one digit '1'. However, due to complaints from players, some number of tanks of one country was removed from the game, hence the number of tanks of this country may not remain beautiful. Your task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case. Input The first line of the input contains the number of countries n (1 ≤ n ≤ 100 000). The second line contains n non-negative integers ai without leading zeroes — the number of tanks of the i-th country. It is guaranteed that the second line contains at least n - 1 beautiful numbers and the total length of all these number's representations doesn't exceed 100 000. Output Print a single number without leading zeroes — the product of the number of tanks presented by each country. Examples Input 3 5 10 1 Output 50 Input 4 1 1 10 11 Output 110 Input 5 0 3 1 100 1 Output 0 Note In sample 1 numbers 10 and 1 are beautiful, number 5 is not not. In sample 2 number 11 is not beautiful (contains two '1's), all others are beautiful. In sample 3 number 3 is not beautiful, all others are beautiful. Submitted Solution: ``` l=int(input()) nums=input().split() non_beaut=-1 you=False for i in range(l) : if nums[i]=='0': print(0) you=True break else: s='1' if nums[i]!='0' and nums[i]!= s+(len(nums[i])-1)*'0': non_beaut=i if you==False: length=0 for j in range(l): if j!=non_beaut: length=length+len(nums[j])-1 #if non_beaut==-1: #result=nums[non_beaut]+'0'*(length-l) #else: #result=nums[non_beaut]+'0'*(length-l+1) if non_beaut == -1: result = '1' + length*'0' else: result=nums[non_beaut]+length*'0' print(result) ``` Yes
89,732
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not enough time to assign tanks into teams and the whole game will collapse! There are exactly n distinct countries in the world and the i-th country added ai tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains at most one digit '1'. However, due to complaints from players, some number of tanks of one country was removed from the game, hence the number of tanks of this country may not remain beautiful. Your task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case. Input The first line of the input contains the number of countries n (1 ≤ n ≤ 100 000). The second line contains n non-negative integers ai without leading zeroes — the number of tanks of the i-th country. It is guaranteed that the second line contains at least n - 1 beautiful numbers and the total length of all these number's representations doesn't exceed 100 000. Output Print a single number without leading zeroes — the product of the number of tanks presented by each country. Examples Input 3 5 10 1 Output 50 Input 4 1 1 10 11 Output 110 Input 5 0 3 1 100 1 Output 0 Note In sample 1 numbers 10 and 1 are beautiful, number 5 is not not. In sample 2 number 11 is not beautiful (contains two '1's), all others are beautiful. In sample 3 number 3 is not beautiful, all others are beautiful. Submitted Solution: ``` n = int(input()) a = list(map(str, input().split())) res1, res2 = '', '1' if '0' in a: print(0) quit() for i in range(n): if a[i]=='0':print(0); quit() x = a[i].count('0') if x == len(a[i]) - 1 and a[i][0] == '1': res1 += '0' * x else: res2 = a[i] print(res2 + res1) ``` Yes
89,733
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not enough time to assign tanks into teams and the whole game will collapse! There are exactly n distinct countries in the world and the i-th country added ai tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains at most one digit '1'. However, due to complaints from players, some number of tanks of one country was removed from the game, hence the number of tanks of this country may not remain beautiful. Your task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case. Input The first line of the input contains the number of countries n (1 ≤ n ≤ 100 000). The second line contains n non-negative integers ai without leading zeroes — the number of tanks of the i-th country. It is guaranteed that the second line contains at least n - 1 beautiful numbers and the total length of all these number's representations doesn't exceed 100 000. Output Print a single number without leading zeroes — the product of the number of tanks presented by each country. Examples Input 3 5 10 1 Output 50 Input 4 1 1 10 11 Output 110 Input 5 0 3 1 100 1 Output 0 Note In sample 1 numbers 10 and 1 are beautiful, number 5 is not not. In sample 2 number 11 is not beautiful (contains two '1's), all others are beautiful. In sample 3 number 3 is not beautiful, all others are beautiful. Submitted Solution: ``` n = int(input()) k = input().split() s = 0 x = '1' for i in range(n): if k[i] == '0': print('0') break elif k[i].count('0') + k[i].count('1') != len(k[i]) or k[i].count('1') >1: x = k[i] else: s+=k[i].count('0') else: print(x+'0'*s) ``` Yes
89,734
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not enough time to assign tanks into teams and the whole game will collapse! There are exactly n distinct countries in the world and the i-th country added ai tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains at most one digit '1'. However, due to complaints from players, some number of tanks of one country was removed from the game, hence the number of tanks of this country may not remain beautiful. Your task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case. Input The first line of the input contains the number of countries n (1 ≤ n ≤ 100 000). The second line contains n non-negative integers ai without leading zeroes — the number of tanks of the i-th country. It is guaranteed that the second line contains at least n - 1 beautiful numbers and the total length of all these number's representations doesn't exceed 100 000. Output Print a single number without leading zeroes — the product of the number of tanks presented by each country. Examples Input 3 5 10 1 Output 50 Input 4 1 1 10 11 Output 110 Input 5 0 3 1 100 1 Output 0 Note In sample 1 numbers 10 and 1 are beautiful, number 5 is not not. In sample 2 number 11 is not beautiful (contains two '1's), all others are beautiful. In sample 3 number 3 is not beautiful, all others are beautiful. Submitted Solution: ``` import sys n = int(input()) a = list(map(int, input().split())) z = 0 ans = "" for i in a: if i==0: print(0) sys.exit(0) elif i==1: continue elif i%10==0: z = z + 1 else: ans = str(i) print(ans+'0'*z) ``` No
89,735
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not enough time to assign tanks into teams and the whole game will collapse! There are exactly n distinct countries in the world and the i-th country added ai tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains at most one digit '1'. However, due to complaints from players, some number of tanks of one country was removed from the game, hence the number of tanks of this country may not remain beautiful. Your task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case. Input The first line of the input contains the number of countries n (1 ≤ n ≤ 100 000). The second line contains n non-negative integers ai without leading zeroes — the number of tanks of the i-th country. It is guaranteed that the second line contains at least n - 1 beautiful numbers and the total length of all these number's representations doesn't exceed 100 000. Output Print a single number without leading zeroes — the product of the number of tanks presented by each country. Examples Input 3 5 10 1 Output 50 Input 4 1 1 10 11 Output 110 Input 5 0 3 1 100 1 Output 0 Note In sample 1 numbers 10 and 1 are beautiful, number 5 is not not. In sample 2 number 11 is not beautiful (contains two '1's), all others are beautiful. In sample 3 number 3 is not beautiful, all others are beautiful. Submitted Solution: ``` def zero(a): su=0 ch=0 for i in range(len(a)): if (a[i]!='1')and(a[i]!='0'): return -1 if (len(a)==1)and(a[i]=='0'): return -2 if ((a[i]=='1')and(ch==0))or(a[i]=='0'): ch=1 else: return -1 if a[i]=='0': su+=1 return su n=int(input()) a=input().split() ind=0 t=0 p=1 for i in a: if zero(i)==-1: ind=int(i) elif zero(i)==-2: p=0 else: t+=zero(i) ans=10**t * ind * p print(ans) ``` No
89,736
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not enough time to assign tanks into teams and the whole game will collapse! There are exactly n distinct countries in the world and the i-th country added ai tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains at most one digit '1'. However, due to complaints from players, some number of tanks of one country was removed from the game, hence the number of tanks of this country may not remain beautiful. Your task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case. Input The first line of the input contains the number of countries n (1 ≤ n ≤ 100 000). The second line contains n non-negative integers ai without leading zeroes — the number of tanks of the i-th country. It is guaranteed that the second line contains at least n - 1 beautiful numbers and the total length of all these number's representations doesn't exceed 100 000. Output Print a single number without leading zeroes — the product of the number of tanks presented by each country. Examples Input 3 5 10 1 Output 50 Input 4 1 1 10 11 Output 110 Input 5 0 3 1 100 1 Output 0 Note In sample 1 numbers 10 and 1 are beautiful, number 5 is not not. In sample 2 number 11 is not beautiful (contains two '1's), all others are beautiful. In sample 3 number 3 is not beautiful, all others are beautiful. Submitted Solution: ``` n = int(input()) a = list(map(str, input().split())) res1, res2 = '', '' if '0' in a: print(0) quit() for i in range(n): x = a[i].count('0') if x == len(a[i]) - 1 and a[i][0] == '1': res1 += '0' * x else: res2 = a[i] print(res1 + res2) ``` No
89,737
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not enough time to assign tanks into teams and the whole game will collapse! There are exactly n distinct countries in the world and the i-th country added ai tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains at most one digit '1'. However, due to complaints from players, some number of tanks of one country was removed from the game, hence the number of tanks of this country may not remain beautiful. Your task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case. Input The first line of the input contains the number of countries n (1 ≤ n ≤ 100 000). The second line contains n non-negative integers ai without leading zeroes — the number of tanks of the i-th country. It is guaranteed that the second line contains at least n - 1 beautiful numbers and the total length of all these number's representations doesn't exceed 100 000. Output Print a single number without leading zeroes — the product of the number of tanks presented by each country. Examples Input 3 5 10 1 Output 50 Input 4 1 1 10 11 Output 110 Input 5 0 3 1 100 1 Output 0 Note In sample 1 numbers 10 and 1 are beautiful, number 5 is not not. In sample 2 number 11 is not beautiful (contains two '1's), all others are beautiful. In sample 3 number 3 is not beautiful, all others are beautiful. Submitted Solution: ``` n=int(input()) a=input().split() count1=0 result="" for i in a: if i=="0": print(0) exit() if i=="1": continue if int(i)%10!=0: result=i else: count1+=(len(i)-1) if result=="": print("1"+"0"*count1) else: print("%s"%result+"0"*count1) ``` No
89,738
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected graph that consists of n vertices and m edges. Initially, each edge is colored either red or blue. Each turn a player picks a single vertex and switches the color of all edges incident to it. That is, all red edges with an endpoint in this vertex change the color to blue, while all blue edges with an endpoint in this vertex change the color to red. Find the minimum possible number of moves required to make the colors of all edges equal. Input The first line of the input contains two integers n and m (1 ≤ n, m ≤ 100 000) — the number of vertices and edges, respectively. The following m lines provide the description of the edges, as the i-th of them contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the indices of the vertices connected by the i-th edge, and a character ci (<image>) providing the initial color of this edge. If ci equals 'R', then this edge is initially colored red. Otherwise, ci is equal to 'B' and this edge is initially colored blue. It's guaranteed that there are no self-loops and multiple edges. Output If there is no way to make the colors of all edges equal output - 1 in the only line of the output. Otherwise first output k — the minimum number of moves required to achieve the goal, then output k integers a1, a2, ..., ak, where ai is equal to the index of the vertex that should be used at the i-th move. If there are multiple optimal sequences of moves, output any of them. Examples Input 3 3 1 2 B 3 1 R 3 2 B Output 1 2 Input 6 5 1 3 R 2 3 R 3 4 B 4 5 R 4 6 R Output 2 3 4 Input 4 5 1 2 R 1 3 R 2 3 B 3 4 B 1 4 B Output -1 Tags: dfs and similar, graphs Correct Solution: ``` from collections import deque n, m = map(int, input().split()) adj = [[] for i in range(n)] for i in range(m): u, v, c = input().split() u, v = int(u)-1, int(v)-1 adj[u].append((v, c)) adj[v].append((u, c)) visited = S = T = None def bfs(i, k): q = deque([(i, 0)]) while q: u, p = q.pop() if visited[u] >= 0: if visited[u] == p: continue else: return False visited[u] = p if p: S.append(u) else: T.append(u) for v, c in adj[u]: nxt = p if c == k else p^1 q.appendleft((v, nxt)) return True def solve(k): global visited, S, T visited = [-1]*n res = [] for i in range(n): if visited[i] < 0: S, T = [], [] if not bfs(i, k): return [0]*(n+1) else: res.extend(S if len(S) < len(T) else T) return res res1 = solve("R") res2 = solve("B") if min(len(res1), len(res2)) > n: print (-1) else: print (min(len(res1), len(res2))) print (" ".join(map(lambda x: str(x+1), res1 if len(res1) < len(res2) else res2))) ```
89,739
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 graph that consists of n vertices and m edges. Initially, each edge is colored either red or blue. Each turn a player picks a single vertex and switches the color of all edges incident to it. That is, all red edges with an endpoint in this vertex change the color to blue, while all blue edges with an endpoint in this vertex change the color to red. Find the minimum possible number of moves required to make the colors of all edges equal. Input The first line of the input contains two integers n and m (1 ≤ n, m ≤ 100 000) — the number of vertices and edges, respectively. The following m lines provide the description of the edges, as the i-th of them contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the indices of the vertices connected by the i-th edge, and a character ci (<image>) providing the initial color of this edge. If ci equals 'R', then this edge is initially colored red. Otherwise, ci is equal to 'B' and this edge is initially colored blue. It's guaranteed that there are no self-loops and multiple edges. Output If there is no way to make the colors of all edges equal output - 1 in the only line of the output. Otherwise first output k — the minimum number of moves required to achieve the goal, then output k integers a1, a2, ..., ak, where ai is equal to the index of the vertex that should be used at the i-th move. If there are multiple optimal sequences of moves, output any of them. Examples Input 3 3 1 2 B 3 1 R 3 2 B Output 1 2 Input 6 5 1 3 R 2 3 R 3 4 B 4 5 R 4 6 R Output 2 3 4 Input 4 5 1 2 R 1 3 R 2 3 B 3 4 B 1 4 B Output -1 Submitted Solution: ``` node_count, vertex_count = map(int, input().split(' ')) nodes = [set() for i in range(node_count)] for i in range(vertex_count): f, t, c = input().split(' ') f, t, c = int(f) - 1, int(t) - 1, (1 if c == 'R' else 2) nodes[f].add((t, c)) nodes[t].add((f, c)) colors = [] # 0 = not visited, 1=not switching, 2=switching def dfs(graph, wanted_color): global colors colors = [0 for i in range(node_count)] can_be_done = True for index, node in enumerate(graph): if colors[index] == 0: try: can_be_done = can_be_done and dastan(graph, index, wanted_color) except: pass return can_be_done def dastan(graph, node_index, global_color, should_switch=None): if colors[node_index] > 0: # check if node is already in the state required (e.g. is switching) return (colors[node_index] == 2) == should_switch else: # check color if should_switch is None: colors[node_index] = 0 should_switch = False elif should_switch: colors[node_index] = 2 else: colors[node_index] = 1 for neighbour in nodes[node_index]: # graph, node_index, global (wanted color) , xor of if we are changing this node and if we should change next node if not dastan(graph, neighbour[0], global_color, ((global_color == neighbour[1]) == should_switch)): return False return True ans = [] if dfs(nodes, 1): ACount, BCount = colors.count(1), colors.count(2) ANodes, BNodes = [i for i, x in enumerate(colors) if x == 1], [i for i, x in enumerate(colors) if x == 2] ans.append((ACount, ANodes)) ans.append((BCount, BNodes)) a = 2 + 2 if dfs(nodes, 2): ACount, BCount = colors.count(1), colors.count(2) ANodes, BNodes = [i for i, x in enumerate(colors) if x == 1], [i for i, x in enumerate(colors) if x == 2] ans.append((ACount, ANodes)) ans.append((BCount, BNodes)) if len(ans) == 0: print(-1) else: shortest = sorted(ans, key=lambda x: x[0])[0] print(shortest[0]) print(' '.join(map(lambda x: str(x + 1), shortest[1]))) ``` No
89,740
Provide tags and a correct Python 3 solution for this coding contest problem. For each string s consisting of characters '0' and '1' one can define four integers a00, a01, a10 and a11, where axy is the number of subsequences of length 2 of the string s equal to the sequence {x, y}. In these problem you are given four integers a00, a01, a10, a11 and have to find any non-empty string s that matches them, or determine that there is no such string. One can prove that if at least one answer exists, there exists an answer of length no more than 1 000 000. Input The only line of the input contains four non-negative integers a00, a01, a10 and a11. Each of them doesn't exceed 109. Output If there exists a non-empty string that matches four integers from the input, print it in the only line of the output. Otherwise, print "Impossible". The length of your answer must not exceed 1 000 000. Examples Input 1 2 3 4 Output Impossible Input 1 2 2 1 Output 0110 Tags: constructive algorithms, greedy, implementation, math Correct Solution: ``` from collections import defaultdict import sys, os, math if __name__ == "__main__": #n, m = list(map(int, input().split())) a00, a01, a10, a11 = map(int, input().split()) x, y = int((1 + math.sqrt(1 + 8 * a11)) // 2), int((1 + math.sqrt(1 + 8 * a00)) // 2) if a11 + a10 + a01 + a00 == 0: print(1) sys.exit(0) elif a11 + a10 + a01 == 0 and y * (y - 1) // 2 == a00: print('0' * y) sys.exit(0) elif a00 + a10 + a01 == 0 and x * (x - 1) // 2 == a11: print('1' * x) sys.exit(0) if y * (y - 1) // 2 != a00 or x * (x - 1) // 2 != a11 or x * y != a10 + a01: print("Impossible") sys.exit(0) l = x - math.ceil((x * y - a10) / y) #no.of left one r = (x * y - a10) // y #no.of right one diff = a10 - l * y #print("x, y, l, r, diff") #print(x, y, l, r, diff) if diff == 0: print('1' * l + '0' * y + '1' * r) else: print('1' * l + '0' * (y - diff) + '1' + '0' * diff + '1' * r) ```
89,741
Provide tags and a correct Python 3 solution for this coding contest problem. For each string s consisting of characters '0' and '1' one can define four integers a00, a01, a10 and a11, where axy is the number of subsequences of length 2 of the string s equal to the sequence {x, y}. In these problem you are given four integers a00, a01, a10, a11 and have to find any non-empty string s that matches them, or determine that there is no such string. One can prove that if at least one answer exists, there exists an answer of length no more than 1 000 000. Input The only line of the input contains four non-negative integers a00, a01, a10 and a11. Each of them doesn't exceed 109. Output If there exists a non-empty string that matches four integers from the input, print it in the only line of the output. Otherwise, print "Impossible". The length of your answer must not exceed 1 000 000. Examples Input 1 2 3 4 Output Impossible Input 1 2 2 1 Output 0110 Tags: constructive algorithms, greedy, implementation, math Correct Solution: ``` a00, a01, a10, a11 = map(int, input().split()) numZeros = 0 numOnes = 0 ans = True for n0 in range(1, 2*a00 + 1): if n0 * (n0 - 1) == 2 * a00: numZeros = n0 break elif n0 * (n0 - 1) > 2 * a00: ans = False break; for n1 in range(1, 2*a11 + 1): if n1 * (n1 - 1) == 2 * a11: numOnes = n1 break elif n1 * (n1 - 1) > 2 * a11: ans = False break; res = [] def generateResult(x,a01, a10, n0, n1): while n0 > 0 or n1 > 0: if a01 >= n1 and n1 > 0: if n0 >= 1: res.append(0) a01 = a01 - n1 n0 = n0-1 else: return elif a10 >= n0 and n0 > 0: if n1 >= 1: res.append(1) a10 = a10 - n0 n1 = n1-1 else: return elif n0 > 0 and n1 > 0: return elif 0 < n0 == a01 + a10 + n0 + n1: for i in range(n0): res.append(0) n0 = 0 elif 0 < n1 == a01 + a10 + n0 + n1: for i in range(n1): res.append(1) n1 = 0 else: return if a01 > 0 or a10 > 0: numOnes = max(numOnes, 1) numZeros = max(numZeros, 1) if a00 == a01 == a10 == a11 == 0: print(1) elif ans: generateResult(res, a01, a10, numZeros, numOnes) if len(res) == numZeros + numOnes: print("".join(map(str, res))) else: print("Impossible") else: print("Impossible") ```
89,742
Provide tags and a correct Python 3 solution for this coding contest problem. For each string s consisting of characters '0' and '1' one can define four integers a00, a01, a10 and a11, where axy is the number of subsequences of length 2 of the string s equal to the sequence {x, y}. In these problem you are given four integers a00, a01, a10, a11 and have to find any non-empty string s that matches them, or determine that there is no such string. One can prove that if at least one answer exists, there exists an answer of length no more than 1 000 000. Input The only line of the input contains four non-negative integers a00, a01, a10 and a11. Each of them doesn't exceed 109. Output If there exists a non-empty string that matches four integers from the input, print it in the only line of the output. Otherwise, print "Impossible". The length of your answer must not exceed 1 000 000. Examples Input 1 2 3 4 Output Impossible Input 1 2 2 1 Output 0110 Tags: constructive algorithms, greedy, implementation, math Correct Solution: ``` #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jun 1 15:32:44 2020 @author: shailesh """ import math a00,a01,a10,a11 = [int(i) for i in input().split()] #l = sorted([a00,a01,a10,a11]) done = 0 if a00==0 and a11 == 0: if a01 + a10 > 1: print('Impossible') done = 1 if not done: N0 = (1+math.sqrt(1+8*a00))/2 N1 = (1+math.sqrt(1+8*a11))/2 if a00 == 0 and N1==int(N1): if a01 == 0 and a10 == 0: print('1'*int(N1)) else: if a01 + a10 == N1: print(a10*'1'+'0'+a01*'1') else: print('Impossible') elif a11 == 0 and N0 == int(N0): if a01 == 0 and a10 == 0: print('0'*int(N0)) else: if a01 + a10 == N0: print(a01*'0'+'1'+a10*'0') else: print('Impossible') elif N0*N1 != a01 + a10 or int(N1) != N1 or int(N0)!=N0: print('Impossible') else: N0 = int(N0) N1 = int(N1) divisor,remainder = divmod(a10,N0) s = '1'*divisor + (N0 - remainder)*'0' if remainder!=0: s+=('1' + remainder*'0') N1-=1 s+= (N1-divisor)*'1' print(s) ```
89,743
Provide tags and a correct Python 3 solution for this coding contest problem. For each string s consisting of characters '0' and '1' one can define four integers a00, a01, a10 and a11, where axy is the number of subsequences of length 2 of the string s equal to the sequence {x, y}. In these problem you are given four integers a00, a01, a10, a11 and have to find any non-empty string s that matches them, or determine that there is no such string. One can prove that if at least one answer exists, there exists an answer of length no more than 1 000 000. Input The only line of the input contains four non-negative integers a00, a01, a10 and a11. Each of them doesn't exceed 109. Output If there exists a non-empty string that matches four integers from the input, print it in the only line of the output. Otherwise, print "Impossible". The length of your answer must not exceed 1 000 000. Examples Input 1 2 3 4 Output Impossible Input 1 2 2 1 Output 0110 Tags: constructive algorithms, greedy, implementation, math Correct Solution: ``` #!/usr/bin/env python3.5 import sys import math def read_data(): return tuple(map(int, next(sys.stdin).split())) def reverse_count(k): d = math.sqrt(1 + 8*k) n = int((1+d)/2 + .5) if n*(n-1) == 2*k: return n return None def solve1(a, b, x01, x10): if x01 + x10 != a * b: return None characters = [] while a > 0 or b > 0: if a >= 1 and x01 >= b: a -= 1 x01 -= b characters.append('0') elif b >= 1 and x10 >= a: b -= 1 x10 -= a characters.append('1') else: return None return ''.join(characters) def solve(x00, x01, x10, x11): if x00 == 0: if x11 == 0: if x01 == x10 == 0: return "0" return solve1(1, 1, x01, x10) b = reverse_count(x11) if b is not None: return solve1(0, b, x01, x10) or solve1(1, b, x01, x10) return None if x11 == 0: a = reverse_count(x00) if a is not None: return solve1(a, 0, x01, x10) or solve1(a, 1, x01, x10) return None a = reverse_count(x00) b = reverse_count(x11) if a is not None and b is not None: return solve1(a, b, x01, x10) return None if __name__ == "__main__": x00, x01, x10, x11 = read_data() s = solve(x00, x01, x10, x11) if s is None: print("Impossible") else: print(s) ```
89,744
Provide tags and a correct Python 3 solution for this coding contest problem. For each string s consisting of characters '0' and '1' one can define four integers a00, a01, a10 and a11, where axy is the number of subsequences of length 2 of the string s equal to the sequence {x, y}. In these problem you are given four integers a00, a01, a10, a11 and have to find any non-empty string s that matches them, or determine that there is no such string. One can prove that if at least one answer exists, there exists an answer of length no more than 1 000 000. Input The only line of the input contains four non-negative integers a00, a01, a10 and a11. Each of them doesn't exceed 109. Output If there exists a non-empty string that matches four integers from the input, print it in the only line of the output. Otherwise, print "Impossible". The length of your answer must not exceed 1 000 000. Examples Input 1 2 3 4 Output Impossible Input 1 2 2 1 Output 0110 Tags: constructive algorithms, greedy, implementation, math Correct Solution: ``` from math import * from sys import * def calc(f): return int((1+sqrt(8*f+1))//2) a,b,c,d=(int(z) for z in input().split()) if a==d==0 and b==1 and c==0: print("01") exit(0) if a==d==0 and b==0 and c==1: print("10") exit(0) if a==d==0: if b+c!=0: print("Impossible") exit(0) print(0) exit(0) if a==0: if(sqrt(8*d+1)!=int(sqrt(8*d+1))): print("Impossible") exit(0) if b==c==0: ans="1"*calc(d) print(ans) else: if b+c!=calc(d): print("Impossible") exit(0) ans=c*"1"+"0"+b*"1" print(ans) exit(0) if d==0: if(sqrt(8*a+1)!=int(sqrt(8*a+1))): print("Impossible") exit(0) if b==c==0: ans="0"*calc(a) print(ans) else: if b+c!=calc(a): print("Impossible") exit(0) ans=b*"0"+"1"+c*"0" print(ans) exit(0) if(sqrt(8*d+1)!=int(sqrt(8*d+1))): print("Impossible") exit(0) if(sqrt(8*a+1)!=int(sqrt(8*a+1))): print("Impossible") exit(0) x=calc(a) y=calc(d) if x*y!=b+c: print("Impossible") exit(0) ans="" res=0 while res+x<=c: ans+="1" y-=1 res+=x while res+x!=c: ans+="0" x-=1 if res!=c: ans+="1" y-=1 while x: x-=1 ans+="0" while y: y-=1 ans+="1" print(ans) ```
89,745
Provide tags and a correct Python 3 solution for this coding contest problem. For each string s consisting of characters '0' and '1' one can define four integers a00, a01, a10 and a11, where axy is the number of subsequences of length 2 of the string s equal to the sequence {x, y}. In these problem you are given four integers a00, a01, a10, a11 and have to find any non-empty string s that matches them, or determine that there is no such string. One can prove that if at least one answer exists, there exists an answer of length no more than 1 000 000. Input The only line of the input contains four non-negative integers a00, a01, a10 and a11. Each of them doesn't exceed 109. Output If there exists a non-empty string that matches four integers from the input, print it in the only line of the output. Otherwise, print "Impossible". The length of your answer must not exceed 1 000 000. Examples Input 1 2 3 4 Output Impossible Input 1 2 2 1 Output 0110 Tags: constructive algorithms, greedy, implementation, math Correct Solution: ``` import sys import math def check(): n = 1000000 for i in range(n): if is_square(1+8*i): print(i) def is_square(integer): root = math.sqrt(integer) if int(root + 0.5) ** 2 == integer: return True else: return False def main(): a,b,c,d = map(int,sys.stdin.readline().split()) if not is_square(1+8*a) or not is_square(1+8*d): print("Impossible") return z = (1+math.sqrt(1+8*a)) o = (1+math.sqrt(1+8*d)) if z%2==1 or o%2==1: print("Impossible") return z = int(z/2) o= int(o/2) if a==0 and b==0 and c==0: z=0 if d==0 and b==0 and c==0: o=0 if z*o != b+c: print("Impossible") return # if z==0: # x = ['1']*o # print(''.join(x)) # return # if o==0: # x = ['0']*z # print(''.join(x)) # return if z==0 and o ==0: print(0) return s = z*o ans = [] while True: if s-z >=b: ans.append('1') s-=z o-=1 else: ans.append('0') z-=1 if z==0 and o==0: break print(''.join(ans)) #check() main() ```
89,746
Provide tags and a correct Python 3 solution for this coding contest problem. For each string s consisting of characters '0' and '1' one can define four integers a00, a01, a10 and a11, where axy is the number of subsequences of length 2 of the string s equal to the sequence {x, y}. In these problem you are given four integers a00, a01, a10, a11 and have to find any non-empty string s that matches them, or determine that there is no such string. One can prove that if at least one answer exists, there exists an answer of length no more than 1 000 000. Input The only line of the input contains four non-negative integers a00, a01, a10 and a11. Each of them doesn't exceed 109. Output If there exists a non-empty string that matches four integers from the input, print it in the only line of the output. Otherwise, print "Impossible". The length of your answer must not exceed 1 000 000. Examples Input 1 2 3 4 Output Impossible Input 1 2 2 1 Output 0110 Tags: constructive algorithms, greedy, implementation, math Correct Solution: ``` def impossible(): print("Impossible") exit() def good(ones, zeros): return ones * zeros == a01 + a10 a00, a01, a10, a11 = map(int, input().split()) if int(round((a00 * 8 + 1) ** 0.5)) ** 2 != a00 * 8 + 1: impossible() if int(round((a11 * 8 + 1) ** 0.5)) ** 2 != a11 * 8 + 1: impossible() zeros = 1 + int(round((a00 * 8 + 1) ** 0.5)) zeros //= 2 ones = 1 + int(round((a11 * 8 + 1) ** 0.5)) ones //= 2 if ones == 1: if not good(ones, zeros) and not good(ones - 1, zeros): impossible() elif good(ones - 1, zeros): ones -= 1 if zeros == 1: if not good(ones, zeros) and not good(ones, zeros - 1): impossible() elif good(ones, zeros - 1) and not good(ones, zeros): zeros -= 1 if zeros == 0 and ones == 0: impossible() if zeros * ones != a01 + a10: impossible() if zeros != 0: start = a10 // zeros end = a01 // zeros if a01 % zeros == 0 and a10 % zeros == 0: print('1' * start + '0' * zeros + '1' * end) else: a01 %= zeros a10 %= zeros print('1' * start + a01 * '0' + '1' + a10 * '0' + '1' * end) else: print('1' * ones) ```
89,747
Provide tags and a correct Python 3 solution for this coding contest problem. For each string s consisting of characters '0' and '1' one can define four integers a00, a01, a10 and a11, where axy is the number of subsequences of length 2 of the string s equal to the sequence {x, y}. In these problem you are given four integers a00, a01, a10, a11 and have to find any non-empty string s that matches them, or determine that there is no such string. One can prove that if at least one answer exists, there exists an answer of length no more than 1 000 000. Input The only line of the input contains four non-negative integers a00, a01, a10 and a11. Each of them doesn't exceed 109. Output If there exists a non-empty string that matches four integers from the input, print it in the only line of the output. Otherwise, print "Impossible". The length of your answer must not exceed 1 000 000. Examples Input 1 2 3 4 Output Impossible Input 1 2 2 1 Output 0110 Tags: constructive algorithms, greedy, implementation, math Correct Solution: ``` def F(s): x00 = x01 = x10 = x11 = 0 for i in range(len(s)): for j in range(i + 1, len(s)): cur = s[i] + s[j] if cur == '00': x00 += 1 if cur == '01': x01 += 1 if cur == '10': x10 += 1 if cur == '11': x11 += 1 return x00, x01, x10, x11 def F2(s): x00 = x01 = x10 = x11 = 0 c0 = s.count(0) c1 = s.count(1) x00 = c0 * (c0 - 1) // 2 x11 = c1 * (c1 - 1) // 2 cur0 = 0 cur1 = 0 for i in range(len(s)): if s[i] == 0: x10 += cur1 cur0 += 1 else: x01 += cur0 cur1 += 1 return x00, x01, x10, x11 def fail(): print('Impossible') exit() a00, a01, a10, a11 = map(int, input().split()) f = lambda x: x * (x - 1) // 2 L, R = 0, 10 ** 6 while R - L > 1: M = (L + R) // 2 if f(M) >= a00: R = M else: L = M c0 = R L, R = 0, 10 ** 6 while R - L > 1: M = (L + R) // 2 if f(M) >= a11: R = M else: L = M c1 = R if a00 == 0 and a11 == 0: if (a01, a10) == (1, 0): s = [0, 1] elif (a01, a10) == (0, 1): s = [1, 0] elif (a01, a10) == (0, 0): s = [1] else: fail() print(''.join(map(str, s))) exit() elif a00 == 0: if (a01, a10) == (0, 0): c0 = 0 elif a11 == 0: if (a01, a10) == (0, 0): c1 = 0 s = [0] * c0 + [1] * c1 b01 = c0 * c1 if b01 != a01 + a10: fail() for i in range(c1): if b01 - c0 < a01: j = i + c0 break b01 -= c0 s[i], s[i + c0] = s[i + c0], s[i] while b01 > a01: s[j], s[j - 1] = s[j - 1], s[j] b01 -= 1 j -= 1 if F2(s) != (a00, a01, a10, a11): fail() print(''.join(map(str, s))) ```
89,748
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For each string s consisting of characters '0' and '1' one can define four integers a00, a01, a10 and a11, where axy is the number of subsequences of length 2 of the string s equal to the sequence {x, y}. In these problem you are given four integers a00, a01, a10, a11 and have to find any non-empty string s that matches them, or determine that there is no such string. One can prove that if at least one answer exists, there exists an answer of length no more than 1 000 000. Input The only line of the input contains four non-negative integers a00, a01, a10 and a11. Each of them doesn't exceed 109. Output If there exists a non-empty string that matches four integers from the input, print it in the only line of the output. Otherwise, print "Impossible". The length of your answer must not exceed 1 000 000. Examples Input 1 2 3 4 Output Impossible Input 1 2 2 1 Output 0110 Submitted Solution: ``` root = lambda k : int((1 + (1 + 8*k) ** 0.5)/2) def check(k): n = root(k) return n*(n-1)/2 == k def solve(a00, a01, a10, a11): s = a00 + a01 + a10 + a11 if not check(a00) or not check(a11) or not check(s): return None x, y, z = root(a00), root(a11), root(s) if a00 == 0 or a11 == 0: if s == 0: return '0' elif a10 == 0 and a01 == 0: return '0'*z if a00 > 0 else '1'*z elif a10 + a01 == z -1: return '1'*a10 + '0' + '1'*a01 if a11 > 0 else '0'*a01 + '1' + '0'*a10 else: return None if x + y != z: return None if x == 0: if a00 == 0 and a01 == 0 and a10 == 0: return '1'*z else: return None t, k = a10//x, a10%x if z-t-x > 0: return '1'*t + '0'*(x-k) + '1' + '0'*k + '1'*(z-t-x-1) else: return '1'*t + x*'0' a00, a01, a10, a11 = [int(x) for x in input().split()] ans = solve(a00, a01, a10, a11) if ans is None: print('Impossible') else: print(ans) ``` Yes
89,749
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For each string s consisting of characters '0' and '1' one can define four integers a00, a01, a10 and a11, where axy is the number of subsequences of length 2 of the string s equal to the sequence {x, y}. In these problem you are given four integers a00, a01, a10, a11 and have to find any non-empty string s that matches them, or determine that there is no such string. One can prove that if at least one answer exists, there exists an answer of length no more than 1 000 000. Input The only line of the input contains four non-negative integers a00, a01, a10 and a11. Each of them doesn't exceed 109. Output If there exists a non-empty string that matches four integers from the input, print it in the only line of the output. Otherwise, print "Impossible". The length of your answer must not exceed 1 000 000. Examples Input 1 2 3 4 Output Impossible Input 1 2 2 1 Output 0110 Submitted Solution: ``` a00, a01, a10, a11 = map(int, input().split()) numZeros = 0 numOnes = 0 ans = True for n0 in range(1, 2*a00 + 1): if n0 * (n0 - 1) == 2 * a00: numZeros = n0 break elif n0 * (n0 - 1) > 2 * a00: ans = False break; for n1 in range(1, 2*a11 + 1): if n1 * (n1 - 1) == 2 * a11: numOnes = n1 break elif n1 * (n1 - 1) > 2 * a11: ans = False break; res = [] def generateResult(x,a01, a10, n0, n1): while n0 > 0 or n1 > 0: if a01 >= n1 and n1 > 0: if n0 >= 1: res.append(0) a01 = a01 - n1 n0 = n0-1 else: return elif a10 >= n0 and n0 > 0: if n1 >= 1: res.append(1) a10 = a10 - n0 n1 = n1-1 else: return elif n0 > 0 and n1 > 0: return elif 0 < n0 == a01 + a10 + n0 + n1: for i in range(n0): res.append(0) n0 = 0 elif 0 < n1 == a01 + a10 + n0 + n1: for i in range(n1): res.append(1) n1 = 0 else: return if a01 > 0 or a10 > 0: numOnes = max(numOnes, 1) numZeros = max(numZeros, 1) if a00 == a01 == a10 == a11 == 0: print(1) elif a11 == 0 and a00 == 0 and a10 == 1 and a01 == 0: print("10") elif a11 == 0 and a00 == 0 and a01 == 1 and a10 == 0: print("01") elif ans: generateResult(res, a01, a10, numZeros, numOnes) if len(res) == numZeros + numOnes: print("".join(map(str, res))) else: print("Impossible") else: print("Impossible") ``` Yes
89,750
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For each string s consisting of characters '0' and '1' one can define four integers a00, a01, a10 and a11, where axy is the number of subsequences of length 2 of the string s equal to the sequence {x, y}. In these problem you are given four integers a00, a01, a10, a11 and have to find any non-empty string s that matches them, or determine that there is no such string. One can prove that if at least one answer exists, there exists an answer of length no more than 1 000 000. Input The only line of the input contains four non-negative integers a00, a01, a10 and a11. Each of them doesn't exceed 109. Output If there exists a non-empty string that matches four integers from the input, print it in the only line of the output. Otherwise, print "Impossible". The length of your answer must not exceed 1 000 000. Examples Input 1 2 3 4 Output Impossible Input 1 2 2 1 Output 0110 Submitted Solution: ``` #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jun 1 15:32:44 2020 @author: shailesh """ import math a00,a01,a10,a11 = [int(i) for i in input().split()] #l = sorted([a00,a01,a10,a11]) done = 0 if a00==0 and a11 == 0: if a01 + a10 > 1: print('Impossible') done = 1 if not done: N0 = (1+math.sqrt(1+8*a00))/2 N1 = (1+math.sqrt(1+8*a11))/2 if N0*N1 != a01 + a10 or int(N1) != N1 or int(N0)!=N0: print('Impossible') elif a00 == 0 and N1==int(N1): if a01 == 0 and a10 == 0: print('1'*int(N1)) else: print(a10*'1'+'0'+a01*'1') elif a11 == 0 and N0 == int(N0): if a01 == 0 and a10 == 0: print('0'*int(N0)) else: print(a01*'0'+'1'+a10*'0') else: N0 = int(N0) N1 = int(N1) divisor,remainder = divmod(a10,N0) s = '1'*divisor + (N0 - remainder)*'0' if remainder!=0: s+=('1' + remainder*'0') N1-=1 s+= (N1-divisor)*'1' print(s) ``` No
89,751
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For each string s consisting of characters '0' and '1' one can define four integers a00, a01, a10 and a11, where axy is the number of subsequences of length 2 of the string s equal to the sequence {x, y}. In these problem you are given four integers a00, a01, a10, a11 and have to find any non-empty string s that matches them, or determine that there is no such string. One can prove that if at least one answer exists, there exists an answer of length no more than 1 000 000. Input The only line of the input contains four non-negative integers a00, a01, a10 and a11. Each of them doesn't exceed 109. Output If there exists a non-empty string that matches four integers from the input, print it in the only line of the output. Otherwise, print "Impossible". The length of your answer must not exceed 1 000 000. Examples Input 1 2 3 4 Output Impossible Input 1 2 2 1 Output 0110 Submitted Solution: ``` from collections import defaultdict import sys, os, math if __name__ == "__main__": #n, m = list(map(int, input().split())) a00, a01, a10, a11 = map(int, input().split()) x, y = int((1 + math.sqrt(1 + 8 * a11)) // 2), int((1 + math.sqrt(1 + 8 * a00)) // 2) if a11 + a10 + a01 + a00 == 0: print(1) sys.exit(0) elif a11 + a10 + a01 == 0 and y * (y - 1) // 2 == a00: print('0' * y) sys.exit(0) elif a00 + a10 + a01 == 0 and x * (x - 1) // 2 == a11: print('1' * x) sys.exit(0) if y * (y - 1) // 2 != a00 or x * (x - 1) // 2 != a11 or x * y != a10 + a01: print("Impossible") sys.exit(0) l = x - math.ceil((x * y - a10) / y) #no.of left one r = (x * y - a10) // y #no.of right one diff = a10 - l * y #print("x, y, l, r, diff") #print(x, y, l, r, diff) if diff == 0: print('1' * l + '0' * y + '1' * r) else: print('1' * l + '0' * diff + '1' + '0' * (y - diff) + '1' * r) ``` No
89,752
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For each string s consisting of characters '0' and '1' one can define four integers a00, a01, a10 and a11, where axy is the number of subsequences of length 2 of the string s equal to the sequence {x, y}. In these problem you are given four integers a00, a01, a10, a11 and have to find any non-empty string s that matches them, or determine that there is no such string. One can prove that if at least one answer exists, there exists an answer of length no more than 1 000 000. Input The only line of the input contains four non-negative integers a00, a01, a10 and a11. Each of them doesn't exceed 109. Output If there exists a non-empty string that matches four integers from the input, print it in the only line of the output. Otherwise, print "Impossible". The length of your answer must not exceed 1 000 000. Examples Input 1 2 3 4 Output Impossible Input 1 2 2 1 Output 0110 Submitted Solution: ``` a00, a01, a10, a11 = map(int, input().split()) numZeros = 0 numOnes = 0 ans = True for n0 in range(1, 2*a00 + 1): if n0 * (n0 - 1) == 2 * a00: numZeros = n0 break elif n0 * (n0 - 1) > 2 * a00: ans = False break; for n1 in range(1, 2*a11 + 1): if n1 * (n1 - 1) == 2 * a11: numOnes = n1 break elif n1 * (n1 - 1) > 2 * a11: ans = False break; res = [] def generateResult(x,a01, a10, n0, n1): while n0 > 0 or n1 > 0: if a01 >= n1 and n1 > 0: if n0 >= 1: res.append(0) a01 = a01 - n1 n0 = n0-1 else: return elif a10 >= n0 and n0 > 0: if n1 >= 1: res.append(1) a10 = a10 - n0 n1 = n1-1 else: return elif n0 > 0 and n1 > 0: return elif 0 < n0 == a01 + a10 + n0 + n1: for i in range(n0): res.append(0) n0 = 0 elif 0 < n1 == a01 + a10 + n0 + n1: for i in range(n1): res.append(1) n1 = 0 else: return if a11 == 0 and a01 > 0: numOnes = 1 if a00 == 0 and a10 > 0: numZeros = 1 if a00 == a01 == a10 == a11 == 0: print(1) elif a11 == 0 and a00 == 0 and a10 == 1 and a01 == 0: print("10") elif a11 == 0 and a00 == 0 and a01 == 1 and a10 == 0: print("01") elif ans: generateResult(res, a01, a10, numZeros, numOnes) if len(res) == numZeros + numOnes: print("".join(map(str, res))) else: print("Impossible") else: print("Impossible") ``` No
89,753
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For each string s consisting of characters '0' and '1' one can define four integers a00, a01, a10 and a11, where axy is the number of subsequences of length 2 of the string s equal to the sequence {x, y}. In these problem you are given four integers a00, a01, a10, a11 and have to find any non-empty string s that matches them, or determine that there is no such string. One can prove that if at least one answer exists, there exists an answer of length no more than 1 000 000. Input The only line of the input contains four non-negative integers a00, a01, a10 and a11. Each of them doesn't exceed 109. Output If there exists a non-empty string that matches four integers from the input, print it in the only line of the output. Otherwise, print "Impossible". The length of your answer must not exceed 1 000 000. Examples Input 1 2 3 4 Output Impossible Input 1 2 2 1 Output 0110 Submitted Solution: ``` from collections import defaultdict import sys, os, math if __name__ == "__main__": #n, m = list(map(int, input().split())) a11, a10, a01, a00 = map(int, input().split()) x, y = int((1 + math.sqrt(1 + 8 * a11)) // 2), int((1 + math.sqrt(1 + 8 * a00)) // 2) if a11 + a10 + a01 + a00 == 0: print(1) sys.exit(0) elif a11 + a10 + a01 == 0 and y * (y - 1) // 2 == a00: print('0' * y) sys.exit(0) elif a00 + a10 + a01 == 0 and x * (x - 1) // 2 == a11: print('1' * x) sys.exit(0) if y * (y - 1) // 2 != a00 or x * (x - 1) // 2 != a11 or x * y != a10 + a01: print("Impossible") sys.exit(0) l = x - math.ceil((x * y - a10) / y) #no.of left one r = (x * y - a10) // y #no.of right one diff = a10 - l * y print("x, y, l, r, diff") print(x, y, l, r, diff) if diff == 0: print('1' * l + '0' * y + '1' * r) else: print('1' * l + '0' * diff + '1' + '0' * (y - diff) + '1' * r) ``` No
89,754
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is a regular customer at the restaurant "Ber Patio". He likes having lunches there. "Ber Patio" has special discount program for regular customers. A customer can collect bonuses and partially cover expenses in the restaurant. Let's assume a customer currently has b bonuses and she has to pay r burles for a lunch. In this case the customer can use bonuses (1 bonus = 1 burle) to reduce the payment. She can cover at most half of the payment using bonuses. However, 1 bonus will be added to the customer's bonus balance per each 10 burles she paid. Formally: 1. a customer can choose any number x of bonuses to use (<image>)), 2. the customer's bonus balance is reduced by x, 3. the customer pays r - x burles, 4. the customer's bonus balance is increased by ⌊(r - x) / 10⌋ (i.e. integer division rounded down is used). Initially, there are b bonuses on Polycarp's account. Polycarp is going to have a lunch in "Ber Patio" for the next n days. He estimated the values a1, a2, ..., an, where ai is the number of burles in a receipt for the i-th day. The sum over all receipts doesn't exceed 105 burles. Write a program to find the minimum number of burles Polycarp has to spend and an optimal strategy to use bonuses. Input The first line contains two integer numbers n and b (1 ≤ n ≤ 5000, 0 ≤ b ≤ 105) — number of days and initial number of bonuses Polycarp has. The second line contains the integer sequence a1, a2, ..., an (1 ≤ ai ≤ 1000), where ai is the amount of burles in the i-th day's receipt. It is guaranteed that the sum of all receipts does not exceed 105 burles. Output On the first line, print the expected minimal number of burles to pay for all n receipts. On the second line, print the sequence of integer numbers b1, b2, ..., bn, where bi is the number of bonuses to use on the i-th day. If there are multiple solutions, print any of them. Examples Input 3 21 12 75 52 Output 110 2 5 22 Input 3 39 58 64 33 Output 107 28 4 16 Submitted Solution: ``` def div2(item): if item < 10: return item//2 else: bod = (item - item%10)//2 if bod%10 == 0: return bod + item%10 - 10 else: return bod + item%10//2 def com(b, v): if b<v: return b else: return v Finput = input().split() b = int(Finput[1]) days = list(map(int, input().split())) total = sum(days) b_used = '' cost = 0 for item in days: total -= item if b >= total//2: used = com(b, div2(item)) else: used = com(b, item%10) b_used += str(used) + " " b = b - used + (item - used)//10 cost += item - used print(cost) print(b_used.strip()) ``` No
89,755
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is a regular customer at the restaurant "Ber Patio". He likes having lunches there. "Ber Patio" has special discount program for regular customers. A customer can collect bonuses and partially cover expenses in the restaurant. Let's assume a customer currently has b bonuses and she has to pay r burles for a lunch. In this case the customer can use bonuses (1 bonus = 1 burle) to reduce the payment. She can cover at most half of the payment using bonuses. However, 1 bonus will be added to the customer's bonus balance per each 10 burles she paid. Formally: 1. a customer can choose any number x of bonuses to use (<image>)), 2. the customer's bonus balance is reduced by x, 3. the customer pays r - x burles, 4. the customer's bonus balance is increased by ⌊(r - x) / 10⌋ (i.e. integer division rounded down is used). Initially, there are b bonuses on Polycarp's account. Polycarp is going to have a lunch in "Ber Patio" for the next n days. He estimated the values a1, a2, ..., an, where ai is the number of burles in a receipt for the i-th day. The sum over all receipts doesn't exceed 105 burles. Write a program to find the minimum number of burles Polycarp has to spend and an optimal strategy to use bonuses. Input The first line contains two integer numbers n and b (1 ≤ n ≤ 5000, 0 ≤ b ≤ 105) — number of days and initial number of bonuses Polycarp has. The second line contains the integer sequence a1, a2, ..., an (1 ≤ ai ≤ 1000), where ai is the amount of burles in the i-th day's receipt. It is guaranteed that the sum of all receipts does not exceed 105 burles. Output On the first line, print the expected minimal number of burles to pay for all n receipts. On the second line, print the sequence of integer numbers b1, b2, ..., bn, where bi is the number of bonuses to use on the i-th day. If there are multiple solutions, print any of them. Examples Input 3 21 12 75 52 Output 110 2 5 22 Input 3 39 58 64 33 Output 107 28 4 16 Submitted Solution: ``` def div2(item): bod = (item - item%10)//2 if bod%10 == 0: return bod + item%10 - 10 else: return bod + item%10//2 def com(b, v): if b<v: return b else: return v Finput = input().split() b = int(Finput[1]) days = list(map(int, input().split())) total = sum(days) b_used = '' cost = 0 for item in days: total -= item if b >= total//2: used = com(b, div2(item)) else: used = com(b, item%10) b_used += str(used) + " " b = b - used + (item - used)//10 cost += item - used print(cost) print(b_used.strip()) ``` No
89,756
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is a regular customer at the restaurant "Ber Patio". He likes having lunches there. "Ber Patio" has special discount program for regular customers. A customer can collect bonuses and partially cover expenses in the restaurant. Let's assume a customer currently has b bonuses and she has to pay r burles for a lunch. In this case the customer can use bonuses (1 bonus = 1 burle) to reduce the payment. She can cover at most half of the payment using bonuses. However, 1 bonus will be added to the customer's bonus balance per each 10 burles she paid. Formally: 1. a customer can choose any number x of bonuses to use (<image>)), 2. the customer's bonus balance is reduced by x, 3. the customer pays r - x burles, 4. the customer's bonus balance is increased by ⌊(r - x) / 10⌋ (i.e. integer division rounded down is used). Initially, there are b bonuses on Polycarp's account. Polycarp is going to have a lunch in "Ber Patio" for the next n days. He estimated the values a1, a2, ..., an, where ai is the number of burles in a receipt for the i-th day. The sum over all receipts doesn't exceed 105 burles. Write a program to find the minimum number of burles Polycarp has to spend and an optimal strategy to use bonuses. Input The first line contains two integer numbers n and b (1 ≤ n ≤ 5000, 0 ≤ b ≤ 105) — number of days and initial number of bonuses Polycarp has. The second line contains the integer sequence a1, a2, ..., an (1 ≤ ai ≤ 1000), where ai is the amount of burles in the i-th day's receipt. It is guaranteed that the sum of all receipts does not exceed 105 burles. Output On the first line, print the expected minimal number of burles to pay for all n receipts. On the second line, print the sequence of integer numbers b1, b2, ..., bn, where bi is the number of bonuses to use on the i-th day. If there are multiple solutions, print any of them. Examples Input 3 21 12 75 52 Output 110 2 5 22 Input 3 39 58 64 33 Output 107 28 4 16 Submitted Solution: ``` def div2(item): if item < 10: return item//2 else: LD1 = item%10 item1 = item//2 LD2 = item1%10 if LD1 == LD2: return item1 elif LD1 > LD2: return item1-(10-(LD1-LD2)) else: return item1 - (LD2-LD1) def com(b, v): if b<v: return b else: return v Finput = input().split() b = int(Finput[1]) days = list(map(int, input().split())) total = sum(days) b_used = '' cost = 0 for item in days: total -= item if item == days[len(days)-1]: used = com(b,item//2) elif b >= total//2: used = com(b, div2(item)) else: used = com(b, item%10) b_used += str(used) + " " b = b - used + (item - used)//10 cost += item - used print(cost) print(b_used.strip()) ``` No
89,757
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is a regular customer at the restaurant "Ber Patio". He likes having lunches there. "Ber Patio" has special discount program for regular customers. A customer can collect bonuses and partially cover expenses in the restaurant. Let's assume a customer currently has b bonuses and she has to pay r burles for a lunch. In this case the customer can use bonuses (1 bonus = 1 burle) to reduce the payment. She can cover at most half of the payment using bonuses. However, 1 bonus will be added to the customer's bonus balance per each 10 burles she paid. Formally: 1. a customer can choose any number x of bonuses to use (<image>)), 2. the customer's bonus balance is reduced by x, 3. the customer pays r - x burles, 4. the customer's bonus balance is increased by ⌊(r - x) / 10⌋ (i.e. integer division rounded down is used). Initially, there are b bonuses on Polycarp's account. Polycarp is going to have a lunch in "Ber Patio" for the next n days. He estimated the values a1, a2, ..., an, where ai is the number of burles in a receipt for the i-th day. The sum over all receipts doesn't exceed 105 burles. Write a program to find the minimum number of burles Polycarp has to spend and an optimal strategy to use bonuses. Input The first line contains two integer numbers n and b (1 ≤ n ≤ 5000, 0 ≤ b ≤ 105) — number of days and initial number of bonuses Polycarp has. The second line contains the integer sequence a1, a2, ..., an (1 ≤ ai ≤ 1000), where ai is the amount of burles in the i-th day's receipt. It is guaranteed that the sum of all receipts does not exceed 105 burles. Output On the first line, print the expected minimal number of burles to pay for all n receipts. On the second line, print the sequence of integer numbers b1, b2, ..., bn, where bi is the number of bonuses to use on the i-th day. If there are multiple solutions, print any of them. Examples Input 3 21 12 75 52 Output 110 2 5 22 Input 3 39 58 64 33 Output 107 28 4 16 Submitted Solution: ``` def div2(item): if item < 10: return item else: bod = (item - item%10)//2 if bod%10 == 0: return bod + item%10 - 10 else: return bod + item%10//2 def com(b, v): if b<v: return b else: return v Finput = input().split() b = int(Finput[1]) days = list(map(int, input().split())) total = sum(days) b_used = '' cost = 0 for item in days: total -= item if b >= total//2: used = com(b, div2(item)) else: used = com(b, item%10) b_used += str(used) + " " b = b - used + (item - used)//10 cost += item - used print(cost) print(b_used.strip()) ``` No
89,758
Provide tags and a correct Python 3 solution for this coding contest problem. One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array A. Lesha is tired now so he asked you to split the array. Help Lesha! Input The first line contains single integer n (1 ≤ n ≤ 100) — the number of elements in the array A. The next line contains n integers a1, a2, ..., an ( - 103 ≤ ai ≤ 103) — the elements of the array A. Output If it is not possible to split the array A and satisfy all the constraints, print single line containing "NO" (without quotes). Otherwise in the first line print "YES" (without quotes). In the next line print single integer k — the number of new arrays. In each of the next k lines print two integers li and ri which denote the subarray A[li... ri] of the initial array A being the i-th new array. Integers li, ri should satisfy the following conditions: * l1 = 1 * rk = n * ri + 1 = li + 1 for each 1 ≤ i < k. If there are multiple answers, print any of them. Examples Input 3 1 2 -3 Output YES 2 1 2 3 3 Input 8 9 -12 3 4 -4 -10 7 3 Output YES 2 1 2 3 8 Input 1 0 Output NO Input 4 1 2 3 -5 Output YES 4 1 1 2 2 3 3 4 4 Tags: constructive algorithms, greedy, implementation Correct Solution: ``` import io, os import sys from atexit import register input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline sys.stdout = io.BytesIO() register(lambda: os.write(1, sys.stdout.getvalue())) tokens = [] tokens_next = 0 def nextStr(): global tokens, tokens_next while tokens_next >= len(tokens): tokens = input().split() tokens_next = 0 tokens_next += 1 return tokens[tokens_next - 1] def nextInt(): return int(nextStr()) def nextIntArr(n): return [nextInt() for i in range(n)] def print(s, end='\n'): sys.stdout.write((str(s) + end).encode()) def split(a): accSum = a[0] for j in range(1, len(a)): if accSum == 0: continue cur = split(a[j:]) if cur: return [a[:j]] + cur return None n = nextInt() a = nextIntArr(n) if sum(a) != 0: print('YES') print('1') print(f'1 {len(a)}') exit(0) nonZero = next((i for i in range(len(a)) if a[i] != 0), len(a)) if nonZero == len(a): print('NO') exit(0) print('YES') print('2') print(f'1 {nonZero + 1}') print(f'{nonZero + 2} {len(a)}') ```
89,759
Provide tags and a correct Python 3 solution for this coding contest problem. One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array A. Lesha is tired now so he asked you to split the array. Help Lesha! Input The first line contains single integer n (1 ≤ n ≤ 100) — the number of elements in the array A. The next line contains n integers a1, a2, ..., an ( - 103 ≤ ai ≤ 103) — the elements of the array A. Output If it is not possible to split the array A and satisfy all the constraints, print single line containing "NO" (without quotes). Otherwise in the first line print "YES" (without quotes). In the next line print single integer k — the number of new arrays. In each of the next k lines print two integers li and ri which denote the subarray A[li... ri] of the initial array A being the i-th new array. Integers li, ri should satisfy the following conditions: * l1 = 1 * rk = n * ri + 1 = li + 1 for each 1 ≤ i < k. If there are multiple answers, print any of them. Examples Input 3 1 2 -3 Output YES 2 1 2 3 3 Input 8 9 -12 3 4 -4 -10 7 3 Output YES 2 1 2 3 8 Input 1 0 Output NO Input 4 1 2 3 -5 Output YES 4 1 1 2 2 3 3 4 4 Tags: constructive algorithms, greedy, implementation Correct Solution: ``` def main(): i=j=0 n = int(input()) ara = list(map(int, input().split())) if any(ara): print("YES") if sum(ara)!=0: print(1) print(1, n) else: for i, j in enumerate(ara): if j!=0: print(2) print(1, i+1) print(i+2, n) break else: print("NO") if __name__ == '__main__': main() ```
89,760
Provide tags and a correct Python 3 solution for this coding contest problem. One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array A. Lesha is tired now so he asked you to split the array. Help Lesha! Input The first line contains single integer n (1 ≤ n ≤ 100) — the number of elements in the array A. The next line contains n integers a1, a2, ..., an ( - 103 ≤ ai ≤ 103) — the elements of the array A. Output If it is not possible to split the array A and satisfy all the constraints, print single line containing "NO" (without quotes). Otherwise in the first line print "YES" (without quotes). In the next line print single integer k — the number of new arrays. In each of the next k lines print two integers li and ri which denote the subarray A[li... ri] of the initial array A being the i-th new array. Integers li, ri should satisfy the following conditions: * l1 = 1 * rk = n * ri + 1 = li + 1 for each 1 ≤ i < k. If there are multiple answers, print any of them. Examples Input 3 1 2 -3 Output YES 2 1 2 3 3 Input 8 9 -12 3 4 -4 -10 7 3 Output YES 2 1 2 3 8 Input 1 0 Output NO Input 4 1 2 3 -5 Output YES 4 1 1 2 2 3 3 4 4 Tags: constructive algorithms, greedy, implementation Correct Solution: ``` #!/usr/bin/env python3 # -*- coding: utf-8 -*- N = int(input()) As = list(map(int,input().split())) if min(As) == max(As) == 0: print("NO") else: print("YES") if sum(As) != 0: print("1") print("{} {}".format(1,N)) else: Bs = [] i = 0 while sum(Bs) == 0: Bs.append(As[i]) i += 1 print("2") print(1, i) print(i+1, N) ```
89,761
Provide tags and a correct Python 3 solution for this coding contest problem. One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array A. Lesha is tired now so he asked you to split the array. Help Lesha! Input The first line contains single integer n (1 ≤ n ≤ 100) — the number of elements in the array A. The next line contains n integers a1, a2, ..., an ( - 103 ≤ ai ≤ 103) — the elements of the array A. Output If it is not possible to split the array A and satisfy all the constraints, print single line containing "NO" (without quotes). Otherwise in the first line print "YES" (without quotes). In the next line print single integer k — the number of new arrays. In each of the next k lines print two integers li and ri which denote the subarray A[li... ri] of the initial array A being the i-th new array. Integers li, ri should satisfy the following conditions: * l1 = 1 * rk = n * ri + 1 = li + 1 for each 1 ≤ i < k. If there are multiple answers, print any of them. Examples Input 3 1 2 -3 Output YES 2 1 2 3 3 Input 8 9 -12 3 4 -4 -10 7 3 Output YES 2 1 2 3 8 Input 1 0 Output NO Input 4 1 2 3 -5 Output YES 4 1 1 2 2 3 3 4 4 Tags: constructive algorithms, greedy, implementation Correct Solution: ``` n = int(input()) arr = list(map(int,input().split())) sm = sum(arr) if sm!=0: print("YES") print(1) print(1,n) else: sm = 0 done = False for i in range(n): sm += arr[i] if sm!=0: print("YES") print(2) print(1,i+1) print(i+2,n) done = True break if not done: print("NO") ```
89,762
Provide tags and a correct Python 3 solution for this coding contest problem. One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array A. Lesha is tired now so he asked you to split the array. Help Lesha! Input The first line contains single integer n (1 ≤ n ≤ 100) — the number of elements in the array A. The next line contains n integers a1, a2, ..., an ( - 103 ≤ ai ≤ 103) — the elements of the array A. Output If it is not possible to split the array A and satisfy all the constraints, print single line containing "NO" (without quotes). Otherwise in the first line print "YES" (without quotes). In the next line print single integer k — the number of new arrays. In each of the next k lines print two integers li and ri which denote the subarray A[li... ri] of the initial array A being the i-th new array. Integers li, ri should satisfy the following conditions: * l1 = 1 * rk = n * ri + 1 = li + 1 for each 1 ≤ i < k. If there are multiple answers, print any of them. Examples Input 3 1 2 -3 Output YES 2 1 2 3 3 Input 8 9 -12 3 4 -4 -10 7 3 Output YES 2 1 2 3 8 Input 1 0 Output NO Input 4 1 2 3 -5 Output YES 4 1 1 2 2 3 3 4 4 Tags: constructive algorithms, greedy, implementation Correct Solution: ``` n = int(input()) lst = list(map(int, input().split())) if sum(lst) != 0: print("YES\n1\n1 %d" % (n)) else: for i in range(1, n): if sum(lst[:i]) != 0: print("YES\n2\n1 %d\n%d %d" % (i, i+1, n)) quit() print("NO") ```
89,763
Provide tags and a correct Python 3 solution for this coding contest problem. One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array A. Lesha is tired now so he asked you to split the array. Help Lesha! Input The first line contains single integer n (1 ≤ n ≤ 100) — the number of elements in the array A. The next line contains n integers a1, a2, ..., an ( - 103 ≤ ai ≤ 103) — the elements of the array A. Output If it is not possible to split the array A and satisfy all the constraints, print single line containing "NO" (without quotes). Otherwise in the first line print "YES" (without quotes). In the next line print single integer k — the number of new arrays. In each of the next k lines print two integers li and ri which denote the subarray A[li... ri] of the initial array A being the i-th new array. Integers li, ri should satisfy the following conditions: * l1 = 1 * rk = n * ri + 1 = li + 1 for each 1 ≤ i < k. If there are multiple answers, print any of them. Examples Input 3 1 2 -3 Output YES 2 1 2 3 3 Input 8 9 -12 3 4 -4 -10 7 3 Output YES 2 1 2 3 8 Input 1 0 Output NO Input 4 1 2 3 -5 Output YES 4 1 1 2 2 3 3 4 4 Tags: constructive algorithms, greedy, implementation Correct Solution: ``` n=int(input()) a=list(map(int, input().split())) if a.count(0)==n: print("NO") else: print("YES") if sum(a)==0: for i in range(n): if sum(a[:i])!=0: print("2") print("1 "+str(i)) print(str(i+1)+" "+str(n)) break else: print("1") print("1 "+str(n)) ```
89,764
Provide tags and a correct Python 3 solution for this coding contest problem. One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array A. Lesha is tired now so he asked you to split the array. Help Lesha! Input The first line contains single integer n (1 ≤ n ≤ 100) — the number of elements in the array A. The next line contains n integers a1, a2, ..., an ( - 103 ≤ ai ≤ 103) — the elements of the array A. Output If it is not possible to split the array A and satisfy all the constraints, print single line containing "NO" (without quotes). Otherwise in the first line print "YES" (without quotes). In the next line print single integer k — the number of new arrays. In each of the next k lines print two integers li and ri which denote the subarray A[li... ri] of the initial array A being the i-th new array. Integers li, ri should satisfy the following conditions: * l1 = 1 * rk = n * ri + 1 = li + 1 for each 1 ≤ i < k. If there are multiple answers, print any of them. Examples Input 3 1 2 -3 Output YES 2 1 2 3 3 Input 8 9 -12 3 4 -4 -10 7 3 Output YES 2 1 2 3 8 Input 1 0 Output NO Input 4 1 2 3 -5 Output YES 4 1 1 2 2 3 3 4 4 Tags: constructive algorithms, greedy, implementation Correct Solution: ``` n=int(input()) a=list(map(int,input().split())) sum = 0 for i in range(n): sum = sum + a[i] if sum: print ("YES") print ("1") print ("1",n) else: teksum,ans = 0,0 for i in range(n): if teksum: ans=i break else: teksum = teksum + a[i] if ans == 0: print("NO") else: print("YES") print("2") print("1",ans) ans = ans +1 print(ans,n) ```
89,765
Provide tags and a correct Python 3 solution for this coding contest problem. One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array A. Lesha is tired now so he asked you to split the array. Help Lesha! Input The first line contains single integer n (1 ≤ n ≤ 100) — the number of elements in the array A. The next line contains n integers a1, a2, ..., an ( - 103 ≤ ai ≤ 103) — the elements of the array A. Output If it is not possible to split the array A and satisfy all the constraints, print single line containing "NO" (without quotes). Otherwise in the first line print "YES" (without quotes). In the next line print single integer k — the number of new arrays. In each of the next k lines print two integers li and ri which denote the subarray A[li... ri] of the initial array A being the i-th new array. Integers li, ri should satisfy the following conditions: * l1 = 1 * rk = n * ri + 1 = li + 1 for each 1 ≤ i < k. If there are multiple answers, print any of them. Examples Input 3 1 2 -3 Output YES 2 1 2 3 3 Input 8 9 -12 3 4 -4 -10 7 3 Output YES 2 1 2 3 8 Input 1 0 Output NO Input 4 1 2 3 -5 Output YES 4 1 1 2 2 3 3 4 4 Tags: constructive algorithms, greedy, implementation Correct Solution: ``` n = int(input()) a = [int(b) for b in input().split()] ans = 0 indexes = [] if len(set(a)) == 1 and a[0] == 0: print("NO") exit() if sum(a) != 0: print("YES") print(1) print(1, n) exit() for i in range(n): if a[i] != 0: indexes.append(i) print("YES") print(2) print(1, indexes[0]+1) print(indexes[0]+2, n) ```
89,766
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array A. Lesha is tired now so he asked you to split the array. Help Lesha! Input The first line contains single integer n (1 ≤ n ≤ 100) — the number of elements in the array A. The next line contains n integers a1, a2, ..., an ( - 103 ≤ ai ≤ 103) — the elements of the array A. Output If it is not possible to split the array A and satisfy all the constraints, print single line containing "NO" (without quotes). Otherwise in the first line print "YES" (without quotes). In the next line print single integer k — the number of new arrays. In each of the next k lines print two integers li and ri which denote the subarray A[li... ri] of the initial array A being the i-th new array. Integers li, ri should satisfy the following conditions: * l1 = 1 * rk = n * ri + 1 = li + 1 for each 1 ≤ i < k. If there are multiple answers, print any of them. Examples Input 3 1 2 -3 Output YES 2 1 2 3 3 Input 8 9 -12 3 4 -4 -10 7 3 Output YES 2 1 2 3 8 Input 1 0 Output NO Input 4 1 2 3 -5 Output YES 4 1 1 2 2 3 3 4 4 Submitted Solution: ``` n = int(input()) a = [int(i) for i in input().split()] if sum(a) != 0: print('YES') print(1) print(1, n) exit() if n == 1 or a.count(0) == n: print('NO') exit() i = 0 while a[i] == 0: i += 1 print('YES') print(2) print(1, i + 1) print(i + 2, n) ``` Yes
89,767
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array A. Lesha is tired now so he asked you to split the array. Help Lesha! Input The first line contains single integer n (1 ≤ n ≤ 100) — the number of elements in the array A. The next line contains n integers a1, a2, ..., an ( - 103 ≤ ai ≤ 103) — the elements of the array A. Output If it is not possible to split the array A and satisfy all the constraints, print single line containing "NO" (without quotes). Otherwise in the first line print "YES" (without quotes). In the next line print single integer k — the number of new arrays. In each of the next k lines print two integers li and ri which denote the subarray A[li... ri] of the initial array A being the i-th new array. Integers li, ri should satisfy the following conditions: * l1 = 1 * rk = n * ri + 1 = li + 1 for each 1 ≤ i < k. If there are multiple answers, print any of them. Examples Input 3 1 2 -3 Output YES 2 1 2 3 3 Input 8 9 -12 3 4 -4 -10 7 3 Output YES 2 1 2 3 8 Input 1 0 Output NO Input 4 1 2 3 -5 Output YES 4 1 1 2 2 3 3 4 4 Submitted Solution: ``` import sys,math n = int(input()) array = list(map(int,input().split())) if array.count(0)==n: print('NO') sys.exit() if sum(array)==0: print('YES') print(2) i = 1 while sum(array[0:i]) ==0 or sum(array[i:])==0: i+=1 print(1,i) print(i+1,n) else: print('YES') print(1) print(1,n) ``` Yes
89,768
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array A. Lesha is tired now so he asked you to split the array. Help Lesha! Input The first line contains single integer n (1 ≤ n ≤ 100) — the number of elements in the array A. The next line contains n integers a1, a2, ..., an ( - 103 ≤ ai ≤ 103) — the elements of the array A. Output If it is not possible to split the array A and satisfy all the constraints, print single line containing "NO" (without quotes). Otherwise in the first line print "YES" (without quotes). In the next line print single integer k — the number of new arrays. In each of the next k lines print two integers li and ri which denote the subarray A[li... ri] of the initial array A being the i-th new array. Integers li, ri should satisfy the following conditions: * l1 = 1 * rk = n * ri + 1 = li + 1 for each 1 ≤ i < k. If there are multiple answers, print any of them. Examples Input 3 1 2 -3 Output YES 2 1 2 3 3 Input 8 9 -12 3 4 -4 -10 7 3 Output YES 2 1 2 3 8 Input 1 0 Output NO Input 4 1 2 3 -5 Output YES 4 1 1 2 2 3 3 4 4 Submitted Solution: ``` def check_zero(ar): for i in range(n): if ar[i] != 0: return False return True n = int(input()) ls = list(map(int, input().split())) sm = sum(ls) if sm: print('YES') print(1) print(1, n) else: if check_zero(ls): print('NO') else: tsm = 0 for i in range(n): tsm += ls[i] if tsm != 0: print('YES') print(2) print(1, i + 1) print(i + 2, n) break ``` Yes
89,769
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array A. Lesha is tired now so he asked you to split the array. Help Lesha! Input The first line contains single integer n (1 ≤ n ≤ 100) — the number of elements in the array A. The next line contains n integers a1, a2, ..., an ( - 103 ≤ ai ≤ 103) — the elements of the array A. Output If it is not possible to split the array A and satisfy all the constraints, print single line containing "NO" (without quotes). Otherwise in the first line print "YES" (without quotes). In the next line print single integer k — the number of new arrays. In each of the next k lines print two integers li and ri which denote the subarray A[li... ri] of the initial array A being the i-th new array. Integers li, ri should satisfy the following conditions: * l1 = 1 * rk = n * ri + 1 = li + 1 for each 1 ≤ i < k. If there are multiple answers, print any of them. Examples Input 3 1 2 -3 Output YES 2 1 2 3 3 Input 8 9 -12 3 4 -4 -10 7 3 Output YES 2 1 2 3 8 Input 1 0 Output NO Input 4 1 2 3 -5 Output YES 4 1 1 2 2 3 3 4 4 Submitted Solution: ``` n=int(input()) l=list(map(int,input().split())) if(l.count(0)==n): print("NO") else: s=0 t=[1] d=[] for i in range(n): s=s+l[i] if(l[i]!=0 and s==0): t.append(i) d.append(t) t=[i+1] s=l[i] t.append(n) d.append(t) print("YES") print(len(d)) for i in d: print(i[0],i[1]) ``` Yes
89,770
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array A. Lesha is tired now so he asked you to split the array. Help Lesha! Input The first line contains single integer n (1 ≤ n ≤ 100) — the number of elements in the array A. The next line contains n integers a1, a2, ..., an ( - 103 ≤ ai ≤ 103) — the elements of the array A. Output If it is not possible to split the array A and satisfy all the constraints, print single line containing "NO" (without quotes). Otherwise in the first line print "YES" (without quotes). In the next line print single integer k — the number of new arrays. In each of the next k lines print two integers li and ri which denote the subarray A[li... ri] of the initial array A being the i-th new array. Integers li, ri should satisfy the following conditions: * l1 = 1 * rk = n * ri + 1 = li + 1 for each 1 ≤ i < k. If there are multiple answers, print any of them. Examples Input 3 1 2 -3 Output YES 2 1 2 3 3 Input 8 9 -12 3 4 -4 -10 7 3 Output YES 2 1 2 3 8 Input 1 0 Output NO Input 4 1 2 3 -5 Output YES 4 1 1 2 2 3 3 4 4 Submitted Solution: ``` n = int(input()) a = list(map(int, input().split())) ss = 0 if a.count('0') == n: print('NO') else: print('YES') print(1, end = ' ') for i in range(0, n): ss += a[i] if ss == 0 and a[i] != 0: print(i) print(i+1, end = ' ') print(n) ``` No
89,771
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array A. Lesha is tired now so he asked you to split the array. Help Lesha! Input The first line contains single integer n (1 ≤ n ≤ 100) — the number of elements in the array A. The next line contains n integers a1, a2, ..., an ( - 103 ≤ ai ≤ 103) — the elements of the array A. Output If it is not possible to split the array A and satisfy all the constraints, print single line containing "NO" (without quotes). Otherwise in the first line print "YES" (without quotes). In the next line print single integer k — the number of new arrays. In each of the next k lines print two integers li and ri which denote the subarray A[li... ri] of the initial array A being the i-th new array. Integers li, ri should satisfy the following conditions: * l1 = 1 * rk = n * ri + 1 = li + 1 for each 1 ≤ i < k. If there are multiple answers, print any of them. Examples Input 3 1 2 -3 Output YES 2 1 2 3 3 Input 8 9 -12 3 4 -4 -10 7 3 Output YES 2 1 2 3 8 Input 1 0 Output NO Input 4 1 2 3 -5 Output YES 4 1 1 2 2 3 3 4 4 Submitted Solution: ``` n = int(input()) t= list(map(int,input().split())) f=[] s=99999 for j in range(n): if t[j]!=0: if s==99999: f.append([j+1,j+1]) else: f.append([s,j+1]) s=99999 else: s=j+1 if len(f)==0: print('NO') else: if s!=99999: a=f.pop()[0] f.append([a,n]) print('YES') print(len(f)) for j in f: print(*j) ``` No
89,772
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array A. Lesha is tired now so he asked you to split the array. Help Lesha! Input The first line contains single integer n (1 ≤ n ≤ 100) — the number of elements in the array A. The next line contains n integers a1, a2, ..., an ( - 103 ≤ ai ≤ 103) — the elements of the array A. Output If it is not possible to split the array A and satisfy all the constraints, print single line containing "NO" (without quotes). Otherwise in the first line print "YES" (without quotes). In the next line print single integer k — the number of new arrays. In each of the next k lines print two integers li and ri which denote the subarray A[li... ri] of the initial array A being the i-th new array. Integers li, ri should satisfy the following conditions: * l1 = 1 * rk = n * ri + 1 = li + 1 for each 1 ≤ i < k. If there are multiple answers, print any of them. Examples Input 3 1 2 -3 Output YES 2 1 2 3 3 Input 8 9 -12 3 4 -4 -10 7 3 Output YES 2 1 2 3 8 Input 1 0 Output NO Input 4 1 2 3 -5 Output YES 4 1 1 2 2 3 3 4 4 Submitted Solution: ``` n = int(input()) a = [int(x) for x in input().split()] T = {} def split_nonzero(a, T, begin, end): if begin == end: T[(begin, end)] = [] elif begin == end - 1: if a[begin] == 0: T[(begin, end)] = 'NO' else: T[(begin, end)] = [(begin, begin)] else: for k in range(end - 1, begin, -1): if (begin, k) in T: fr = T[(begin, k)] else: fr = split_nonzero(a, T, begin, k) if fr != 'NO': if (k, end) in T: sr = T[(k, end)] else: sr = split_nonzero(a, T, k, end) if sr != 'NO': T[(begin, end)] = [(begin, k - 1)] + sr break else: T[(begin, end)] = 'NO' return T[(begin, end)] result = split_nonzero(a, T, 0, len(a)) if result == 'NO': print('NO') else: print('YES') print(len(result)) for (i, j) in result: print(i + 1, j + 1) ``` No
89,773
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array A. Lesha is tired now so he asked you to split the array. Help Lesha! Input The first line contains single integer n (1 ≤ n ≤ 100) — the number of elements in the array A. The next line contains n integers a1, a2, ..., an ( - 103 ≤ ai ≤ 103) — the elements of the array A. Output If it is not possible to split the array A and satisfy all the constraints, print single line containing "NO" (without quotes). Otherwise in the first line print "YES" (without quotes). In the next line print single integer k — the number of new arrays. In each of the next k lines print two integers li and ri which denote the subarray A[li... ri] of the initial array A being the i-th new array. Integers li, ri should satisfy the following conditions: * l1 = 1 * rk = n * ri + 1 = li + 1 for each 1 ≤ i < k. If there are multiple answers, print any of them. Examples Input 3 1 2 -3 Output YES 2 1 2 3 3 Input 8 9 -12 3 4 -4 -10 7 3 Output YES 2 1 2 3 8 Input 1 0 Output NO Input 4 1 2 3 -5 Output YES 4 1 1 2 2 3 3 4 4 Submitted Solution: ``` N = int(input()) A = [int(x) for x in input().split()] if all(A[i] == 0 for i in range(N)): print("NO") else: print("YES") ans = [] nz_l, nz_r = 0, N-1 while A[nz_l] == 0: nz_l += 1 while A[nz_r] == 0: nz_r -= 1 now = nz_l while now <= nz_r: total = 0 for i in range(now, N): total += A[i] if A[i] != 0: ans.append([now, i]) now = i + 1 break ans[0][0] = 0 ans[-1][1] = N-1 for l, r in ans: print(l+1, r+1) ``` No
89,774
Provide tags and a correct Python 3 solution for this coding contest problem. Well, the series which Stepan watched for a very long time, ended. In total, the series had n episodes. For each of them, Stepan remembers either that he definitely has watched it, or that he definitely hasn't watched it, or he is unsure, has he watched this episode or not. Stepan's dissatisfaction is the maximum number of consecutive series that Stepan did not watch. Your task is to determine according to Stepan's memories if his dissatisfaction could be exactly equal to k. Input The first line contains two integers n and k (1 ≤ n ≤ 100, 0 ≤ k ≤ n) — the number of episodes in the series and the dissatisfaction which should be checked. The second line contains the sequence which consists of n symbols "Y", "N" and "?". If the i-th symbol equals "Y", Stepan remembers that he has watched the episode number i. If the i-th symbol equals "N", Stepan remembers that he hasn't watched the epizode number i. If the i-th symbol equals "?", Stepan doesn't exactly remember if he has watched the episode number i or not. Output If Stepan's dissatisfaction can be exactly equal to k, then print "YES" (without qoutes). Otherwise print "NO" (without qoutes). Examples Input 5 2 NYNNY Output YES Input 6 1 ????NN Output NO Note In the first test Stepan remembers about all the episodes whether he has watched them or not. His dissatisfaction is 2, because he hasn't watch two episodes in a row — the episode number 3 and the episode number 4. The answer is "YES", because k = 2. In the second test k = 1, Stepan's dissatisfaction is greater than or equal to 2 (because he remembers that he hasn't watch at least two episodes in a row — number 5 and number 6), even if he has watched the episodes from the first to the fourth, inclusive. Tags: *special, dp Correct Solution: ``` from sys import stdin from functools import lru_cache from collections import defaultdict infile = stdin N, K = map(int, infile.readline().split()) watched = infile.readline().strip() mem = set() mem.add((0,0,0)) for i, letter in enumerate(watched): for d in range(K+1): for c in range(K+1): if (i,d,c) in mem: if letter in ('N', '?'): mem.add((i+1, max(d, c+1), c+1)) if letter in ('Y', '?'): mem.add((i+1, d, 0)) def good(): for i,d,c in mem: if i == N and d == K: return 'YES' return 'NO' print(good()) ```
89,775
Provide tags and a correct Python 3 solution for this coding contest problem. Well, the series which Stepan watched for a very long time, ended. In total, the series had n episodes. For each of them, Stepan remembers either that he definitely has watched it, or that he definitely hasn't watched it, or he is unsure, has he watched this episode or not. Stepan's dissatisfaction is the maximum number of consecutive series that Stepan did not watch. Your task is to determine according to Stepan's memories if his dissatisfaction could be exactly equal to k. Input The first line contains two integers n and k (1 ≤ n ≤ 100, 0 ≤ k ≤ n) — the number of episodes in the series and the dissatisfaction which should be checked. The second line contains the sequence which consists of n symbols "Y", "N" and "?". If the i-th symbol equals "Y", Stepan remembers that he has watched the episode number i. If the i-th symbol equals "N", Stepan remembers that he hasn't watched the epizode number i. If the i-th symbol equals "?", Stepan doesn't exactly remember if he has watched the episode number i or not. Output If Stepan's dissatisfaction can be exactly equal to k, then print "YES" (without qoutes). Otherwise print "NO" (without qoutes). Examples Input 5 2 NYNNY Output YES Input 6 1 ????NN Output NO Note In the first test Stepan remembers about all the episodes whether he has watched them or not. His dissatisfaction is 2, because he hasn't watch two episodes in a row — the episode number 3 and the episode number 4. The answer is "YES", because k = 2. In the second test k = 1, Stepan's dissatisfaction is greater than or equal to 2 (because he remembers that he hasn't watch at least two episodes in a row — number 5 and number 6), even if he has watched the episodes from the first to the fourth, inclusive. Tags: *special, dp Correct Solution: ``` def process(S, k): n = len(S) if k > n: return 'NO' current = 0 for i in range(n): if S[i]=='N': current+=1 if current > k: return 'NO' else: current = 0 start_work = True for i in range(k): if S[i]=='Y': start_work = False if start_work and (k==n or k < n and S[k] != 'N'): return 'YES' if n==1: if k==1 and S[0] in ['?N']: return 'YES' if k==0 and S[0] in ['?Y']: return 'YES' return 'NO' if k==n: if 'Y' in S: return 'NO' return 'YES' Y_count = 0 p1 = 0 for i in range(1, k+1): if S[i]=='Y': Y_count+=1 p2 = i for i in range(k+1, n): # print(p1, Y_count, p2) if Y_count==0 and S[p1] != 'N' and (p2==n-1 or S[p2+1] != 'N'): return 'YES' p1+=1 p2+=1 if p2 < n and S[p2]=='Y': Y_count+=1 if p1 < n and S[p1]=='Y': Y_count-=1 # print(p1, Y_count, p2) if Y_count==0 and p1 < n and S[p1] != 'N': return 'YES' return 'NO' n, k = [int(x) for x in input().split()] S = input() print(process(S, k)) ```
89,776
Provide tags and a correct Python 3 solution for this coding contest problem. Well, the series which Stepan watched for a very long time, ended. In total, the series had n episodes. For each of them, Stepan remembers either that he definitely has watched it, or that he definitely hasn't watched it, or he is unsure, has he watched this episode or not. Stepan's dissatisfaction is the maximum number of consecutive series that Stepan did not watch. Your task is to determine according to Stepan's memories if his dissatisfaction could be exactly equal to k. Input The first line contains two integers n and k (1 ≤ n ≤ 100, 0 ≤ k ≤ n) — the number of episodes in the series and the dissatisfaction which should be checked. The second line contains the sequence which consists of n symbols "Y", "N" and "?". If the i-th symbol equals "Y", Stepan remembers that he has watched the episode number i. If the i-th symbol equals "N", Stepan remembers that he hasn't watched the epizode number i. If the i-th symbol equals "?", Stepan doesn't exactly remember if he has watched the episode number i or not. Output If Stepan's dissatisfaction can be exactly equal to k, then print "YES" (without qoutes). Otherwise print "NO" (without qoutes). Examples Input 5 2 NYNNY Output YES Input 6 1 ????NN Output NO Note In the first test Stepan remembers about all the episodes whether he has watched them or not. His dissatisfaction is 2, because he hasn't watch two episodes in a row — the episode number 3 and the episode number 4. The answer is "YES", because k = 2. In the second test k = 1, Stepan's dissatisfaction is greater than or equal to 2 (because he remembers that he hasn't watch at least two episodes in a row — number 5 and number 6), even if he has watched the episodes from the first to the fourth, inclusive. Tags: *special, dp Correct Solution: ``` import sys # sys.stdin = open("actext.txt","r") n,k = map(int,input().split()) s = input() dp = [-1 for i in range(n+1)] count = 0 mxcount = 0 for i in s: if(i=='N'): count+=1 else: if(mxcount<count): mxcount = count count = 0 if(mxcount<count): mxcount = count status = 0 if(mxcount>k): print("NO") status = 1 elif(mxcount==k): print("YES") else: s = s+"Y" # print(s) for i in range(k,n+1): if(s[i]!='N' and s[i-k-1]!='N'): temp = False # print(s[i-k:i]) for j in range(i-k,i): if(s[j]=='Y'): temp = True break # print(temp) if(not temp): print("YES") exit() print("NO") ```
89,777
Provide tags and a correct Python 3 solution for this coding contest problem. Well, the series which Stepan watched for a very long time, ended. In total, the series had n episodes. For each of them, Stepan remembers either that he definitely has watched it, or that he definitely hasn't watched it, or he is unsure, has he watched this episode or not. Stepan's dissatisfaction is the maximum number of consecutive series that Stepan did not watch. Your task is to determine according to Stepan's memories if his dissatisfaction could be exactly equal to k. Input The first line contains two integers n and k (1 ≤ n ≤ 100, 0 ≤ k ≤ n) — the number of episodes in the series and the dissatisfaction which should be checked. The second line contains the sequence which consists of n symbols "Y", "N" and "?". If the i-th symbol equals "Y", Stepan remembers that he has watched the episode number i. If the i-th symbol equals "N", Stepan remembers that he hasn't watched the epizode number i. If the i-th symbol equals "?", Stepan doesn't exactly remember if he has watched the episode number i or not. Output If Stepan's dissatisfaction can be exactly equal to k, then print "YES" (without qoutes). Otherwise print "NO" (without qoutes). Examples Input 5 2 NYNNY Output YES Input 6 1 ????NN Output NO Note In the first test Stepan remembers about all the episodes whether he has watched them or not. His dissatisfaction is 2, because he hasn't watch two episodes in a row — the episode number 3 and the episode number 4. The answer is "YES", because k = 2. In the second test k = 1, Stepan's dissatisfaction is greater than or equal to 2 (because he remembers that he hasn't watch at least two episodes in a row — number 5 and number 6), even if he has watched the episodes from the first to the fourth, inclusive. Tags: *special, dp Correct Solution: ``` n, m = list(map(int, input().split())) s = input() cnt = int(0) for ch in s: if ch == 'N': cnt += 1 elif cnt > m: print("NO") exit(0); else: cnt = int(0) if cnt > m: print("NO") exit(0); s = "Y"+s for i in range(0, n+1): if s[i] == '?' or s[i] == 'Y': cnt = int(0) for j in range(i+1, n+1): #print(i, j, cnt, end = "\n") if s[j] == 'Y': if cnt == m: print("YES") exit(0) break if s[j] == '?': if cnt == m: print("YES") exit(0) cnt += 1 if cnt == m: print("YES") exit(0) print("NO") ```
89,778
Provide tags and a correct Python 3 solution for this coding contest problem. Well, the series which Stepan watched for a very long time, ended. In total, the series had n episodes. For each of them, Stepan remembers either that he definitely has watched it, or that he definitely hasn't watched it, or he is unsure, has he watched this episode or not. Stepan's dissatisfaction is the maximum number of consecutive series that Stepan did not watch. Your task is to determine according to Stepan's memories if his dissatisfaction could be exactly equal to k. Input The first line contains two integers n and k (1 ≤ n ≤ 100, 0 ≤ k ≤ n) — the number of episodes in the series and the dissatisfaction which should be checked. The second line contains the sequence which consists of n symbols "Y", "N" and "?". If the i-th symbol equals "Y", Stepan remembers that he has watched the episode number i. If the i-th symbol equals "N", Stepan remembers that he hasn't watched the epizode number i. If the i-th symbol equals "?", Stepan doesn't exactly remember if he has watched the episode number i or not. Output If Stepan's dissatisfaction can be exactly equal to k, then print "YES" (without qoutes). Otherwise print "NO" (without qoutes). Examples Input 5 2 NYNNY Output YES Input 6 1 ????NN Output NO Note In the first test Stepan remembers about all the episodes whether he has watched them or not. His dissatisfaction is 2, because he hasn't watch two episodes in a row — the episode number 3 and the episode number 4. The answer is "YES", because k = 2. In the second test k = 1, Stepan's dissatisfaction is greater than or equal to 2 (because he remembers that he hasn't watch at least two episodes in a row — number 5 and number 6), even if he has watched the episodes from the first to the fourth, inclusive. Tags: *special, dp Correct Solution: ``` n, k = map(int, input().split()) k = int(k) s = input() s = "Y" + s + "Y" res = "NO" cnt = 0 can = True for ch in s: if(ch == 'N'): cnt += 1 if(cnt > k): can = False else: cnt = 0 for i in range(1,n+1): if(i + k - 2 < n): subs = s[i:i+k] # print(subs) flag = True for ch in subs: if(not ch in "N?"): flag = False if((s[i-1] in "Y?" and s[i+k] in "Y?") and flag): res = "YES" # print(s[i-1], subs, s[i+k]) if can: print(res) else: print("NO") ```
89,779
Provide tags and a correct Python 3 solution for this coding contest problem. Well, the series which Stepan watched for a very long time, ended. In total, the series had n episodes. For each of them, Stepan remembers either that he definitely has watched it, or that he definitely hasn't watched it, or he is unsure, has he watched this episode or not. Stepan's dissatisfaction is the maximum number of consecutive series that Stepan did not watch. Your task is to determine according to Stepan's memories if his dissatisfaction could be exactly equal to k. Input The first line contains two integers n and k (1 ≤ n ≤ 100, 0 ≤ k ≤ n) — the number of episodes in the series and the dissatisfaction which should be checked. The second line contains the sequence which consists of n symbols "Y", "N" and "?". If the i-th symbol equals "Y", Stepan remembers that he has watched the episode number i. If the i-th symbol equals "N", Stepan remembers that he hasn't watched the epizode number i. If the i-th symbol equals "?", Stepan doesn't exactly remember if he has watched the episode number i or not. Output If Stepan's dissatisfaction can be exactly equal to k, then print "YES" (without qoutes). Otherwise print "NO" (without qoutes). Examples Input 5 2 NYNNY Output YES Input 6 1 ????NN Output NO Note In the first test Stepan remembers about all the episodes whether he has watched them or not. His dissatisfaction is 2, because he hasn't watch two episodes in a row — the episode number 3 and the episode number 4. The answer is "YES", because k = 2. In the second test k = 1, Stepan's dissatisfaction is greater than or equal to 2 (because he remembers that he hasn't watch at least two episodes in a row — number 5 and number 6), even if he has watched the episodes from the first to the fourth, inclusive. Tags: *special, dp Correct Solution: ``` # from Crypto.Util.number import * # from Crypto.PublicKey import RSA # from Crypto.Cipher import PKCS1_OAEP # # # def gcd(a, b): # if a == 0: # return b, 0, 1 # d, x1, y1 = gcd(b % a, a) # x = y1 - (b // a) * x1 # y = x1 # return d, x, y # # # def find_private_key(p, q, e): # f = (p - 1) * (q - 1) # d = gcd(e, f)[1] # while d < 0: # d += f # return d # # # n = 114603416258617277914112950886933842277017613048768896986887063295795075651032133331342538430388087616693581335924733790772692053706860660493046367184589390096319068611843480381499933909451620838321468620579057390519217231379164202675046840772638142625114303262708400933811096588213415014292281310788830121449 # # q = 8931970881300680082796820734365022222452747937209215859340339248013322229502496422895802649243487560690551112016430906973314030768362034269763079075131391 # # p = 12830697477814509540399242283518279629025340392811455061638565349197540239841408191167449256086467748949090279070442786996339222196995600246150833643209239 # # e = 78078409585916972042386784533013985111341440946219174025831418904974306682701 # # f = 114603416258617277914112950886933842277017613048768896986887063295795075651032133331342538430388087616693581335924733790772692053706860660493046367184589368333650709496653857185436916026149769360233138599908136411614620020516694858770432777520732812669804663621317314060117126934960449656657765396876111780820 # # d = 95617909040393155444786936446642179824041050920013801086828472351343249663960737590719979187458429568264589317317553181803837347371438624774016758221657991995265788792118497392951947899512373618098318332328397239065334523447713343639400315086378757038001615086063906730779984567240713176171007926923058722581 # # rsa = RSA.construct((n, e, d)) # # # #key = RSA.importKey(open('11.txt', 'r').read()) # key = RSA.importKey(open('public_key', 'r').read()) # # print(key.__dict__) # # n = 5629218730419894595823026663331501597897818160771697280840122531313799328035654852733468829411876184951508514832506002593002170978628016095067716010208905588870963783855109137307480667920058731486899983319164243850148229252772614367640165351224879369373847162133237931086116505957707781534245331485441 # p = 2372597464893675257469711937093671629348264195072192501684944517176070474701064022851367306150417447503454422147341366642712704243329694637078892947639 # q = n // p # e = 17 # # d = find_private_key(p, q, e) # # encrypted = 1111861507760457047964156325933048837925622938918416900082721305322555941153755195985545404321101492441045781915244282849548935206776118071569007445626459132036648013508921232096378109573160336245447392600788211167388900011173139344891307651852665571685713133157519571136012382352182349879574471249590 # result = pow(encrypted, d, n) # # result = hex(result)[2:] # # ans = b'' # for i in range(0, len(result), 2): # ans += bytes([int(result[i:i+2], 16)]) # # print(ans) # # exit() # # key = RSA.construct((n, e, d)) # # with open('22.txt', 'wb') as fi: # fi.write(key.exportKey('PEM')) # # print('d =', d) # import time # import requests # # url = 'http://sql.training.hackerdom.ru/10lastlevel.php?text=' # condition = 'ORD(SUBSTRING(COLUMN_NAME, {}, 1)) = {}' # query = "IF(ORD(SUBSTRING(chocolate, {}, 1)) = {}, SLEEP(1), 1) FROM davidblayne;" # pos = 1 # sleep_time = 1 # a = {''} # # s = '' # for i in range(1, 30): # for c in range(32, 128): # start = time.time() # requests.get(url + query.format(i, c)) # end = time.time() # # d = end - start # # if d >= sleep_time: # print(chr(c)) # s += chr(c) # break # else: # break # # print(s) def calc(s): max_len = 0 cur_len = 0 for i in range(len(s)): if s[i] == 'N': cur_len += 1 else: cur_len = 0 max_len = max(max_len, cur_len) return max_len n, k = map(int, input().split()) s = input() if calc(s) > k: print('NO') exit() start = 0 while start + k - 1 < len(s): good = True for i in range(start, start + k): if s[i] == 'Y': good = False break if start - 1 >= 0 and s[start - 1] == 'N': good = False if start + k < len(s) and s[start + k] == 'N': good = False if good: print('YES') exit() start += 1 print('NO') ```
89,780
Provide tags and a correct Python 3 solution for this coding contest problem. Well, the series which Stepan watched for a very long time, ended. In total, the series had n episodes. For each of them, Stepan remembers either that he definitely has watched it, or that he definitely hasn't watched it, or he is unsure, has he watched this episode or not. Stepan's dissatisfaction is the maximum number of consecutive series that Stepan did not watch. Your task is to determine according to Stepan's memories if his dissatisfaction could be exactly equal to k. Input The first line contains two integers n and k (1 ≤ n ≤ 100, 0 ≤ k ≤ n) — the number of episodes in the series and the dissatisfaction which should be checked. The second line contains the sequence which consists of n symbols "Y", "N" and "?". If the i-th symbol equals "Y", Stepan remembers that he has watched the episode number i. If the i-th symbol equals "N", Stepan remembers that he hasn't watched the epizode number i. If the i-th symbol equals "?", Stepan doesn't exactly remember if he has watched the episode number i or not. Output If Stepan's dissatisfaction can be exactly equal to k, then print "YES" (without qoutes). Otherwise print "NO" (without qoutes). Examples Input 5 2 NYNNY Output YES Input 6 1 ????NN Output NO Note In the first test Stepan remembers about all the episodes whether he has watched them or not. His dissatisfaction is 2, because he hasn't watch two episodes in a row — the episode number 3 and the episode number 4. The answer is "YES", because k = 2. In the second test k = 1, Stepan's dissatisfaction is greater than or equal to 2 (because he remembers that he hasn't watch at least two episodes in a row — number 5 and number 6), even if he has watched the episodes from the first to the fourth, inclusive. Tags: *special, dp Correct Solution: ``` n, k = map(int, input().split()) s = input() cnt, mx = 0, 0 for i in range(n): if s[i] == "N": cnt += 1 else: cnt = 0 mx = max(mx, cnt) if mx > k: print("NO\n") exit() for r in range(k, n + 1): l = r - k if l > 0 and s[l - 1] == "N": continue if r < n and s[r] == "N": continue bad = False for i in range(l, r): if s[i] == "Y": bad = True break if not bad: print("YES\n") exit() print("NO\n") ```
89,781
Provide tags and a correct Python 3 solution for this coding contest problem. Well, the series which Stepan watched for a very long time, ended. In total, the series had n episodes. For each of them, Stepan remembers either that he definitely has watched it, or that he definitely hasn't watched it, or he is unsure, has he watched this episode or not. Stepan's dissatisfaction is the maximum number of consecutive series that Stepan did not watch. Your task is to determine according to Stepan's memories if his dissatisfaction could be exactly equal to k. Input The first line contains two integers n and k (1 ≤ n ≤ 100, 0 ≤ k ≤ n) — the number of episodes in the series and the dissatisfaction which should be checked. The second line contains the sequence which consists of n symbols "Y", "N" and "?". If the i-th symbol equals "Y", Stepan remembers that he has watched the episode number i. If the i-th symbol equals "N", Stepan remembers that he hasn't watched the epizode number i. If the i-th symbol equals "?", Stepan doesn't exactly remember if he has watched the episode number i or not. Output If Stepan's dissatisfaction can be exactly equal to k, then print "YES" (without qoutes). Otherwise print "NO" (without qoutes). Examples Input 5 2 NYNNY Output YES Input 6 1 ????NN Output NO Note In the first test Stepan remembers about all the episodes whether he has watched them or not. His dissatisfaction is 2, because he hasn't watch two episodes in a row — the episode number 3 and the episode number 4. The answer is "YES", because k = 2. In the second test k = 1, Stepan's dissatisfaction is greater than or equal to 2 (because he remembers that he hasn't watch at least two episodes in a row — number 5 and number 6), even if he has watched the episodes from the first to the fourth, inclusive. Tags: *special, dp Correct Solution: ``` n, k = map(int, input().split()) string = input() series = [] now = "" for elem in string: if elem == "Y": if now: series.append(now) now = "" else: now += elem if now: series.append(now) answer = False no_max = True if not k: for elem in series: if elem.count('N'): answer = True print("YES" if not answer else "NO") else: for elem in series: m = len(elem) for i in range(m - k + 1): if (not i or elem[i - 1] == '?') and ((i + k - 1) == m - 1 or elem[i + k] == '?'): answer = True counter = 0 for letter in elem: if letter == 'N': counter += 1 if counter > k: no_max = False else: counter = 0 print("YES" if answer and no_max else "NO") ```
89,782
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Well, the series which Stepan watched for a very long time, ended. In total, the series had n episodes. For each of them, Stepan remembers either that he definitely has watched it, or that he definitely hasn't watched it, or he is unsure, has he watched this episode or not. Stepan's dissatisfaction is the maximum number of consecutive series that Stepan did not watch. Your task is to determine according to Stepan's memories if his dissatisfaction could be exactly equal to k. Input The first line contains two integers n and k (1 ≤ n ≤ 100, 0 ≤ k ≤ n) — the number of episodes in the series and the dissatisfaction which should be checked. The second line contains the sequence which consists of n symbols "Y", "N" and "?". If the i-th symbol equals "Y", Stepan remembers that he has watched the episode number i. If the i-th symbol equals "N", Stepan remembers that he hasn't watched the epizode number i. If the i-th symbol equals "?", Stepan doesn't exactly remember if he has watched the episode number i or not. Output If Stepan's dissatisfaction can be exactly equal to k, then print "YES" (without qoutes). Otherwise print "NO" (without qoutes). Examples Input 5 2 NYNNY Output YES Input 6 1 ????NN Output NO Note In the first test Stepan remembers about all the episodes whether he has watched them or not. His dissatisfaction is 2, because he hasn't watch two episodes in a row — the episode number 3 and the episode number 4. The answer is "YES", because k = 2. In the second test k = 1, Stepan's dissatisfaction is greater than or equal to 2 (because he remembers that he hasn't watch at least two episodes in a row — number 5 and number 6), even if he has watched the episodes from the first to the fourth, inclusive. Submitted Solution: ``` import sys n, k = map(int, input().split(' ')) s = input() def max_streak(s): result = 0 for i in range(len(s)): j = i while j < len(s) and s[j] == 'N': j += 1 result = max(result, j - i) return result for i in range(n - k + 1): cur = list(s) for j in range(i, i + k): if cur[j] == '?': cur[j] = 'N' for j in range(i): if cur[j] == '?': cur[j] = 'Y' for j in range(i + k, n): if cur[j] == '?': cur[j] = 'Y' if max_streak(cur) == k: print('YES') sys.exit(0) print('NO') ``` Yes
89,783
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Well, the series which Stepan watched for a very long time, ended. In total, the series had n episodes. For each of them, Stepan remembers either that he definitely has watched it, or that he definitely hasn't watched it, or he is unsure, has he watched this episode or not. Stepan's dissatisfaction is the maximum number of consecutive series that Stepan did not watch. Your task is to determine according to Stepan's memories if his dissatisfaction could be exactly equal to k. Input The first line contains two integers n and k (1 ≤ n ≤ 100, 0 ≤ k ≤ n) — the number of episodes in the series and the dissatisfaction which should be checked. The second line contains the sequence which consists of n symbols "Y", "N" and "?". If the i-th symbol equals "Y", Stepan remembers that he has watched the episode number i. If the i-th symbol equals "N", Stepan remembers that he hasn't watched the epizode number i. If the i-th symbol equals "?", Stepan doesn't exactly remember if he has watched the episode number i or not. Output If Stepan's dissatisfaction can be exactly equal to k, then print "YES" (without qoutes). Otherwise print "NO" (without qoutes). Examples Input 5 2 NYNNY Output YES Input 6 1 ????NN Output NO Note In the first test Stepan remembers about all the episodes whether he has watched them or not. His dissatisfaction is 2, because he hasn't watch two episodes in a row — the episode number 3 and the episode number 4. The answer is "YES", because k = 2. In the second test k = 1, Stepan's dissatisfaction is greater than or equal to 2 (because he remembers that he hasn't watch at least two episodes in a row — number 5 and number 6), even if he has watched the episodes from the first to the fourth, inclusive. Submitted Solution: ``` n, k = map(int, input().split()) s = list(input()) ans = False for i in range(len(s) - k + 1): flag = True for j in range(i, i + k): if (s[j] == 'Y'): flag = False break if ((i + k) < len(s)) and s[i + k] == 'N': flag = False if (i > 0) and (s[i - 1] == 'N'): flag = False #print(i, flag) if (flag): ans = True break maximum = 0 i = 0 while (i < len(s)): now = 0 while (s[i] != 'N'): i += 1 if (i >= len(s)): break if (i >= len(s)): break while (i < len(s)) and (s[i] == 'N'): i += 1 now += 1 maximum = max(maximum, now) if ans and (maximum <= k): print('YES') else: print('NO') ``` Yes
89,784
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Well, the series which Stepan watched for a very long time, ended. In total, the series had n episodes. For each of them, Stepan remembers either that he definitely has watched it, or that he definitely hasn't watched it, or he is unsure, has he watched this episode or not. Stepan's dissatisfaction is the maximum number of consecutive series that Stepan did not watch. Your task is to determine according to Stepan's memories if his dissatisfaction could be exactly equal to k. Input The first line contains two integers n and k (1 ≤ n ≤ 100, 0 ≤ k ≤ n) — the number of episodes in the series and the dissatisfaction which should be checked. The second line contains the sequence which consists of n symbols "Y", "N" and "?". If the i-th symbol equals "Y", Stepan remembers that he has watched the episode number i. If the i-th symbol equals "N", Stepan remembers that he hasn't watched the epizode number i. If the i-th symbol equals "?", Stepan doesn't exactly remember if he has watched the episode number i or not. Output If Stepan's dissatisfaction can be exactly equal to k, then print "YES" (without qoutes). Otherwise print "NO" (without qoutes). Examples Input 5 2 NYNNY Output YES Input 6 1 ????NN Output NO Note In the first test Stepan remembers about all the episodes whether he has watched them or not. His dissatisfaction is 2, because he hasn't watch two episodes in a row — the episode number 3 and the episode number 4. The answer is "YES", because k = 2. In the second test k = 1, Stepan's dissatisfaction is greater than or equal to 2 (because he remembers that he hasn't watch at least two episodes in a row — number 5 and number 6), even if he has watched the episodes from the first to the fourth, inclusive. Submitted Solution: ``` n, k = map(int, input().split()) s = input() mnx = 0 mn = 0 mx = 0 ok = 0 for j in range(0, n-1): if (s[j] == "N"): mn += 1 mx += 1 if (mn > mnx): mnx = mn if (s[j] == "Y"): mn = 0 mx = 0 if (s[j] == "?"): mx += 1 if (k >= mn and k <= mx): ok = 1 for i in range(j+1, n): if (s[i] == "N"): mn += 1 mx += 1 if (mn > mnx): mnx = mn if (s[i] == "Y"): mn = 0 mx = 0 if (s[i] == "?"): mx += 1 if (mn > mnx): mnx = mn if (k >= mn and k <= mx): ok = 1 if (k < mnx): ok = 0 if (ok == 1): print("YES") else: print("NO") ``` No
89,785
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Well, the series which Stepan watched for a very long time, ended. In total, the series had n episodes. For each of them, Stepan remembers either that he definitely has watched it, or that he definitely hasn't watched it, or he is unsure, has he watched this episode or not. Stepan's dissatisfaction is the maximum number of consecutive series that Stepan did not watch. Your task is to determine according to Stepan's memories if his dissatisfaction could be exactly equal to k. Input The first line contains two integers n and k (1 ≤ n ≤ 100, 0 ≤ k ≤ n) — the number of episodes in the series and the dissatisfaction which should be checked. The second line contains the sequence which consists of n symbols "Y", "N" and "?". If the i-th symbol equals "Y", Stepan remembers that he has watched the episode number i. If the i-th symbol equals "N", Stepan remembers that he hasn't watched the epizode number i. If the i-th symbol equals "?", Stepan doesn't exactly remember if he has watched the episode number i or not. Output If Stepan's dissatisfaction can be exactly equal to k, then print "YES" (without qoutes). Otherwise print "NO" (without qoutes). Examples Input 5 2 NYNNY Output YES Input 6 1 ????NN Output NO Note In the first test Stepan remembers about all the episodes whether he has watched them or not. His dissatisfaction is 2, because he hasn't watch two episodes in a row — the episode number 3 and the episode number 4. The answer is "YES", because k = 2. In the second test k = 1, Stepan's dissatisfaction is greater than or equal to 2 (because he remembers that he hasn't watch at least two episodes in a row — number 5 and number 6), even if he has watched the episodes from the first to the fourth, inclusive. Submitted Solution: ``` n, k = map(int, input().split()) s = input() mnx = 0 mn = 0 mx = 0 ok = 0 for j in range(0, n-1): mn = 0 mx = 0 if (s[j] == "N"): mn += 1 mx += 1 if (mn > mnx): mnx = mn if (s[j] == "?"): mx += 1 if (k >= mn and k <= mx): ok = 1 for i in range(j+1, n): if (s[i] == "N"): mn += 1 mx += 1 if (mn > mnx): mnx = mn if (s[i] == "Y"): mn = 0 mx = 0 if (s[i] == "?"): mx += 1 if (mn > mnx): mnx = mn if (k >= mn and k <= mx): ok = 1 if (k < mnx): ok = 0 if (ok == 1): print("YES") else: print("NO") ``` No
89,786
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Well, the series which Stepan watched for a very long time, ended. In total, the series had n episodes. For each of them, Stepan remembers either that he definitely has watched it, or that he definitely hasn't watched it, or he is unsure, has he watched this episode or not. Stepan's dissatisfaction is the maximum number of consecutive series that Stepan did not watch. Your task is to determine according to Stepan's memories if his dissatisfaction could be exactly equal to k. Input The first line contains two integers n and k (1 ≤ n ≤ 100, 0 ≤ k ≤ n) — the number of episodes in the series and the dissatisfaction which should be checked. The second line contains the sequence which consists of n symbols "Y", "N" and "?". If the i-th symbol equals "Y", Stepan remembers that he has watched the episode number i. If the i-th symbol equals "N", Stepan remembers that he hasn't watched the epizode number i. If the i-th symbol equals "?", Stepan doesn't exactly remember if he has watched the episode number i or not. Output If Stepan's dissatisfaction can be exactly equal to k, then print "YES" (without qoutes). Otherwise print "NO" (without qoutes). Examples Input 5 2 NYNNY Output YES Input 6 1 ????NN Output NO Note In the first test Stepan remembers about all the episodes whether he has watched them or not. His dissatisfaction is 2, because he hasn't watch two episodes in a row — the episode number 3 and the episode number 4. The answer is "YES", because k = 2. In the second test k = 1, Stepan's dissatisfaction is greater than or equal to 2 (because he remembers that he hasn't watch at least two episodes in a row — number 5 and number 6), even if he has watched the episodes from the first to the fourth, inclusive. Submitted Solution: ``` n, relax = map(int, input().split()) x = [] s = input() for i in range(len(s)): x.append(s[i]) reader = [] while 'N' in x: reader.append(x.index('N')) del x[reader[-1]] while '?' in x: reader.append(x.index('?')) del x[reader[-1]] k = 0 for i in reader: if i == reader[0]: dno = i elif i == dno + 1: k += 1 else: k = 0 if k == relax: print('YES') else: print('NO') ''' 5 2 NYNNY 6 1 ????NN ''' ``` No
89,787
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Well, the series which Stepan watched for a very long time, ended. In total, the series had n episodes. For each of them, Stepan remembers either that he definitely has watched it, or that he definitely hasn't watched it, or he is unsure, has he watched this episode or not. Stepan's dissatisfaction is the maximum number of consecutive series that Stepan did not watch. Your task is to determine according to Stepan's memories if his dissatisfaction could be exactly equal to k. Input The first line contains two integers n and k (1 ≤ n ≤ 100, 0 ≤ k ≤ n) — the number of episodes in the series and the dissatisfaction which should be checked. The second line contains the sequence which consists of n symbols "Y", "N" and "?". If the i-th symbol equals "Y", Stepan remembers that he has watched the episode number i. If the i-th symbol equals "N", Stepan remembers that he hasn't watched the epizode number i. If the i-th symbol equals "?", Stepan doesn't exactly remember if he has watched the episode number i or not. Output If Stepan's dissatisfaction can be exactly equal to k, then print "YES" (without qoutes). Otherwise print "NO" (without qoutes). Examples Input 5 2 NYNNY Output YES Input 6 1 ????NN Output NO Note In the first test Stepan remembers about all the episodes whether he has watched them or not. His dissatisfaction is 2, because he hasn't watch two episodes in a row — the episode number 3 and the episode number 4. The answer is "YES", because k = 2. In the second test k = 1, Stepan's dissatisfaction is greater than or equal to 2 (because he remembers that he hasn't watch at least two episodes in a row — number 5 and number 6), even if he has watched the episodes from the first to the fourth, inclusive. Submitted Solution: ``` n, k = map(int, input().split()) string = input() series = [] now = "" for elem in string: if elem == "Y": if now: series.append(now) now = "" else: now += elem if now: series.append(now) answer = False no_max = True for elem in series: m = len(elem) for i in range(m - k + 1): if (not i or elem[i - 1] == '?') and ((i + k - 1) == m - 1 or elem[i + k] == '?'): answer = True counter = 0 for letter in elem: if letter == 'N': counter += 1 no_max = not counter > k else: counter = 0 print("YES" if answer and no_max else "NO") ``` No
89,788
Provide tags and a correct Python 3 solution for this coding contest problem. After Fox Ciel got off a bus, she found that the bus she was on was a wrong bus and she lost her way in a strange town. However, she fortunately met her friend Beaver Taro and asked which way to go to her castle. Taro's response to her was a string s, and she tried to remember the string s correctly. However, Ciel feels n strings b1, b2, ... , bn are really boring, and unfortunately she dislikes to remember a string that contains a boring substring. To make the thing worse, what she can remember is only the contiguous substring of s. Determine the longest contiguous substring of s that does not contain any boring string, so that she can remember the longest part of Taro's response. Input In the first line there is a string s. The length of s will be between 1 and 105, inclusive. In the second line there is a single integer n (1 ≤ n ≤ 10). Next n lines, there is a string bi (1 ≤ i ≤ n). Each length of bi will be between 1 and 10, inclusive. Each character of the given strings will be either a English alphabet (both lowercase and uppercase) or a underscore ('_') or a digit. Assume that these strings are case-sensitive. Output Output in the first line two space-separated integers len and pos: the length of the longest contiguous substring of s that does not contain any bi, and the first position of the substring (0-indexed). The position pos must be between 0 and |s| - len inclusive, where |s| is the length of string s. If there are several solutions, output any. Examples Input Go_straight_along_this_street 5 str long tree biginteger ellipse Output 12 4 Input IhaveNoIdea 9 I h a v e N o I d Output 0 0 Input unagioisii 2 ioi unagi Output 5 5 Note In the first sample, the solution is traight_alon. In the second sample, the solution is an empty string, so the output can be «0 0», «0 1», «0 2», and so on. In the third sample, the solution is either nagio or oisii. Tags: data structures, dp, greedy, hashing, strings, two pointers Correct Solution: ``` S=str(input()) n=int(input()) b=str(input()) M=[b] m=11 for i in range(n-1): f=0 b=str(input()) for i in range(len(M)): if len(M[i])>=len(b): M=M[:i]+[b]+M[i:] f=1 break if f==0: M+=[b] f=0 L=[] for i in M: f=0 for j in M: if j!=i and j in i: f=1 if f==0: L+=[i] f=0 k=0 p=0 v=0 s=0 for i in range(len(S)): if k==0: s=i for j in L: if S[i:i+len(j)]==j: k+=len(j)-1 if k>p: f=1 p=k v=s k=-1 break k+=1 if f==0 or k>p: p,v=k,s print(p,v) ```
89,789
Provide tags and a correct Python 3 solution for this coding contest problem. After Fox Ciel got off a bus, she found that the bus she was on was a wrong bus and she lost her way in a strange town. However, she fortunately met her friend Beaver Taro and asked which way to go to her castle. Taro's response to her was a string s, and she tried to remember the string s correctly. However, Ciel feels n strings b1, b2, ... , bn are really boring, and unfortunately she dislikes to remember a string that contains a boring substring. To make the thing worse, what she can remember is only the contiguous substring of s. Determine the longest contiguous substring of s that does not contain any boring string, so that she can remember the longest part of Taro's response. Input In the first line there is a string s. The length of s will be between 1 and 105, inclusive. In the second line there is a single integer n (1 ≤ n ≤ 10). Next n lines, there is a string bi (1 ≤ i ≤ n). Each length of bi will be between 1 and 10, inclusive. Each character of the given strings will be either a English alphabet (both lowercase and uppercase) or a underscore ('_') or a digit. Assume that these strings are case-sensitive. Output Output in the first line two space-separated integers len and pos: the length of the longest contiguous substring of s that does not contain any bi, and the first position of the substring (0-indexed). The position pos must be between 0 and |s| - len inclusive, where |s| is the length of string s. If there are several solutions, output any. Examples Input Go_straight_along_this_street 5 str long tree biginteger ellipse Output 12 4 Input IhaveNoIdea 9 I h a v e N o I d Output 0 0 Input unagioisii 2 ioi unagi Output 5 5 Note In the first sample, the solution is traight_alon. In the second sample, the solution is an empty string, so the output can be «0 0», «0 1», «0 2», and so on. In the third sample, the solution is either nagio or oisii. Tags: data structures, dp, greedy, hashing, strings, two pointers Correct Solution: ``` S=str(input()) n=int(input()) b=str(input()) M=[b] m=11 for i in range(n-1): f=0 b=str(input()) for i in range(len(M)): if len(M[i])>=len(b): M=M[:i]+[b]+M[i:] f=1 break if f==0: M+=[b] f=0 L=[] for i in M: f=0 for j in M: if j!=i and j in i: f=1 if f==0: L+=[i] f=0 k=0 p=0 v=0 s=0 for i in range(len(S)): if k==0: s=i for j in L: if S[i:i+len(j)]==j: k+=len(j)-1 if k>p: f=1 p=k v=s k=-1 break k+=1 if f==0 or k>p: p,v=k,s print(p,v) # Made By Mostafa_Khaled ```
89,790
Provide tags and a correct Python 3 solution for this coding contest problem. After Fox Ciel got off a bus, she found that the bus she was on was a wrong bus and she lost her way in a strange town. However, she fortunately met her friend Beaver Taro and asked which way to go to her castle. Taro's response to her was a string s, and she tried to remember the string s correctly. However, Ciel feels n strings b1, b2, ... , bn are really boring, and unfortunately she dislikes to remember a string that contains a boring substring. To make the thing worse, what she can remember is only the contiguous substring of s. Determine the longest contiguous substring of s that does not contain any boring string, so that she can remember the longest part of Taro's response. Input In the first line there is a string s. The length of s will be between 1 and 105, inclusive. In the second line there is a single integer n (1 ≤ n ≤ 10). Next n lines, there is a string bi (1 ≤ i ≤ n). Each length of bi will be between 1 and 10, inclusive. Each character of the given strings will be either a English alphabet (both lowercase and uppercase) or a underscore ('_') or a digit. Assume that these strings are case-sensitive. Output Output in the first line two space-separated integers len and pos: the length of the longest contiguous substring of s that does not contain any bi, and the first position of the substring (0-indexed). The position pos must be between 0 and |s| - len inclusive, where |s| is the length of string s. If there are several solutions, output any. Examples Input Go_straight_along_this_street 5 str long tree biginteger ellipse Output 12 4 Input IhaveNoIdea 9 I h a v e N o I d Output 0 0 Input unagioisii 2 ioi unagi Output 5 5 Note In the first sample, the solution is traight_alon. In the second sample, the solution is an empty string, so the output can be «0 0», «0 1», «0 2», and so on. In the third sample, the solution is either nagio or oisii. Tags: data structures, dp, greedy, hashing, strings, two pointers Correct Solution: ``` import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") ########################################################## from collections import Counter, defaultdict import math for _ in range(1): #n=input() #n,m=map(int, input().split()) #arr =list(map(int, input().split())) #for i in range(n): s= input() data=[] for _ in range(int(input())): data.append(input()) cnt = 0 pos = 0 l = 0 r = 1 length = len(s) while r <= length: found = False size = 0 for sub in data: if (r - l >= len(sub)) and (sub == s[max(l, r - len(sub)):r]): found = True size = max(len(sub), size) # break if not found: r += 1 else: l = r - size + 1 if cnt < r - l - 1: cnt = r - l - 1 pos = l print(cnt, pos) ```
89,791
Provide tags and a correct Python 3 solution for this coding contest problem. After Fox Ciel got off a bus, she found that the bus she was on was a wrong bus and she lost her way in a strange town. However, she fortunately met her friend Beaver Taro and asked which way to go to her castle. Taro's response to her was a string s, and she tried to remember the string s correctly. However, Ciel feels n strings b1, b2, ... , bn are really boring, and unfortunately she dislikes to remember a string that contains a boring substring. To make the thing worse, what she can remember is only the contiguous substring of s. Determine the longest contiguous substring of s that does not contain any boring string, so that she can remember the longest part of Taro's response. Input In the first line there is a string s. The length of s will be between 1 and 105, inclusive. In the second line there is a single integer n (1 ≤ n ≤ 10). Next n lines, there is a string bi (1 ≤ i ≤ n). Each length of bi will be between 1 and 10, inclusive. Each character of the given strings will be either a English alphabet (both lowercase and uppercase) or a underscore ('_') or a digit. Assume that these strings are case-sensitive. Output Output in the first line two space-separated integers len and pos: the length of the longest contiguous substring of s that does not contain any bi, and the first position of the substring (0-indexed). The position pos must be between 0 and |s| - len inclusive, where |s| is the length of string s. If there are several solutions, output any. Examples Input Go_straight_along_this_street 5 str long tree biginteger ellipse Output 12 4 Input IhaveNoIdea 9 I h a v e N o I d Output 0 0 Input unagioisii 2 ioi unagi Output 5 5 Note In the first sample, the solution is traight_alon. In the second sample, the solution is an empty string, so the output can be «0 0», «0 1», «0 2», and so on. In the third sample, the solution is either nagio or oisii. Tags: data structures, dp, greedy, hashing, strings, two pointers Correct Solution: ``` # import functools # # # class Automaton: # def __init__(self, start, ends, transitions): # self.start = start # self.ends = set(ends) # self.transitions = transitions # [dict] # # def next_states(self, states, char): # states = functools.reduce(set.union, (self.transitions[state].get(char, set()) for state in states), set()) # states.add(0) # return states # # def char_keys(self, states): # return functools.reduce(set.union, map(set, (self.transitions[state].keys() for state in states)), set()) # # def okay(self, word): # states = {self.start} # for char in word: # states = self.next_states(states, char) # # return len(states.intersection(self.ends)) > 0 # # def determistic(self): # transitions = [dict() for _ in range(2 ** len(self.transitions) + 1)] # get_id = lambda states: sum(2 ** state for state in states) # start = get_id({0}) # ends = set() # # l = {(0,)} # seen = set() # # while l: # states = set(l.pop()) # seen.add(tuple(states)) # id = get_id(states) # if self.ends.intersection(states): # ends.add(id) # # for char in self.char_keys(states): # transitions[id][char] = self.next_states(states, char) # if not tuple(transitions[id][char]) in seen: # l.add(tuple(transitions[id][char])) # transitions[id][char] = {get_id(transitions[id][char])} # # return Automaton(start, ends, transitions) # # @staticmethod # def suffix_word_automaton(word): # return Automaton( # 0, # {len(word)}, # [{word[i]: {i + 1}} for i in range(len(word))] + [{}], # ) # # @staticmethod # def KMP(word, text): # A = Automaton.suffix_word_automaton(word) # states = {A.start} # # for i, char in enumerate(text): # states = A.next_states(states, char) # if states.intersection(A.ends): # yield i - len(word) + 1 # def KMP(word, text): # r = [0] * (len(word) + 1) # r[0] = -1 # Si la comparaison plante à la comparaison des j-ième lettres, on peut reprendre à partir de r[j] # # j = -1 # for i in range(1, len(word) + 1): # while 0 <= j < len(word) and word[i - 1] != word[j]: # j = r[j] # Si ça plante, on essaie de continuer une sous-chaîne plus petite # # j += 1 # On passe à la lettre suivante # # r[i] = j # # j = 0 # indice de la lettre du mot qu'on est en train de lire # for i in range(len(text)): # while j >= 0 and text[i] != word[j]: # j = r[j] # Idem, si ça plante, on essaie de continuer une sous-chaîne plus petite # # j += 1 # # if j == len(word): # on a fini # yield i - len(word) + 1 # j = r[j] def word_present(words, text, s): for word in words: if word == text[s:s + len(word)]: return word # try: # if False not in (word[i] == text[s + i] for i in range(len(word))): # return word # except: # pass def smallest_ends(words, text): words = list(sorted(words, key=len)) d = [float("inf")] * len(text) for i in range(0, len(text)): word = word_present(words, text, i) if word: # e = (i, i + len(word)) d[i] = min(len(word), d[i]) # for word in words: # for i in KMP(word, text): # d[i] = min(len(word), d[i]) return d if __name__ == '__main__': text = input() n = int(input()) words = [input() for _ in range(n)] ends = smallest_ends(words, text) longuest_starting = [0] * (len(text) + 1) for i in range(len(text) - 1, -1, -1): longuest_starting[i] = min(1 + longuest_starting[i + 1], ends[i] - 1) i_max = max(range(len(text), -1, -1), key=lambda i: longuest_starting[i]) print(longuest_starting[i_max], i_max if longuest_starting[i_max] else 0) ```
89,792
Provide tags and a correct Python 3 solution for this coding contest problem. After Fox Ciel got off a bus, she found that the bus she was on was a wrong bus and she lost her way in a strange town. However, she fortunately met her friend Beaver Taro and asked which way to go to her castle. Taro's response to her was a string s, and she tried to remember the string s correctly. However, Ciel feels n strings b1, b2, ... , bn are really boring, and unfortunately she dislikes to remember a string that contains a boring substring. To make the thing worse, what she can remember is only the contiguous substring of s. Determine the longest contiguous substring of s that does not contain any boring string, so that she can remember the longest part of Taro's response. Input In the first line there is a string s. The length of s will be between 1 and 105, inclusive. In the second line there is a single integer n (1 ≤ n ≤ 10). Next n lines, there is a string bi (1 ≤ i ≤ n). Each length of bi will be between 1 and 10, inclusive. Each character of the given strings will be either a English alphabet (both lowercase and uppercase) or a underscore ('_') or a digit. Assume that these strings are case-sensitive. Output Output in the first line two space-separated integers len and pos: the length of the longest contiguous substring of s that does not contain any bi, and the first position of the substring (0-indexed). The position pos must be between 0 and |s| - len inclusive, where |s| is the length of string s. If there are several solutions, output any. Examples Input Go_straight_along_this_street 5 str long tree biginteger ellipse Output 12 4 Input IhaveNoIdea 9 I h a v e N o I d Output 0 0 Input unagioisii 2 ioi unagi Output 5 5 Note In the first sample, the solution is traight_alon. In the second sample, the solution is an empty string, so the output can be «0 0», «0 1», «0 2», and so on. In the third sample, the solution is either nagio or oisii. Tags: data structures, dp, greedy, hashing, strings, two pointers Correct Solution: ``` s = input() n = int(input()) b = [] for i in range(n): b.append(input()) s_original = s s_dict = {s: 1} for bi in b: while True: new_s_dict = {} for s in s_dict.keys(): part_list = s.split(bi) if len(part_list) <= 1: new_s_dict[s] = 1 continue for i, part in enumerate(part_list): # first if i == 0: new_s_dict[part + bi[:-1]] = 1 # middles if 0 < i < len(part_list) - 1: new_s_dict[bi[1:] + part + bi[:-1]] = 1 # last if i == len(part_list) - 1: new_s_dict[bi[1:] + part] = 1 if s_dict == new_s_dict: break s_dict = new_s_dict max_length = 0 result = "" for s in s_dict.keys(): if max_length < len(s): max_length = len(s) result = s print(max_length, s_original.index(result)) ```
89,793
Provide tags and a correct Python 3 solution for this coding contest problem. After Fox Ciel got off a bus, she found that the bus she was on was a wrong bus and she lost her way in a strange town. However, she fortunately met her friend Beaver Taro and asked which way to go to her castle. Taro's response to her was a string s, and she tried to remember the string s correctly. However, Ciel feels n strings b1, b2, ... , bn are really boring, and unfortunately she dislikes to remember a string that contains a boring substring. To make the thing worse, what she can remember is only the contiguous substring of s. Determine the longest contiguous substring of s that does not contain any boring string, so that she can remember the longest part of Taro's response. Input In the first line there is a string s. The length of s will be between 1 and 105, inclusive. In the second line there is a single integer n (1 ≤ n ≤ 10). Next n lines, there is a string bi (1 ≤ i ≤ n). Each length of bi will be between 1 and 10, inclusive. Each character of the given strings will be either a English alphabet (both lowercase and uppercase) or a underscore ('_') or a digit. Assume that these strings are case-sensitive. Output Output in the first line two space-separated integers len and pos: the length of the longest contiguous substring of s that does not contain any bi, and the first position of the substring (0-indexed). The position pos must be between 0 and |s| - len inclusive, where |s| is the length of string s. If there are several solutions, output any. Examples Input Go_straight_along_this_street 5 str long tree biginteger ellipse Output 12 4 Input IhaveNoIdea 9 I h a v e N o I d Output 0 0 Input unagioisii 2 ioi unagi Output 5 5 Note In the first sample, the solution is traight_alon. In the second sample, the solution is an empty string, so the output can be «0 0», «0 1», «0 2», and so on. In the third sample, the solution is either nagio or oisii. Tags: data structures, dp, greedy, hashing, strings, two pointers Correct Solution: ``` #On récupère les données chaine = input() n = int(input()) all_borings = sorted([input() for _ in range(n)], key=lambda s : len(s)) #On traite un cas particulier à priori pb chaine_uniforme = True; first = chaine[0] for c in chaine: if c != first: chaine_uniforme = False; break; if chaine_uniforme: plus_court = len(chaine) for bi in all_borings: uniforme = True; for c in bi: if c != first: uniforme = False; break; if uniforme: plus_court = len(bi)-1 break print(plus_court, 0) exit(); #On prétraitre borings = [] for s in all_borings: li = len(s)-1 for s2, l2 in borings: pos = s.find(s2); if pos != -1: li = min(li, pos + l2) borings.append((s, li)); ##borings = sorted([input() for _ in range(n)], key=lambda s : len(s)) def allOcc(chaine, s, li, occ): n = 0 prev = -1; while n != len(occ): n = len(occ) pos = chaine.find(s, prev+1) if pos != -1: occ.append((pos, li)) prev = pos return occ prev_pos = -2 def f(pos): global prev_pos; if pos[0] != prev_pos: prev_pos = pos[0] return True; return False; all_occ = [(len(chaine)-1, 1)] [allOcc(chaine, bi, li, all_occ) for bi, li in borings] all_occ.sort() all_pos = [occ for occ in all_occ if f(occ)]; prev = -1 best = 0 best_pos = 0 for pos, li in all_pos: n_len = pos +li - prev - 1 if n_len > best: best = n_len best_pos = prev+1 prev = pos ###Approche dynamique ##length, pos = 0, 0 ##for debut in range(len(chaine)-1, -1, -1): ## n_len = len(chaine) - debut ## for i, bi in enumerate(borings): ## li = len(bi) ## if chaine[debut: debut+li] == bi: ## last_founds[i] = debut; ## if n_len > length: ## long = last_founds[i] + li - 1 - debut ## n_len = min(long, n_len) ## ## if n_len > length: ## length = n_len ## pos = debut print(best, best_pos) ```
89,794
Provide tags and a correct Python 3 solution for this coding contest problem. After Fox Ciel got off a bus, she found that the bus she was on was a wrong bus and she lost her way in a strange town. However, she fortunately met her friend Beaver Taro and asked which way to go to her castle. Taro's response to her was a string s, and she tried to remember the string s correctly. However, Ciel feels n strings b1, b2, ... , bn are really boring, and unfortunately she dislikes to remember a string that contains a boring substring. To make the thing worse, what she can remember is only the contiguous substring of s. Determine the longest contiguous substring of s that does not contain any boring string, so that she can remember the longest part of Taro's response. Input In the first line there is a string s. The length of s will be between 1 and 105, inclusive. In the second line there is a single integer n (1 ≤ n ≤ 10). Next n lines, there is a string bi (1 ≤ i ≤ n). Each length of bi will be between 1 and 10, inclusive. Each character of the given strings will be either a English alphabet (both lowercase and uppercase) or a underscore ('_') or a digit. Assume that these strings are case-sensitive. Output Output in the first line two space-separated integers len and pos: the length of the longest contiguous substring of s that does not contain any bi, and the first position of the substring (0-indexed). The position pos must be between 0 and |s| - len inclusive, where |s| is the length of string s. If there are several solutions, output any. Examples Input Go_straight_along_this_street 5 str long tree biginteger ellipse Output 12 4 Input IhaveNoIdea 9 I h a v e N o I d Output 0 0 Input unagioisii 2 ioi unagi Output 5 5 Note In the first sample, the solution is traight_alon. In the second sample, the solution is an empty string, so the output can be «0 0», «0 1», «0 2», and so on. In the third sample, the solution is either nagio or oisii. Tags: data structures, dp, greedy, hashing, strings, two pointers Correct Solution: ``` s, n = input(), int(input()) t = [input() for i in range(n)] def f(i): global t for j in range(n): if i < j: if len(t[j]) < len(t[i]) and t[j] in t[i]: return False elif j < i and t[j] in t[i]: return False return True t = [t[i] for i in range(n) if f(i)] n = len(s) r = [0] * n for p in t: i, m = -1, len(p) - 1 while True: i = s.find(p, i + 1) if i == -1: break r[i] += 1 r[i + m] += 2 d, j, q = 0, -1, [-1] for i in range(n): if r[i] & 1: q.append(i) if r[i] & 2: j = q.pop(0) if i - j > d: d, k = i - j, j j = q.pop(0) if n - j > d: d, k = n - j, j print(d - 1, k + 1) ```
89,795
Provide tags and a correct Python 3 solution for this coding contest problem. After Fox Ciel got off a bus, she found that the bus she was on was a wrong bus and she lost her way in a strange town. However, she fortunately met her friend Beaver Taro and asked which way to go to her castle. Taro's response to her was a string s, and she tried to remember the string s correctly. However, Ciel feels n strings b1, b2, ... , bn are really boring, and unfortunately she dislikes to remember a string that contains a boring substring. To make the thing worse, what she can remember is only the contiguous substring of s. Determine the longest contiguous substring of s that does not contain any boring string, so that she can remember the longest part of Taro's response. Input In the first line there is a string s. The length of s will be between 1 and 105, inclusive. In the second line there is a single integer n (1 ≤ n ≤ 10). Next n lines, there is a string bi (1 ≤ i ≤ n). Each length of bi will be between 1 and 10, inclusive. Each character of the given strings will be either a English alphabet (both lowercase and uppercase) or a underscore ('_') or a digit. Assume that these strings are case-sensitive. Output Output in the first line two space-separated integers len and pos: the length of the longest contiguous substring of s that does not contain any bi, and the first position of the substring (0-indexed). The position pos must be between 0 and |s| - len inclusive, where |s| is the length of string s. If there are several solutions, output any. Examples Input Go_straight_along_this_street 5 str long tree biginteger ellipse Output 12 4 Input IhaveNoIdea 9 I h a v e N o I d Output 0 0 Input unagioisii 2 ioi unagi Output 5 5 Note In the first sample, the solution is traight_alon. In the second sample, the solution is an empty string, so the output can be «0 0», «0 1», «0 2», and so on. In the third sample, the solution is either nagio or oisii. Tags: data structures, dp, greedy, hashing, strings, two pointers Correct Solution: ``` R = lambda : map(int, input().split()) s = input() n = int(input()) words = [input() for i in range(n)] dp = [-1] * len(s) for w in words: si = 0 while si != -1: si = s.find(w, si) if si >= 0: dp[si + len(w) - 1] = max(si + 1, dp[si + len(w) - 1]) si += 1 fl = 0 fr = 0 l = 0 found = False for r in range(len(s)): if dp[r] >= 0: l = max(l, dp[r]) if r - l >= fr - fl: found = True fl, fr = l, r print(fr - fl + found, fl) ```
89,796
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. After Fox Ciel got off a bus, she found that the bus she was on was a wrong bus and she lost her way in a strange town. However, she fortunately met her friend Beaver Taro and asked which way to go to her castle. Taro's response to her was a string s, and she tried to remember the string s correctly. However, Ciel feels n strings b1, b2, ... , bn are really boring, and unfortunately she dislikes to remember a string that contains a boring substring. To make the thing worse, what she can remember is only the contiguous substring of s. Determine the longest contiguous substring of s that does not contain any boring string, so that she can remember the longest part of Taro's response. Input In the first line there is a string s. The length of s will be between 1 and 105, inclusive. In the second line there is a single integer n (1 ≤ n ≤ 10). Next n lines, there is a string bi (1 ≤ i ≤ n). Each length of bi will be between 1 and 10, inclusive. Each character of the given strings will be either a English alphabet (both lowercase and uppercase) or a underscore ('_') or a digit. Assume that these strings are case-sensitive. Output Output in the first line two space-separated integers len and pos: the length of the longest contiguous substring of s that does not contain any bi, and the first position of the substring (0-indexed). The position pos must be between 0 and |s| - len inclusive, where |s| is the length of string s. If there are several solutions, output any. Examples Input Go_straight_along_this_street 5 str long tree biginteger ellipse Output 12 4 Input IhaveNoIdea 9 I h a v e N o I d Output 0 0 Input unagioisii 2 ioi unagi Output 5 5 Note In the first sample, the solution is traight_alon. In the second sample, the solution is an empty string, so the output can be «0 0», «0 1», «0 2», and so on. In the third sample, the solution is either nagio or oisii. Submitted Solution: ``` #------------------------template--------------------------# import os import sys # from math import * from collections import * # from fractions import * # from heapq import* from bisect import * from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") ALPHA='abcdefghijklmnopqrstuvwxyz' M=10**9+7 EPS=1e-6 def Ceil(a,b): return a//b+int(a%b>0) def value():return tuple(map(int,input().split())) def array():return [int(i) for i in input().split()] def Int():return int(input()) def Str():return input() def arrayS():return [i for i in input().split()] #-------------------------code---------------------------# # vsInput() def check(start,end): # print(s[start:end],start,end) here='' c=0 while(end>=start and c<10): here+=s[end] end-=1 c+=1 if(here in have): return end+1 return -1 s=input() n=len(s) m=Int() have=set() for i in range(m): have.add(input()[::-1]) ans=(0,0) i=0 while(i<n): pos=i l=0 while(i<n and check(pos,i)==-1): l+=1 i+=1 if(l>ans[1]): ans=(pos,l) if(i==n):break i=check(pos,i)+1 print(*ans[::-1]) ``` Yes
89,797
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. After Fox Ciel got off a bus, she found that the bus she was on was a wrong bus and she lost her way in a strange town. However, she fortunately met her friend Beaver Taro and asked which way to go to her castle. Taro's response to her was a string s, and she tried to remember the string s correctly. However, Ciel feels n strings b1, b2, ... , bn are really boring, and unfortunately she dislikes to remember a string that contains a boring substring. To make the thing worse, what she can remember is only the contiguous substring of s. Determine the longest contiguous substring of s that does not contain any boring string, so that she can remember the longest part of Taro's response. Input In the first line there is a string s. The length of s will be between 1 and 105, inclusive. In the second line there is a single integer n (1 ≤ n ≤ 10). Next n lines, there is a string bi (1 ≤ i ≤ n). Each length of bi will be between 1 and 10, inclusive. Each character of the given strings will be either a English alphabet (both lowercase and uppercase) or a underscore ('_') or a digit. Assume that these strings are case-sensitive. Output Output in the first line two space-separated integers len and pos: the length of the longest contiguous substring of s that does not contain any bi, and the first position of the substring (0-indexed). The position pos must be between 0 and |s| - len inclusive, where |s| is the length of string s. If there are several solutions, output any. Examples Input Go_straight_along_this_street 5 str long tree biginteger ellipse Output 12 4 Input IhaveNoIdea 9 I h a v e N o I d Output 0 0 Input unagioisii 2 ioi unagi Output 5 5 Note In the first sample, the solution is traight_alon. In the second sample, the solution is an empty string, so the output can be «0 0», «0 1», «0 2», and so on. In the third sample, the solution is either nagio or oisii. Submitted Solution: ``` #On récupère les données chaine = input() n = int(input()) all_borings = sorted([input() for _ in range(n)], key=lambda s : len(s)) #On prétraitre borings = [] for s in all_borings: li = len(s)-1 for s2, l2 in borings: pos = s.find(s2); if pos != -1: li = pos + l2 borings.append((s, li)); ##borings = sorted([input() for _ in range(n)], key=lambda s : len(s)) def allOcc(chaine, s, li, occ): n = 0 prev = -1; print(s) while n != len(occ): n = len(occ) pos = chaine.find(s, prev+1) if pos != -1: occ.append((pos, li)) prev = pos print(" ", pos, li) return occ prev_pos = -2 def f(pos): global prev_pos; if pos[0] != prev_pos: prev_pos = pos[0] return True; return False; all_occ = [(len(chaine)-1, 2)] [allOcc(chaine, bi, li, all_occ) for bi, li in borings] all_occ.sort() all_pos = [occ for occ in all_occ if f(occ)]; print(all_pos) prev = -1 best = 0 best_pos = 0 for pos, li in all_pos: n_len = pos +li - prev - 2 print(n_len, prev+1) if n_len > best: best = n_len best_pos = prev+1 prev = pos ###Approche dynamique ##length, pos = 0, 0 ##for debut in range(len(chaine)-1, -1, -1): ## n_len = len(chaine) - debut ## for i, bi in enumerate(borings): ## li = len(bi) ## if chaine[debut: debut+li] == bi: ## last_founds[i] = debut; ## if n_len > length: ## long = last_founds[i] + li - 1 - debut ## n_len = min(long, n_len) ## ## if n_len > length: ## length = n_len ## pos = debut print(best, best_pos) ``` No
89,798
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. After Fox Ciel got off a bus, she found that the bus she was on was a wrong bus and she lost her way in a strange town. However, she fortunately met her friend Beaver Taro and asked which way to go to her castle. Taro's response to her was a string s, and she tried to remember the string s correctly. However, Ciel feels n strings b1, b2, ... , bn are really boring, and unfortunately she dislikes to remember a string that contains a boring substring. To make the thing worse, what she can remember is only the contiguous substring of s. Determine the longest contiguous substring of s that does not contain any boring string, so that she can remember the longest part of Taro's response. Input In the first line there is a string s. The length of s will be between 1 and 105, inclusive. In the second line there is a single integer n (1 ≤ n ≤ 10). Next n lines, there is a string bi (1 ≤ i ≤ n). Each length of bi will be between 1 and 10, inclusive. Each character of the given strings will be either a English alphabet (both lowercase and uppercase) or a underscore ('_') or a digit. Assume that these strings are case-sensitive. Output Output in the first line two space-separated integers len and pos: the length of the longest contiguous substring of s that does not contain any bi, and the first position of the substring (0-indexed). The position pos must be between 0 and |s| - len inclusive, where |s| is the length of string s. If there are several solutions, output any. Examples Input Go_straight_along_this_street 5 str long tree biginteger ellipse Output 12 4 Input IhaveNoIdea 9 I h a v e N o I d Output 0 0 Input unagioisii 2 ioi unagi Output 5 5 Note In the first sample, the solution is traight_alon. In the second sample, the solution is an empty string, so the output can be «0 0», «0 1», «0 2», and so on. In the third sample, the solution is either nagio or oisii. Submitted Solution: ``` s, n = input(), int(input()) t = [input() for i in range(n)] def g(i): global t for j in range(n): if i != j and len(t[i]) > len(t[j]): if t[j] in t[i]: return False return True t = [t[i] for i in range(n) if g(i)] def f(i): global s, t k = len(s) - i for p in t: if len(p) < k and all(c == s[j] for j, c in enumerate(p, i)): return i + len(p) return 0 u, n = 2, len(s) v = k = -1 for i in range(n): j = f(i) if j: if j - k > u: u, v = j - k, k k = i j = n + 1 if j - k > u: u, v = j - k, k print(u - 2, v + 1) ``` No
89,799