text
stringlengths
198
433k
conversation_id
int64
0
109k
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Luke Skywalker got locked up in a rubbish shredder between two presses. R2D2 is already working on his rescue, but Luke needs to stay alive as long as possible. For simplicity we will assume that everything happens on a straight line, the presses are initially at coordinates 0 and L, and they move towards each other with speed v1 and v2, respectively. Luke has width d and is able to choose any position between the presses. Luke dies as soon as the distance between the presses is less than his width. Your task is to determine for how long Luke can stay alive. Input The first line of the input contains four integers d, L, v1, v2 (1 ≀ d, L, v1, v2 ≀ 10 000, d < L) β€” Luke's width, the initial position of the second press and the speed of the first and second presses, respectively. Output Print a single real value β€” the maximum period of time Luke can stay alive for. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 2 6 2 2 Output 1.00000000000000000000 Input 1 9 1 2 Output 2.66666666666666650000 Note In the first sample Luke should stay exactly in the middle of the segment, that is at coordinates [2;4], as the presses move with the same speed. In the second sample he needs to occupy the position <image>. In this case both presses move to his edges at the same time. Submitted Solution: ``` d,l,v1,v2=map(int,input().split());count=0;left=0;right=l while d < abs(left-right): left=left+v1;right=right-v2 count+=1 print(count) ``` No
95,700
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Luke Skywalker got locked up in a rubbish shredder between two presses. R2D2 is already working on his rescue, but Luke needs to stay alive as long as possible. For simplicity we will assume that everything happens on a straight line, the presses are initially at coordinates 0 and L, and they move towards each other with speed v1 and v2, respectively. Luke has width d and is able to choose any position between the presses. Luke dies as soon as the distance between the presses is less than his width. Your task is to determine for how long Luke can stay alive. Input The first line of the input contains four integers d, L, v1, v2 (1 ≀ d, L, v1, v2 ≀ 10 000, d < L) β€” Luke's width, the initial position of the second press and the speed of the first and second presses, respectively. Output Print a single real value β€” the maximum period of time Luke can stay alive for. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 2 6 2 2 Output 1.00000000000000000000 Input 1 9 1 2 Output 2.66666666666666650000 Note In the first sample Luke should stay exactly in the middle of the segment, that is at coordinates [2;4], as the presses move with the same speed. In the second sample he needs to occupy the position <image>. In this case both presses move to his edges at the same time. Submitted Solution: ``` width, right, v1, v2=map(int, input().split()) left=0;t=0 d=right-left while d>=width: right-=v2;left+=v1 d=right-left if d<width: break t+=1 print(t) ``` No
95,701
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Luke Skywalker got locked up in a rubbish shredder between two presses. R2D2 is already working on his rescue, but Luke needs to stay alive as long as possible. For simplicity we will assume that everything happens on a straight line, the presses are initially at coordinates 0 and L, and they move towards each other with speed v1 and v2, respectively. Luke has width d and is able to choose any position between the presses. Luke dies as soon as the distance between the presses is less than his width. Your task is to determine for how long Luke can stay alive. Input The first line of the input contains four integers d, L, v1, v2 (1 ≀ d, L, v1, v2 ≀ 10 000, d < L) β€” Luke's width, the initial position of the second press and the speed of the first and second presses, respectively. Output Print a single real value β€” the maximum period of time Luke can stay alive for. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 2 6 2 2 Output 1.00000000000000000000 Input 1 9 1 2 Output 2.66666666666666650000 Note In the first sample Luke should stay exactly in the middle of the segment, that is at coordinates [2;4], as the presses move with the same speed. In the second sample he needs to occupy the position <image>. In this case both presses move to his edges at the same time. Submitted Solution: ``` a=input().split() b=int(a[1])-int(a[0]) c=int(a[2])+int(a[3]) print(c/b) ``` No
95,702
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. After getting kicked out of her reporting job for not knowing the alphabet, Bessie has decided to attend school at the Fillet and Eggs Eater Academy. She has been making good progress with her studies and now knows the first k English letters. Each morning, Bessie travels to school along a sidewalk consisting of m + n tiles. In order to help Bessie review, Mr. Moozing has labeled each of the first m sidewalk tiles with one of the first k lowercase English letters, spelling out a string t. Mr. Moozing, impressed by Bessie's extensive knowledge of farm animals, plans to let her finish labeling the last n tiles of the sidewalk by herself. Consider the resulting string s (|s| = m + n) consisting of letters labeled on tiles in order from home to school. For any sequence of indices p1 < p2 < ... < pq we can define subsequence of the string s as string sp1sp2... spq. Two subsequences are considered to be distinct if they differ as strings. Bessie wants to label the remaining part of the sidewalk such that the number of distinct subsequences of tiles is maximum possible. However, since Bessie hasn't even finished learning the alphabet, she needs your help! Note that empty subsequence also counts. Input The first line of the input contains two integers n and k (0 ≀ n ≀ 1 000 000, 1 ≀ k ≀ 26). The second line contains a string t (|t| = m, 1 ≀ m ≀ 1 000 000) consisting of only first k lowercase English letters. Output Determine the maximum number of distinct subsequences Bessie can form after labeling the last n sidewalk tiles each with one of the first k lowercase English letters. Since this number can be rather large, you should print it modulo 109 + 7. Please note, that you are not asked to maximize the remainder modulo 109 + 7! The goal is to maximize the initial value and then print the remainder. Examples Input 1 3 ac Output 8 Input 0 2 aaba Output 10 Note In the first sample, the optimal labeling gives 8 different subsequences: "" (the empty string), "a", "c", "b", "ac", "ab", "cb", and "acb". <image> In the second sample, the entire sidewalk is already labeled. The are 10 possible different subsequences: "" (the empty string), "a", "b", "aa", "ab", "ba", "aaa", "aab", "aba", and "aaba". Note that some strings, including "aa", can be obtained with multiple sequences of tiles, but are only counted once. Submitted Solution: ``` import operator s = list(map(int,input().split())) n = s[0] k = s[1] s = input() base = 10 ** 9 + 7 start = ord('a') substrings = [0 for i in range(k + 1)] heap = [[i,0] for i in range(k)] substrings[k] = 1 def Insert(heap, size, number, comparator = operator.lt): heap[size] = number i = size while True: if i == 0 or comparator(heap[(i + 1) // 2 - 1], heap[i]): break else: heap[i], heap[(i + 1) // 2 - 1] = heap[(i + 1) // 2 - 1], heap[i] i = (i + 1) // 2 - 1 def Extract(heap, size, comparator = operator.lt): result = heap[0] heap[0] = heap[size - 1] size -= 1 i = 0 while True: if (i + 1) * 2 - 1 > size: break else: if comparator(heap[i], heap[(i + 1) * 2 - 1]): if (i + 1) * 2 > size or comparator(heap[i], heap[(i + 1) * 2]): break else: heap[i], heap[(i + 1) * 2] = heap[(i + 1) * 2], heap[i] i = (i + 1) * 2 else: if (i + 1) * 2 > size or comparator(heap[i], heap[(i + 1) * 2]): heap[i], heap[(i + 1) * 2 - 1] = heap[(i + 1) * 2 - 1], heap[i] i = (i + 1) * 2 - 1 else: if comparator(heap[(i + 1) * 2 - 1], heap[(i + 1) * 2]): heap[i], heap[(i + 1) * 2 - 1] = heap[(i + 1) * 2 - 1], heap[i] i = (i + 1) * 2 - 1 else: heap[i], heap[(i + 1) * 2] = heap[(i + 1) * 2], heap[i] i = (i + 1) * 2 return result if n == 1000000: for i in range(n): i += 1 else: for c in s: num = ord(c) - start new = substrings[k] - substrings[num] substrings[num] = substrings[k] substrings[k] += new for i in range(k): Insert(heap, i, [i, substrings[i]], lambda x, y: x[1] < y[1]) num_cicles = n // k for i in range(n): num_val = Extract(heap, k, lambda x, y: x[1] < y[1]) new = substrings[k] - num_val[1] substrings[num_val[0]] = substrings[k] substrings[k] += new substrings[k] %= base Insert(heap, k - 1, [num_val[0], substrings[num_val[0]]], lambda x, y: x[1] < y[1]) print(substrings[k] % base) ``` No
95,703
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. After getting kicked out of her reporting job for not knowing the alphabet, Bessie has decided to attend school at the Fillet and Eggs Eater Academy. She has been making good progress with her studies and now knows the first k English letters. Each morning, Bessie travels to school along a sidewalk consisting of m + n tiles. In order to help Bessie review, Mr. Moozing has labeled each of the first m sidewalk tiles with one of the first k lowercase English letters, spelling out a string t. Mr. Moozing, impressed by Bessie's extensive knowledge of farm animals, plans to let her finish labeling the last n tiles of the sidewalk by herself. Consider the resulting string s (|s| = m + n) consisting of letters labeled on tiles in order from home to school. For any sequence of indices p1 < p2 < ... < pq we can define subsequence of the string s as string sp1sp2... spq. Two subsequences are considered to be distinct if they differ as strings. Bessie wants to label the remaining part of the sidewalk such that the number of distinct subsequences of tiles is maximum possible. However, since Bessie hasn't even finished learning the alphabet, she needs your help! Note that empty subsequence also counts. Input The first line of the input contains two integers n and k (0 ≀ n ≀ 1 000 000, 1 ≀ k ≀ 26). The second line contains a string t (|t| = m, 1 ≀ m ≀ 1 000 000) consisting of only first k lowercase English letters. Output Determine the maximum number of distinct subsequences Bessie can form after labeling the last n sidewalk tiles each with one of the first k lowercase English letters. Since this number can be rather large, you should print it modulo 109 + 7. Please note, that you are not asked to maximize the remainder modulo 109 + 7! The goal is to maximize the initial value and then print the remainder. Examples Input 1 3 ac Output 8 Input 0 2 aaba Output 10 Note In the first sample, the optimal labeling gives 8 different subsequences: "" (the empty string), "a", "c", "b", "ac", "ab", "cb", and "acb". <image> In the second sample, the entire sidewalk is already labeled. The are 10 possible different subsequences: "" (the empty string), "a", "b", "aa", "ab", "ba", "aaa", "aab", "aba", and "aaba". Note that some strings, including "aa", can be obtained with multiple sequences of tiles, but are only counted once. Submitted Solution: ``` s = list(map(int,input().split())) n = s[0] k = s[1] s = input() m = len(s) start = ord('a') substrings = [0] * (k + 1) substrings[k] = 1 for i in range (m): num = ord(s[i]) - start new = substrings[k] - substrings[num] substrings[k] = (substrings[k] + new) % (10 ^ 9 + 7) substrings[num] = (substrings[num] + new) % (10 ^ 9 + 7) for i in range (n): min_in = 0 for j in range(k): if substrings[min_in] > substrings[j]: min_in = j num = min_in new = substrings[k] - substrings[num] substrings[k] = (substrings[k] + new) % (10 ^ 9 + 7) substrings[num] = (substrings[num] + new) % (10 ^ 9 + 7) print(substrings[k]) ``` No
95,704
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. After getting kicked out of her reporting job for not knowing the alphabet, Bessie has decided to attend school at the Fillet and Eggs Eater Academy. She has been making good progress with her studies and now knows the first k English letters. Each morning, Bessie travels to school along a sidewalk consisting of m + n tiles. In order to help Bessie review, Mr. Moozing has labeled each of the first m sidewalk tiles with one of the first k lowercase English letters, spelling out a string t. Mr. Moozing, impressed by Bessie's extensive knowledge of farm animals, plans to let her finish labeling the last n tiles of the sidewalk by herself. Consider the resulting string s (|s| = m + n) consisting of letters labeled on tiles in order from home to school. For any sequence of indices p1 < p2 < ... < pq we can define subsequence of the string s as string sp1sp2... spq. Two subsequences are considered to be distinct if they differ as strings. Bessie wants to label the remaining part of the sidewalk such that the number of distinct subsequences of tiles is maximum possible. However, since Bessie hasn't even finished learning the alphabet, she needs your help! Note that empty subsequence also counts. Input The first line of the input contains two integers n and k (0 ≀ n ≀ 1 000 000, 1 ≀ k ≀ 26). The second line contains a string t (|t| = m, 1 ≀ m ≀ 1 000 000) consisting of only first k lowercase English letters. Output Determine the maximum number of distinct subsequences Bessie can form after labeling the last n sidewalk tiles each with one of the first k lowercase English letters. Since this number can be rather large, you should print it modulo 109 + 7. Please note, that you are not asked to maximize the remainder modulo 109 + 7! The goal is to maximize the initial value and then print the remainder. Examples Input 1 3 ac Output 8 Input 0 2 aaba Output 10 Note In the first sample, the optimal labeling gives 8 different subsequences: "" (the empty string), "a", "c", "b", "ac", "ab", "cb", and "acb". <image> In the second sample, the entire sidewalk is already labeled. The are 10 possible different subsequences: "" (the empty string), "a", "b", "aa", "ab", "ba", "aaa", "aab", "aba", and "aaba". Note that some strings, including "aa", can be obtained with multiple sequences of tiles, but are only counted once. Submitted Solution: ``` import operator s = list(map(int,input().split())) n = s[0] k = s[1] s = input() base = 10 ** 9 + 7 start = ord('a') substrings = [0 for i in range(k + 1)] heap = [[i,0] for i in range(k)] substrings[k] = 1 def Insert(heap, size, number, comparator = operator.lt): heap[size] = number i = size while True: if i == 0 or comparator(heap[(i + 1) // 2 - 1], heap[i]): break else: heap[i], heap[(i + 1) // 2 - 1] = heap[(i + 1) // 2 - 1], heap[i] i = (i + 1) // 2 - 1 def Extract(heap, size, comparator = operator.lt): result = heap[0] heap[0] = heap[size - 1] size -= 1 i = 0 while True: if (i + 1) * 2 - 1 > size: break else: if comparator(heap[i], heap[(i + 1) * 2 - 1]): if (i + 1) * 2 > size or comparator(heap[i], heap[(i + 1) * 2]): break else: heap[i], heap[(i + 1) * 2] = heap[(i + 1) * 2], heap[i] i = (i + 1) * 2 else: if (i + 1) * 2 > size or comparator(heap[i], heap[(i + 1) * 2]): heap[i], heap[(i + 1) * 2 - 1] = heap[(i + 1) * 2 - 1], heap[i] i = (i + 1) * 2 - 1 else: if comparator(heap[(i + 1) * 2 - 1], heap[(i + 1) * 2]): heap[i], heap[(i + 1) * 2 - 1] = heap[(i + 1) * 2 - 1], heap[i] i = (i + 1) * 2 - 1 else: heap[i], heap[(i + 1) * 2] = heap[(i + 1) * 2], heap[i] i = (i + 1) * 2 return result for c in s: num = ord(c) - start new = substrings[k] - substrings[num] substrings[num] = substrings[k] substrings[k] += new substrings[k] %= base for i in range(k): Insert(heap, i, [i, substrings[i]], lambda x, y: x[1] < y[1]) num_cicles = n // k if n != 1000000: for i in range(n): num_val = Extract(heap, k, lambda x, y: x[1] < y[1]) new = substrings[k] - num_val[1] substrings[num_val[0]] = substrings[k] substrings[k] += new substrings[k] %= base Insert(heap, k - 1, [num_val[0], substrings[num_val[0]]], lambda x, y: x[1] < y[1]) print(substrings[k] % base) ``` No
95,705
Provide tags and a correct Python 3 solution for this coding contest problem. It was recycling day in Kekoland. To celebrate it Adil and Bera went to Central Perk where they can take bottles from the ground and put them into a recycling bin. We can think Central Perk as coordinate plane. There are n bottles on the ground, the i-th bottle is located at position (xi, yi). Both Adil and Bera can carry only one bottle at once each. For both Adil and Bera the process looks as follows: 1. Choose to stop or to continue to collect bottles. 2. If the choice was to continue then choose some bottle and walk towards it. 3. Pick this bottle and walk to the recycling bin. 4. Go to step 1. Adil and Bera may move independently. They are allowed to pick bottles simultaneously, all bottles may be picked by any of the two, it's allowed that one of them stays still while the other one continues to pick bottles. They want to organize the process such that the total distance they walk (the sum of distance walked by Adil and distance walked by Bera) is minimum possible. Of course, at the end all bottles should lie in the recycling bin. Input First line of the input contains six integers ax, ay, bx, by, tx and ty (0 ≀ ax, ay, bx, by, tx, ty ≀ 109) β€” initial positions of Adil, Bera and recycling bin respectively. The second line contains a single integer n (1 ≀ n ≀ 100 000) β€” the number of bottles on the ground. Then follow n lines, each of them contains two integers xi and yi (0 ≀ xi, yi ≀ 109) β€” position of the i-th bottle. It's guaranteed that positions of Adil, Bera, recycling bin and all bottles are distinct. Output Print one real number β€” the minimum possible total distance Adil and Bera need to walk in order to put all bottles into recycling bin. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if <image>. Examples Input 3 1 1 2 0 0 3 1 1 2 1 2 3 Output 11.084259940083 Input 5 0 4 2 2 0 5 5 2 3 0 5 5 3 5 3 3 Output 33.121375178000 Note Consider the first sample. Adil will use the following path: <image>. Bera will use the following path: <image>. Adil's path will be <image> units long, while Bera's path will be <image> units long. Tags: dp, geometry, greedy, implementation Correct Solution: ``` ax,ay,bx,by,tx,ty=map(int,input().split()) n=int(input()) l=[tuple(map(int,input().split())) for _ in range(n)] a,b=[],[] for i in range(n): x,y=l[i] lt=((tx-x)*(tx-x)+(ty-y)*(ty-y))**0.5 la=((ax-x)*(ax-x)+(ay-y)*(ay-y))**0.5 lb=((bx-x)*(bx-x)+(by-y)*(by-y))**0.5 a+=[(la-lt,i)] b+=[(lb-lt,i)] a.sort();b.sort() if a[0][1]==b[0][1] and n>1: ans=min(a[0][0],b[0][0],a[0][0]+b[1][0],a[1][0]+b[0][0]) else: if a[0][1]==b[0][1]: ans=min(a[0][0],b[0][0]) else: ans=min(a[0][0],b[0][0],a[0][0]+b[0][0]) for i in range(n): x,y=l[i] lt=((tx-x)*(tx-x)+(ty-y)*(ty-y))**0.5 ans+=lt+lt print(ans) ```
95,706
Provide tags and a correct Python 3 solution for this coding contest problem. It was recycling day in Kekoland. To celebrate it Adil and Bera went to Central Perk where they can take bottles from the ground and put them into a recycling bin. We can think Central Perk as coordinate plane. There are n bottles on the ground, the i-th bottle is located at position (xi, yi). Both Adil and Bera can carry only one bottle at once each. For both Adil and Bera the process looks as follows: 1. Choose to stop or to continue to collect bottles. 2. If the choice was to continue then choose some bottle and walk towards it. 3. Pick this bottle and walk to the recycling bin. 4. Go to step 1. Adil and Bera may move independently. They are allowed to pick bottles simultaneously, all bottles may be picked by any of the two, it's allowed that one of them stays still while the other one continues to pick bottles. They want to organize the process such that the total distance they walk (the sum of distance walked by Adil and distance walked by Bera) is minimum possible. Of course, at the end all bottles should lie in the recycling bin. Input First line of the input contains six integers ax, ay, bx, by, tx and ty (0 ≀ ax, ay, bx, by, tx, ty ≀ 109) β€” initial positions of Adil, Bera and recycling bin respectively. The second line contains a single integer n (1 ≀ n ≀ 100 000) β€” the number of bottles on the ground. Then follow n lines, each of them contains two integers xi and yi (0 ≀ xi, yi ≀ 109) β€” position of the i-th bottle. It's guaranteed that positions of Adil, Bera, recycling bin and all bottles are distinct. Output Print one real number β€” the minimum possible total distance Adil and Bera need to walk in order to put all bottles into recycling bin. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if <image>. Examples Input 3 1 1 2 0 0 3 1 1 2 1 2 3 Output 11.084259940083 Input 5 0 4 2 2 0 5 5 2 3 0 5 5 3 5 3 3 Output 33.121375178000 Note Consider the first sample. Adil will use the following path: <image>. Bera will use the following path: <image>. Adil's path will be <image> units long, while Bera's path will be <image> units long. Tags: dp, geometry, greedy, implementation Correct Solution: ``` def glen(x1,y1,x2,y2): return ((x1-x2)**2+(y1-y2)**2)**0.5 xa, ya, xb, yb, xt, yt = map(int,input().split()) n = int(input()) x = [0]*n y = [0]*n for i in range(n): x[i], y[i] = map(int,input().split()) inf = 10**10 afmin = [0, 0] asmin = [0, 0] for i in range(n): a = glen(xa,ya,x[i],y[i])-glen(xa,ya,xt,yt)-glen(xt,yt,x[i],y[i]) if asmin[0] > a: asmin[0] = a asmin[1] = i if asmin[0] < afmin[0]: asmin,afmin = afmin, asmin bfmin = [0, 0] bsmin = [0, 0] for i in range(n): b = glen(xb,yb,x[i],y[i])-glen(xb,yb,xt,yt)-glen(xt,yt,x[i],y[i]) if bsmin[0] > b: bsmin[0] = b bsmin[1] = i if bsmin[0] < bfmin[0]: bsmin,bfmin = bfmin, bsmin res = 0 b = bfmin[1] a = afmin[1] b1 = bsmin[1] a1 = asmin[1] res1 = min(glen(x[a], y[a], xa, ya) - glen(x[a],y[a],xt,yt), glen(x[b], y[b], xb, yb) - glen(x[b],y[b],xt,yt)) if b != a: res += glen(x[a], y[a], xa, ya) - glen(x[a],y[a],xt,yt) res += glen(x[b], y[b], xb, yb) - glen(x[b],y[b],xt,yt) else: res += min(glen(x[a], y[a], xa, ya) - glen(x[a],y[a],xt,yt) + glen(x[b1], y[b1], xb, yb) - glen(x[b1],y[b1],xt,yt), glen(x[a1], y[a1], xa, ya) - glen(x[a],y[a],xt,yt) + glen(x[b], y[b], xb, yb) - glen(x[b1],y[b1],xt,yt)) for i in range(n): res += 2*glen(xt,yt,x[i],y[i]) res1 += 2*glen(xt,yt,x[i],y[i]) if n == 1: res = 10**11 print(min(res, res1)) ```
95,707
Provide tags and a correct Python 3 solution for this coding contest problem. It was recycling day in Kekoland. To celebrate it Adil and Bera went to Central Perk where they can take bottles from the ground and put them into a recycling bin. We can think Central Perk as coordinate plane. There are n bottles on the ground, the i-th bottle is located at position (xi, yi). Both Adil and Bera can carry only one bottle at once each. For both Adil and Bera the process looks as follows: 1. Choose to stop or to continue to collect bottles. 2. If the choice was to continue then choose some bottle and walk towards it. 3. Pick this bottle and walk to the recycling bin. 4. Go to step 1. Adil and Bera may move independently. They are allowed to pick bottles simultaneously, all bottles may be picked by any of the two, it's allowed that one of them stays still while the other one continues to pick bottles. They want to organize the process such that the total distance they walk (the sum of distance walked by Adil and distance walked by Bera) is minimum possible. Of course, at the end all bottles should lie in the recycling bin. Input First line of the input contains six integers ax, ay, bx, by, tx and ty (0 ≀ ax, ay, bx, by, tx, ty ≀ 109) β€” initial positions of Adil, Bera and recycling bin respectively. The second line contains a single integer n (1 ≀ n ≀ 100 000) β€” the number of bottles on the ground. Then follow n lines, each of them contains two integers xi and yi (0 ≀ xi, yi ≀ 109) β€” position of the i-th bottle. It's guaranteed that positions of Adil, Bera, recycling bin and all bottles are distinct. Output Print one real number β€” the minimum possible total distance Adil and Bera need to walk in order to put all bottles into recycling bin. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if <image>. Examples Input 3 1 1 2 0 0 3 1 1 2 1 2 3 Output 11.084259940083 Input 5 0 4 2 2 0 5 5 2 3 0 5 5 3 5 3 3 Output 33.121375178000 Note Consider the first sample. Adil will use the following path: <image>. Bera will use the following path: <image>. Adil's path will be <image> units long, while Bera's path will be <image> units long. Tags: dp, geometry, greedy, implementation Correct Solution: ``` read = lambda : map(int, input().split()) def dis(x1, y1, x2, y2): return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5 ax, ay, bx, by, tx, ty = read() n = int(input()) a, b = [], [] sum = 0 for i in range(n): x, y = read() dist = dis(tx, ty, x, y) a.append((dis(ax, ay, x, y) - dist, i)) b.append((dis(bx, by, x, y) - dist, i)) sum += dist * 2 a.sort() b.sort() if n > 1 and a[0][1] == b[0][1]: ans = min(a[0][0], b[0][0], a[0][0] + b[1][0], a[1][0] + b[0][0]) else: ans = min(a[0][0], b[0][0]) if (n > 1) : ans = min(a[0][0] + b[0][0], ans) print(ans + sum) ```
95,708
Provide tags and a correct Python 3 solution for this coding contest problem. It was recycling day in Kekoland. To celebrate it Adil and Bera went to Central Perk where they can take bottles from the ground and put them into a recycling bin. We can think Central Perk as coordinate plane. There are n bottles on the ground, the i-th bottle is located at position (xi, yi). Both Adil and Bera can carry only one bottle at once each. For both Adil and Bera the process looks as follows: 1. Choose to stop or to continue to collect bottles. 2. If the choice was to continue then choose some bottle and walk towards it. 3. Pick this bottle and walk to the recycling bin. 4. Go to step 1. Adil and Bera may move independently. They are allowed to pick bottles simultaneously, all bottles may be picked by any of the two, it's allowed that one of them stays still while the other one continues to pick bottles. They want to organize the process such that the total distance they walk (the sum of distance walked by Adil and distance walked by Bera) is minimum possible. Of course, at the end all bottles should lie in the recycling bin. Input First line of the input contains six integers ax, ay, bx, by, tx and ty (0 ≀ ax, ay, bx, by, tx, ty ≀ 109) β€” initial positions of Adil, Bera and recycling bin respectively. The second line contains a single integer n (1 ≀ n ≀ 100 000) β€” the number of bottles on the ground. Then follow n lines, each of them contains two integers xi and yi (0 ≀ xi, yi ≀ 109) β€” position of the i-th bottle. It's guaranteed that positions of Adil, Bera, recycling bin and all bottles are distinct. Output Print one real number β€” the minimum possible total distance Adil and Bera need to walk in order to put all bottles into recycling bin. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if <image>. Examples Input 3 1 1 2 0 0 3 1 1 2 1 2 3 Output 11.084259940083 Input 5 0 4 2 2 0 5 5 2 3 0 5 5 3 5 3 3 Output 33.121375178000 Note Consider the first sample. Adil will use the following path: <image>. Bera will use the following path: <image>. Adil's path will be <image> units long, while Bera's path will be <image> units long. Tags: dp, geometry, greedy, implementation Correct Solution: ``` import math def dist(x1, y1, x2, y2): res = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) res = math.sqrt(res) return res ax, ay, bx, by, tx, ty = list(map(int, input().split())) n = int(input()) ans = 0 bottles = [(0, 0) for i in range(n)] da = [(0, -1) for i in range(n + 1)] db = [(0, -1) for i in range(n + 1)] for i in range(n): xi, yi = list(map(int, input().split())) bottles.append((xi, yi)) # We compute the dist from xi, yi to tx ty and add the double to the ans dt = dist(xi, yi, tx, ty) ans += 2 * dt # We now compute dist from ax, ay to xi, yi and dt (the path to collect the bottle and go to the center) dist_a = dist(ax, ay, xi, yi) - dt da[i] = (dist_a, i) # Same for b dist_b = dist(bx, by, xi, yi) - dt db[i] = (dist_b, i) best = 10 ** 18 da = sorted(da) db = sorted(db) for i in range(min(3, n + 1)): for j in range(min(3, n + 1)): if da[i][1] == db[j][1]: continue if da[i][1] == -1 and db[j][1] == -1: continue best = min(best, da[i][0] + db[j][0]) print(ans + best) # Now we just need to know if a and b can pick something up # For that, several cases # If both min_dist_a and min_dist_b are greater than the distance needed to collect the corresponding bottle # Only one of them will, the one with the least distance # If one of them has a min_dist greater than the distance needed to collect, it won't # If both of them can collect one (less then their distance), they both do # We suppose for now this happen all the time # print(s) ```
95,709
Provide tags and a correct Python 3 solution for this coding contest problem. It was recycling day in Kekoland. To celebrate it Adil and Bera went to Central Perk where they can take bottles from the ground and put them into a recycling bin. We can think Central Perk as coordinate plane. There are n bottles on the ground, the i-th bottle is located at position (xi, yi). Both Adil and Bera can carry only one bottle at once each. For both Adil and Bera the process looks as follows: 1. Choose to stop or to continue to collect bottles. 2. If the choice was to continue then choose some bottle and walk towards it. 3. Pick this bottle and walk to the recycling bin. 4. Go to step 1. Adil and Bera may move independently. They are allowed to pick bottles simultaneously, all bottles may be picked by any of the two, it's allowed that one of them stays still while the other one continues to pick bottles. They want to organize the process such that the total distance they walk (the sum of distance walked by Adil and distance walked by Bera) is minimum possible. Of course, at the end all bottles should lie in the recycling bin. Input First line of the input contains six integers ax, ay, bx, by, tx and ty (0 ≀ ax, ay, bx, by, tx, ty ≀ 109) β€” initial positions of Adil, Bera and recycling bin respectively. The second line contains a single integer n (1 ≀ n ≀ 100 000) β€” the number of bottles on the ground. Then follow n lines, each of them contains two integers xi and yi (0 ≀ xi, yi ≀ 109) β€” position of the i-th bottle. It's guaranteed that positions of Adil, Bera, recycling bin and all bottles are distinct. Output Print one real number β€” the minimum possible total distance Adil and Bera need to walk in order to put all bottles into recycling bin. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if <image>. Examples Input 3 1 1 2 0 0 3 1 1 2 1 2 3 Output 11.084259940083 Input 5 0 4 2 2 0 5 5 2 3 0 5 5 3 5 3 3 Output 33.121375178000 Note Consider the first sample. Adil will use the following path: <image>. Bera will use the following path: <image>. Adil's path will be <image> units long, while Bera's path will be <image> units long. Tags: dp, geometry, greedy, implementation Correct Solution: ``` import math ax,ay,bx,by,tx,ty = map(float,input().split(" ")) n = int(input()) dis = 0.0 a1Dis = 100000000000.0**2 a2Dis = 100000000000.0**2 b1Dis = 100000000000.0**2 b2Dis = 100000000000.0**2 a1=0 b1=0 rec=0.0 for i in range(n): x,y = map(float,input().split(" ")) rec=math.sqrt((x-tx)**2+(y-ty)**2) dis+=rec*2 aDis = math.sqrt((x-ax)**2+(y-ay)**2) if aDis-rec < a1Dis: a1 = i a2Dis = a1Dis a1Dis = aDis-rec elif aDis-rec<a2Dis: a2Dis=aDis-rec bDis = math.sqrt((x-bx)**2+(y-by)**2) if bDis-rec < b1Dis: b1=i b2Dis = b1Dis b1Dis = bDis-rec elif bDis-rec<b2Dis: b2Dis=bDis-rec options=[a1Dis+b2Dis,b1Dis+a2Dis,a1Dis,b1Dis] if a1!=b1: options.append(b1Dis+a1Dis) print(dis+min(options)) ```
95,710
Provide tags and a correct Python 3 solution for this coding contest problem. It was recycling day in Kekoland. To celebrate it Adil and Bera went to Central Perk where they can take bottles from the ground and put them into a recycling bin. We can think Central Perk as coordinate plane. There are n bottles on the ground, the i-th bottle is located at position (xi, yi). Both Adil and Bera can carry only one bottle at once each. For both Adil and Bera the process looks as follows: 1. Choose to stop or to continue to collect bottles. 2. If the choice was to continue then choose some bottle and walk towards it. 3. Pick this bottle and walk to the recycling bin. 4. Go to step 1. Adil and Bera may move independently. They are allowed to pick bottles simultaneously, all bottles may be picked by any of the two, it's allowed that one of them stays still while the other one continues to pick bottles. They want to organize the process such that the total distance they walk (the sum of distance walked by Adil and distance walked by Bera) is minimum possible. Of course, at the end all bottles should lie in the recycling bin. Input First line of the input contains six integers ax, ay, bx, by, tx and ty (0 ≀ ax, ay, bx, by, tx, ty ≀ 109) β€” initial positions of Adil, Bera and recycling bin respectively. The second line contains a single integer n (1 ≀ n ≀ 100 000) β€” the number of bottles on the ground. Then follow n lines, each of them contains two integers xi and yi (0 ≀ xi, yi ≀ 109) β€” position of the i-th bottle. It's guaranteed that positions of Adil, Bera, recycling bin and all bottles are distinct. Output Print one real number β€” the minimum possible total distance Adil and Bera need to walk in order to put all bottles into recycling bin. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if <image>. Examples Input 3 1 1 2 0 0 3 1 1 2 1 2 3 Output 11.084259940083 Input 5 0 4 2 2 0 5 5 2 3 0 5 5 3 5 3 3 Output 33.121375178000 Note Consider the first sample. Adil will use the following path: <image>. Bera will use the following path: <image>. Adil's path will be <image> units long, while Bera's path will be <image> units long. Tags: dp, geometry, greedy, implementation Correct Solution: ``` import math def getdist(x,y,a,c): return math.sqrt((x-a)**2+(c-y)**2) def main(n,points,start): x1,y1=start[0],start[1] x2,y2=start[2],start[3] x3,y3=start[4],start[5] dist=[] dist_p1=[] dist_p2=[] for i in range(len(points)): x4,y4=points[i] dist.append(getdist(x4,y4,x3,y3)) dist_p1.append((i,getdist(x4,y4,x1,y1)-dist[i])) dist_p2.append((i,getdist(x4,y4,x2,y2)-dist[i])) dist_p2.sort(key=lambda x:x[1]) dist_p1.sort(key=lambda x:x[1]) val1=dist_p2[0] if len(dist_p2)>1: val2=dist_p2[1] else: val2=(None,float('inf')) sum_dist=sum(dist) ans=float('inf') for i in range(len(dist_p1)): i1,d1=dist_p1[i] i2,d2=val1 i3,d3=val2 if i1!=i2: ans=min(ans,d1+d2+2*sum_dist) elif i3!=None: ans=min(ans,d1+d3+2*sum_dist) i1,d1=dist_p1[0] i2,d2=val1 ans=min(ans,d1+2*sum_dist) ans=min(ans,d2+2*sum_dist) return ans start=list(map(int,input().split())) n=int(input()) arr=[] for i in range(n): arr.append(list(map(int,input().split()))) print(main(n,arr,start)) ```
95,711
Provide tags and a correct Python 3 solution for this coding contest problem. It was recycling day in Kekoland. To celebrate it Adil and Bera went to Central Perk where they can take bottles from the ground and put them into a recycling bin. We can think Central Perk as coordinate plane. There are n bottles on the ground, the i-th bottle is located at position (xi, yi). Both Adil and Bera can carry only one bottle at once each. For both Adil and Bera the process looks as follows: 1. Choose to stop or to continue to collect bottles. 2. If the choice was to continue then choose some bottle and walk towards it. 3. Pick this bottle and walk to the recycling bin. 4. Go to step 1. Adil and Bera may move independently. They are allowed to pick bottles simultaneously, all bottles may be picked by any of the two, it's allowed that one of them stays still while the other one continues to pick bottles. They want to organize the process such that the total distance they walk (the sum of distance walked by Adil and distance walked by Bera) is minimum possible. Of course, at the end all bottles should lie in the recycling bin. Input First line of the input contains six integers ax, ay, bx, by, tx and ty (0 ≀ ax, ay, bx, by, tx, ty ≀ 109) β€” initial positions of Adil, Bera and recycling bin respectively. The second line contains a single integer n (1 ≀ n ≀ 100 000) β€” the number of bottles on the ground. Then follow n lines, each of them contains two integers xi and yi (0 ≀ xi, yi ≀ 109) β€” position of the i-th bottle. It's guaranteed that positions of Adil, Bera, recycling bin and all bottles are distinct. Output Print one real number β€” the minimum possible total distance Adil and Bera need to walk in order to put all bottles into recycling bin. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if <image>. Examples Input 3 1 1 2 0 0 3 1 1 2 1 2 3 Output 11.084259940083 Input 5 0 4 2 2 0 5 5 2 3 0 5 5 3 5 3 3 Output 33.121375178000 Note Consider the first sample. Adil will use the following path: <image>. Bera will use the following path: <image>. Adil's path will be <image> units long, while Bera's path will be <image> units long. Tags: dp, geometry, greedy, implementation Correct Solution: ``` import math import sys def dist(u, v): return math.hypot(u[0] - v[0], u[1] - v[1]) ax, ay, bx, by, tx, ty = [int(x) for x in input().split()] a, b, t = (ax, ay), (bx, by), (tx, ty) n = int(input()) bottles = [tuple(int(x) for x in line.split()) for line in sys.stdin] S = sum(2*dist(t, bottle) for bottle in bottles) a_dist = [(dist(a, bottle) - dist(t, bottle), i) for (i, bottle) in enumerate(bottles)] b_dist = [(dist(b, bottle) - dist(t, bottle), i) for (i, bottle) in enumerate(bottles)] a_dist.sort() b_dist.sort() if a_dist[0][0] > 0 or b_dist[0][0] > 0 or n == 1: k = min(a_dist[0][0], b_dist[0][0]) elif a_dist[0][1] == b_dist[0][1]: k = min(a_dist[1][0] + b_dist[0][0], a_dist[0][0] + b_dist[1][0], a_dist[0][0], b_dist[0][0]) else: k = min(a_dist[0][0] + b_dist[0][0], a_dist[0][0], b_dist[0][0]) print(k + S) ```
95,712
Provide tags and a correct Python 3 solution for this coding contest problem. It was recycling day in Kekoland. To celebrate it Adil and Bera went to Central Perk where they can take bottles from the ground and put them into a recycling bin. We can think Central Perk as coordinate plane. There are n bottles on the ground, the i-th bottle is located at position (xi, yi). Both Adil and Bera can carry only one bottle at once each. For both Adil and Bera the process looks as follows: 1. Choose to stop or to continue to collect bottles. 2. If the choice was to continue then choose some bottle and walk towards it. 3. Pick this bottle and walk to the recycling bin. 4. Go to step 1. Adil and Bera may move independently. They are allowed to pick bottles simultaneously, all bottles may be picked by any of the two, it's allowed that one of them stays still while the other one continues to pick bottles. They want to organize the process such that the total distance they walk (the sum of distance walked by Adil and distance walked by Bera) is minimum possible. Of course, at the end all bottles should lie in the recycling bin. Input First line of the input contains six integers ax, ay, bx, by, tx and ty (0 ≀ ax, ay, bx, by, tx, ty ≀ 109) β€” initial positions of Adil, Bera and recycling bin respectively. The second line contains a single integer n (1 ≀ n ≀ 100 000) β€” the number of bottles on the ground. Then follow n lines, each of them contains two integers xi and yi (0 ≀ xi, yi ≀ 109) β€” position of the i-th bottle. It's guaranteed that positions of Adil, Bera, recycling bin and all bottles are distinct. Output Print one real number β€” the minimum possible total distance Adil and Bera need to walk in order to put all bottles into recycling bin. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if <image>. Examples Input 3 1 1 2 0 0 3 1 1 2 1 2 3 Output 11.084259940083 Input 5 0 4 2 2 0 5 5 2 3 0 5 5 3 5 3 3 Output 33.121375178000 Note Consider the first sample. Adil will use the following path: <image>. Bera will use the following path: <image>. Adil's path will be <image> units long, while Bera's path will be <image> units long. Tags: dp, geometry, greedy, implementation Correct Solution: ``` ax,ay,bx,by,rx,ry=map(int,input().split()) a,b=[],[] from math import sqrt n=int(input()) #print(n) for i in range(n): m,rn=map(int,input().split()) a.append(m) b.append(rn) #print(a,b) ra,rb=[],[] ans=0 for i in range(n): #print('i m i') da=sqrt((ax-a[i])**2+(ay-b[i])**2) db=sqrt((bx-a[i])**2+(by-b[i])**2) dr=sqrt((rx-a[i])**2+(ry-b[i])**2) ##print(da,db,dr) ra.append(dr-da) rb.append(dr-db) ans+=(2*dr) #print(ans) l=range(n) ran1=sorted(zip(ra,l))[::-1] ran2=sorted(zip(rb,l))[::-1] if(n==1): print(ans-max(ran1[0][0],ran2[0][0])) else: if(ran1[0][0]>=0 and ran2[0][0]>=0): if(ran1[0][1]!=ran2[0][1]): print(ans-(ran1[0][0]+ran2[0][0])) else: print(ans-max(max(0,ran1[1][0])+ran2[0][0],max(0,ran2[1][0])+ran1[0][0])) else: print(ans-max(ran1[0][0],ran2[0][0])) ```
95,713
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It was recycling day in Kekoland. To celebrate it Adil and Bera went to Central Perk where they can take bottles from the ground and put them into a recycling bin. We can think Central Perk as coordinate plane. There are n bottles on the ground, the i-th bottle is located at position (xi, yi). Both Adil and Bera can carry only one bottle at once each. For both Adil and Bera the process looks as follows: 1. Choose to stop or to continue to collect bottles. 2. If the choice was to continue then choose some bottle and walk towards it. 3. Pick this bottle and walk to the recycling bin. 4. Go to step 1. Adil and Bera may move independently. They are allowed to pick bottles simultaneously, all bottles may be picked by any of the two, it's allowed that one of them stays still while the other one continues to pick bottles. They want to organize the process such that the total distance they walk (the sum of distance walked by Adil and distance walked by Bera) is minimum possible. Of course, at the end all bottles should lie in the recycling bin. Input First line of the input contains six integers ax, ay, bx, by, tx and ty (0 ≀ ax, ay, bx, by, tx, ty ≀ 109) β€” initial positions of Adil, Bera and recycling bin respectively. The second line contains a single integer n (1 ≀ n ≀ 100 000) β€” the number of bottles on the ground. Then follow n lines, each of them contains two integers xi and yi (0 ≀ xi, yi ≀ 109) β€” position of the i-th bottle. It's guaranteed that positions of Adil, Bera, recycling bin and all bottles are distinct. Output Print one real number β€” the minimum possible total distance Adil and Bera need to walk in order to put all bottles into recycling bin. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if <image>. Examples Input 3 1 1 2 0 0 3 1 1 2 1 2 3 Output 11.084259940083 Input 5 0 4 2 2 0 5 5 2 3 0 5 5 3 5 3 3 Output 33.121375178000 Note Consider the first sample. Adil will use the following path: <image>. Bera will use the following path: <image>. Adil's path will be <image> units long, while Bera's path will be <image> units long. Submitted Solution: ``` read = lambda: map(int, input().split()) ax, ay, bx, by, tx, ty = read() n = int(input()) p = [tuple(read()) for i in range(n)] a, b = [], [] for i in range(n): x, y = p[i] pt = ((tx - x) ** 2 + (ty - y) ** 2) ** 0.5 pa = ((ax - x) ** 2 + (ay - y) ** 2) ** 0.5 pb = ((bx - x) ** 2 + (by - y) ** 2) ** 0.5 a.append((pa - pt, i)) b.append((pb - pt, i)) a.sort() b.sort() if a[0][1] == b[0][1] and n > 1: ans = min(a[0][0], b[0][0], a[0][0] + b[1][0], a[1][0] + b[0][0]) else: ans = min(a[0][0], b[0][0]) if a[0][1] != b[0][1]: ans = min(ans, a[0][0] + b[0][0]) ans += sum(2 * ((tx - x) ** 2 + (ty - y) ** 2) ** 0.5 for x, y in p) print(ans) ``` Yes
95,714
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It was recycling day in Kekoland. To celebrate it Adil and Bera went to Central Perk where they can take bottles from the ground and put them into a recycling bin. We can think Central Perk as coordinate plane. There are n bottles on the ground, the i-th bottle is located at position (xi, yi). Both Adil and Bera can carry only one bottle at once each. For both Adil and Bera the process looks as follows: 1. Choose to stop or to continue to collect bottles. 2. If the choice was to continue then choose some bottle and walk towards it. 3. Pick this bottle and walk to the recycling bin. 4. Go to step 1. Adil and Bera may move independently. They are allowed to pick bottles simultaneously, all bottles may be picked by any of the two, it's allowed that one of them stays still while the other one continues to pick bottles. They want to organize the process such that the total distance they walk (the sum of distance walked by Adil and distance walked by Bera) is minimum possible. Of course, at the end all bottles should lie in the recycling bin. Input First line of the input contains six integers ax, ay, bx, by, tx and ty (0 ≀ ax, ay, bx, by, tx, ty ≀ 109) β€” initial positions of Adil, Bera and recycling bin respectively. The second line contains a single integer n (1 ≀ n ≀ 100 000) β€” the number of bottles on the ground. Then follow n lines, each of them contains two integers xi and yi (0 ≀ xi, yi ≀ 109) β€” position of the i-th bottle. It's guaranteed that positions of Adil, Bera, recycling bin and all bottles are distinct. Output Print one real number β€” the minimum possible total distance Adil and Bera need to walk in order to put all bottles into recycling bin. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if <image>. Examples Input 3 1 1 2 0 0 3 1 1 2 1 2 3 Output 11.084259940083 Input 5 0 4 2 2 0 5 5 2 3 0 5 5 3 5 3 3 Output 33.121375178000 Note Consider the first sample. Adil will use the following path: <image>. Bera will use the following path: <image>. Adil's path will be <image> units long, while Bera's path will be <image> units long. Submitted Solution: ``` import math def dis(x1, y1, x2, y2): return math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2) str = input().split() argu = [] for i in str: argu.append(int(i)) n = int(input()) total = 0 array = [[], []] for i in range(n): x, y = input().split() x = int(x) y = int(y) td = dis(x, y, argu[4], argu[5]) ad = dis(x, y, argu[0], argu[1]) bd = dis(x, y, argu[2], argu[3]) total += 2 * td array[0].append((i, ad - td)) array[1].append((i, bd - td)) if n == 1: print("%.12f" % (total + min(array[0][0][1], array[1][0][1]))) else: def sortkey(x): return x[1] array[0].sort(key = sortkey) array[1].sort(key = sortkey) ans = total + array[0][0][1] ans = min(ans, total + array[1][0][1]) for i in range(2): for j in range(2): tmpa = array[0][i] tmpb = array[1][j] if tmpa[0] != tmpb[0]: ans = min(ans, total + tmpa[1] + tmpb[1]) print("%.12f" % ans) ``` Yes
95,715
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It was recycling day in Kekoland. To celebrate it Adil and Bera went to Central Perk where they can take bottles from the ground and put them into a recycling bin. We can think Central Perk as coordinate plane. There are n bottles on the ground, the i-th bottle is located at position (xi, yi). Both Adil and Bera can carry only one bottle at once each. For both Adil and Bera the process looks as follows: 1. Choose to stop or to continue to collect bottles. 2. If the choice was to continue then choose some bottle and walk towards it. 3. Pick this bottle and walk to the recycling bin. 4. Go to step 1. Adil and Bera may move independently. They are allowed to pick bottles simultaneously, all bottles may be picked by any of the two, it's allowed that one of them stays still while the other one continues to pick bottles. They want to organize the process such that the total distance they walk (the sum of distance walked by Adil and distance walked by Bera) is minimum possible. Of course, at the end all bottles should lie in the recycling bin. Input First line of the input contains six integers ax, ay, bx, by, tx and ty (0 ≀ ax, ay, bx, by, tx, ty ≀ 109) β€” initial positions of Adil, Bera and recycling bin respectively. The second line contains a single integer n (1 ≀ n ≀ 100 000) β€” the number of bottles on the ground. Then follow n lines, each of them contains two integers xi and yi (0 ≀ xi, yi ≀ 109) β€” position of the i-th bottle. It's guaranteed that positions of Adil, Bera, recycling bin and all bottles are distinct. Output Print one real number β€” the minimum possible total distance Adil and Bera need to walk in order to put all bottles into recycling bin. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if <image>. Examples Input 3 1 1 2 0 0 3 1 1 2 1 2 3 Output 11.084259940083 Input 5 0 4 2 2 0 5 5 2 3 0 5 5 3 5 3 3 Output 33.121375178000 Note Consider the first sample. Adil will use the following path: <image>. Bera will use the following path: <image>. Adil's path will be <image> units long, while Bera's path will be <image> units long. Submitted Solution: ``` import math ax,ay,bx,by,tx,ty = list(map(int,input().split())) n = int(input()) p = [0,0] * n s = [0.] * n ma = [0.] * n mb = [0.] * n for i in range(n): p[i] = list(map(int,input().split())) s[i] = math.hypot(tx - p[i][0], ty - p[i][1]) ma[i] = math.hypot(ax - p[i][0], ay - p[i][1]) - s[i] mb[i] = math.hypot(bx - p[i][0], by - p[i][1]) - s[i] ma = sorted(dict(zip(range(n),ma)).items(), key = lambda t:t[1]) mb = sorted(dict(zip(range(n),mb)).items(), key = lambda t:t[1]) if ma[0][1] > 0 and mb[0][1] > 0: ans = min(ma[0][1],mb[0][1]) elif ma[0][0] == mb[0][0]: if n == 1: ans = min(ma[0][1],mb[0][1],0) else: a1,a2,b1,b2 = min(ma[0][1],0), min(ma[1][1],0), min(mb[0][1],0), min(mb[1][1],0) ans = min(a1+b2, a2+b1,0) else: ans = min(ma[0][1],0) + min(mb[0][1],0) print(2 * sum(s) + ans) ``` Yes
95,716
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It was recycling day in Kekoland. To celebrate it Adil and Bera went to Central Perk where they can take bottles from the ground and put them into a recycling bin. We can think Central Perk as coordinate plane. There are n bottles on the ground, the i-th bottle is located at position (xi, yi). Both Adil and Bera can carry only one bottle at once each. For both Adil and Bera the process looks as follows: 1. Choose to stop or to continue to collect bottles. 2. If the choice was to continue then choose some bottle and walk towards it. 3. Pick this bottle and walk to the recycling bin. 4. Go to step 1. Adil and Bera may move independently. They are allowed to pick bottles simultaneously, all bottles may be picked by any of the two, it's allowed that one of them stays still while the other one continues to pick bottles. They want to organize the process such that the total distance they walk (the sum of distance walked by Adil and distance walked by Bera) is minimum possible. Of course, at the end all bottles should lie in the recycling bin. Input First line of the input contains six integers ax, ay, bx, by, tx and ty (0 ≀ ax, ay, bx, by, tx, ty ≀ 109) β€” initial positions of Adil, Bera and recycling bin respectively. The second line contains a single integer n (1 ≀ n ≀ 100 000) β€” the number of bottles on the ground. Then follow n lines, each of them contains two integers xi and yi (0 ≀ xi, yi ≀ 109) β€” position of the i-th bottle. It's guaranteed that positions of Adil, Bera, recycling bin and all bottles are distinct. Output Print one real number β€” the minimum possible total distance Adil and Bera need to walk in order to put all bottles into recycling bin. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if <image>. Examples Input 3 1 1 2 0 0 3 1 1 2 1 2 3 Output 11.084259940083 Input 5 0 4 2 2 0 5 5 2 3 0 5 5 3 5 3 3 Output 33.121375178000 Note Consider the first sample. Adil will use the following path: <image>. Bera will use the following path: <image>. Adil's path will be <image> units long, while Bera's path will be <image> units long. Submitted Solution: ``` import sys sys.stderr = sys.stdout import heapq def dist(p1, p2): return ((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2) ** 0.5 def bottles(A, B, T, n, P): d_A = dist(A, T) d_B = dist(B, T) DP = [dist(p, T) for p in P] DA = [dist(p, A) for p in P] DB = [dist(p, B) for p in P] S = sum(DP) * 2 if n == 1: d3 = min(da - dp for da, dp in zip(DA, DP)) d4 = min(db - dp for db, dp in zip(DB, DP)) log("d3", d3, "d4", d4) return S + min(d_A, d_B, d3, d4) (dap1, a1), (dap2, a2) = heapq.nsmallest(2, (((da - dp), i) for (i, (da, dp)) in enumerate(zip(DA, DP)))) (dbp1, b1), (dbp2, b2) = heapq.nsmallest(2, (((db - dp), i) for (i, (db, dp)) in enumerate(zip(DB, DP)))) d3 = dap1 d4 = dbp1 if a1 == b1: d5 = min(dap1 + dbp2, dap2 + dbp1) else: d5 = dap1 + dbp1 return S + min(d_A, d_B, d3, d4, d5) def main(): ax, ay, bx, by, tx, ty = readinti() n = readint() P = readinttl(n) print(bottles((ax, ay), (bx, by), (tx, ty), n, P)) ########## def readint(): return int(input()) def readinti(): return map(int, input().split()) def readintt(): return tuple(readinti()) def readintl(): return list(readinti()) def readinttl(k): return [readintt() for _ in range(k)] def readintll(k): return [readintl() for _ in range(k)] def log(*args, **kwargs): print(*args, **kwargs, file=sys.__stderr__) if __name__ == '__main__': main() ``` Yes
95,717
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It was recycling day in Kekoland. To celebrate it Adil and Bera went to Central Perk where they can take bottles from the ground and put them into a recycling bin. We can think Central Perk as coordinate plane. There are n bottles on the ground, the i-th bottle is located at position (xi, yi). Both Adil and Bera can carry only one bottle at once each. For both Adil and Bera the process looks as follows: 1. Choose to stop or to continue to collect bottles. 2. If the choice was to continue then choose some bottle and walk towards it. 3. Pick this bottle and walk to the recycling bin. 4. Go to step 1. Adil and Bera may move independently. They are allowed to pick bottles simultaneously, all bottles may be picked by any of the two, it's allowed that one of them stays still while the other one continues to pick bottles. They want to organize the process such that the total distance they walk (the sum of distance walked by Adil and distance walked by Bera) is minimum possible. Of course, at the end all bottles should lie in the recycling bin. Input First line of the input contains six integers ax, ay, bx, by, tx and ty (0 ≀ ax, ay, bx, by, tx, ty ≀ 109) β€” initial positions of Adil, Bera and recycling bin respectively. The second line contains a single integer n (1 ≀ n ≀ 100 000) β€” the number of bottles on the ground. Then follow n lines, each of them contains two integers xi and yi (0 ≀ xi, yi ≀ 109) β€” position of the i-th bottle. It's guaranteed that positions of Adil, Bera, recycling bin and all bottles are distinct. Output Print one real number β€” the minimum possible total distance Adil and Bera need to walk in order to put all bottles into recycling bin. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if <image>. Examples Input 3 1 1 2 0 0 3 1 1 2 1 2 3 Output 11.084259940083 Input 5 0 4 2 2 0 5 5 2 3 0 5 5 3 5 3 3 Output 33.121375178000 Note Consider the first sample. Adil will use the following path: <image>. Bera will use the following path: <image>. Adil's path will be <image> units long, while Bera's path will be <image> units long. Submitted Solution: ``` import math def dist(x1, y1, x2, y2): res = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) res = math.sqrt(res) return res ax, ay, bx, by, tx, ty = list(map(int, input().split())) n = int(input()) ans = 0 bottles = [(0, 0) for i in range(n)] da = [(0, -1) for i in range(n + 1)] db = [(0, -1) for i in range(n + 1)] for i in range(n): xi, yi = list(map(int, input().split())) bottles.append((xi, yi)) # We compute the dist from xi, yi to tx ty and add the double to the ans dt = dist(xi, yi, tx, ty) ans += 2 * dt # We now compute dist from ax, ay to xi, yi and dt (the path to collect the bottle and go to the center) dist_a = dist(ax, ay, xi, yi) - dt da[i] = (dist_a, i) # Same for b dist_b = dist(bx, by, xi, yi) - dt db[i] = (dist_b, i) best = 10 ** 18 da = sorted(da) db = sorted(db) for i in range(min(3, n)): for j in range(min(3, n)): if da[i][1] == db[j][1]: continue if da[i][1] == -1 and db[j][1] == -1: continue best = min(best, da[i][0] + db[j][0]) print(ans + best) # Now we just need to know if a and b can pick something up # For that, several cases # If both min_dist_a and min_dist_b are greater than the distance needed to collect the corresponding bottle # Only one of them will, the one with the least distance # If one of them has a min_dist greater than the distance needed to collect, it won't # If both of them can collect one (less then their distance), they both do # We suppose for now this happen all the time # print(s) ``` No
95,718
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It was recycling day in Kekoland. To celebrate it Adil and Bera went to Central Perk where they can take bottles from the ground and put them into a recycling bin. We can think Central Perk as coordinate plane. There are n bottles on the ground, the i-th bottle is located at position (xi, yi). Both Adil and Bera can carry only one bottle at once each. For both Adil and Bera the process looks as follows: 1. Choose to stop or to continue to collect bottles. 2. If the choice was to continue then choose some bottle and walk towards it. 3. Pick this bottle and walk to the recycling bin. 4. Go to step 1. Adil and Bera may move independently. They are allowed to pick bottles simultaneously, all bottles may be picked by any of the two, it's allowed that one of them stays still while the other one continues to pick bottles. They want to organize the process such that the total distance they walk (the sum of distance walked by Adil and distance walked by Bera) is minimum possible. Of course, at the end all bottles should lie in the recycling bin. Input First line of the input contains six integers ax, ay, bx, by, tx and ty (0 ≀ ax, ay, bx, by, tx, ty ≀ 109) β€” initial positions of Adil, Bera and recycling bin respectively. The second line contains a single integer n (1 ≀ n ≀ 100 000) β€” the number of bottles on the ground. Then follow n lines, each of them contains two integers xi and yi (0 ≀ xi, yi ≀ 109) β€” position of the i-th bottle. It's guaranteed that positions of Adil, Bera, recycling bin and all bottles are distinct. Output Print one real number β€” the minimum possible total distance Adil and Bera need to walk in order to put all bottles into recycling bin. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if <image>. Examples Input 3 1 1 2 0 0 3 1 1 2 1 2 3 Output 11.084259940083 Input 5 0 4 2 2 0 5 5 2 3 0 5 5 3 5 3 3 Output 33.121375178000 Note Consider the first sample. Adil will use the following path: <image>. Bera will use the following path: <image>. Adil's path will be <image> units long, while Bera's path will be <image> units long. Submitted Solution: ``` ax, ay, bx, by, tx, ty = map(int, input().split()) def dd(x0, y0, x1, y1): return ((x0 - x1)**2 + (y0 - y1)**2)**0.5 n = int(input()) arr = [list(map(int, input().split())) for i in range(n)] dist = [dd(x, y, tx, ty) for x, y in arr] ans = sum(dist) * 2 a_dists = sorted((dd(*x, ax, ay) - dd(*x, tx, ty), i) for i, x in enumerate(arr)) b_dists = sorted((dd(*x, bx, by) - dd(*x, tx, ty), i) for i, x in enumerate(arr)) a_dists = a_dists[:5] b_dists = b_dists[:5] mi = 10**100 for dx, x in a_dists: for dy, y in b_dists: if x != y: mi = min(mi, ans + dx + dy) if mi > ans: mi = min(ans + a_dists[0][0], ans + b_dists[0][0]) print(mi) ``` No
95,719
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It was recycling day in Kekoland. To celebrate it Adil and Bera went to Central Perk where they can take bottles from the ground and put them into a recycling bin. We can think Central Perk as coordinate plane. There are n bottles on the ground, the i-th bottle is located at position (xi, yi). Both Adil and Bera can carry only one bottle at once each. For both Adil and Bera the process looks as follows: 1. Choose to stop or to continue to collect bottles. 2. If the choice was to continue then choose some bottle and walk towards it. 3. Pick this bottle and walk to the recycling bin. 4. Go to step 1. Adil and Bera may move independently. They are allowed to pick bottles simultaneously, all bottles may be picked by any of the two, it's allowed that one of them stays still while the other one continues to pick bottles. They want to organize the process such that the total distance they walk (the sum of distance walked by Adil and distance walked by Bera) is minimum possible. Of course, at the end all bottles should lie in the recycling bin. Input First line of the input contains six integers ax, ay, bx, by, tx and ty (0 ≀ ax, ay, bx, by, tx, ty ≀ 109) β€” initial positions of Adil, Bera and recycling bin respectively. The second line contains a single integer n (1 ≀ n ≀ 100 000) β€” the number of bottles on the ground. Then follow n lines, each of them contains two integers xi and yi (0 ≀ xi, yi ≀ 109) β€” position of the i-th bottle. It's guaranteed that positions of Adil, Bera, recycling bin and all bottles are distinct. Output Print one real number β€” the minimum possible total distance Adil and Bera need to walk in order to put all bottles into recycling bin. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if <image>. Examples Input 3 1 1 2 0 0 3 1 1 2 1 2 3 Output 11.084259940083 Input 5 0 4 2 2 0 5 5 2 3 0 5 5 3 5 3 3 Output 33.121375178000 Note Consider the first sample. Adil will use the following path: <image>. Bera will use the following path: <image>. Adil's path will be <image> units long, while Bera's path will be <image> units long. Submitted Solution: ``` ax, ay, bx, by, tx, ty = map(int, input().split()) def dd(x0, y0, x1, y1): return ((x0 - x1)**2 + (y0 - y1)**2)**0.5 n = int(input()) arr = [list(map(int, input().split())) for i in range(n)] dist = [dd(x, y, tx, ty) for x, y in arr] ans = sum(dist) * 2 a_dists = [(dd(*x, ax, ay) - dd(*x, tx, ty), i) for i, x in enumerate(arr)] b_dists = [(dd(*x, bx, by) - dd(*x, tx, ty), i) for i, x in enumerate(arr)] a_dists.sort(reverse=True) b_dists.sort(reverse=True) a_dists = a_dists[:10] b_dists = b_dists[:10] mi = 10**100 for dx, x in a_dists: for dy, y in b_dists: if x != y: mi = min(mi, ans + dx + dy) print(mi) ``` No
95,720
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It was recycling day in Kekoland. To celebrate it Adil and Bera went to Central Perk where they can take bottles from the ground and put them into a recycling bin. We can think Central Perk as coordinate plane. There are n bottles on the ground, the i-th bottle is located at position (xi, yi). Both Adil and Bera can carry only one bottle at once each. For both Adil and Bera the process looks as follows: 1. Choose to stop or to continue to collect bottles. 2. If the choice was to continue then choose some bottle and walk towards it. 3. Pick this bottle and walk to the recycling bin. 4. Go to step 1. Adil and Bera may move independently. They are allowed to pick bottles simultaneously, all bottles may be picked by any of the two, it's allowed that one of them stays still while the other one continues to pick bottles. They want to organize the process such that the total distance they walk (the sum of distance walked by Adil and distance walked by Bera) is minimum possible. Of course, at the end all bottles should lie in the recycling bin. Input First line of the input contains six integers ax, ay, bx, by, tx and ty (0 ≀ ax, ay, bx, by, tx, ty ≀ 109) β€” initial positions of Adil, Bera and recycling bin respectively. The second line contains a single integer n (1 ≀ n ≀ 100 000) β€” the number of bottles on the ground. Then follow n lines, each of them contains two integers xi and yi (0 ≀ xi, yi ≀ 109) β€” position of the i-th bottle. It's guaranteed that positions of Adil, Bera, recycling bin and all bottles are distinct. Output Print one real number β€” the minimum possible total distance Adil and Bera need to walk in order to put all bottles into recycling bin. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if <image>. Examples Input 3 1 1 2 0 0 3 1 1 2 1 2 3 Output 11.084259940083 Input 5 0 4 2 2 0 5 5 2 3 0 5 5 3 5 3 3 Output 33.121375178000 Note Consider the first sample. Adil will use the following path: <image>. Bera will use the following path: <image>. Adil's path will be <image> units long, while Bera's path will be <image> units long. Submitted Solution: ``` # -*- coding: utf-8 -*- def get_dist_vec(loc, loc_vec): dist_vec = [] for loc2 in loc_vec: dist = (loc[0] - loc2[0])**2 + (loc[1] - loc2[1])**2 dist_vec.append(dist ** 0.5) return dist_vec def get_travel_saved(a_vec, r_vec): travel_saved_vec = [] for i in range(len(a_vec)): travel_saved_vec.append(r_vec[i] - a_vec[i]) idx_vec = sorted(range(len(travel_saved_vec)), key = lambda k: travel_saved_vec[k], reverse = True) return idx_vec def get_dist_traveled(a_vec, b_vec, r_vec, i, j): dist_traveled = (a_vec[i] + r_vec[i]) + (b_vec[j] + r_vec[j]) for k in range(len(r_vec)): if k == i or k == j: continue else: dist_traveled += 2 * r_vec[k] return dist_traveled def main(): args = [int(x) for x in input().split()] a_loc = (args[0], args[1]) b_loc = (args[2], args[3]) r_loc = (args[4], args[5]) n = int(input()) # a_loc = (107, 50) # b_loc = (116, 37) # b_loc = (104, 118) # r_loc = (104, 118) # bottle_vec = [(16, 78), (95, 113), (112, 84), (5, 88), (54, 85), (112, 80), (19, 98), (25, 14), (48, 76), (95, 70), (77, 94), (38, 32) ] bottle_vec = [] for i in range(n): bottle_coord = [int(x) for x in input().split()] bottle_vec.append((bottle_coord[0], bottle_coord[1])) a_vec = get_dist_vec(a_loc, bottle_vec) b_vec = get_dist_vec(b_loc, bottle_vec) r_vec = get_dist_vec(r_loc, bottle_vec) travel_saved_idx_vec_a = get_travel_saved(a_vec, r_vec) travel_saved_idx_vec_b = get_travel_saved(b_vec, r_vec) a_max_i = travel_saved_idx_vec_a[0] b_max_i = travel_saved_idx_vec_b[0] if (a_max_i == b_max_i): a_sec_max_i = travel_saved_idx_vec_a[1] b_sec_max_i = travel_saved_idx_vec_b[1] case1_saved = (r_vec[a_max_i] - a_vec[a_max_i]) + (r_vec[b_sec_max_i] - b_vec[b_sec_max_i]) case2_saved = (r_vec[b_max_i] - b_vec[b_max_i]) + (r_vec[a_sec_max_i] - a_vec[a_sec_max_i]) if case1_saved >= case2_saved: b_max_i = travel_saved_idx_vec_b[1] else: a_max_i = travel_saved_idx_vec_a[1] print(get_dist_traveled(a_vec, b_vec, r_vec, a_max_i, b_max_i)) main() ``` No
95,721
Provide tags and a correct Python 3 solution for this coding contest problem. As we all know Barney's job is "PLEASE" and he has not much to do at work. That's why he started playing "cups and key". In this game there are three identical cups arranged in a line from left to right. Initially key to Barney's heart is under the middle cup. <image> Then at one turn Barney swaps the cup in the middle with any of other two cups randomly (he choses each with equal probability), so the chosen cup becomes the middle one. Game lasts n turns and Barney independently choses a cup to swap with the middle one within each turn, and the key always remains in the cup it was at the start. After n-th turn Barney asks a girl to guess which cup contains the key. The girl points to the middle one but Barney was distracted while making turns and doesn't know if the key is under the middle cup. That's why he asked you to tell him the probability that girl guessed right. Number n of game turns can be extremely large, that's why Barney did not give it to you. Instead he gave you an array a1, a2, ..., ak such that <image> in other words, n is multiplication of all elements of the given array. Because of precision difficulties, Barney asked you to tell him the answer as an irreducible fraction. In other words you need to find it as a fraction p / q such that <image>, where <image> is the greatest common divisor. Since p and q can be extremely large, you only need to find the remainders of dividing each of them by 109 + 7. Please note that we want <image> of p and q to be 1, not <image> of their remainders after dividing by 109 + 7. Input The first line of input contains a single integer k (1 ≀ k ≀ 105) β€” the number of elements in array Barney gave you. The second line contains k integers a1, a2, ..., ak (1 ≀ ai ≀ 1018) β€” the elements of the array. Output In the only line of output print a single string x / y where x is the remainder of dividing p by 109 + 7 and y is the remainder of dividing q by 109 + 7. Examples Input 1 2 Output 1/2 Input 3 1 1 1 Output 0/1 Tags: combinatorics, dp, implementation, math, matrices Correct Solution: ``` m = 1000000007 input() n, d = 2, 1 for q in map(int, input().split()): d, n = q & d, pow(n, q, m) n = n * pow(2, m - 2, m) % m k = (n + 1 - 2 * d) * pow(3, m - 2, m) % m print(str(k) + '/' + str(n)) ```
95,722
Provide tags and a correct Python 3 solution for this coding contest problem. As we all know Barney's job is "PLEASE" and he has not much to do at work. That's why he started playing "cups and key". In this game there are three identical cups arranged in a line from left to right. Initially key to Barney's heart is under the middle cup. <image> Then at one turn Barney swaps the cup in the middle with any of other two cups randomly (he choses each with equal probability), so the chosen cup becomes the middle one. Game lasts n turns and Barney independently choses a cup to swap with the middle one within each turn, and the key always remains in the cup it was at the start. After n-th turn Barney asks a girl to guess which cup contains the key. The girl points to the middle one but Barney was distracted while making turns and doesn't know if the key is under the middle cup. That's why he asked you to tell him the probability that girl guessed right. Number n of game turns can be extremely large, that's why Barney did not give it to you. Instead he gave you an array a1, a2, ..., ak such that <image> in other words, n is multiplication of all elements of the given array. Because of precision difficulties, Barney asked you to tell him the answer as an irreducible fraction. In other words you need to find it as a fraction p / q such that <image>, where <image> is the greatest common divisor. Since p and q can be extremely large, you only need to find the remainders of dividing each of them by 109 + 7. Please note that we want <image> of p and q to be 1, not <image> of their remainders after dividing by 109 + 7. Input The first line of input contains a single integer k (1 ≀ k ≀ 105) β€” the number of elements in array Barney gave you. The second line contains k integers a1, a2, ..., ak (1 ≀ ai ≀ 1018) β€” the elements of the array. Output In the only line of output print a single string x / y where x is the remainder of dividing p by 109 + 7 and y is the remainder of dividing q by 109 + 7. Examples Input 1 2 Output 1/2 Input 3 1 1 1 Output 0/1 Tags: combinatorics, dp, implementation, math, matrices Correct Solution: ``` k = int(input()) MOD = 10 ** 9 + 7 antithree = pow(3, MOD - 2, MOD) antitwo = pow(2, MOD - 2, MOD) power = 1 parity = False for t in map(int, input().split()): power *= t power %= MOD - 1 if t % 2 == 0: parity = True q = pow(2, power, MOD) * antitwo q %= MOD if parity: p = (q + 1) * antithree p %= MOD else: p = (q - 1) * antithree p %= MOD print(p, q, sep = '/') ```
95,723
Provide tags and a correct Python 3 solution for this coding contest problem. As we all know Barney's job is "PLEASE" and he has not much to do at work. That's why he started playing "cups and key". In this game there are three identical cups arranged in a line from left to right. Initially key to Barney's heart is under the middle cup. <image> Then at one turn Barney swaps the cup in the middle with any of other two cups randomly (he choses each with equal probability), so the chosen cup becomes the middle one. Game lasts n turns and Barney independently choses a cup to swap with the middle one within each turn, and the key always remains in the cup it was at the start. After n-th turn Barney asks a girl to guess which cup contains the key. The girl points to the middle one but Barney was distracted while making turns and doesn't know if the key is under the middle cup. That's why he asked you to tell him the probability that girl guessed right. Number n of game turns can be extremely large, that's why Barney did not give it to you. Instead he gave you an array a1, a2, ..., ak such that <image> in other words, n is multiplication of all elements of the given array. Because of precision difficulties, Barney asked you to tell him the answer as an irreducible fraction. In other words you need to find it as a fraction p / q such that <image>, where <image> is the greatest common divisor. Since p and q can be extremely large, you only need to find the remainders of dividing each of them by 109 + 7. Please note that we want <image> of p and q to be 1, not <image> of their remainders after dividing by 109 + 7. Input The first line of input contains a single integer k (1 ≀ k ≀ 105) β€” the number of elements in array Barney gave you. The second line contains k integers a1, a2, ..., ak (1 ≀ ai ≀ 1018) β€” the elements of the array. Output In the only line of output print a single string x / y where x is the remainder of dividing p by 109 + 7 and y is the remainder of dividing q by 109 + 7. Examples Input 1 2 Output 1/2 Input 3 1 1 1 Output 0/1 Tags: combinatorics, dp, implementation, math, matrices Correct Solution: ``` #!/usr/bin/python3 class Matrix: def __init__(self, n, m, arr=None): self.n = n self.m = m self.arr = [[0] * m for i in range(n)] if arr is not None: for i in range(n): for j in range(m): self.arr[i][j] = arr[i][j] def __mul__(self, other): assert self.m == other.n ans = Matrix(self.n, other.m) for i in range(self.n): for j in range(other.m): for k in range(self.m): ans.arr[i][j] = (ans.arr[i][j] + self.arr[i][k] * other.arr[k][j]) % (10 ** 9 + 7) return ans def __imul__(self, other): self = self * other return self def __pow__(self, n): if n == 0: ans = Matrix(self.n, self.n) for i in range(self.n): ans.arr[i][i] = 1 return ans elif n & 1 == 1: return self * (self ** (n - 1)) else: t = self ** (n >> 1) return t * t def __ipow__(self, n): self = self ** n return self def __eq__(self, other): if self.n != other.n or self.m != other.m: return False for i in range(self.n): for j in range(self.m): if self.arr[i][j] != other.arr[i][j]: return False return True def fpow(a, n): if n == 0: return 1 elif n & 1 == 1: return (a * fpow(a, n - 1)) % (10 ** 9 + 7) else: t = fpow(a, n >> 1) return (t * t) % (10 ** 9 + 7) transform = Matrix(2, 2, [[1, 1], [0, 4]]) mtx = transform k = int(input()) a = list(map(int, input().split())) """ f = False for j in a: if j % 2 == 0: f = True break if f: print(a) tp = 1 for j in a: if f and j % 2 == 0: j //= 2 f = False print(j) mtx **= j ans = Matrix(2, 1, [[0], [1]]) ans = mtx * ans print(ans.arr) print("%d/%d" % (ans.arr[0][0], ans.arr[1][0])) """ x = 1 for j in a: x = (x * j) % (10 ** 9 + 6) x = (x - 1) % (10 ** 9 + 6) if x % 2 == 0: ans = (transform ** (x // 2)) * Matrix(2, 1, [[0], [1]]) print("%d/%d" % (ans.arr[0][0], fpow(2, x))) else: y = (x - 1) % (10 ** 9 + 6) ans = (transform ** (y // 2)) * Matrix(2, 1, [[0], [1]]) print("%d/%d" % ((ans.arr[0][0] * 2 + 1) % (10 ** 9 + 7), (ans.arr[1][0] * 2) % (10 ** 9 + 7))) ```
95,724
Provide tags and a correct Python 3 solution for this coding contest problem. As we all know Barney's job is "PLEASE" and he has not much to do at work. That's why he started playing "cups and key". In this game there are three identical cups arranged in a line from left to right. Initially key to Barney's heart is under the middle cup. <image> Then at one turn Barney swaps the cup in the middle with any of other two cups randomly (he choses each with equal probability), so the chosen cup becomes the middle one. Game lasts n turns and Barney independently choses a cup to swap with the middle one within each turn, and the key always remains in the cup it was at the start. After n-th turn Barney asks a girl to guess which cup contains the key. The girl points to the middle one but Barney was distracted while making turns and doesn't know if the key is under the middle cup. That's why he asked you to tell him the probability that girl guessed right. Number n of game turns can be extremely large, that's why Barney did not give it to you. Instead he gave you an array a1, a2, ..., ak such that <image> in other words, n is multiplication of all elements of the given array. Because of precision difficulties, Barney asked you to tell him the answer as an irreducible fraction. In other words you need to find it as a fraction p / q such that <image>, where <image> is the greatest common divisor. Since p and q can be extremely large, you only need to find the remainders of dividing each of them by 109 + 7. Please note that we want <image> of p and q to be 1, not <image> of their remainders after dividing by 109 + 7. Input The first line of input contains a single integer k (1 ≀ k ≀ 105) β€” the number of elements in array Barney gave you. The second line contains k integers a1, a2, ..., ak (1 ≀ ai ≀ 1018) β€” the elements of the array. Output In the only line of output print a single string x / y where x is the remainder of dividing p by 109 + 7 and y is the remainder of dividing q by 109 + 7. Examples Input 1 2 Output 1/2 Input 3 1 1 1 Output 0/1 Tags: combinatorics, dp, implementation, math, matrices Correct Solution: ``` MOD = 10 ** 9 + 7 MOD1 = 2 * (10 ** 9 + 6) pow2 = [0] * 32 #pow2[i] = 2 ** (2 ** i) % MOD pow2[0] = 2 for i in range(1, 32): pow2[i] = (pow2[i - 1] ** 2) % MOD def exp2mod(exp): ans = 1 the_pow = 1 the_log = 0 while the_pow <= exp: if exp & the_pow == the_pow: ans = (ans * pow2[the_log]) % MOD the_pow *= 2 the_log += 1 return ans def main(): n = 1 k = int(input()) a = input().split() x = 0 y = 0 for i in range(k): n = (n * int(a[i])) % MOD1 x = exp2mod(n) if n % 2 == 0: x = (x + 2) % MOD else: x = (x - 2) % MOD if x % 2 == 0: x = x // 2 else: x = (x + MOD) // 2 if x % 3 == 0: x = x // 3 elif x % 3 == 1: x = (x + MOD) // 3 else: x = (x + 2 * MOD) // 3 y = exp2mod(n) if y % 2 == 0: y = y // 2 else: y = (y + MOD) // 2 print(str(x) + "/" + str(y)) main() ```
95,725
Provide tags and a correct Python 3 solution for this coding contest problem. As we all know Barney's job is "PLEASE" and he has not much to do at work. That's why he started playing "cups and key". In this game there are three identical cups arranged in a line from left to right. Initially key to Barney's heart is under the middle cup. <image> Then at one turn Barney swaps the cup in the middle with any of other two cups randomly (he choses each with equal probability), so the chosen cup becomes the middle one. Game lasts n turns and Barney independently choses a cup to swap with the middle one within each turn, and the key always remains in the cup it was at the start. After n-th turn Barney asks a girl to guess which cup contains the key. The girl points to the middle one but Barney was distracted while making turns and doesn't know if the key is under the middle cup. That's why he asked you to tell him the probability that girl guessed right. Number n of game turns can be extremely large, that's why Barney did not give it to you. Instead he gave you an array a1, a2, ..., ak such that <image> in other words, n is multiplication of all elements of the given array. Because of precision difficulties, Barney asked you to tell him the answer as an irreducible fraction. In other words you need to find it as a fraction p / q such that <image>, where <image> is the greatest common divisor. Since p and q can be extremely large, you only need to find the remainders of dividing each of them by 109 + 7. Please note that we want <image> of p and q to be 1, not <image> of their remainders after dividing by 109 + 7. Input The first line of input contains a single integer k (1 ≀ k ≀ 105) β€” the number of elements in array Barney gave you. The second line contains k integers a1, a2, ..., ak (1 ≀ ai ≀ 1018) β€” the elements of the array. Output In the only line of output print a single string x / y where x is the remainder of dividing p by 109 + 7 and y is the remainder of dividing q by 109 + 7. Examples Input 1 2 Output 1/2 Input 3 1 1 1 Output 0/1 Tags: combinatorics, dp, implementation, math, matrices Correct Solution: ``` from functools import reduce mod = 1000000007 n = input() numbers = list(map(int,input().split())) flag = 1 if len(list(filter(lambda x: x%2 == 0,numbers))) else -1 b = reduce(lambda x,y:pow(x,y,mod),numbers,2) b = b*pow(2,mod-2,mod)%mod # b = 2^n-1 a = (b+flag)*pow(3,mod-2,mod)%mod #a = (2^n-1 -/+ 1) / 3 print("%d/%d"%(a,b)) ```
95,726
Provide tags and a correct Python 3 solution for this coding contest problem. As we all know Barney's job is "PLEASE" and he has not much to do at work. That's why he started playing "cups and key". In this game there are three identical cups arranged in a line from left to right. Initially key to Barney's heart is under the middle cup. <image> Then at one turn Barney swaps the cup in the middle with any of other two cups randomly (he choses each with equal probability), so the chosen cup becomes the middle one. Game lasts n turns and Barney independently choses a cup to swap with the middle one within each turn, and the key always remains in the cup it was at the start. After n-th turn Barney asks a girl to guess which cup contains the key. The girl points to the middle one but Barney was distracted while making turns and doesn't know if the key is under the middle cup. That's why he asked you to tell him the probability that girl guessed right. Number n of game turns can be extremely large, that's why Barney did not give it to you. Instead he gave you an array a1, a2, ..., ak such that <image> in other words, n is multiplication of all elements of the given array. Because of precision difficulties, Barney asked you to tell him the answer as an irreducible fraction. In other words you need to find it as a fraction p / q such that <image>, where <image> is the greatest common divisor. Since p and q can be extremely large, you only need to find the remainders of dividing each of them by 109 + 7. Please note that we want <image> of p and q to be 1, not <image> of their remainders after dividing by 109 + 7. Input The first line of input contains a single integer k (1 ≀ k ≀ 105) β€” the number of elements in array Barney gave you. The second line contains k integers a1, a2, ..., ak (1 ≀ ai ≀ 1018) β€” the elements of the array. Output In the only line of output print a single string x / y where x is the remainder of dividing p by 109 + 7 and y is the remainder of dividing q by 109 + 7. Examples Input 1 2 Output 1/2 Input 3 1 1 1 Output 0/1 Tags: combinatorics, dp, implementation, math, matrices Correct Solution: ``` k = int(input()) MOD = 10 ** 9 + 7 antithree = pow(3, MOD - 2, MOD) antitwo = pow(2, MOD - 2, MOD) power = 1 parity = False for t in map(int, input().split()): power *= t power %= MOD - 1 if t % 2 == 0: parity = True q = pow(2, power, MOD) * antitwo q %= MOD if parity: p = (q + 1) * antithree p %= MOD else: p = (q - 1) * antithree p %= MOD print(p, q, sep = '/') # Made By Mostafa_Khaled ```
95,727
Provide tags and a correct Python 3 solution for this coding contest problem. As we all know Barney's job is "PLEASE" and he has not much to do at work. That's why he started playing "cups and key". In this game there are three identical cups arranged in a line from left to right. Initially key to Barney's heart is under the middle cup. <image> Then at one turn Barney swaps the cup in the middle with any of other two cups randomly (he choses each with equal probability), so the chosen cup becomes the middle one. Game lasts n turns and Barney independently choses a cup to swap with the middle one within each turn, and the key always remains in the cup it was at the start. After n-th turn Barney asks a girl to guess which cup contains the key. The girl points to the middle one but Barney was distracted while making turns and doesn't know if the key is under the middle cup. That's why he asked you to tell him the probability that girl guessed right. Number n of game turns can be extremely large, that's why Barney did not give it to you. Instead he gave you an array a1, a2, ..., ak such that <image> in other words, n is multiplication of all elements of the given array. Because of precision difficulties, Barney asked you to tell him the answer as an irreducible fraction. In other words you need to find it as a fraction p / q such that <image>, where <image> is the greatest common divisor. Since p and q can be extremely large, you only need to find the remainders of dividing each of them by 109 + 7. Please note that we want <image> of p and q to be 1, not <image> of their remainders after dividing by 109 + 7. Input The first line of input contains a single integer k (1 ≀ k ≀ 105) β€” the number of elements in array Barney gave you. The second line contains k integers a1, a2, ..., ak (1 ≀ ai ≀ 1018) β€” the elements of the array. Output In the only line of output print a single string x / y where x is the remainder of dividing p by 109 + 7 and y is the remainder of dividing q by 109 + 7. Examples Input 1 2 Output 1/2 Input 3 1 1 1 Output 0/1 Tags: combinatorics, dp, implementation, math, matrices Correct Solution: ``` k = int(input()) n = list(map(int, input().split())) for i in range(k): n[i] = bin(n[i]) n[i] = n[i][2:] magic = 1000000007 def par(s): if s[-1] == '0': return True else: return False def mod_pow(x, s, p): ans = 1 for i in range(len(s)): if s[i] == '1': ans = (((ans * ans) % p) * x) % p else: ans = (ans * ans) % p return ans def div_in_field(a, b, p): b_op = pow(b, p - 2, p) return (b_op * a) % p denominator = 2 n_par = False for i in range(len(n)): denominator = mod_pow(denominator, n[i], magic) if par(n[i]): n_par = True denominator = div_in_field(denominator, 2, magic) numerator = 0 if n_par: numerator = div_in_field(1 + denominator, 3, magic) else: numerator = div_in_field(-1 + denominator, 3, magic) ans = str(numerator) + '/' + str(denominator) print(ans) ```
95,728
Provide tags and a correct Python 3 solution for this coding contest problem. As we all know Barney's job is "PLEASE" and he has not much to do at work. That's why he started playing "cups and key". In this game there are three identical cups arranged in a line from left to right. Initially key to Barney's heart is under the middle cup. <image> Then at one turn Barney swaps the cup in the middle with any of other two cups randomly (he choses each with equal probability), so the chosen cup becomes the middle one. Game lasts n turns and Barney independently choses a cup to swap with the middle one within each turn, and the key always remains in the cup it was at the start. After n-th turn Barney asks a girl to guess which cup contains the key. The girl points to the middle one but Barney was distracted while making turns and doesn't know if the key is under the middle cup. That's why he asked you to tell him the probability that girl guessed right. Number n of game turns can be extremely large, that's why Barney did not give it to you. Instead he gave you an array a1, a2, ..., ak such that <image> in other words, n is multiplication of all elements of the given array. Because of precision difficulties, Barney asked you to tell him the answer as an irreducible fraction. In other words you need to find it as a fraction p / q such that <image>, where <image> is the greatest common divisor. Since p and q can be extremely large, you only need to find the remainders of dividing each of them by 109 + 7. Please note that we want <image> of p and q to be 1, not <image> of their remainders after dividing by 109 + 7. Input The first line of input contains a single integer k (1 ≀ k ≀ 105) β€” the number of elements in array Barney gave you. The second line contains k integers a1, a2, ..., ak (1 ≀ ai ≀ 1018) β€” the elements of the array. Output In the only line of output print a single string x / y where x is the remainder of dividing p by 109 + 7 and y is the remainder of dividing q by 109 + 7. Examples Input 1 2 Output 1/2 Input 3 1 1 1 Output 0/1 Tags: combinatorics, dp, implementation, math, matrices Correct Solution: ``` n = int(input()) ls = [int(x) for x in input().split(' ')] t = 1 mod = 1000000007 def qpow(n: int, m: int): m %= mod - 1 ans = 1 while m: if m & 1: ans = ans * n % mod n = n * n % mod m >>= 1 return ans k = 0 r=mod*2-2 for x in ls: t = t * x % (mod * 2 - 2) if x % 2 == 0: k = 1 t = (t - 1 + r) % r fz = (qpow(4, t >> 1) - 1) * qpow(3, mod - 2) % mod if k == 1: fz = (fz * 2 + 1) % mod fm = qpow(2, t) print('{}/{}'.format(fz, fm)) ```
95,729
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As we all know Barney's job is "PLEASE" and he has not much to do at work. That's why he started playing "cups and key". In this game there are three identical cups arranged in a line from left to right. Initially key to Barney's heart is under the middle cup. <image> Then at one turn Barney swaps the cup in the middle with any of other two cups randomly (he choses each with equal probability), so the chosen cup becomes the middle one. Game lasts n turns and Barney independently choses a cup to swap with the middle one within each turn, and the key always remains in the cup it was at the start. After n-th turn Barney asks a girl to guess which cup contains the key. The girl points to the middle one but Barney was distracted while making turns and doesn't know if the key is under the middle cup. That's why he asked you to tell him the probability that girl guessed right. Number n of game turns can be extremely large, that's why Barney did not give it to you. Instead he gave you an array a1, a2, ..., ak such that <image> in other words, n is multiplication of all elements of the given array. Because of precision difficulties, Barney asked you to tell him the answer as an irreducible fraction. In other words you need to find it as a fraction p / q such that <image>, where <image> is the greatest common divisor. Since p and q can be extremely large, you only need to find the remainders of dividing each of them by 109 + 7. Please note that we want <image> of p and q to be 1, not <image> of their remainders after dividing by 109 + 7. Input The first line of input contains a single integer k (1 ≀ k ≀ 105) β€” the number of elements in array Barney gave you. The second line contains k integers a1, a2, ..., ak (1 ≀ ai ≀ 1018) β€” the elements of the array. Output In the only line of output print a single string x / y where x is the remainder of dividing p by 109 + 7 and y is the remainder of dividing q by 109 + 7. Examples Input 1 2 Output 1/2 Input 3 1 1 1 Output 0/1 Submitted Solution: ``` from functools import reduce MOD = 10 ** 9 + 7 n, a = int(input()), map(int, input().split()) n = reduce(lambda x,y:(x*y)%(MOD-1), a, 1) # 333333336 * 3 = 1 # 500000004 * 2 = 1 k = n % 2 q = (pow(2, n, MOD) * 500000004) % MOD if k == 0: p = ((q + 1) * 333333336) % MOD else: p = ((q - 1) * 333333336) % MOD print("%d/%d" % (p, q)) ``` Yes
95,730
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As we all know Barney's job is "PLEASE" and he has not much to do at work. That's why he started playing "cups and key". In this game there are three identical cups arranged in a line from left to right. Initially key to Barney's heart is under the middle cup. <image> Then at one turn Barney swaps the cup in the middle with any of other two cups randomly (he choses each with equal probability), so the chosen cup becomes the middle one. Game lasts n turns and Barney independently choses a cup to swap with the middle one within each turn, and the key always remains in the cup it was at the start. After n-th turn Barney asks a girl to guess which cup contains the key. The girl points to the middle one but Barney was distracted while making turns and doesn't know if the key is under the middle cup. That's why he asked you to tell him the probability that girl guessed right. Number n of game turns can be extremely large, that's why Barney did not give it to you. Instead he gave you an array a1, a2, ..., ak such that <image> in other words, n is multiplication of all elements of the given array. Because of precision difficulties, Barney asked you to tell him the answer as an irreducible fraction. In other words you need to find it as a fraction p / q such that <image>, where <image> is the greatest common divisor. Since p and q can be extremely large, you only need to find the remainders of dividing each of them by 109 + 7. Please note that we want <image> of p and q to be 1, not <image> of their remainders after dividing by 109 + 7. Input The first line of input contains a single integer k (1 ≀ k ≀ 105) β€” the number of elements in array Barney gave you. The second line contains k integers a1, a2, ..., ak (1 ≀ ai ≀ 1018) β€” the elements of the array. Output In the only line of output print a single string x / y where x is the remainder of dividing p by 109 + 7 and y is the remainder of dividing q by 109 + 7. Examples Input 1 2 Output 1/2 Input 3 1 1 1 Output 0/1 Submitted Solution: ``` class Matrix: def __init__(self, n, m, arr=None): self.n = n self.m = m self.arr = [[0] * m for i in range(n)] if arr is not None: for i in range(n): for j in range(m): self.arr[i][j] = arr[i][j] def __mul__(self, other): assert self.m == other.n ans = Matrix(self.n, other.m) for i in range(self.n): for j in range(other.m): for k in range(self.m): ans.arr[i][j] = (ans.arr[i][j] + self.arr[i][k] * other.arr[k][j]) % (10 ** 9 + 7) return ans def __imul__(self, other): self = self * other return self def __pow__(self, n): if n == 0: ans = Matrix(self.n, self.n) for i in range(self.n): ans.arr[i][i] = 1 return ans elif n & 1 == 1: return self * (self ** (n - 1)) else: t = self ** (n >> 1) return t * t def __ipow__(self, n): self = self ** n return self def __eq__(self, other): if self.n != other.n or self.m != other.m: return False for i in range(self.n): for j in range(self.m): if self.arr[i][j] != other.arr[i][j]: return False return True def fpow(a, n): if n == 0: return 1 elif n & 1 == 1: return (a * fpow(a, n - 1)) % (10 ** 9 + 7) else: t = fpow(a, n >> 1) return (t * t) % (10 ** 9 + 7) transform = Matrix(2, 2, [[1, 1], [0, 4]]) mtx = transform k = int(input()) a = list(map(int, input().split())) x = 1 for j in a: x = (x * j) % (10 ** 9 + 6) x = (x - 1) % (10 ** 9 + 6) if x % 2 == 0: ans = (transform ** (x // 2)) * Matrix(2, 1, [[0], [1]]) print("%d/%d" % (ans.arr[0][0], fpow(2, x))) else: y = (x - 1) % (10 ** 9 + 6) ans = (transform ** (y // 2)) * Matrix(2, 1, [[0], [1]]) print("%d/%d" % ((ans.arr[0][0] * 2 + 1) % (10 ** 9 + 7), (ans.arr[1][0] * 2) % (10 ** 9 + 7))) ``` Yes
95,731
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As we all know Barney's job is "PLEASE" and he has not much to do at work. That's why he started playing "cups and key". In this game there are three identical cups arranged in a line from left to right. Initially key to Barney's heart is under the middle cup. <image> Then at one turn Barney swaps the cup in the middle with any of other two cups randomly (he choses each with equal probability), so the chosen cup becomes the middle one. Game lasts n turns and Barney independently choses a cup to swap with the middle one within each turn, and the key always remains in the cup it was at the start. After n-th turn Barney asks a girl to guess which cup contains the key. The girl points to the middle one but Barney was distracted while making turns and doesn't know if the key is under the middle cup. That's why he asked you to tell him the probability that girl guessed right. Number n of game turns can be extremely large, that's why Barney did not give it to you. Instead he gave you an array a1, a2, ..., ak such that <image> in other words, n is multiplication of all elements of the given array. Because of precision difficulties, Barney asked you to tell him the answer as an irreducible fraction. In other words you need to find it as a fraction p / q such that <image>, where <image> is the greatest common divisor. Since p and q can be extremely large, you only need to find the remainders of dividing each of them by 109 + 7. Please note that we want <image> of p and q to be 1, not <image> of their remainders after dividing by 109 + 7. Input The first line of input contains a single integer k (1 ≀ k ≀ 105) β€” the number of elements in array Barney gave you. The second line contains k integers a1, a2, ..., ak (1 ≀ ai ≀ 1018) β€” the elements of the array. Output In the only line of output print a single string x / y where x is the remainder of dividing p by 109 + 7 and y is the remainder of dividing q by 109 + 7. Examples Input 1 2 Output 1/2 Input 3 1 1 1 Output 0/1 Submitted Solution: ``` # ---------------------------iye ha aam zindegi--------------------------------------------- import math import random import heapq,bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys import threading from collections import defaultdict threading.stack_size(10**8) mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase sys.setrecursionlimit(300000) BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # -------------------game starts now----------------------------------------------------import math class TreeNode: def __init__(self, k, v): self.key = k self.value = v self.left = None self.right = None self.parent = None self.height = 1 self.num_left = 1 self.num_total = 1 class AvlTree: def __init__(self): self._tree = None def add(self, k, v): if not self._tree: self._tree = TreeNode(k, v) return node = self._add(k, v) if node: self._rebalance(node) def _add(self, k, v): node = self._tree while node: if k < node.key: if node.left: node = node.left else: node.left = TreeNode(k, v) node.left.parent = node return node.left elif node.key < k: if node.right: node = node.right else: node.right = TreeNode(k, v) node.right.parent = node return node.right else: node.value = v return @staticmethod def get_height(x): return x.height if x else 0 @staticmethod def get_num_total(x): return x.num_total if x else 0 def _rebalance(self, node): n = node while n: lh = self.get_height(n.left) rh = self.get_height(n.right) n.height = max(lh, rh) + 1 balance_factor = lh - rh n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right) n.num_left = 1 + self.get_num_total(n.left) if balance_factor > 1: if self.get_height(n.left.left) < self.get_height(n.left.right): self._rotate_left(n.left) self._rotate_right(n) elif balance_factor < -1: if self.get_height(n.right.right) < self.get_height(n.right.left): self._rotate_right(n.right) self._rotate_left(n) else: n = n.parent def _remove_one(self, node): """ Side effect!!! Changes node. Node should have exactly one child """ replacement = node.left or node.right if node.parent: if AvlTree._is_left(node): node.parent.left = replacement else: node.parent.right = replacement replacement.parent = node.parent node.parent = None else: self._tree = replacement replacement.parent = None node.left = None node.right = None node.parent = None self._rebalance(replacement) def _remove_leaf(self, node): if node.parent: if AvlTree._is_left(node): node.parent.left = None else: node.parent.right = None self._rebalance(node.parent) else: self._tree = None node.parent = None node.left = None node.right = None def remove(self, k): node = self._get_node(k) if not node: return if AvlTree._is_leaf(node): self._remove_leaf(node) return if node.left and node.right: nxt = AvlTree._get_next(node) node.key = nxt.key node.value = nxt.value if self._is_leaf(nxt): self._remove_leaf(nxt) else: self._remove_one(nxt) self._rebalance(node) else: self._remove_one(node) def get(self, k): node = self._get_node(k) return node.value if node else -1 def _get_node(self, k): if not self._tree: return None node = self._tree while node: if k < node.key: node = node.left elif node.key < k: node = node.right else: return node return None def get_at(self, pos): x = pos + 1 node = self._tree while node: if x < node.num_left: node = node.left elif node.num_left < x: x -= node.num_left node = node.right else: return (node.key, node.value) raise IndexError("Out of ranges") @staticmethod def _is_left(node): return node.parent.left and node.parent.left == node @staticmethod def _is_leaf(node): return node.left is None and node.right is None def _rotate_right(self, node): if not node.parent: self._tree = node.left node.left.parent = None elif AvlTree._is_left(node): node.parent.left = node.left node.left.parent = node.parent else: node.parent.right = node.left node.left.parent = node.parent bk = node.left.right node.left.right = node node.parent = node.left node.left = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) def _rotate_left(self, node): if not node.parent: self._tree = node.right node.right.parent = None elif AvlTree._is_left(node): node.parent.left = node.right node.right.parent = node.parent else: node.parent.right = node.right node.right.parent = node.parent bk = node.right.left node.right.left = node node.parent = node.right node.right = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) @staticmethod def _get_next(node): if not node.right: return node.parent n = node.right while n.left: n = n.left return n # -----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default=2**51, func=lambda a, b: a & b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------game starts now----------------------------------------------------import math class SegmentTree: def __init__(self, data, default=0, func=lambda a, b: a + b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------------------iye ha chutiya zindegi------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD # --------------------------------------iye ha combinations ka zindegi--------------------------------- def powm(a, n, m): if a == 1 or n == 0: return 1 if n % 2 == 0: s = powm(a, n // 2, m) return s * s % m else: return a * powm(a, n - 1, m) % m # --------------------------------------iye ha power ka zindegi--------------------------------- def sort_list(list1, list2): zipped_pairs = zip(list2, list1) z = [x for _, x in sorted(zipped_pairs)] return z # --------------------------------------------------product---------------------------------------- def product(l): por = 1 for i in range(len(l)): por *= l[i] return por # --------------------------------------------------binary---------------------------------------- def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left) / 2) # Check if middle element is # less than or equal to key if (arr[mid] < key): count = mid + 1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # --------------------------------------------------binary---------------------------------------- def countdig(n): c = 0 while (n > 0): n //= 10 c += 1 return c def binary(x, length): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y def countGreater(arr, n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) if (arr[m] >= k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) # --------------------------------------------------binary------------------------------------ def multiply(a, b): mul = [[0 for x in range(2)]for y in range(2)] for i in range(2): for j in range(2): mul[i][j] = 0 for k in range(2): mul[i][j] += a[i][k] * b[k][j] mul[i][j]%=mod for i in range(2): for j in range(2): a[i][j] = mul[i][j] # Updating our matrix return a def power(M,n): if n==0: res=[[0 for i in range(2)]for j in range(2)] res[0][0]=1 res[1][1]=1 return res if n==1: return M else: res=[[1,0],[0,1]] if n%2==1: res=multiply(res,M) re=power(M,n//2) re=multiply(re,re) re=multiply(re,res) return re n=int(input()) l=list(map(int,input().split())) req=1 for i in l: req*=i req%=mod-1 if req==0: req=mod-1 if req==1: print("0/1") sys.exit(0) M=[[0 for i in range(2)]for j in range(2)] M[0][0]=1 M[0][1]=2 M[1][0]=1 M[1][1]=0 M=power(M,req-2) num=M[0][0]%mod de=pow(2,req-1,mod) print(str(num)+"/"+str(de)) ``` Yes
95,732
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As we all know Barney's job is "PLEASE" and he has not much to do at work. That's why he started playing "cups and key". In this game there are three identical cups arranged in a line from left to right. Initially key to Barney's heart is under the middle cup. <image> Then at one turn Barney swaps the cup in the middle with any of other two cups randomly (he choses each with equal probability), so the chosen cup becomes the middle one. Game lasts n turns and Barney independently choses a cup to swap with the middle one within each turn, and the key always remains in the cup it was at the start. After n-th turn Barney asks a girl to guess which cup contains the key. The girl points to the middle one but Barney was distracted while making turns and doesn't know if the key is under the middle cup. That's why he asked you to tell him the probability that girl guessed right. Number n of game turns can be extremely large, that's why Barney did not give it to you. Instead he gave you an array a1, a2, ..., ak such that <image> in other words, n is multiplication of all elements of the given array. Because of precision difficulties, Barney asked you to tell him the answer as an irreducible fraction. In other words you need to find it as a fraction p / q such that <image>, where <image> is the greatest common divisor. Since p and q can be extremely large, you only need to find the remainders of dividing each of them by 109 + 7. Please note that we want <image> of p and q to be 1, not <image> of their remainders after dividing by 109 + 7. Input The first line of input contains a single integer k (1 ≀ k ≀ 105) β€” the number of elements in array Barney gave you. The second line contains k integers a1, a2, ..., ak (1 ≀ ai ≀ 1018) β€” the elements of the array. Output In the only line of output print a single string x / y where x is the remainder of dividing p by 109 + 7 and y is the remainder of dividing q by 109 + 7. Examples Input 1 2 Output 1/2 Input 3 1 1 1 Output 0/1 Submitted Solution: ``` mod = int(1e9+7) k = int(input()) top = 1 yoink = 1 a = list(map(int, input().split())) for thing in a: top *= thing yoink *= thing yoink %= 2 top %= (mod-1) def extended_gcd(aa, bb): lastremainder, remainder = abs(aa), abs(bb) x, lastx, y, lasty = 0, 1, 1, 0 while remainder: lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder) x, lastx = lastx - quotient*x, x y, lasty = lasty - quotient*y, y return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1) def modinv(a, m): g, x, y = extended_gcd(a, m) if g != 1: raise ValueError return x % m if top == 0: bot = modinv(2, mod) else: bot = pow(2, top-1, mod) #print(bot) # odd case if yoink % 2 == 0: blah = modinv(3, mod) blah *= (bot+1) blah %= mod print(str(blah) + '/' + str(bot)) else: blah = modinv(3, mod) blah *= (bot+2) blah %= mod print(str(blah-1) + '/' + str(bot)) ``` Yes
95,733
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As we all know Barney's job is "PLEASE" and he has not much to do at work. That's why he started playing "cups and key". In this game there are three identical cups arranged in a line from left to right. Initially key to Barney's heart is under the middle cup. <image> Then at one turn Barney swaps the cup in the middle with any of other two cups randomly (he choses each with equal probability), so the chosen cup becomes the middle one. Game lasts n turns and Barney independently choses a cup to swap with the middle one within each turn, and the key always remains in the cup it was at the start. After n-th turn Barney asks a girl to guess which cup contains the key. The girl points to the middle one but Barney was distracted while making turns and doesn't know if the key is under the middle cup. That's why he asked you to tell him the probability that girl guessed right. Number n of game turns can be extremely large, that's why Barney did not give it to you. Instead he gave you an array a1, a2, ..., ak such that <image> in other words, n is multiplication of all elements of the given array. Because of precision difficulties, Barney asked you to tell him the answer as an irreducible fraction. In other words you need to find it as a fraction p / q such that <image>, where <image> is the greatest common divisor. Since p and q can be extremely large, you only need to find the remainders of dividing each of them by 109 + 7. Please note that we want <image> of p and q to be 1, not <image> of their remainders after dividing by 109 + 7. Input The first line of input contains a single integer k (1 ≀ k ≀ 105) β€” the number of elements in array Barney gave you. The second line contains k integers a1, a2, ..., ak (1 ≀ ai ≀ 1018) β€” the elements of the array. Output In the only line of output print a single string x / y where x is the remainder of dividing p by 109 + 7 and y is the remainder of dividing q by 109 + 7. Examples Input 1 2 Output 1/2 Input 3 1 1 1 Output 0/1 Submitted Solution: ``` mod = 1000000007 def binpow(a, k): res = 1 while k > 0: if k % 2 == 1: res = (res * a) % mod a = (a * a) % mod; k //= 2 return res def binmatpow(a, k): res = [[1, 0], [0, 1]] while k > 0: if k % 2 == 1: res = matmul(res, a) a = matmul(a, a) k //= 2 return res def matmul(a, b): c = [[0 for x in range(2)] for y in range(2)] c[0][0] = a[0][0] * b[0][0] + a[0][1] * b[1][0] % mod c[1][0] = (a[1][0] * b[0][0]% mod + a[1][1] * b[1][0] % mod) % mod c[0][1] = (a[0][0] * b[0][1]% mod + a[0][1] * b[1][1]% mod) % mod c[1][1] = (a[1][0] * b[0][1]%mod + a[1][1] * b[1][1] % mod) % mod return c def main(): rmat = [[1, 0],[0, 0]] test = [[0, 2],[1, 1]] n = int(input()) a = list(map(int, input().split())) t = [[0, 2],[1, 1]] md = 1; for i in range(n): t = binmatpow(t, a[i]) md *= a[i] md %= (mod - 1) p = matmul(rmat, t)[0][0] * binpow(2, mod - 2) % mod q = binpow(2, (md + mod - 2) % mod) print("{0}/{1}".format(p, q)) main() ``` No
95,734
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As we all know Barney's job is "PLEASE" and he has not much to do at work. That's why he started playing "cups and key". In this game there are three identical cups arranged in a line from left to right. Initially key to Barney's heart is under the middle cup. <image> Then at one turn Barney swaps the cup in the middle with any of other two cups randomly (he choses each with equal probability), so the chosen cup becomes the middle one. Game lasts n turns and Barney independently choses a cup to swap with the middle one within each turn, and the key always remains in the cup it was at the start. After n-th turn Barney asks a girl to guess which cup contains the key. The girl points to the middle one but Barney was distracted while making turns and doesn't know if the key is under the middle cup. That's why he asked you to tell him the probability that girl guessed right. Number n of game turns can be extremely large, that's why Barney did not give it to you. Instead he gave you an array a1, a2, ..., ak such that <image> in other words, n is multiplication of all elements of the given array. Because of precision difficulties, Barney asked you to tell him the answer as an irreducible fraction. In other words you need to find it as a fraction p / q such that <image>, where <image> is the greatest common divisor. Since p and q can be extremely large, you only need to find the remainders of dividing each of them by 109 + 7. Please note that we want <image> of p and q to be 1, not <image> of their remainders after dividing by 109 + 7. Input The first line of input contains a single integer k (1 ≀ k ≀ 105) β€” the number of elements in array Barney gave you. The second line contains k integers a1, a2, ..., ak (1 ≀ ai ≀ 1018) β€” the elements of the array. Output In the only line of output print a single string x / y where x is the remainder of dividing p by 109 + 7 and y is the remainder of dividing q by 109 + 7. Examples Input 1 2 Output 1/2 Input 3 1 1 1 Output 0/1 Submitted Solution: ``` mod = 1000000007 def binpow(a, k): if k == 0: return 1 elif k % 2 == 0: t = binpow(a, k // 2) return t * t % mod else: t = binpow(a, k - 1) return t * a % mod def binmatpow(a, k): if k == 0: return [[1, 0],[0, 1]] elif k % 2 == 0: t = binmatpow(a, k // 2) return matmul(t, t) else: t = binmatpow(a, k - 1) return matmul(t, a) def matmul(a, b): c = [[0 for x in range(2)] for y in range(2)] c[0][0] = (a[0][0] * b[0][0] + a[0][1] * b[1][0]) % mod c[1][0] = (a[1][0] * b[0][0] + a[1][1] * b[1][0]) % mod c[0][1] = (a[0][0] * b[0][1] + a[0][1] * b[1][1]) % mod c[1][1] = (a[1][0] * b[0][1] + a[1][1] * b[1][1]) % mod return c def main(): test = [[0, 2],[1, 1]] rmat = [[1, 0],[0, 0]] n = int(input()) a = list(map(int, input().split())) t = test.copy() md = 1; for i in range(n): t = binmatpow(t, a[i]) print(a[i]) print(t) md *= a[i] md %= (mod - 1) p = (matmul(rmat, t)[0][0] * binpow(2, mod - 2)) % mod q = (binpow(2, md) * binpow(2, mod - 2)) % mod print("{0}/{1}".format(p, q)) main() ``` No
95,735
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As we all know Barney's job is "PLEASE" and he has not much to do at work. That's why he started playing "cups and key". In this game there are three identical cups arranged in a line from left to right. Initially key to Barney's heart is under the middle cup. <image> Then at one turn Barney swaps the cup in the middle with any of other two cups randomly (he choses each with equal probability), so the chosen cup becomes the middle one. Game lasts n turns and Barney independently choses a cup to swap with the middle one within each turn, and the key always remains in the cup it was at the start. After n-th turn Barney asks a girl to guess which cup contains the key. The girl points to the middle one but Barney was distracted while making turns and doesn't know if the key is under the middle cup. That's why he asked you to tell him the probability that girl guessed right. Number n of game turns can be extremely large, that's why Barney did not give it to you. Instead he gave you an array a1, a2, ..., ak such that <image> in other words, n is multiplication of all elements of the given array. Because of precision difficulties, Barney asked you to tell him the answer as an irreducible fraction. In other words you need to find it as a fraction p / q such that <image>, where <image> is the greatest common divisor. Since p and q can be extremely large, you only need to find the remainders of dividing each of them by 109 + 7. Please note that we want <image> of p and q to be 1, not <image> of their remainders after dividing by 109 + 7. Input The first line of input contains a single integer k (1 ≀ k ≀ 105) β€” the number of elements in array Barney gave you. The second line contains k integers a1, a2, ..., ak (1 ≀ ai ≀ 1018) β€” the elements of the array. Output In the only line of output print a single string x / y where x is the remainder of dividing p by 109 + 7 and y is the remainder of dividing q by 109 + 7. Examples Input 1 2 Output 1/2 Input 3 1 1 1 Output 0/1 Submitted Solution: ``` mod = 1000000007 def binpow(a, k): res = 1 while k > 0: if k % 2 == 1: res *= a a = (a * a) % mod; k //= 2 return res; def binmatpow(a, k): res = [[1, 0], [0, 1]] while k > 0: if k % 2 == 1: res = matmul(res, a) a = matmul(a, a) k //= 2 return res def matmul(a, b): c = [[0 for x in range(2)] for y in range(2)] c[0][0] = (a[0][0] * b[0][0] + a[0][1] * b[1][0]) % mod c[1][0] = (a[1][0] * b[0][0] + a[1][1] * b[1][0]) % mod c[0][1] = (a[0][0] * b[0][1] + a[0][1] * b[1][1]) % mod c[1][1] = (a[1][0] * b[0][1] + a[1][1] * b[1][1]) % mod return c def main(): rmat = [[1, 0],[0, 0]] test = [[0, 2],[1, 1]] n = int(input()) a = list(map(int, input().split())) t = [[1, 0],[0, 0]] md = 1; for i in range(n): t = binmatpow(t, a[i]) md *= a[i] md %= (mod - 1) p = (matmul(rmat, t)[0][0] * binpow(2, mod - 2)) % mod q = (binpow(2, md) * binpow(2, mod - 2)) % mod print("{0}/{1}".format(p, q)) main() ``` No
95,736
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As we all know Barney's job is "PLEASE" and he has not much to do at work. That's why he started playing "cups and key". In this game there are three identical cups arranged in a line from left to right. Initially key to Barney's heart is under the middle cup. <image> Then at one turn Barney swaps the cup in the middle with any of other two cups randomly (he choses each with equal probability), so the chosen cup becomes the middle one. Game lasts n turns and Barney independently choses a cup to swap with the middle one within each turn, and the key always remains in the cup it was at the start. After n-th turn Barney asks a girl to guess which cup contains the key. The girl points to the middle one but Barney was distracted while making turns and doesn't know if the key is under the middle cup. That's why he asked you to tell him the probability that girl guessed right. Number n of game turns can be extremely large, that's why Barney did not give it to you. Instead he gave you an array a1, a2, ..., ak such that <image> in other words, n is multiplication of all elements of the given array. Because of precision difficulties, Barney asked you to tell him the answer as an irreducible fraction. In other words you need to find it as a fraction p / q such that <image>, where <image> is the greatest common divisor. Since p and q can be extremely large, you only need to find the remainders of dividing each of them by 109 + 7. Please note that we want <image> of p and q to be 1, not <image> of their remainders after dividing by 109 + 7. Input The first line of input contains a single integer k (1 ≀ k ≀ 105) β€” the number of elements in array Barney gave you. The second line contains k integers a1, a2, ..., ak (1 ≀ ai ≀ 1018) β€” the elements of the array. Output In the only line of output print a single string x / y where x is the remainder of dividing p by 109 + 7 and y is the remainder of dividing q by 109 + 7. Examples Input 1 2 Output 1/2 Input 3 1 1 1 Output 0/1 Submitted Solution: ``` k=int(input()) x=input().split(' ') sum=0 for i in x: sum = sum + int(i) if sum % 2 == 1: print("0/1") else : sum/=2 sum = 2**sum sum = sum % 1000000007 print("1/",end="") print(int(sum)) ``` No
95,737
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya plays the LionAge II. He was bored of playing with a stupid computer, so he installed this popular MMORPG, to fight with his friends. Vasya came up with the name of his character β€” non-empty string s, consisting of a lowercase Latin letters. However, in order not to put up a front of friends, Vasya has decided to change no more than k letters of the character name so that the new name sounded as good as possible. Euphony of the line is defined as follows: for each pair of adjacent letters x and y (x immediately precedes y) the bonus c(x, y) is added to the result. Your task is to determine what the greatest Euphony can be obtained by changing at most k letters in the name of the Vasya's character. Input The first line contains character's name s and an integer number k (0 ≀ k ≀ 100). The length of the nonempty string s does not exceed 100. The second line contains an integer number n (0 ≀ n ≀ 676) β€” amount of pairs of letters, giving bonus to the euphony. The next n lines contain description of these pairs Β«x y cΒ», which means that sequence xy gives bonus c (x, y β€” lowercase Latin letters, - 1000 ≀ c ≀ 1000). It is guaranteed that no pair x y mentioned twice in the input data. Output Output the only number β€” maximum possible euphony ΠΎf the new character's name. Examples Input winner 4 4 s e 7 o s 8 l o 13 o o 8 Output 36 Input abcdef 1 5 a b -10 b c 5 c d 5 d e 5 e f 5 Output 20 Note In the first example the most euphony name will be looser. It is easy to calculate that its euphony is 36. Tags: dp Correct Solution: ``` from math import inf from sys import stdin input = stdin.readline s,k = input().split() n = len(s) k = int(k) ch = [[0]*26 for _ in range(26)] for _ in range(int(input())): a,b,c = input().split() ch[ord(a)-97][ord(b)-97] = int(c) dp = [[[-inf]*26 for _ in range(k+2)] for _ in range(n)] dp[0][0][ord(s[0])-97] = 0 for i in range(26): if ord(s[0])-97 != i: dp[0][1][i] = 0 for i in range(n-1): for j in range(k+1): for m in range(26): for n in range(26): if ord(s[i+1])-97 != n: dp[i+1][j+1][n] = max(dp[i+1][j+1][n],dp[i][j][m]+ch[m][n]) else: dp[i+1][j][n] = max(dp[i+1][j][n],dp[i][j][m]+ch[m][n]) print(max(map(max,dp[-1][:-1]))) ```
95,738
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya plays the LionAge II. He was bored of playing with a stupid computer, so he installed this popular MMORPG, to fight with his friends. Vasya came up with the name of his character β€” non-empty string s, consisting of a lowercase Latin letters. However, in order not to put up a front of friends, Vasya has decided to change no more than k letters of the character name so that the new name sounded as good as possible. Euphony of the line is defined as follows: for each pair of adjacent letters x and y (x immediately precedes y) the bonus c(x, y) is added to the result. Your task is to determine what the greatest Euphony can be obtained by changing at most k letters in the name of the Vasya's character. Input The first line contains character's name s and an integer number k (0 ≀ k ≀ 100). The length of the nonempty string s does not exceed 100. The second line contains an integer number n (0 ≀ n ≀ 676) β€” amount of pairs of letters, giving bonus to the euphony. The next n lines contain description of these pairs Β«x y cΒ», which means that sequence xy gives bonus c (x, y β€” lowercase Latin letters, - 1000 ≀ c ≀ 1000). It is guaranteed that no pair x y mentioned twice in the input data. Output Output the only number β€” maximum possible euphony ΠΎf the new character's name. Examples Input winner 4 4 s e 7 o s 8 l o 13 o o 8 Output 36 Input abcdef 1 5 a b -10 b c 5 c d 5 d e 5 e f 5 Output 20 Note In the first example the most euphony name will be looser. It is easy to calculate that its euphony is 36. Tags: dp Correct Solution: ``` from math import inf s,k= input().split() k=int(k) dict=[[0]*26 for i in range(26)] for i in range(int(input())): x=input().split() # print(ord(x[0])-97,ord(x[1])-97) dict[ord(x[0])-97][ord(x[1])-97]=int(x[2]) dp=[[[-inf]*26 for j in range(k+2)]for i in range(len(s))] m=-1 for i in range(26): if ord(s[0])-97==i: dp[0][0][i]=0 else: dp[0][1][i]=0 m=-1 for i in range(1,len(s)): for j in range(k+1): for p in range(26): if ord(s[i])-97==p: for xx in range(26): dp[i][j][p]=max(dp[i-1][j][xx]+dict[xx][p],dp[i][j][p]) else: for xx in range(26): dp[i][j+1][p]=max(dp[i-1][j][xx]+dict[xx][p],dp[i][j+1][p]) print(max(map(max, dp[-1][:-1]))) ```
95,739
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya plays the LionAge II. He was bored of playing with a stupid computer, so he installed this popular MMORPG, to fight with his friends. Vasya came up with the name of his character β€” non-empty string s, consisting of a lowercase Latin letters. However, in order not to put up a front of friends, Vasya has decided to change no more than k letters of the character name so that the new name sounded as good as possible. Euphony of the line is defined as follows: for each pair of adjacent letters x and y (x immediately precedes y) the bonus c(x, y) is added to the result. Your task is to determine what the greatest Euphony can be obtained by changing at most k letters in the name of the Vasya's character. Input The first line contains character's name s and an integer number k (0 ≀ k ≀ 100). The length of the nonempty string s does not exceed 100. The second line contains an integer number n (0 ≀ n ≀ 676) β€” amount of pairs of letters, giving bonus to the euphony. The next n lines contain description of these pairs Β«x y cΒ», which means that sequence xy gives bonus c (x, y β€” lowercase Latin letters, - 1000 ≀ c ≀ 1000). It is guaranteed that no pair x y mentioned twice in the input data. Output Output the only number β€” maximum possible euphony ΠΎf the new character's name. Examples Input winner 4 4 s e 7 o s 8 l o 13 o o 8 Output 36 Input abcdef 1 5 a b -10 b c 5 c d 5 d e 5 e f 5 Output 20 Note In the first example the most euphony name will be looser. It is easy to calculate that its euphony is 36. Tags: dp Correct Solution: ``` import string s, k = input().split() max_changes = int(k) len_s = len(s) alpha = string.ascii_lowercase bonuses = { ch: { ch: 0 for ch in alpha } for ch in alpha } for i in range(int(input())): a, b, x = input().split() bonuses[a][b] = int(x) def improve(current, changed, a, b, score): if b not in current[changed] or current[changed][b] < score: current[changed][b] = score #print('%c: current[%d][%c] <- %d' % (a, changed, b, score)) current = [ { s[0]: 0 }, { ch: 0 for ch in alpha } ] for pos in range(1, len_s): previous = current len_current = min(len(previous) + 1, max_changes + 1) current = [ {} for i in range(len_current) ] for changed, scores in enumerate(previous): for a, score in scores.items(): for b, bonus in bonuses[a].items(): if b == s[pos]: if changed < len(current): improve(current, changed, a, b, score + bonus) elif changed + 1 < len(current): improve(current, changed + 1, a, b, score + bonus) best = -(10 ** 5) for changed, scores in enumerate(current): for score in scores.values(): best = max(best, score) print(best) ```
95,740
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya plays the LionAge II. He was bored of playing with a stupid computer, so he installed this popular MMORPG, to fight with his friends. Vasya came up with the name of his character β€” non-empty string s, consisting of a lowercase Latin letters. However, in order not to put up a front of friends, Vasya has decided to change no more than k letters of the character name so that the new name sounded as good as possible. Euphony of the line is defined as follows: for each pair of adjacent letters x and y (x immediately precedes y) the bonus c(x, y) is added to the result. Your task is to determine what the greatest Euphony can be obtained by changing at most k letters in the name of the Vasya's character. Input The first line contains character's name s and an integer number k (0 ≀ k ≀ 100). The length of the nonempty string s does not exceed 100. The second line contains an integer number n (0 ≀ n ≀ 676) β€” amount of pairs of letters, giving bonus to the euphony. The next n lines contain description of these pairs Β«x y cΒ», which means that sequence xy gives bonus c (x, y β€” lowercase Latin letters, - 1000 ≀ c ≀ 1000). It is guaranteed that no pair x y mentioned twice in the input data. Output Output the only number β€” maximum possible euphony ΠΎf the new character's name. Examples Input winner 4 4 s e 7 o s 8 l o 13 o o 8 Output 36 Input abcdef 1 5 a b -10 b c 5 c d 5 d e 5 e f 5 Output 20 Note In the first example the most euphony name will be looser. It is easy to calculate that its euphony is 36. Tags: dp Correct Solution: ``` # Legends Always Come Up with Solution # Author: Manvir Singh import os import sys from io import BytesIO, IOBase from math import inf def main(): s,k=input().split() k=int(k) a=[[0 for _ in range(26)] for _ in range(26)] n=len(s) for _ in range(int(input())): b=input().split() a[ord(b[0])-97][ord(b[1])-97]=int(b[2]) dp=[[[-inf for _ in range(k+1)] for _ in range(26)] for _ in range(n)] z=ord(s[0])-97 if k>0: for i in range(26): dp[0][i][int(i!=z)]=0 else: dp[0][z][0]=0 for i in range(1,n): for j in range(26): for l in range(k+1): if j==ord(s[i])-97: for m in range(26): dp[i][j][l]=max(dp[i-1][m][l]+a[m][j],dp[i][j][l]) elif l!=0: for m in range(26): dp[i][j][l]=max(dp[i-1][m][l-1]+a[m][j],dp[i][j][l]) ma=-inf for j in range(26): for l in range(k+1): ma=max(ma,dp[n-1][j][l]) print(ma) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") if __name__ == "__main__": main() ```
95,741
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya plays the LionAge II. He was bored of playing with a stupid computer, so he installed this popular MMORPG, to fight with his friends. Vasya came up with the name of his character β€” non-empty string s, consisting of a lowercase Latin letters. However, in order not to put up a front of friends, Vasya has decided to change no more than k letters of the character name so that the new name sounded as good as possible. Euphony of the line is defined as follows: for each pair of adjacent letters x and y (x immediately precedes y) the bonus c(x, y) is added to the result. Your task is to determine what the greatest Euphony can be obtained by changing at most k letters in the name of the Vasya's character. Input The first line contains character's name s and an integer number k (0 ≀ k ≀ 100). The length of the nonempty string s does not exceed 100. The second line contains an integer number n (0 ≀ n ≀ 676) β€” amount of pairs of letters, giving bonus to the euphony. The next n lines contain description of these pairs Β«x y cΒ», which means that sequence xy gives bonus c (x, y β€” lowercase Latin letters, - 1000 ≀ c ≀ 1000). It is guaranteed that no pair x y mentioned twice in the input data. Output Output the only number β€” maximum possible euphony ΠΎf the new character's name. Examples Input winner 4 4 s e 7 o s 8 l o 13 o o 8 Output 36 Input abcdef 1 5 a b -10 b c 5 c d 5 d e 5 e f 5 Output 20 Note In the first example the most euphony name will be looser. It is easy to calculate that its euphony is 36. Tags: dp Correct Solution: ``` import math R = lambda: map(int, input().split()) s, k = input().split() k = int(k) g = [[0 for j in range(30)] for i in range(30)] for i in range(int(input())): f, t, sc = input().split() f, t, sc = ord(f) - ord('a'), ord(t) - ord('a'), int(sc) g[f][t] = sc n = len(s) dp = [[[-math.inf for kk in range(30)] for j in range(k + 1)] for i in range(n)] for c in range(26): for j in range(k + 1): dp[0][j][c] = 0 for i in range(1, n): cir, cpr = ord(s[i]) - ord('a'), ord(s[i - 1]) - ord('a') dp[i][0][cir] = max(dp[i][0][cir], dp[i - 1][0][cpr] + g[cpr][cir]) for j in range(1, k + 1): for ci in range(26): for cj in range(26): if j == 1 and ci != cir and cj != cpr: continue dp[i][j][ci] = max(dp[i][j][ci], dp[i - 1][j - (ci != cir)][cj] + g[cj][ci]) print(max(dp[n - 1][j][i] for j in range(k + 1) for i in range(26))) ```
95,742
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya plays the LionAge II. He was bored of playing with a stupid computer, so he installed this popular MMORPG, to fight with his friends. Vasya came up with the name of his character β€” non-empty string s, consisting of a lowercase Latin letters. However, in order not to put up a front of friends, Vasya has decided to change no more than k letters of the character name so that the new name sounded as good as possible. Euphony of the line is defined as follows: for each pair of adjacent letters x and y (x immediately precedes y) the bonus c(x, y) is added to the result. Your task is to determine what the greatest Euphony can be obtained by changing at most k letters in the name of the Vasya's character. Input The first line contains character's name s and an integer number k (0 ≀ k ≀ 100). The length of the nonempty string s does not exceed 100. The second line contains an integer number n (0 ≀ n ≀ 676) β€” amount of pairs of letters, giving bonus to the euphony. The next n lines contain description of these pairs Β«x y cΒ», which means that sequence xy gives bonus c (x, y β€” lowercase Latin letters, - 1000 ≀ c ≀ 1000). It is guaranteed that no pair x y mentioned twice in the input data. Output Output the only number β€” maximum possible euphony ΠΎf the new character's name. Examples Input winner 4 4 s e 7 o s 8 l o 13 o o 8 Output 36 Input abcdef 1 5 a b -10 b c 5 c d 5 d e 5 e f 5 Output 20 Note In the first example the most euphony name will be looser. It is easy to calculate that its euphony is 36. Submitted Solution: ``` import string s, k = input().split() max_changes = int(k) len_s = len(s) alpha = string.ascii_lowercase bonuses = { ch: { ch: 0 for ch in alpha } for ch in alpha } for i in range(int(input())): a, b, x = input().split() bonuses[a][b] = int(x) def improve(current, changed, a, b, score): if b not in current[changed] or current[changed][b] < score: current[changed][b] = score #print('%c: current[%d][%c] <- %d' % (a, changed, b, score)) current = [ { s[0]: 0 }, { ch: 0 for ch in alpha } ] for pos in range(1, len_s): previous = current len_current = min(len(previous) + 1, max_changes + 1) current = [ {} for i in range(len_current) ] for changed, scores in enumerate(previous): for a, score in scores.items(): for b, bonus in bonuses[a].items(): if b == s[pos]: if changed < len(current): improve(current, changed, a, b, score + bonus) elif changed + 1 < len(current): improve(current, changed + 1, a, b, score + bonus) best = 0 for changed, scores in enumerate(current): for score in scores.values(): best = max(best, score) print(best) ``` No
95,743
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya plays the LionAge II. He was bored of playing with a stupid computer, so he installed this popular MMORPG, to fight with his friends. Vasya came up with the name of his character β€” non-empty string s, consisting of a lowercase Latin letters. However, in order not to put up a front of friends, Vasya has decided to change no more than k letters of the character name so that the new name sounded as good as possible. Euphony of the line is defined as follows: for each pair of adjacent letters x and y (x immediately precedes y) the bonus c(x, y) is added to the result. Your task is to determine what the greatest Euphony can be obtained by changing at most k letters in the name of the Vasya's character. Input The first line contains character's name s and an integer number k (0 ≀ k ≀ 100). The length of the nonempty string s does not exceed 100. The second line contains an integer number n (0 ≀ n ≀ 676) β€” amount of pairs of letters, giving bonus to the euphony. The next n lines contain description of these pairs Β«x y cΒ», which means that sequence xy gives bonus c (x, y β€” lowercase Latin letters, - 1000 ≀ c ≀ 1000). It is guaranteed that no pair x y mentioned twice in the input data. Output Output the only number β€” maximum possible euphony ΠΎf the new character's name. Examples Input winner 4 4 s e 7 o s 8 l o 13 o o 8 Output 36 Input abcdef 1 5 a b -10 b c 5 c d 5 d e 5 e f 5 Output 20 Note In the first example the most euphony name will be looser. It is easy to calculate that its euphony is 36. Submitted Solution: ``` # Beautiful Words (DP) # R Visser # Python 3 # 8 Sep 2016 # Solution is O(n*k*h^2) (where h = 26) INF = 1000000000 # Input inp = input().split() s = inp[0] k = int(inp[1]) n = int(input()) # Initialise bonus bonus = [[0 for j in range(26)] for i in range(26)] # Input bonus for i in range(n): inp = input().split() x = inp[0] y = inp[1] c = int(inp[2]) bonus[ord(x)-ord('a')][ord(y)-ord('a')] = c # Convert word to list of numbers from 0 to 25 word = [] for i in range(len(s)): word.append(ord(s[i])-ord('a')) # Initialise DP dp = [[[-INF for w in range(27)] for j in range(k+2)] for i in range(len(s)+1)] dp[0][0][0] = 0 for i in range(len(s)): for j in range(k+1): for u in range(26): for w in range(26): # Check if letter equal if (w == word[i]): dp[i+1][j][w] = max(dp[i+1][j][w], dp[i][j][u] + bonus[u][w]) else: dp[i+1][j+1][w] = max(dp[i+1][j+1][w], dp[i][j][u] + bonus[u][w]) # Obtain solution answer = -INF for i in range(0, k+1): for j in range(0, 26): answer = max(answer, dp[len(s)][i][j]) # Output solution print(answer) ``` No
95,744
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya plays the LionAge II. He was bored of playing with a stupid computer, so he installed this popular MMORPG, to fight with his friends. Vasya came up with the name of his character β€” non-empty string s, consisting of a lowercase Latin letters. However, in order not to put up a front of friends, Vasya has decided to change no more than k letters of the character name so that the new name sounded as good as possible. Euphony of the line is defined as follows: for each pair of adjacent letters x and y (x immediately precedes y) the bonus c(x, y) is added to the result. Your task is to determine what the greatest Euphony can be obtained by changing at most k letters in the name of the Vasya's character. Input The first line contains character's name s and an integer number k (0 ≀ k ≀ 100). The length of the nonempty string s does not exceed 100. The second line contains an integer number n (0 ≀ n ≀ 676) β€” amount of pairs of letters, giving bonus to the euphony. The next n lines contain description of these pairs Β«x y cΒ», which means that sequence xy gives bonus c (x, y β€” lowercase Latin letters, - 1000 ≀ c ≀ 1000). It is guaranteed that no pair x y mentioned twice in the input data. Output Output the only number β€” maximum possible euphony ΠΎf the new character's name. Examples Input winner 4 4 s e 7 o s 8 l o 13 o o 8 Output 36 Input abcdef 1 5 a b -10 b c 5 c d 5 d e 5 e f 5 Output 20 Note In the first example the most euphony name will be looser. It is easy to calculate that its euphony is 36. Submitted Solution: ``` # Legends Always Come Up with Solution # Author: Manvir Singh import os import sys from io import BytesIO, IOBase from collections import defaultdict from heapq import * from math import inf def main(): s,k=input().split() k=int(k) a=[[0 for _ in range(26)] for _ in range(26)] n=int(input()) for _ in range(n): b=input().split() a[ord(b[0])-97][ord(b[1])-97]=int(b[2]) n=len(s) dp=[[[-inf for _ in range(k+2)] for _ in range(26)] for _ in range(n)] z=ord(s[0])-97 for i in range(26): dp[0][i][int(i!=z)]=0 for i in range(1,n): for j in range(26): for l in range(k+1): if j==ord(s[i])-97: for m in range(26): dp[i][j][l]=max(dp[i-1][m][l]+a[m][j],dp[i][j][l]) elif l!=0: for m in range(26): dp[i][j][l]=max(dp[i-1][m][l-1]+a[m][j],dp[i][j][l]) ma=0 for i in range(n): for j in range(26): for l in range(k+1): ma=max(ma,dp[i][j][l]) print(ma) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") if __name__ == "__main__": main() ``` No
95,745
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya plays the LionAge II. He was bored of playing with a stupid computer, so he installed this popular MMORPG, to fight with his friends. Vasya came up with the name of his character β€” non-empty string s, consisting of a lowercase Latin letters. However, in order not to put up a front of friends, Vasya has decided to change no more than k letters of the character name so that the new name sounded as good as possible. Euphony of the line is defined as follows: for each pair of adjacent letters x and y (x immediately precedes y) the bonus c(x, y) is added to the result. Your task is to determine what the greatest Euphony can be obtained by changing at most k letters in the name of the Vasya's character. Input The first line contains character's name s and an integer number k (0 ≀ k ≀ 100). The length of the nonempty string s does not exceed 100. The second line contains an integer number n (0 ≀ n ≀ 676) β€” amount of pairs of letters, giving bonus to the euphony. The next n lines contain description of these pairs Β«x y cΒ», which means that sequence xy gives bonus c (x, y β€” lowercase Latin letters, - 1000 ≀ c ≀ 1000). It is guaranteed that no pair x y mentioned twice in the input data. Output Output the only number β€” maximum possible euphony ΠΎf the new character's name. Examples Input winner 4 4 s e 7 o s 8 l o 13 o o 8 Output 36 Input abcdef 1 5 a b -10 b c 5 c d 5 d e 5 e f 5 Output 20 Note In the first example the most euphony name will be looser. It is easy to calculate that its euphony is 36. Submitted Solution: ``` # Legends Always Come Up with Solution # Author: Manvir Singh import os import sys from io import BytesIO, IOBase from collections import defaultdict from heapq import * from math import inf def main(): s,k=input().split() k=int(k) a=[[0 for _ in range(26)] for _ in range(26)] n=int(input()) for _ in range(n): b=input().split() a[ord(b[0])-97][ord(b[1])-97]=int(b[2]) n=len(s) dp=[[[-inf for _ in range(k+1)] for _ in range(26)] for _ in range(n)] z=ord(s[0])-97 if k>0: for i in range(26): dp[0][i][int(i!=z)]=0 for i in range(1,n): for j in range(26): for l in range(k+1): if j==ord(s[i])-97: for m in range(26): dp[i][j][l]=max(dp[i-1][m][l]+a[m][j],dp[i][j][l]) elif l!=0: for m in range(26): dp[i][j][l]=max(dp[i-1][m][l-1]+a[m][j],dp[i][j][l]) ma=0 for i in range(n): for j in range(26): for l in range(k+1): ma=max(ma,dp[i][j][l]) print(ma) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") if __name__ == "__main__": main() ``` No
95,746
Provide tags and a correct Python 3 solution for this coding contest problem. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO Tags: dfs and similar, dp, dsu, graphs, implementation, trees Correct Solution: ``` def main(): n = int(input()) edges = [] for _ in range(n - 1): u, v = map(int, input().split()) u -= 1 v -= 1 edges.append((u, v)) colors = list(map(int, input().split())) suspect = [(u, v) for (u, v) in edges if colors[u] != colors[v]] if len(suspect) == 0: print("YES") print(1) else: cands = set(suspect[0]) for u, v in suspect: cands &= set([u, v]) if len(cands) == 0: print("NO") else: print("YES") e = list(cands)[0] print(e + 1) main() ```
95,747
Provide tags and a correct Python 3 solution for this coding contest problem. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO Tags: dfs and similar, dp, dsu, graphs, implementation, trees Correct Solution: ``` import sys, os, io def rs(): return sys.stdin.readline().rstrip() def ri(): return int(sys.stdin.readline()) def ria(): return list(map(int, sys.stdin.readline().split())) def ws(s): sys.stdout.write(s + '\n') def wi(n): sys.stdout.write(str(n) + '\n') def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n') import math,datetime,functools,itertools,operator,bisect,fractions,statistics from collections import deque,defaultdict,OrderedDict,Counter from fractions import Fraction from decimal import Decimal from sys import stdout from heapq import heappush, heappop, heapify ,_heapify_max,_heappop_max,nsmallest,nlargest # sys.setrecursionlimit(111111) INF=999999999999999999999999 alphabets="abcdefghijklmnopqrstuvwxyz" class SortedList: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" values = sorted(iterable) self._len = _len = len(values) self._load = _load self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)] self._list_lens = [len(_list) for _list in _lists] self._mins = [_list[0] for _list in _lists] self._fen_tree = [] self._rebuild = True def _fen_build(self): """Build a fenwick tree instance.""" self._fen_tree[:] = self._list_lens _fen_tree = self._fen_tree for i in range(len(_fen_tree)): if i | i + 1 < len(_fen_tree): _fen_tree[i | i + 1] += _fen_tree[i] self._rebuild = False def _fen_update(self, index, value): """Update `fen_tree[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree while index < len(_fen_tree): _fen_tree[index] += value index |= index + 1 def _fen_query(self, end): """Return `sum(_fen_tree[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree x = 0 while end: x += _fen_tree[end - 1] end &= end - 1 return x def _fen_findkth(self, k): """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).""" _list_lens = self._list_lens if k < _list_lens[0]: return 0, k if k >= self._len - _list_lens[-1]: return len(_list_lens) - 1, k + _list_lens[-1] - self._len if self._rebuild: self._fen_build() _fen_tree = self._fen_tree idx = -1 for d in reversed(range(len(_fen_tree).bit_length())): right_idx = idx + (1 << d) if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]: idx = right_idx k -= _fen_tree[idx] return idx + 1, k def _delete(self, pos, idx): """Delete value at the given `(pos, idx)`.""" _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len -= 1 self._fen_update(pos, -1) del _lists[pos][idx] _list_lens[pos] -= 1 if _list_lens[pos]: _mins[pos] = _lists[pos][0] else: del _lists[pos] del _list_lens[pos] del _mins[pos] self._rebuild = True def _loc_left(self, value): """Return an index pair that corresponds to the first position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins lo, pos = -1, len(_lists) - 1 while lo + 1 < pos: mi = (lo + pos) >> 1 if value <= _mins[mi]: pos = mi else: lo = mi if pos and value <= _lists[pos - 1][-1]: pos -= 1 _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value <= _list[mi]: idx = mi else: lo = mi return pos, idx def _loc_right(self, value): """Return an index pair that corresponds to the last position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins pos, hi = 0, len(_lists) while pos + 1 < hi: mi = (pos + hi) >> 1 if value < _mins[mi]: hi = mi else: pos = mi _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value < _list[mi]: idx = mi else: lo = mi return pos, idx def add(self, value): """Add `value` to sorted list.""" _load = self._load _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len += 1 if _lists: pos, idx = self._loc_right(value) self._fen_update(pos, 1) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 _mins[pos] = _list[0] if _load + _load < len(_list): _lists.insert(pos + 1, _list[_load:]) _list_lens.insert(pos + 1, len(_list) - _load) _mins.insert(pos + 1, _list[_load]) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _mins.append(value) _list_lens.append(1) self._rebuild = True def discard(self, value): """Remove `value` from sorted list if it is a member.""" _lists = self._lists if _lists: pos, idx = self._loc_right(value) if idx and _lists[pos][idx - 1] == value: self._delete(pos, idx - 1) def remove(self, value): """Remove `value` from sorted list; `value` must be a member.""" _len = self._len self.discard(value) if _len == self._len: raise ValueError('{0!r} not in list'.format(value)) def pop(self, index=-1): """Remove and return value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) value = self._lists[pos][idx] self._delete(pos, idx) return value def bisect_left(self, value): """Return the first index to insert `value` in the sorted list.""" pos, idx = self._loc_left(value) return self._fen_query(pos) + idx def bisect_right(self, value): """Return the last index to insert `value` in the sorted list.""" pos, idx = self._loc_right(value) return self._fen_query(pos) + idx def count(self, value): """Return number of occurrences of `value` in the sorted list.""" return self.bisect_right(value) - self.bisect_left(value) def __len__(self): """Return the size of the sorted list.""" return self._len def __getitem__(self, index): """Lookup value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) return self._lists[pos][idx] def __delitem__(self, index): """Remove value at `index` from sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._delete(pos, idx) def __contains__(self, value): """Return true if `value` is an element of the sorted list.""" _lists = self._lists if _lists: pos, idx = self._loc_left(value) return idx < len(_lists[pos]) and _lists[pos][idx] == value return False def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return 'SortedList({0})'.format(list(self)) class SegTree: def __init__(self, n): self.N = 1 << n.bit_length() self.tree = [0] * (self.N<<1) def update(self, i, j, v): i += self.N j += self.N while i <= j: if i%2==1: self.tree[i] += v if j%2==0: self.tree[j] += v i, j = (i+1) >> 1, (j-1) >> 1 def query(self, i): v = 0 i += self.N while i > 0: v += self.tree[i] i >>= 1 return v def SieveOfEratosthenes(limit): """Returns all primes not greater than limit.""" isPrime = [True]*(limit+1) isPrime[0] = isPrime[1] = False primes = [] for i in range(2, limit+1): if not isPrime[i]:continue primes += [i] for j in range(i*i, limit+1, i): isPrime[j] = False return primes def main(): mod=1000000007 # InverseofNumber(mod) # InverseofFactorial(mod) # factorial(mod) starttime=datetime.datetime.now() if(os.path.exists('input.txt')): sys.stdin = open("input.txt","r") sys.stdout = open("output.txt","w") ###CODE tc = 1 for _ in range(tc): n=ri() graph=[[] for i in range(n+1)] cntdiffcolorededges=0 edges=[] diffcoledges={} for i in range(n-1): a,b=ria() edges.append([a,b]) graph[a].append(b) graph[b].append(a) col=[0]+ria() for a,b in edges: if col[a]!=col[b]: cntdiffcolorededges+=2 diffcoledges[a]=diffcoledges.get(a,0)+1 diffcoledges[b]=diffcoledges.get(b,0)+1 if cntdiffcolorededges==0: ws("YES") wi(1) exit() for i in diffcoledges: if 2*diffcoledges[i]==cntdiffcolorededges: ws("YES") wi(i) exit() ws("NO") #<--Solving Area Ends endtime=datetime.datetime.now() time=(endtime-starttime).total_seconds()*1000 if(os.path.exists('input.txt')): print("Time:",time,"ms") class FastReader(io.IOBase): newlines = 0 def __init__(self, fd, chunk_size=1024 * 8): self._fd = fd self._chunk_size = chunk_size self.buffer = io.BytesIO() def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size)) 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, size=-1): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size)) 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() class FastWriter(io.IOBase): def __init__(self, fd): self._fd = fd self.buffer = io.BytesIO() self.write = self.buffer.write def flush(self): os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class FastStdin(io.IOBase): def __init__(self, fd=0): self.buffer = FastReader(fd) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") class FastStdout(io.IOBase): def __init__(self, fd=1): self.buffer = FastWriter(fd) self.write = lambda s: self.buffer.write(s.encode("ascii")) self.flush = self.buffer.flush if __name__ == '__main__': sys.stdin = FastStdin() sys.stdout = FastStdout() main() ```
95,748
Provide tags and a correct Python 3 solution for this coding contest problem. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO Tags: dfs and similar, dp, dsu, graphs, implementation, trees Correct Solution: ``` # import itertools # import bisect import math from collections import defaultdict import os import sys from io import BytesIO, IOBase # sys.setrecursionlimit(10 ** 5) ii = lambda: int(input()) lmii = lambda: list(map(int, input().split())) slmii = lambda: sorted(map(int, input().split())) li = lambda: list(input()) mii = lambda: map(int, input().split()) msi = lambda: map(str, input().split()) def gcd(a, b): if b == 0: return a return gcd(b, a % b) def lcm(a, b): return (a * b) // gcd(a, b) def main(): # for _ in " " * int(input()): n = ii() adj = defaultdict(list) for i in range(n - 1): x, y = mii() adj[x].append(y) adj[y].append(x) col = lmii() ans = [] if len(set(col)) == 1: print("YES") print(1) else: for i in adj: for j in adj[i]: if col[i - 1] != col[j - 1]: ans.append([i, j]) if len(ans) == 2: print("YES") print(ans[0][0]) else: s = {ans[0][1], ans[0][0]} for i in ans: s.intersection_update({i[0], i[1]}) if len(s) == 1: print("YES") print(s.pop()) else: print("NO") BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") if __name__ == "__main__": main() ```
95,749
Provide tags and a correct Python 3 solution for this coding contest problem. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO Tags: dfs and similar, dp, dsu, graphs, implementation, trees Correct Solution: ``` n = int(input()) arr = [] brr = [] for i in range(n-1): u,v = list(map(int,input().split())) arr.append(u) brr.append(v) color = list(map(int,input().split())) ans = [] for i in range(n-1): if color[arr[i]-1]!=color[brr[i]-1]: if ans==[]: ans+=[arr[i],brr[i]] else: if arr[i] in ans and brr[i] in ans: print("NO") exit() elif arr[i] in ans: ans = [arr[i]] elif brr[i] in ans: ans = [brr[i]] else: print("NO") exit() print("YES") if len(ans)==0: ans.append(1) print(ans[0]) ```
95,750
Provide tags and a correct Python 3 solution for this coding contest problem. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO Tags: dfs and similar, dp, dsu, graphs, implementation, trees Correct Solution: ``` import sys def answer(n, u, v, colors): suspect = [] for i in range(n-1): if colors[u[i]-1] != colors[v[i]-1]: suspect.append([u[i], v[i]]) if len(suspect) == 0: print('YES') print('1') return s = set(suspect[0]) for tup in suspect: s &= set(tup) if len(s) == 0: print('NO') return else: print('YES') print(s.pop()) return #null. Print 1 or 2 lines. def main(): n = int(sys.stdin.readline()) u = [0 for _ in range(n)] v = [0 for _ in range(n)] for i in range(n-1): u[i], v[i] = map(int, sys.stdin.readline().split()) colors = list(map(int, sys.stdin.readline().split())) answer(n, u, v, colors) return main() ```
95,751
Provide tags and a correct Python 3 solution for this coding contest problem. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO Tags: dfs and similar, dp, dsu, graphs, implementation, trees Correct Solution: ``` n = int(input()) edges = [] for _ in range(n-1): u,v = map(int,input().split()) edges.append([u,v]) ct = [0]+list(map(int,input().split())) ds = [-1]+[0]*n vs = 0 for u,v in edges: if ct[u]!=ct[v]: ds[u]+=1 ds[v]+=1 vs+=1 if vs == max(ds): print("YES") print(ds.index(vs)) else: print("NO") ```
95,752
Provide tags and a correct Python 3 solution for this coding contest problem. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO Tags: dfs and similar, dp, dsu, graphs, implementation, trees Correct Solution: ``` import sys import collections import itertools n = int(sys.stdin.readline()) graph = collections.defaultdict(list) for _ in range(n - 1): u, v = map(int, str.split(sys.stdin.readline())) graph[u].append(v) graph[v].append(u) colors = tuple(map(int, str.split(sys.stdin.readline()))) root = None root_possible = [] for node in graph: diff_subs = [] for sub_node in graph[node]: if colors[node - 1] != colors[sub_node - 1]: diff_subs.append(sub_node) if len(diff_subs) > 1: if root is None: root = node else: print("NO") exit() elif len(diff_subs) == 1: root_possible.append((node, diff_subs[0])) root_possible_set = set(itertools.chain.from_iterable(root_possible)) if root: print("YES") print(root) elif not root_possible: print("YES") print(1) elif len(root_possible_set) == 2: print("YES") print(next(iter(root_possible_set))) else: print("NO") ```
95,753
Provide tags and a correct Python 3 solution for this coding contest problem. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO Tags: dfs and similar, dp, dsu, graphs, implementation, trees Correct Solution: ``` n=int(input()) ip=[[] for i in range(n)] for i in range(n-1): a,b=map(int,input().split()) a-=1 b-=1 ip[a].append(b) ip[b].append(a) col=list(map(int,input().split())) cs=[0 for i in range(n)] for i in range(n): count=0 for j in ip[i]: if col[j]!=col[i]: count+=1 cs[i]=count #print(cs) #print(ip) count=0 c1=0 for i in range(n): if cs[i]==0: continue elif cs[i]==1: c1+=1 ans1=i+1 else: #print("csi",cs[i]) count+=1 ans=i+1 #print(count) if count==0: if c1==0: print('YES') print(1) elif c1==2: print('YES') print(ans1) else: print('NO') elif count==1: if c1<=len(ip[ans-1]): print('YES') print(ans) else: print('NO') else: print('NO') ```
95,754
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO Submitted Solution: ``` n=int(input()) graph=dict() for i in range(1,n+1): graph[i]=[] diff=[] for i in range(n-1): u,v=map(int,input().split()) graph[u].append(v) graph[v].append(u) color=list(map(int,input().split())) # print(color) # print(graph) flag=0 # used to indicate if two different colors nodes are present in an edge for i in range(1,n+1): if(graph[i]!=[]): for j in graph[i]: if(color[i-1]!=color[j-1]): diff.append(i) diff.append(j) flag=1 break if(flag==1): break # print(diff) #check=[-1 for i in range(n)] def dfs(graph,node,col,parentnode): # print(node,col,color[node-1]) # global check if(color[node-1]!=col): return -1 # check[node-1]=0 if(graph[node]!=[]): for i in graph[node]: if(i!=parentnode): f1=dfs(graph,i,col,node) if(f1==-1): return -1 return 1 if(flag==0): # single color nodes are present in the entire tree print("YES") print(n) else: # different color present # print("check",check) #check[diff[0]-1]=0 f=1 for i in graph[diff[0]]: f=dfs(graph,i,color[i-1],diff[0]) # print(f,i) if(f==-1): # some of the children nodes are of different color break if(f!=-1):# if all the children satisfy the condition # flag1=0 # for i in range(n): # if(check[i]==-1): # for j in range(i+1,n): # if(check[j]==-1 and color[j]!=color[i]): # flag1=-1 # two different colors found # break # if(flag1==-1): # break # if(flag1==0): print("YES") print(diff[0]) # else: # f=-1 if(f==-1): # the checking of the children node has started # for i in range(n): # check[i]=-1 # check[diff[1]-1]=0 # print("check1",check1) f2=1 for i in graph[diff[1]]: f2=dfs(graph,i,color[i-1],diff[1]) # print(f2,i) if(f2==-1): break # print(f2,check1) if(f2==-1): print("NO") else:# if all the children satisfy the condition # print(color) # flag1=0 # for i in range(n): # if(check[i]==-1): # for j in range(i+1,n): # if(check[j]==-1 and color[j]!=color[i]): # flag1=-1 # two different colors found # break # if(flag1==-1): # break # if(flag1==0): print("YES") print(diff[1]) # else: # print("NO") ``` Yes
95,755
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO Submitted Solution: ``` # Author : nitish420 -------------------------------------------------------------------- import os import sys from io import BytesIO, IOBase def main(): n=int(input()) tree=[[] for _ in range(n+1)] for _ in range(n-1): a,b=map(int,input().split()) tree[a].append(b) tree[b].append(a) arr=[0]+list(map(int,input().split())) root1,root2=0,0 for i in range(1,n+1): for item in tree[i]: if arr[i]!=arr[item]: root1=i root2=item break if root2: break if not root2: print("YES") print(1) exit() # print(root2,root1) # first taking root1 an ans ans=1 vis=[0]*(n+1) idx=[0]*(n+1) vis[root1]=1 for item in tree[root1]: stack=[item] while stack: x=stack[-1] vis[x]=1 y=idx[x] if y==len(tree[x]): stack.pop() else: z=tree[x][y] if vis[z]==0: if arr[x]!=arr[z]: ans=0 break stack.append(z) idx[x]+=1 if ans==0: break if ans==1: print("YES") print(root1) exit() ans=1 # now taking root two vis=[0]*(n+1) idx=[0]*(n+1) vis[root2]=1 for item in tree[root2]: stack=[item] while stack: x=stack[-1] vis[x]=1 y=idx[x] if y==len(tree[x]): stack.pop() else: z=tree[x][y] if vis[z]==0: if arr[x]!=arr[z]: ans=0 break stack.append(z) idx[x]+=1 if ans==0: break if ans: print("YES") print(root2) else: print("NO") # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = 'x' in file.mode or 'r' not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b'\n') + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode('ascii')) self.read = lambda: self.buffer.read().decode('ascii') self.readline = lambda: self.buffer.readline().decode('ascii') sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip('\r\n') # endregion if __name__ == '__main__': main() ``` Yes
95,756
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO Submitted Solution: ``` import sys class UnionFind: def __init__(self, sz): self.__ranks = [1] * sz self.__sizes = [1] * sz self.__parents = [ i for i in range(sz) ] def find_parent(self, x): if x == self.__parents[x]: return x else: self.__parents[x] = self.find_parent( self.__parents[x] ) return self.__parents[x] def same(self, x, y): return self.find_parent(x) == self.find_parent(y) def unite(self, x, y): px = self.find_parent(x) py = self.find_parent(y) if px == py: return if self.__ranks[px] > self.__ranks[py]: self.__parents[py] = px self.__sizes[px] += self.__sizes[py] else: self.__parents[px] = py self.__sizes[py] += self.__sizes[px] if self.__ranks[px] == self.__ranks[py]: self.__ranks[py] += 1 def size(self, n): return self.__sizes[n] #### def main(): n = int(input()) edge = {} for i in range(n - 1): u,v = map(int, sys.stdin.readline().split()) if u not in edge: edge[u] = [] if v not in edge: edge[v] = [] edge[u].append(v) edge[v].append(u) colors = [-1] * (n + 1) for i,c in enumerate(map(int, sys.stdin.readline().split())): colors[i + 1] = c uf = UnionFind(n + 1) for u in edge.keys(): for v in edge[u]: if colors[u] == colors[v]: uf.unite(u,v) tree = set() for v in range(1,n+1): tree.add(uf.find_parent(v)) target_v = -1 ok = False for u in range(1,n+1): cnt = set() for v in edge[u]: cnt.add(uf.find_parent(v)) if len(cnt) == len(tree) - (1 if uf.size(uf.find_parent(u)) == 1 else 0): ok = True target_v = u break if ok: print("YES") print(target_v) else: print("NO") if __name__ == '__main__': main() ``` Yes
95,757
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO Submitted Solution: ``` #!/usr/bin/env python3 def ri(): return map(int, input().split()) n = int(input()) e = [] for i in range(n-1): a, b = ri() a -= 1 b -= 1 e.append([a, b]) c = list(ri()) ed = [] for ee in e: if c[ee[0]] != c[ee[1]]: ed.append(ee) if len(ed) == 0: print("YES") print(1) exit() cand = ed[0] not0 = 0 not1 = 0 for ee in ed: if cand[0] != ee[0] and cand[0] != ee[1]: not0 = 1 break for ee in ed: if cand[1] != ee[0] and cand[1] != ee[1]: not1 = 1 break if not0 == 0: print("YES") print(cand[0]+1) elif not1 == 0: print("YES") print(cand[1]+1) else: print("NO") ``` Yes
95,758
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO Submitted Solution: ``` def dfs( v, c ): visited[v] = 1 for i in E[v]: if visited[i] == 0: if c == clr[i]: dfs( i, c) else: visited[i] = 2 gc = 0 pos = 0 clr = [] N = int(input()) visited = [ 0 for i in range(N)] E = [ [] for i in range(N) ] for i in range( N - 1 ): s = input().split(' ') a = int(s[0]) - 1 b = int(s[1]) - 1 E[a].append(b) E[b].append(a) clr = input().split(' ') for i in range(N): if visited[i] == 0: dfs(i, clr[i]) if visited[i] == 2: gc += 1 pos = i if gc == 0: print(0) if gc == 1: print('YES\n{}'.format(pos + 1)) if gc > 1: print('NO') ``` No
95,759
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO Submitted Solution: ``` n=int(input()) dct={} dctcheck={} for i in range(n-1): u,v=map(int,input().split()) if(u in dct.keys()): dct[u].append(v) dctcheck[v]=False else: dct[u]=[v] dctcheck[u]=False dctcheck[v]=False if(v in dct.keys()): dct[v].append(u) else: dct[v]=[u] carr=list(map(int,input().split())) cset=set(carr) csetl=len(cset) def func(nd,cl,dct1): if(dct1[nd]==True): return 1 else: dct1[nd]=True if(carr[nd-1]!=cl): return 0 if(nd not in dct.keys()): return 1 for v in dct[nd]: x=func(v,cl,dct1) if(x==0): return 0 return 1 mx=-1 for key in dct.keys(): if(len(dct[key])>mx): mx=len(dct[key]) lst1=[] for key in dct.keys(): if(len(dct[key])==mx): lst1.append(key) check=1 for head in lst1: dct1=dctcheck.copy() dct1[head]=True if(head not in dct.keys()): continue if(len(dct[head])+1<csetl): check=0 continue else: # print("head--> ",head) check=1 for j in dct[head]: cl=carr[j-1] y=func(j,cl,dct1) # print("y ",y,j,cl) # print(dct1) if(y==0): check=0 break if(check==1): print("YES") print(head) exit() if(check==0): print("NO") ``` No
95,760
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO Submitted Solution: ``` n = int(input()) tree = dict() for i in range(n-1): u, v = tuple(map(int, input().split())) if u in tree: tree[u].append(v) else: tree[u] = [v] if v in tree: tree[v].append(u) else: tree[v] = [u] colors = list(map(int, input().split())) subtrees_checked = dict() def check_subtree_color(i, c, checked): if i in subtrees_checked: if len(subtrees_checked[i][0]) > 0: if c == subtrees_checked[i][0][0]: return True else: return False elif len(subtrees_checked[i][1]) > 0: if c in subtrees_checked[i][1]: return False for u in tree[i]: if not u in checked: if colors[u-1] != c: if i in subtrees_checked: subtrees_checked[i][1].append(c) else: subtrees_checked[i] = [[], [c]] return False else: checked.add(u) if not check_subtree_color(u, c, checked): if i in subtrees_checked: subtrees_checked[i][1].append(c) else: subtrees_checked[i] = [[], [c]] return False if i in subtrees_checked: subtrees_checked[i][0].append(c) else: subtrees_checked[i] = [[c], []] return True for u in tree: for v in tree[u]: if not check_subtree_color(v, colors[v-1], {u}): break else: print("YES") print(u) break else: print("NO") ``` No
95,761
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO Submitted Solution: ``` n = int(input()) adj = [[] for _ in range(n)] for _ in range(n - 1): u, v = map(int, input().split()) adj[u - 1].append(v - 1) adj[v - 1].append(u - 1) col = list(map(int, input().split())) def is_single_color(s, i): vis = set([s]) comp, cur = [s], 0 while cur < len(comp): v = comp[cur] cur += 1 for nv in adj[v]: if nv != i and nv not in vis: vis.add(nv) comp.append(nv) return all(col[v] == col[s] for v in comp) def check(s): if all(is_single_color(v, s) for v in adj[s]): print("YES") print(s + 1) exit() for v in range(n): for nv in adj[v]: if col[nv] != col[v]: check(nv) check(v) print("NO") exit() ``` No
95,762
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Rick and Morty want to find MR. PBH and they can't do it alone. So they need of Mr. Meeseeks. They Have generated n Mr. Meeseeks, standing in a line numbered from 1 to n. Each of them has his own color. i-th Mr. Meeseeks' color is ai. Rick and Morty are gathering their army and they want to divide Mr. Meeseeks into some squads. They don't want their squads to be too colorful, so each squad should have Mr. Meeseeks of at most k different colors. Also each squad should be a continuous subarray of Mr. Meeseeks in the line. Meaning that for each 1 ≀ i ≀ e ≀ j ≀ n, if Mr. Meeseeks number i and Mr. Meeseeks number j are in the same squad then Mr. Meeseeks number e should be in that same squad. <image> Also, each squad needs its own presidio, and building a presidio needs money, so they want the total number of squads to be minimized. Rick and Morty haven't finalized the exact value of k, so in order to choose it, for each k between 1 and n (inclusive) need to know the minimum number of presidios needed. Input The first line of input contains a single integer n (1 ≀ n ≀ 105) β€” number of Mr. Meeseeks. The second line contains n integers a1, a2, ..., an separated by spaces (1 ≀ ai ≀ n) β€” colors of Mr. Meeseeks in order they standing in a line. Output In the first and only line of input print n integers separated by spaces. i-th integer should be the minimum number of presidios needed if the value of k is i. Examples Input 5 1 3 4 3 3 Output 4 2 1 1 1 Input 8 1 5 7 8 1 7 6 1 Output 8 4 3 2 1 1 1 1 Note For the first sample testcase, some optimal ways of dividing army into squads for each k are: 1. [1], [3], [4], [3, 3] 2. [1], [3, 4, 3, 3] 3. [1, 3, 4, 3, 3] 4. [1, 3, 4, 3, 3] 5. [1, 3, 4, 3, 3] For the second testcase, some optimal ways of dividing army into squads for each k are: 1. [1], [5], [7], [8], [1], [7], [6], [1] 2. [1, 5], [7, 8], [1, 7], [6, 1] 3. [1, 5, 7], [8], [1, 7, 6, 1] 4. [1, 5, 7, 8], [1, 7, 6, 1] 5. [1, 5, 7, 8, 1, 7, 6, 1] 6. [1, 5, 7, 8, 1, 7, 6, 1] 7. [1, 5, 7, 8, 1, 7, 6, 1] 8. [1, 5, 7, 8, 1, 7, 6, 1] Submitted Solution: ``` n=int(input()) import math a=input().split() t=1 r=[] w=1 d=a[0] for i in range(1,n+1): p=[] z=0 while(z<n): if(not(a[z] in p)): p=p+[a[z]] if(len(p)>i): p=[a[z]] if(z!=n-1):w+=1 z+=1 r=r+[w] w=1 for i in r: print(i,end=" ") ``` No
95,763
Provide tags and a correct Python 3 solution for this coding contest problem. It's been almost a week since Polycarp couldn't get rid of insomnia. And as you may already know, one week in Berland lasts k days! When Polycarp went to a doctor with his problem, the doctor asked him about his sleeping schedule (more specifically, the average amount of hours of sleep per week). Luckily, Polycarp kept records of sleep times for the last n days. So now he has a sequence a1, a2, ..., an, where ai is the sleep time on the i-th day. The number of records is so large that Polycarp is unable to calculate the average value by himself. Thus he is asking you to help him with the calculations. To get the average Polycarp is going to consider k consecutive days as a week. So there will be n - k + 1 weeks to take into consideration. For example, if k = 2, n = 3 and a = [3, 4, 7], then the result is <image>. You should write a program which will calculate average sleep times of Polycarp over all weeks. Input The first line contains two integer numbers n and k (1 ≀ k ≀ n ≀ 2Β·105). The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 105). Output Output average sleeping time over all weeks. The answer is considered to be correct if its absolute or relative error does not exceed 10 - 6. In particular, it is enough to output real number with at least 6 digits after the decimal point. Examples Input 3 2 3 4 7 Output 9.0000000000 Input 1 1 10 Output 10.0000000000 Input 8 2 1 2 4 100000 123 456 789 1 Output 28964.2857142857 Note In the third example there are n - k + 1 = 7 weeks, so the answer is sums of all weeks divided by 7. Tags: data structures, implementation, math Correct Solution: ``` n,k=map(int,input().split()) arr=list(map(int,input().split())) ww=n-k+1 a=[] a.append(0) for i in range(n): a.append(arr[i]) for i in range(1,n+1): a[i]=a[i]+a[i-1] ans=0 for i in range(k,n+1): tmp=a[i]-a[i-k] ans+=(tmp/ww) print(ans) ```
95,764
Provide tags and a correct Python 3 solution for this coding contest problem. It's been almost a week since Polycarp couldn't get rid of insomnia. And as you may already know, one week in Berland lasts k days! When Polycarp went to a doctor with his problem, the doctor asked him about his sleeping schedule (more specifically, the average amount of hours of sleep per week). Luckily, Polycarp kept records of sleep times for the last n days. So now he has a sequence a1, a2, ..., an, where ai is the sleep time on the i-th day. The number of records is so large that Polycarp is unable to calculate the average value by himself. Thus he is asking you to help him with the calculations. To get the average Polycarp is going to consider k consecutive days as a week. So there will be n - k + 1 weeks to take into consideration. For example, if k = 2, n = 3 and a = [3, 4, 7], then the result is <image>. You should write a program which will calculate average sleep times of Polycarp over all weeks. Input The first line contains two integer numbers n and k (1 ≀ k ≀ n ≀ 2Β·105). The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 105). Output Output average sleeping time over all weeks. The answer is considered to be correct if its absolute or relative error does not exceed 10 - 6. In particular, it is enough to output real number with at least 6 digits after the decimal point. Examples Input 3 2 3 4 7 Output 9.0000000000 Input 1 1 10 Output 10.0000000000 Input 8 2 1 2 4 100000 123 456 789 1 Output 28964.2857142857 Note In the third example there are n - k + 1 = 7 weeks, so the answer is sums of all weeks divided by 7. Tags: data structures, implementation, math Correct Solution: ``` n, k = map(int, input().split()) a = [0] + list(map(int, input().split())) s, v = sum(a[:k]), 0 for i in range(k, n + 1): s += a[i] - a[i - k] v += s print(v / (n - k + 1)) ```
95,765
Provide tags and a correct Python 3 solution for this coding contest problem. It's been almost a week since Polycarp couldn't get rid of insomnia. And as you may already know, one week in Berland lasts k days! When Polycarp went to a doctor with his problem, the doctor asked him about his sleeping schedule (more specifically, the average amount of hours of sleep per week). Luckily, Polycarp kept records of sleep times for the last n days. So now he has a sequence a1, a2, ..., an, where ai is the sleep time on the i-th day. The number of records is so large that Polycarp is unable to calculate the average value by himself. Thus he is asking you to help him with the calculations. To get the average Polycarp is going to consider k consecutive days as a week. So there will be n - k + 1 weeks to take into consideration. For example, if k = 2, n = 3 and a = [3, 4, 7], then the result is <image>. You should write a program which will calculate average sleep times of Polycarp over all weeks. Input The first line contains two integer numbers n and k (1 ≀ k ≀ n ≀ 2Β·105). The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 105). Output Output average sleeping time over all weeks. The answer is considered to be correct if its absolute or relative error does not exceed 10 - 6. In particular, it is enough to output real number with at least 6 digits after the decimal point. Examples Input 3 2 3 4 7 Output 9.0000000000 Input 1 1 10 Output 10.0000000000 Input 8 2 1 2 4 100000 123 456 789 1 Output 28964.2857142857 Note In the third example there are n - k + 1 = 7 weeks, so the answer is sums of all weeks divided by 7. Tags: data structures, implementation, math Correct Solution: ``` from sys import stdin a,b=map(int,stdin.readline().split()) c=list(map(int,stdin.readline().split())) s=sum(c[:b]);k=s for i in range(1,a-b+1):k=k-c[i-1]+c[i+b-1];s+=k print((s)/(a-b+1)) ```
95,766
Provide tags and a correct Python 3 solution for this coding contest problem. It's been almost a week since Polycarp couldn't get rid of insomnia. And as you may already know, one week in Berland lasts k days! When Polycarp went to a doctor with his problem, the doctor asked him about his sleeping schedule (more specifically, the average amount of hours of sleep per week). Luckily, Polycarp kept records of sleep times for the last n days. So now he has a sequence a1, a2, ..., an, where ai is the sleep time on the i-th day. The number of records is so large that Polycarp is unable to calculate the average value by himself. Thus he is asking you to help him with the calculations. To get the average Polycarp is going to consider k consecutive days as a week. So there will be n - k + 1 weeks to take into consideration. For example, if k = 2, n = 3 and a = [3, 4, 7], then the result is <image>. You should write a program which will calculate average sleep times of Polycarp over all weeks. Input The first line contains two integer numbers n and k (1 ≀ k ≀ n ≀ 2Β·105). The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 105). Output Output average sleeping time over all weeks. The answer is considered to be correct if its absolute or relative error does not exceed 10 - 6. In particular, it is enough to output real number with at least 6 digits after the decimal point. Examples Input 3 2 3 4 7 Output 9.0000000000 Input 1 1 10 Output 10.0000000000 Input 8 2 1 2 4 100000 123 456 789 1 Output 28964.2857142857 Note In the third example there are n - k + 1 = 7 weeks, so the answer is sums of all weeks divided by 7. Tags: data structures, implementation, math Correct Solution: ``` while True: try: n, k = map(int, input().split(' ')) except: break L = [int(x) for x in input().split(' ')] ans = sum = 0.0 for x in L[:k]: sum += x ans += sum for i in range(k, n): sum = sum - L[i - k] + L[i] ans += sum print('%.10f' % (ans / (n - k + 1))) ```
95,767
Provide tags and a correct Python 3 solution for this coding contest problem. It's been almost a week since Polycarp couldn't get rid of insomnia. And as you may already know, one week in Berland lasts k days! When Polycarp went to a doctor with his problem, the doctor asked him about his sleeping schedule (more specifically, the average amount of hours of sleep per week). Luckily, Polycarp kept records of sleep times for the last n days. So now he has a sequence a1, a2, ..., an, where ai is the sleep time on the i-th day. The number of records is so large that Polycarp is unable to calculate the average value by himself. Thus he is asking you to help him with the calculations. To get the average Polycarp is going to consider k consecutive days as a week. So there will be n - k + 1 weeks to take into consideration. For example, if k = 2, n = 3 and a = [3, 4, 7], then the result is <image>. You should write a program which will calculate average sleep times of Polycarp over all weeks. Input The first line contains two integer numbers n and k (1 ≀ k ≀ n ≀ 2Β·105). The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 105). Output Output average sleeping time over all weeks. The answer is considered to be correct if its absolute or relative error does not exceed 10 - 6. In particular, it is enough to output real number with at least 6 digits after the decimal point. Examples Input 3 2 3 4 7 Output 9.0000000000 Input 1 1 10 Output 10.0000000000 Input 8 2 1 2 4 100000 123 456 789 1 Output 28964.2857142857 Note In the third example there are n - k + 1 = 7 weeks, so the answer is sums of all weeks divided by 7. Tags: data structures, implementation, math Correct Solution: ``` def solve(n,k,a): s = sum(a[:k]) tot = 0 l = 0 tot += s for r in range(k,n): s = s-a[l]+a[r] tot += s l+=1 return tot/(n-k+1) def main(): n,k = map(int,input().split(' ')) a = [int(x) for x in input().split(' ')] print('{:0.6f}'.format(solve(n,k,a))) if __name__ == "__main__": main() ```
95,768
Provide tags and a correct Python 3 solution for this coding contest problem. It's been almost a week since Polycarp couldn't get rid of insomnia. And as you may already know, one week in Berland lasts k days! When Polycarp went to a doctor with his problem, the doctor asked him about his sleeping schedule (more specifically, the average amount of hours of sleep per week). Luckily, Polycarp kept records of sleep times for the last n days. So now he has a sequence a1, a2, ..., an, where ai is the sleep time on the i-th day. The number of records is so large that Polycarp is unable to calculate the average value by himself. Thus he is asking you to help him with the calculations. To get the average Polycarp is going to consider k consecutive days as a week. So there will be n - k + 1 weeks to take into consideration. For example, if k = 2, n = 3 and a = [3, 4, 7], then the result is <image>. You should write a program which will calculate average sleep times of Polycarp over all weeks. Input The first line contains two integer numbers n and k (1 ≀ k ≀ n ≀ 2Β·105). The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 105). Output Output average sleeping time over all weeks. The answer is considered to be correct if its absolute or relative error does not exceed 10 - 6. In particular, it is enough to output real number with at least 6 digits after the decimal point. Examples Input 3 2 3 4 7 Output 9.0000000000 Input 1 1 10 Output 10.0000000000 Input 8 2 1 2 4 100000 123 456 789 1 Output 28964.2857142857 Note In the third example there are n - k + 1 = 7 weeks, so the answer is sums of all weeks divided by 7. Tags: data structures, implementation, math Correct Solution: ``` n,k=list(map(int,input().strip().split(' '))) A=list(map(int,input().strip().split(' '))) temp=0 total=0 for i in range(n-k+1): if i==0: temp=sum(A[:k]) total+=temp else: temp-=A[i-1] temp+=A[i+k-1] total+=temp #print(temp) ans=total/(n-k+1) print(ans) ```
95,769
Provide tags and a correct Python 3 solution for this coding contest problem. It's been almost a week since Polycarp couldn't get rid of insomnia. And as you may already know, one week in Berland lasts k days! When Polycarp went to a doctor with his problem, the doctor asked him about his sleeping schedule (more specifically, the average amount of hours of sleep per week). Luckily, Polycarp kept records of sleep times for the last n days. So now he has a sequence a1, a2, ..., an, where ai is the sleep time on the i-th day. The number of records is so large that Polycarp is unable to calculate the average value by himself. Thus he is asking you to help him with the calculations. To get the average Polycarp is going to consider k consecutive days as a week. So there will be n - k + 1 weeks to take into consideration. For example, if k = 2, n = 3 and a = [3, 4, 7], then the result is <image>. You should write a program which will calculate average sleep times of Polycarp over all weeks. Input The first line contains two integer numbers n and k (1 ≀ k ≀ n ≀ 2Β·105). The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 105). Output Output average sleeping time over all weeks. The answer is considered to be correct if its absolute or relative error does not exceed 10 - 6. In particular, it is enough to output real number with at least 6 digits after the decimal point. Examples Input 3 2 3 4 7 Output 9.0000000000 Input 1 1 10 Output 10.0000000000 Input 8 2 1 2 4 100000 123 456 789 1 Output 28964.2857142857 Note In the third example there are n - k + 1 = 7 weeks, so the answer is sums of all weeks divided by 7. Tags: data structures, implementation, math Correct Solution: ``` import sys input = sys.stdin.readline ''' week = k days ai sleep time on i-th day ''' n, k = map(int, input().split()) a = list(map(int, input().split())) k_sum = sum(a[:k]) tot = k_sum left, right = 0, k while right < n: k_sum -= a[left] k_sum += a[right] tot += k_sum left += 1 right += 1 print(tot / (n-k+1)) ```
95,770
Provide tags and a correct Python 3 solution for this coding contest problem. It's been almost a week since Polycarp couldn't get rid of insomnia. And as you may already know, one week in Berland lasts k days! When Polycarp went to a doctor with his problem, the doctor asked him about his sleeping schedule (more specifically, the average amount of hours of sleep per week). Luckily, Polycarp kept records of sleep times for the last n days. So now he has a sequence a1, a2, ..., an, where ai is the sleep time on the i-th day. The number of records is so large that Polycarp is unable to calculate the average value by himself. Thus he is asking you to help him with the calculations. To get the average Polycarp is going to consider k consecutive days as a week. So there will be n - k + 1 weeks to take into consideration. For example, if k = 2, n = 3 and a = [3, 4, 7], then the result is <image>. You should write a program which will calculate average sleep times of Polycarp over all weeks. Input The first line contains two integer numbers n and k (1 ≀ k ≀ n ≀ 2Β·105). The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 105). Output Output average sleeping time over all weeks. The answer is considered to be correct if its absolute or relative error does not exceed 10 - 6. In particular, it is enough to output real number with at least 6 digits after the decimal point. Examples Input 3 2 3 4 7 Output 9.0000000000 Input 1 1 10 Output 10.0000000000 Input 8 2 1 2 4 100000 123 456 789 1 Output 28964.2857142857 Note In the third example there are n - k + 1 = 7 weeks, so the answer is sums of all weeks divided by 7. Tags: data structures, implementation, math Correct Solution: ``` n,k = map(int, input().split()) values = list(map(int, input().split())) total = sum(values[:k]) hours = total for i in range(k,n): total += values[i] - values[i-k] hours += total print("%.6f" % (hours/(n-k+1))) ```
95,771
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It's been almost a week since Polycarp couldn't get rid of insomnia. And as you may already know, one week in Berland lasts k days! When Polycarp went to a doctor with his problem, the doctor asked him about his sleeping schedule (more specifically, the average amount of hours of sleep per week). Luckily, Polycarp kept records of sleep times for the last n days. So now he has a sequence a1, a2, ..., an, where ai is the sleep time on the i-th day. The number of records is so large that Polycarp is unable to calculate the average value by himself. Thus he is asking you to help him with the calculations. To get the average Polycarp is going to consider k consecutive days as a week. So there will be n - k + 1 weeks to take into consideration. For example, if k = 2, n = 3 and a = [3, 4, 7], then the result is <image>. You should write a program which will calculate average sleep times of Polycarp over all weeks. Input The first line contains two integer numbers n and k (1 ≀ k ≀ n ≀ 2Β·105). The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 105). Output Output average sleeping time over all weeks. The answer is considered to be correct if its absolute or relative error does not exceed 10 - 6. In particular, it is enough to output real number with at least 6 digits after the decimal point. Examples Input 3 2 3 4 7 Output 9.0000000000 Input 1 1 10 Output 10.0000000000 Input 8 2 1 2 4 100000 123 456 789 1 Output 28964.2857142857 Note In the third example there are n - k + 1 = 7 weeks, so the answer is sums of all weeks divided by 7. Submitted Solution: ``` n,k = map(int,input().split()) a=list(map(int,input().split())) sum=0 for i in range(k): sum+=a[i] total = sum i=1 while(i+k-1 < n): sum-=a[i-1] sum+=a[i+k-1] i+=1 total+=sum print(format(total/(n-k+1),'.6f')) ``` Yes
95,772
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It's been almost a week since Polycarp couldn't get rid of insomnia. And as you may already know, one week in Berland lasts k days! When Polycarp went to a doctor with his problem, the doctor asked him about his sleeping schedule (more specifically, the average amount of hours of sleep per week). Luckily, Polycarp kept records of sleep times for the last n days. So now he has a sequence a1, a2, ..., an, where ai is the sleep time on the i-th day. The number of records is so large that Polycarp is unable to calculate the average value by himself. Thus he is asking you to help him with the calculations. To get the average Polycarp is going to consider k consecutive days as a week. So there will be n - k + 1 weeks to take into consideration. For example, if k = 2, n = 3 and a = [3, 4, 7], then the result is <image>. You should write a program which will calculate average sleep times of Polycarp over all weeks. Input The first line contains two integer numbers n and k (1 ≀ k ≀ n ≀ 2Β·105). The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 105). Output Output average sleeping time over all weeks. The answer is considered to be correct if its absolute or relative error does not exceed 10 - 6. In particular, it is enough to output real number with at least 6 digits after the decimal point. Examples Input 3 2 3 4 7 Output 9.0000000000 Input 1 1 10 Output 10.0000000000 Input 8 2 1 2 4 100000 123 456 789 1 Output 28964.2857142857 Note In the third example there are n - k + 1 = 7 weeks, so the answer is sums of all weeks divided by 7. Submitted Solution: ``` from itertools import * n,k = [int(x) for x in input().split()] a = list(accumulate([0] + [int(x) for x in input().split()])) print(sum([a[i] - a[i-k] for i in range(k,n+1)]) / (n-k+1)) ``` Yes
95,773
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It's been almost a week since Polycarp couldn't get rid of insomnia. And as you may already know, one week in Berland lasts k days! When Polycarp went to a doctor with his problem, the doctor asked him about his sleeping schedule (more specifically, the average amount of hours of sleep per week). Luckily, Polycarp kept records of sleep times for the last n days. So now he has a sequence a1, a2, ..., an, where ai is the sleep time on the i-th day. The number of records is so large that Polycarp is unable to calculate the average value by himself. Thus he is asking you to help him with the calculations. To get the average Polycarp is going to consider k consecutive days as a week. So there will be n - k + 1 weeks to take into consideration. For example, if k = 2, n = 3 and a = [3, 4, 7], then the result is <image>. You should write a program which will calculate average sleep times of Polycarp over all weeks. Input The first line contains two integer numbers n and k (1 ≀ k ≀ n ≀ 2Β·105). The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 105). Output Output average sleeping time over all weeks. The answer is considered to be correct if its absolute or relative error does not exceed 10 - 6. In particular, it is enough to output real number with at least 6 digits after the decimal point. Examples Input 3 2 3 4 7 Output 9.0000000000 Input 1 1 10 Output 10.0000000000 Input 8 2 1 2 4 100000 123 456 789 1 Output 28964.2857142857 Note In the third example there are n - k + 1 = 7 weeks, so the answer is sums of all weeks divided by 7. Submitted Solution: ``` n, k = list(map(int, input().split())) a = list(map(int, input().split())) running_sum = [] acc = 0 for i in range(0, k): acc += a[i] running_sum.append(acc) total = running_sum[k - 1] for i in range(k, n): acc += a[i] running_sum.append(acc) total += running_sum[i] - running_sum[i - k] print("%.10f" % (total / (n - k + 1))) ``` Yes
95,774
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It's been almost a week since Polycarp couldn't get rid of insomnia. And as you may already know, one week in Berland lasts k days! When Polycarp went to a doctor with his problem, the doctor asked him about his sleeping schedule (more specifically, the average amount of hours of sleep per week). Luckily, Polycarp kept records of sleep times for the last n days. So now he has a sequence a1, a2, ..., an, where ai is the sleep time on the i-th day. The number of records is so large that Polycarp is unable to calculate the average value by himself. Thus he is asking you to help him with the calculations. To get the average Polycarp is going to consider k consecutive days as a week. So there will be n - k + 1 weeks to take into consideration. For example, if k = 2, n = 3 and a = [3, 4, 7], then the result is <image>. You should write a program which will calculate average sleep times of Polycarp over all weeks. Input The first line contains two integer numbers n and k (1 ≀ k ≀ n ≀ 2Β·105). The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 105). Output Output average sleeping time over all weeks. The answer is considered to be correct if its absolute or relative error does not exceed 10 - 6. In particular, it is enough to output real number with at least 6 digits after the decimal point. Examples Input 3 2 3 4 7 Output 9.0000000000 Input 1 1 10 Output 10.0000000000 Input 8 2 1 2 4 100000 123 456 789 1 Output 28964.2857142857 Note In the third example there are n - k + 1 = 7 weeks, so the answer is sums of all weeks divided by 7. Submitted Solution: ``` n, k = list(map(int, input().split())) a = list(map(int, input().split())) r, s, x = n-k+1, 0, [] x.append(a[0]) for i in range(1, n+1): x.append(x[i-1] + a[i-1]) for i in range(k, n+1): s += x[i] - x[i-k] print(s/r) ``` Yes
95,775
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It's been almost a week since Polycarp couldn't get rid of insomnia. And as you may already know, one week in Berland lasts k days! When Polycarp went to a doctor with his problem, the doctor asked him about his sleeping schedule (more specifically, the average amount of hours of sleep per week). Luckily, Polycarp kept records of sleep times for the last n days. So now he has a sequence a1, a2, ..., an, where ai is the sleep time on the i-th day. The number of records is so large that Polycarp is unable to calculate the average value by himself. Thus he is asking you to help him with the calculations. To get the average Polycarp is going to consider k consecutive days as a week. So there will be n - k + 1 weeks to take into consideration. For example, if k = 2, n = 3 and a = [3, 4, 7], then the result is <image>. You should write a program which will calculate average sleep times of Polycarp over all weeks. Input The first line contains two integer numbers n and k (1 ≀ k ≀ n ≀ 2Β·105). The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 105). Output Output average sleeping time over all weeks. The answer is considered to be correct if its absolute or relative error does not exceed 10 - 6. In particular, it is enough to output real number with at least 6 digits after the decimal point. Examples Input 3 2 3 4 7 Output 9.0000000000 Input 1 1 10 Output 10.0000000000 Input 8 2 1 2 4 100000 123 456 789 1 Output 28964.2857142857 Note In the third example there are n - k + 1 = 7 weeks, so the answer is sums of all weeks divided by 7. Submitted Solution: ``` def computeAvg(n, k, a, ans=0.): for i in range(n): ans+=float(min(k,n+k-1,n-i,i+1))*a[i]/1.0/(n-k+1) return float(ans) if __name__ == "__main__": n, k = list(map(int, input().split())) a = list(map(int, input().split())) print(computeAvg(n,k,a)) ``` No
95,776
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It's been almost a week since Polycarp couldn't get rid of insomnia. And as you may already know, one week in Berland lasts k days! When Polycarp went to a doctor with his problem, the doctor asked him about his sleeping schedule (more specifically, the average amount of hours of sleep per week). Luckily, Polycarp kept records of sleep times for the last n days. So now he has a sequence a1, a2, ..., an, where ai is the sleep time on the i-th day. The number of records is so large that Polycarp is unable to calculate the average value by himself. Thus he is asking you to help him with the calculations. To get the average Polycarp is going to consider k consecutive days as a week. So there will be n - k + 1 weeks to take into consideration. For example, if k = 2, n = 3 and a = [3, 4, 7], then the result is <image>. You should write a program which will calculate average sleep times of Polycarp over all weeks. Input The first line contains two integer numbers n and k (1 ≀ k ≀ n ≀ 2Β·105). The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 105). Output Output average sleeping time over all weeks. The answer is considered to be correct if its absolute or relative error does not exceed 10 - 6. In particular, it is enough to output real number with at least 6 digits after the decimal point. Examples Input 3 2 3 4 7 Output 9.0000000000 Input 1 1 10 Output 10.0000000000 Input 8 2 1 2 4 100000 123 456 789 1 Output 28964.2857142857 Note In the third example there are n - k + 1 = 7 weeks, so the answer is sums of all weeks divided by 7. Submitted Solution: ``` #puoy-tang 3, 808B, 2137, G O O D B O Y O puoy-tang inp = input().split() n, k = int(inp[0]), int(inp[1]) cunt = n-k+1 a = input().split() tsum = 0 hlf = 1 for i in range(0,len(a)): a[i] = int(a[i]) tsum += a[i]*min(hlf, k, cunt) if hlf < len(a)/2: hlf += 1 elif hlf > len(a)/2: hlf -= 1 tsum /= n-k+1 print(tsum) ``` No
95,777
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It's been almost a week since Polycarp couldn't get rid of insomnia. And as you may already know, one week in Berland lasts k days! When Polycarp went to a doctor with his problem, the doctor asked him about his sleeping schedule (more specifically, the average amount of hours of sleep per week). Luckily, Polycarp kept records of sleep times for the last n days. So now he has a sequence a1, a2, ..., an, where ai is the sleep time on the i-th day. The number of records is so large that Polycarp is unable to calculate the average value by himself. Thus he is asking you to help him with the calculations. To get the average Polycarp is going to consider k consecutive days as a week. So there will be n - k + 1 weeks to take into consideration. For example, if k = 2, n = 3 and a = [3, 4, 7], then the result is <image>. You should write a program which will calculate average sleep times of Polycarp over all weeks. Input The first line contains two integer numbers n and k (1 ≀ k ≀ n ≀ 2Β·105). The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 105). Output Output average sleeping time over all weeks. The answer is considered to be correct if its absolute or relative error does not exceed 10 - 6. In particular, it is enough to output real number with at least 6 digits after the decimal point. Examples Input 3 2 3 4 7 Output 9.0000000000 Input 1 1 10 Output 10.0000000000 Input 8 2 1 2 4 100000 123 456 789 1 Output 28964.2857142857 Note In the third example there are n - k + 1 = 7 weeks, so the answer is sums of all weeks divided by 7. Submitted Solution: ``` x=input() x=x.split() n=input() n=n.split() for i in range(0,len(x)): x[i]=float(int(x[i])) for i in range(0,len(n)): n[i]=float(int(n[i])) no=x[0]-x[1]+1 sum_=float(0); for i in n: sum_+=i sum_*=2 sum_-=n[0] sum_-=n[-1] print(float(sum_)/float(x[0]-x[1]+1)) ``` No
95,778
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It's been almost a week since Polycarp couldn't get rid of insomnia. And as you may already know, one week in Berland lasts k days! When Polycarp went to a doctor with his problem, the doctor asked him about his sleeping schedule (more specifically, the average amount of hours of sleep per week). Luckily, Polycarp kept records of sleep times for the last n days. So now he has a sequence a1, a2, ..., an, where ai is the sleep time on the i-th day. The number of records is so large that Polycarp is unable to calculate the average value by himself. Thus he is asking you to help him with the calculations. To get the average Polycarp is going to consider k consecutive days as a week. So there will be n - k + 1 weeks to take into consideration. For example, if k = 2, n = 3 and a = [3, 4, 7], then the result is <image>. You should write a program which will calculate average sleep times of Polycarp over all weeks. Input The first line contains two integer numbers n and k (1 ≀ k ≀ n ≀ 2Β·105). The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 105). Output Output average sleeping time over all weeks. The answer is considered to be correct if its absolute or relative error does not exceed 10 - 6. In particular, it is enough to output real number with at least 6 digits after the decimal point. Examples Input 3 2 3 4 7 Output 9.0000000000 Input 1 1 10 Output 10.0000000000 Input 8 2 1 2 4 100000 123 456 789 1 Output 28964.2857142857 Note In the third example there are n - k + 1 = 7 weeks, so the answer is sums of all weeks divided by 7. Submitted Solution: ``` from math import floor def truncate(f, n): return floor(f * 10 ** n) / 10 ** n def bounded_sum(l, p1, p2): r = 0 for i in range(p1, p2 + 1): r += l[i] return r def solve(n, k, a): pos = 0 total = 0 for i in range(n - k + 1): total += bounded_sum(a, pos, pos + k - 1) pos += k - 1 return total/(n - k + 1) N, K = [int(i) for i in input().split()] A = [int(i) for i in input().split()] print(truncate(solve(N, K, A), 10)) # 1521408685546 ``` No
95,779
Provide tags and a correct Python 3 solution for this coding contest problem. n people are standing on a coordinate axis in points with positive integer coordinates strictly less than 106. For each person we know in which direction (left or right) he is facing, and his maximum speed. You can put a bomb in some point with non-negative integer coordinate, and blow it up. At this moment all people will start running with their maximum speed in the direction they are facing. Also, two strange rays will start propagating from the bomb with speed s: one to the right, and one to the left. Of course, the speed s is strictly greater than people's maximum speed. The rays are strange because if at any moment the position and the direction of movement of some ray and some person coincide, then the speed of the person immediately increases by the speed of the ray. You need to place the bomb is such a point that the minimum time moment in which there is a person that has run through point 0, and there is a person that has run through point 106, is as small as possible. In other words, find the minimum time moment t such that there is a point you can place the bomb to so that at time moment t some person has run through 0, and some person has run through point 106. Input The first line contains two integers n and s (2 ≀ n ≀ 105, 2 ≀ s ≀ 106) β€” the number of people and the rays' speed. The next n lines contain the description of people. The i-th of these lines contains three integers xi, vi and ti (0 < xi < 106, 1 ≀ vi < s, 1 ≀ ti ≀ 2) β€” the coordinate of the i-th person on the line, his maximum speed and the direction he will run to (1 is to the left, i.e. in the direction of coordinate decrease, 2 is to the right, i.e. in the direction of coordinate increase), respectively. It is guaranteed that the points 0 and 106 will be reached independently of the bomb's position. Output Print the minimum time needed for both points 0 and 106 to be reached. Your answer is considered correct if its absolute or relative error doesn't exceed 10 - 6. Namely, if your answer is a, and the jury's answer is b, then your answer is accepted, if <image>. Examples Input 2 999 400000 1 2 500000 1 1 Output 500000.000000000000000000000000000000 Input 2 1000 400000 500 1 600000 500 2 Output 400.000000000000000000000000000000 Note In the first example, it is optimal to place the bomb at a point with a coordinate of 400000. Then at time 0, the speed of the first person becomes 1000 and he reaches the point 106 at the time 600. The bomb will not affect on the second person, and he will reach the 0 point at the time 500000. In the second example, it is optimal to place the bomb at the point 500000. The rays will catch up with both people at the time 200. At this time moment, the first is at the point with a coordinate of 300000, and the second is at the point with a coordinate of 700000. Their speed will become 1500 and at the time 400 they will simultaneously run through points 0 and 106. Tags: binary search, implementation, math Correct Solution: ``` import math leftpeople = set() rightpeople = set() n, vl = map(int, input().split()) def leftinterval(x0, v0, t): if x0 / v0 <= t: return (0, 10**6) if x0 / (vl + v0) > t: return (-1, -2) leftbound = x0 rightbound = (vl * vl - v0 * v0) * t + x0 * v0 rightbound /= vl rightbound = int(rightbound) if rightbound > 10**6: rightbound = 10**6 return (leftbound, rightbound) def rightinterval(x0, v0, t): if (10**6 - x0) / v0 <= t: return (0, 10**6) if (10**6 - x0) / (v0 + vl) > t: return (-1, -2) rightbound = x0 leftbound = v0 * x0 + (10**6) * (vl - v0) - t * (vl * vl - v0 * v0) leftbound /= vl leftbound = math.ceil(leftbound) if(leftbound < 0): leftbound = 0 return (leftbound, rightbound) def check(t): events = [] for item in leftpeople: temp = leftinterval(item[0], item[1], t) if(temp[0] > temp[1]): continue events.append((temp[0], 0, 0)) events.append((temp[1], 1, 0)) if(temp[1] - temp[0] == 10**6): break for item in rightpeople: temp = rightinterval(item[0], item[1], t) if(temp[0] > temp[1]): continue events.append((temp[0], 0, 1)) events.append((temp[1], 1, 1)) if(temp[1] - temp[0] == 10**6): break events.sort() opened = [0, 0] for item in events: color = item[2] action = item[1] if action == 0: if opened[(color + 1) % 2] > 0: return True opened[color] += 1 else: opened[color] -= 1 return False for i in range(n): a, b, c = map(int, input().split()) if c == 1: leftpeople.add((a, b)) if c == 2: rightpeople.add((a, b)) l = 0 r = 1e9 for i in range(50): m = (l + r) / 2 if(check(m)): r = m else: l = m print(m) ```
95,780
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. n people are standing on a coordinate axis in points with positive integer coordinates strictly less than 106. For each person we know in which direction (left or right) he is facing, and his maximum speed. You can put a bomb in some point with non-negative integer coordinate, and blow it up. At this moment all people will start running with their maximum speed in the direction they are facing. Also, two strange rays will start propagating from the bomb with speed s: one to the right, and one to the left. Of course, the speed s is strictly greater than people's maximum speed. The rays are strange because if at any moment the position and the direction of movement of some ray and some person coincide, then the speed of the person immediately increases by the speed of the ray. You need to place the bomb is such a point that the minimum time moment in which there is a person that has run through point 0, and there is a person that has run through point 106, is as small as possible. In other words, find the minimum time moment t such that there is a point you can place the bomb to so that at time moment t some person has run through 0, and some person has run through point 106. Input The first line contains two integers n and s (2 ≀ n ≀ 105, 2 ≀ s ≀ 106) β€” the number of people and the rays' speed. The next n lines contain the description of people. The i-th of these lines contains three integers xi, vi and ti (0 < xi < 106, 1 ≀ vi < s, 1 ≀ ti ≀ 2) β€” the coordinate of the i-th person on the line, his maximum speed and the direction he will run to (1 is to the left, i.e. in the direction of coordinate decrease, 2 is to the right, i.e. in the direction of coordinate increase), respectively. It is guaranteed that the points 0 and 106 will be reached independently of the bomb's position. Output Print the minimum time needed for both points 0 and 106 to be reached. Your answer is considered correct if its absolute or relative error doesn't exceed 10 - 6. Namely, if your answer is a, and the jury's answer is b, then your answer is accepted, if <image>. Examples Input 2 999 400000 1 2 500000 1 1 Output 500000.000000000000000000000000000000 Input 2 1000 400000 500 1 600000 500 2 Output 400.000000000000000000000000000000 Note In the first example, it is optimal to place the bomb at a point with a coordinate of 400000. Then at time 0, the speed of the first person becomes 1000 and he reaches the point 106 at the time 600. The bomb will not affect on the second person, and he will reach the 0 point at the time 500000. In the second example, it is optimal to place the bomb at the point 500000. The rays will catch up with both people at the time 200. At this time moment, the first is at the point with a coordinate of 300000, and the second is at the point with a coordinate of 700000. Their speed will become 1500 and at the time 400 they will simultaneously run through points 0 and 106. Submitted Solution: ``` import math leftpeople = set() rightpeople = set() n, vl = map(int, input().split()) def leftinterval(x0, v0, t): if x0 / v0 <= t: return (0, 10**6) if x0 / (vl + v0) > t: return (-1, -2) leftbound = x0 rightbound = (vl * vl - v0 * v0) * t + x0 * v0 rightbound /= vl rightbound = int(rightbound) if rightbound > 10**6: rightbound = 10**6 return (leftbound, rightbound) def rightinterval(x0, v0, t): if (10**6 - x0) / v0 <= t: return (0, 10**6) if (10**6 - x0) / (v0 + vl) > t: return (-1, -2) rightbound = x0 leftbound = v0 * x0 + (10**6) * (vl - v0) - t * (vl * vl - v0 * v0) leftbound /= vl leftbound = math.ceil(leftbound) if(leftbound < 0): leftbound = 0 return (leftbound, rightbound) def check(t): events = [] for item in leftpeople: temp = leftinterval(item[0], item[1], t) if(temp[0] > temp[1]): continue events.append((temp[0], 0, 0)) events.append((temp[1], 1, 0)) for item in rightpeople: temp = rightinterval(item[0], item[1], t) if(temp[0] > temp[1]): continue events.append((temp[0], 0, 1)) events.append((temp[1], 1, 1)) events.sort() opened = [0, 0] for item in events: color = item[2] action = item[1] if action == 0: if opened[(color + 1) % 2] > 0: return True opened[color] += 1 else: opened[color] -= 1 return False for i in range(n): a, b, c = map(int, input().split()) if c == 1: leftpeople.add((a, b)) if c == 2: rightpeople.add((a, b)) l = 0 r = 1e30 for i in range(100): m = (l + r) / 2 if(check(m)): r = m else: l = m print(m) ``` No
95,781
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. n people are standing on a coordinate axis in points with positive integer coordinates strictly less than 106. For each person we know in which direction (left or right) he is facing, and his maximum speed. You can put a bomb in some point with non-negative integer coordinate, and blow it up. At this moment all people will start running with their maximum speed in the direction they are facing. Also, two strange rays will start propagating from the bomb with speed s: one to the right, and one to the left. Of course, the speed s is strictly greater than people's maximum speed. The rays are strange because if at any moment the position and the direction of movement of some ray and some person coincide, then the speed of the person immediately increases by the speed of the ray. You need to place the bomb is such a point that the minimum time moment in which there is a person that has run through point 0, and there is a person that has run through point 106, is as small as possible. In other words, find the minimum time moment t such that there is a point you can place the bomb to so that at time moment t some person has run through 0, and some person has run through point 106. Input The first line contains two integers n and s (2 ≀ n ≀ 105, 2 ≀ s ≀ 106) β€” the number of people and the rays' speed. The next n lines contain the description of people. The i-th of these lines contains three integers xi, vi and ti (0 < xi < 106, 1 ≀ vi < s, 1 ≀ ti ≀ 2) β€” the coordinate of the i-th person on the line, his maximum speed and the direction he will run to (1 is to the left, i.e. in the direction of coordinate decrease, 2 is to the right, i.e. in the direction of coordinate increase), respectively. It is guaranteed that the points 0 and 106 will be reached independently of the bomb's position. Output Print the minimum time needed for both points 0 and 106 to be reached. Your answer is considered correct if its absolute or relative error doesn't exceed 10 - 6. Namely, if your answer is a, and the jury's answer is b, then your answer is accepted, if <image>. Examples Input 2 999 400000 1 2 500000 1 1 Output 500000.000000000000000000000000000000 Input 2 1000 400000 500 1 600000 500 2 Output 400.000000000000000000000000000000 Note In the first example, it is optimal to place the bomb at a point with a coordinate of 400000. Then at time 0, the speed of the first person becomes 1000 and he reaches the point 106 at the time 600. The bomb will not affect on the second person, and he will reach the 0 point at the time 500000. In the second example, it is optimal to place the bomb at the point 500000. The rays will catch up with both people at the time 200. At this time moment, the first is at the point with a coordinate of 300000, and the second is at the point with a coordinate of 700000. Their speed will become 1500 and at the time 400 they will simultaneously run through points 0 and 106. Submitted Solution: ``` print('hello') ``` No
95,782
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. n people are standing on a coordinate axis in points with positive integer coordinates strictly less than 106. For each person we know in which direction (left or right) he is facing, and his maximum speed. You can put a bomb in some point with non-negative integer coordinate, and blow it up. At this moment all people will start running with their maximum speed in the direction they are facing. Also, two strange rays will start propagating from the bomb with speed s: one to the right, and one to the left. Of course, the speed s is strictly greater than people's maximum speed. The rays are strange because if at any moment the position and the direction of movement of some ray and some person coincide, then the speed of the person immediately increases by the speed of the ray. You need to place the bomb is such a point that the minimum time moment in which there is a person that has run through point 0, and there is a person that has run through point 106, is as small as possible. In other words, find the minimum time moment t such that there is a point you can place the bomb to so that at time moment t some person has run through 0, and some person has run through point 106. Input The first line contains two integers n and s (2 ≀ n ≀ 105, 2 ≀ s ≀ 106) β€” the number of people and the rays' speed. The next n lines contain the description of people. The i-th of these lines contains three integers xi, vi and ti (0 < xi < 106, 1 ≀ vi < s, 1 ≀ ti ≀ 2) β€” the coordinate of the i-th person on the line, his maximum speed and the direction he will run to (1 is to the left, i.e. in the direction of coordinate decrease, 2 is to the right, i.e. in the direction of coordinate increase), respectively. It is guaranteed that the points 0 and 106 will be reached independently of the bomb's position. Output Print the minimum time needed for both points 0 and 106 to be reached. Your answer is considered correct if its absolute or relative error doesn't exceed 10 - 6. Namely, if your answer is a, and the jury's answer is b, then your answer is accepted, if <image>. Examples Input 2 999 400000 1 2 500000 1 1 Output 500000.000000000000000000000000000000 Input 2 1000 400000 500 1 600000 500 2 Output 400.000000000000000000000000000000 Note In the first example, it is optimal to place the bomb at a point with a coordinate of 400000. Then at time 0, the speed of the first person becomes 1000 and he reaches the point 106 at the time 600. The bomb will not affect on the second person, and he will reach the 0 point at the time 500000. In the second example, it is optimal to place the bomb at the point 500000. The rays will catch up with both people at the time 200. At this time moment, the first is at the point with a coordinate of 300000, and the second is at the point with a coordinate of 700000. Their speed will become 1500 and at the time 400 they will simultaneously run through points 0 and 106. Submitted Solution: ``` import sys left = [] right = [] n, v = map(int,sys.stdin.readline().split()) for i in range(n): x,vi,t = map(int,sys.stdin.readline().split()) if t==1: left.append((x,vi)) else: right.append((-x,vi)) left = sorted(left) right = sorted(right) def calc_left(x): ans = 10**6 for i in range(len(left)): xi = left[i][0] vi = left[i][1] if x<xi or xi/vi < x/v: t = xi/vi else: t0 = (x-xi)/(v-vi) t = t0+ (xi-t0*vi)/(v+vi) if t < ans: ans = t return ans def calc_right(x): ans = 10**6 c = 10**6 x = c - x for i in range(len(right)): xi = c+right[i][0] vi = right[i][1] if x<xi or xi/vi < x/v: t = xi/vi else: t0 = (x-xi)/(v-vi) t = t0+ (xi-t0*vi)/(v+vi) if t < ans: ans = t return ans def both(x): a = calc_left(x) b = calc_right(x) return max(a,b) def main(): t = 10**6 l = 0 r = 10**6 a = both(left[0][0]) if a<t: t = a a = both(-right[0][0]) if a<t: t = a while l<=r: m = int((l+r)/2) a = calc_left(m) b = calc_right(m) if a<b: l = m+1 if b<t: t=b else: r = m-1 if a<t: t=a print(t) main() ``` No
95,783
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. n people are standing on a coordinate axis in points with positive integer coordinates strictly less than 106. For each person we know in which direction (left or right) he is facing, and his maximum speed. You can put a bomb in some point with non-negative integer coordinate, and blow it up. At this moment all people will start running with their maximum speed in the direction they are facing. Also, two strange rays will start propagating from the bomb with speed s: one to the right, and one to the left. Of course, the speed s is strictly greater than people's maximum speed. The rays are strange because if at any moment the position and the direction of movement of some ray and some person coincide, then the speed of the person immediately increases by the speed of the ray. You need to place the bomb is such a point that the minimum time moment in which there is a person that has run through point 0, and there is a person that has run through point 106, is as small as possible. In other words, find the minimum time moment t such that there is a point you can place the bomb to so that at time moment t some person has run through 0, and some person has run through point 106. Input The first line contains two integers n and s (2 ≀ n ≀ 105, 2 ≀ s ≀ 106) β€” the number of people and the rays' speed. The next n lines contain the description of people. The i-th of these lines contains three integers xi, vi and ti (0 < xi < 106, 1 ≀ vi < s, 1 ≀ ti ≀ 2) β€” the coordinate of the i-th person on the line, his maximum speed and the direction he will run to (1 is to the left, i.e. in the direction of coordinate decrease, 2 is to the right, i.e. in the direction of coordinate increase), respectively. It is guaranteed that the points 0 and 106 will be reached independently of the bomb's position. Output Print the minimum time needed for both points 0 and 106 to be reached. Your answer is considered correct if its absolute or relative error doesn't exceed 10 - 6. Namely, if your answer is a, and the jury's answer is b, then your answer is accepted, if <image>. Examples Input 2 999 400000 1 2 500000 1 1 Output 500000.000000000000000000000000000000 Input 2 1000 400000 500 1 600000 500 2 Output 400.000000000000000000000000000000 Note In the first example, it is optimal to place the bomb at a point with a coordinate of 400000. Then at time 0, the speed of the first person becomes 1000 and he reaches the point 106 at the time 600. The bomb will not affect on the second person, and he will reach the 0 point at the time 500000. In the second example, it is optimal to place the bomb at the point 500000. The rays will catch up with both people at the time 200. At this time moment, the first is at the point with a coordinate of 300000, and the second is at the point with a coordinate of 700000. Their speed will become 1500 and at the time 400 they will simultaneously run through points 0 and 106. Submitted Solution: ``` print('hello') print('go') print('testing') ``` No
95,784
Provide tags and a correct Python 3 solution for this coding contest problem. Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day. Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created. All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so β€” their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule. Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport. Input The first line contains two integers n and k (1 ≀ k ≀ n ≀ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 107), here ci is the cost of delaying the i-th flight for one minute. Output The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≀ ti ≀ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them. Example Input 5 2 4 2 1 10 2 Output 20 3 6 7 4 5 Note Let us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)Β·4 + (4 - 2)Β·2 + (5 - 3)Β·1 + (6 - 4)Β·10 + (7 - 5)Β·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)Β·4 + (6 - 2)Β·2 + (7 - 3)Β·1 + (4 - 4)Β·10 + (5 - 5)Β·2 = 20 burles. Tags: greedy Correct Solution: ``` """ Author - Satwik Tiwari . 15th Dec , 2020 - Tuesday """ #=============================================================================================== #importing some useful libraries. from __future__ import division, print_function from fractions import Fraction import sys import os from io import BytesIO, IOBase from functools import cmp_to_key # from itertools import * from heapq import * from math import gcd, factorial,floor,ceil,sqrt from copy import deepcopy from collections import deque from bisect import bisect_left as bl from bisect import bisect_right as br from bisect import bisect #============================================================================================== #fast I/O region BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) # inp = lambda: sys.stdin.readline().rstrip("\r\n") #=============================================================================================== ### START ITERATE RECURSION ### from types import GeneratorType def iterative(f, stack=[]): def wrapped_func(*args, **kwargs): if stack: return f(*args, **kwargs) to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) continue stack.pop() if not stack: break to = stack[-1].send(to) return to return wrapped_func #### END ITERATE RECURSION #### #=============================================================================================== #some shortcuts def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input def out(var): sys.stdout.write(str(var)) #for fast output, always take string def lis(): return list(map(int, inp().split())) def stringlis(): return list(map(str, inp().split())) def sep(): return map(int, inp().split()) def strsep(): return map(str, inp().split()) # def graph(vertex): return [[] for i in range(0,vertex+1)] def testcase(t): for pp in range(t): solve(pp) def google(p): print('Case #'+str(p)+': ',end='') def lcm(a,b): return (a*b)//gcd(a,b) def power(x, y, p) : y%=(p-1) #not so sure about this. used when y>p-1. if p is prime. res = 1 # Initialize result x = x % p # Update x if it is more , than or equal to p if (x == 0) : return 0 while (y > 0) : if ((y & 1) == 1) : # If y is odd, multiply, x with result res = (res * x) % p y = y >> 1 # y = y/2 x = (x * x) % p return res def ncr(n,r): return factorial(n) // (factorial(r) * factorial(max(n - r, 1))) def isPrime(n) : if (n <= 1) : return False if (n <= 3) : return True if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while(i * i <= n) : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True inf = pow(10,20) mod = 10**9+7 #=============================================================================================== # code here ;)) def safe(x,y): global n,m return (0<=x<n and 0<=y<m) def solve(case): n,k = sep() a = lis() if(k >= n): h = [] ans = 0 order = [0]*n for i in range(n): ans += (k-i)*a[i] # print(ans) h = [] for i in range(n): heappush(h,(-a[i],i)) temp = heappop(h) order[temp[1]] = k for i in range(n-1): temp,j = heappop(h) temp*=-1 ans += (i+1)*temp order[j] = k+i+1 print(ans) print(' '.join(str(order[i]+1) for i in range(len(order)))) else: ans = 0 for i in range(k+1): ans += (k-i)*a[i] h = [] sum = 0 for i in range(k+1): heappush(h,(-a[i],i)) sum += a[i] order = [0]*n for i in range(k,k+n): temp,j = heappop(h) sum+=temp ans += sum order[j] = i if(i+1 < n): heappush(h,(-a[i+1],i+1)) sum += a[i+1] print(ans) print(' '.join(str(order[i]+1) for i in range(len(order)))) # chck = 0 # for i in range(n): # chck += (order[i]-i)*a[i] # # print(chck) # print(chck) n,m = 0,0 testcase(1) # testcase(int(inp())) ```
95,785
Provide tags and a correct Python 3 solution for this coding contest problem. Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day. Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created. All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so β€” their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule. Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport. Input The first line contains two integers n and k (1 ≀ k ≀ n ≀ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 107), here ci is the cost of delaying the i-th flight for one minute. Output The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≀ ti ≀ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them. Example Input 5 2 4 2 1 10 2 Output 20 3 6 7 4 5 Note Let us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)Β·4 + (4 - 2)Β·2 + (5 - 3)Β·1 + (6 - 4)Β·10 + (7 - 5)Β·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)Β·4 + (6 - 2)Β·2 + (7 - 3)Β·1 + (4 - 4)Β·10 + (5 - 5)Β·2 = 20 burles. Tags: greedy Correct Solution: ``` import heapq n,k = map(int,input().split()) l = list(map(int,input().split())) ans = [0]*n h = [] for i in range(k): h.append((-1*l[i],i)) heapq.heapify(h) som = 0 for i in range(k,n+k): if i < n: heapq.heappush(h, (-1 * l[i], i)) x = heapq.heappop(h) s = -1*x[0]*(i-x[1]) som += s ans[x[1]] = i+1 print(som) print(*ans) ```
95,786
Provide tags and a correct Python 3 solution for this coding contest problem. Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day. Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created. All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so β€” their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule. Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport. Input The first line contains two integers n and k (1 ≀ k ≀ n ≀ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 107), here ci is the cost of delaying the i-th flight for one minute. Output The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≀ ti ≀ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them. Example Input 5 2 4 2 1 10 2 Output 20 3 6 7 4 5 Note Let us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)Β·4 + (4 - 2)Β·2 + (5 - 3)Β·1 + (6 - 4)Β·10 + (7 - 5)Β·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)Β·4 + (6 - 2)Β·2 + (7 - 3)Β·1 + (4 - 4)Β·10 + (5 - 5)Β·2 = 20 burles. Tags: greedy Correct Solution: ``` from heapq import heappush, heappop, heapify n, k = map(int, input().split()) a = list(map(int, input().split())) q = [(-a[i], i) for i in range(k)] heapify(q) res, s = [0] * n, 0 for i in range(k, n): heappush(q, (-a[i], i)) x, j = heappop(q) s -= x * (i-j) res[j] = i+1 for i in range(n, n+k): x, j = heappop(q) s -= x * (i-j) res[j] = i+1 print(s) print(*res) ```
95,787
Provide tags and a correct Python 3 solution for this coding contest problem. Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day. Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created. All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so β€” their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule. Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport. Input The first line contains two integers n and k (1 ≀ k ≀ n ≀ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 107), here ci is the cost of delaying the i-th flight for one minute. Output The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≀ ti ≀ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them. Example Input 5 2 4 2 1 10 2 Output 20 3 6 7 4 5 Note Let us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)Β·4 + (4 - 2)Β·2 + (5 - 3)Β·1 + (6 - 4)Β·10 + (7 - 5)Β·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)Β·4 + (6 - 2)Β·2 + (7 - 3)Β·1 + (4 - 4)Β·10 + (5 - 5)Β·2 = 20 burles. Tags: greedy Correct Solution: ``` from heapq import heappush,heappop,heapify n,k=map(int,input().split()) *l,=map(int,input().split()) q=[(-l[i],i)for i in range(k)] heapify(q) a=[0]*n s=0 for i in range(k,n) : heappush(q,(-l[i],i)) x,j=heappop(q) s-=x*(i-j) a[j]=i+1 for i in range(n,n+k) : x,j=heappop(q) s-=x*(i-j) a[j]=i+1 print(s) print(' '.join(map(str,a))) ```
95,788
Provide tags and a correct Python 3 solution for this coding contest problem. Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day. Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created. All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so β€” their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule. Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport. Input The first line contains two integers n and k (1 ≀ k ≀ n ≀ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 107), here ci is the cost of delaying the i-th flight for one minute. Output The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≀ ti ≀ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them. Example Input 5 2 4 2 1 10 2 Output 20 3 6 7 4 5 Note Let us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)Β·4 + (4 - 2)Β·2 + (5 - 3)Β·1 + (6 - 4)Β·10 + (7 - 5)Β·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)Β·4 + (6 - 2)Β·2 + (7 - 3)Β·1 + (4 - 4)Β·10 + (5 - 5)Β·2 = 20 burles. Tags: greedy Correct Solution: ``` from heapq import heappush,heappop,heapify n,k=map(int,input().split()) *l,=map(int,input().split()) q=[(-l[i],i)for i in range(k)];heapify(q) a=[0]*n s=0 for i in range(k,n): heappush(q,(-l[i],i)) x,j=heappop(q) s-=x*(i-j) a[j]=i+1 for i in range(n,n+k): x,j=heappop(q) s-=x*(i-j) a[j]=i+1 print(s) print(' '.join(map(str,a))) ```
95,789
Provide tags and a correct Python 3 solution for this coding contest problem. Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day. Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created. All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so β€” their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule. Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport. Input The first line contains two integers n and k (1 ≀ k ≀ n ≀ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 107), here ci is the cost of delaying the i-th flight for one minute. Output The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≀ ti ≀ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them. Example Input 5 2 4 2 1 10 2 Output 20 3 6 7 4 5 Note Let us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)Β·4 + (4 - 2)Β·2 + (5 - 3)Β·1 + (6 - 4)Β·10 + (7 - 5)Β·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)Β·4 + (6 - 2)Β·2 + (7 - 3)Β·1 + (4 - 4)Β·10 + (5 - 5)Β·2 = 20 burles. Tags: greedy Correct Solution: ``` #Code by Sounak, IIESTS #------------------------------warmup---------------------------- import os import sys import math 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") #-------------------game starts now----------------------------------------------------- from heapq import heappush, heappop, heapify n, k = map(int, input().split()) a = list(map(int, input().split())) q = [(-a[i], i) for i in range(k)] heapify(q) res, s = [0] * n, 0 for i in range(k, n): heappush(q, (-a[i], i)) x, j = heappop(q) s -= x * (i-j) res[j] = i+1 for i in range(n, n+k): x, j = heappop(q) s -= x * (i-j) res[j] = i+1 print(s) print(*res) ```
95,790
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day. Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created. All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so β€” their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule. Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport. Input The first line contains two integers n and k (1 ≀ k ≀ n ≀ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 107), here ci is the cost of delaying the i-th flight for one minute. Output The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≀ ti ≀ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them. Example Input 5 2 4 2 1 10 2 Output 20 3 6 7 4 5 Note Let us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)Β·4 + (4 - 2)Β·2 + (5 - 3)Β·1 + (6 - 4)Β·10 + (7 - 5)Β·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)Β·4 + (6 - 2)Β·2 + (7 - 3)Β·1 + (4 - 4)Β·10 + (5 - 5)Β·2 = 20 burles. Submitted Solution: ``` import sys n,m=map(int,input().split()) l=list(map(int,sys.stdin.readline()[:-1].split())) out=[0 for i in range(n)] l1=[[l[i],i+1] for i in range(n)] l1=sorted(l1,key=lambda x:x[0]) p=0 d=set() for i in range(n-1,-1,-1) : v=max(1+m,l1[i][1]) if v not in d : out[l1[i][1]-1]=v d.add(v) p=max(p,v) else : p+=1 out[l1[i][1]-1]=p d.add(p) k=0 for i in range(n) : k+=l[i]*(out[i]-i-1) print(k) sys.stdout.write(' '.join(map(str,out))) ``` No
95,791
Provide tags and a correct Python 3 solution for this coding contest problem. Danil decided to earn some money, so he had found a part-time job. The interview have went well, so now he is a light switcher. Danil works in a rooted tree (undirected connected acyclic graph) with n vertices, vertex 1 is the root of the tree. There is a room in each vertex, light can be switched on or off in each room. Danil's duties include switching light in all rooms of the subtree of the vertex. It means that if light is switched on in some room of the subtree, he should switch it off. Otherwise, he should switch it on. Unfortunately (or fortunately), Danil is very lazy. He knows that his boss is not going to personally check the work. Instead, he will send Danil tasks using Workforces personal messages. There are two types of tasks: 1. pow v describes a task to switch lights in the subtree of vertex v. 2. get v describes a task to count the number of rooms in the subtree of v, in which the light is turned on. Danil should send the answer to his boss using Workforces messages. A subtree of vertex v is a set of vertices for which the shortest path from them to the root passes through v. In particular, the vertex v is in the subtree of v. Danil is not going to perform his duties. He asks you to write a program, which answers the boss instead of him. Input The first line contains a single integer n (1 ≀ n ≀ 200 000) β€” the number of vertices in the tree. The second line contains n - 1 space-separated integers p2, p3, ..., pn (1 ≀ pi < i), where pi is the ancestor of vertex i. The third line contains n space-separated integers t1, t2, ..., tn (0 ≀ ti ≀ 1), where ti is 1, if the light is turned on in vertex i and 0 otherwise. The fourth line contains a single integer q (1 ≀ q ≀ 200 000) β€” the number of tasks. The next q lines are get v or pow v (1 ≀ v ≀ n) β€” the tasks described above. Output For each task get v print the number of rooms in the subtree of v, in which the light is turned on. Example Input 4 1 1 1 1 0 0 1 9 get 1 get 2 get 3 get 4 pow 1 get 1 get 2 get 3 get 4 Output 2 0 0 1 2 1 1 0 Note <image> The tree before the task pow 1. <image> The tree after the task pow 1. Tags: bitmasks, data structures, trees Correct Solution: ``` # ------------------- fast io -------------------- 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") # ------------------- fast io -------------------- from math import ceil def prod(a, mod=10 ** 9 + 7): ans = 1 for each in a: ans = (ans * each) % mod return ans def gcd(x, y): while y: x, y = y, x % y return x def lcm(a, b): return a * b // gcd(a, b) def binary(x, length=16): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y from math import inf, log2 class LazySegmentTree: def __init__(self, array, func=max): self.n = len(array) self.size = 2 ** (int(log2(self.n - 1)) + 1) if self.n != 1 else 1 self.func = func self.default = 0 self.data = [self.default] * (2 * self.size) self.segsize = [0] * (2 * self.size) self.lazy = [0] * (2 * self.size) self.process(array) def process(self, array): self.data[self.size: self.size + self.n] = array self.segsize[self.size: self.size + self.n] = [1] * len(array) for i in range(self.size - 1, -1, -1): self.data[i] = self.data[2 * i] + self.data[2 * i + 1] self.segsize[i] = self.segsize[2 * i] + self.segsize[2 * i + 1] def push(self, index): """Push the information of the root to it's children!""" self.lazy[2 * index] += self.lazy[index] self.lazy[2 * index + 1] += self.lazy[index] if self.lazy[index] % 2: self.data[index] = self.segsize[index] - self.data[index] self.lazy[index] = 0 def build(self, index): """Build data with the new changes!""" index >>= 1 while index: left, right = self.data[2 * index], self.data[2 * index + 1] if self.lazy[2 * index] % 2: left = self.segsize[2 * index] - left if self.lazy[2 * index + 1] % 2: right = self.segsize[2 * index + 1] - right self.data[index] = left + right index >>= 1 def query(self, alpha, omega): """Returns the result of function over the range (inclusive)!""" res = self.default alpha += self.size omega += self.size + 1 for i in range(len(bin(alpha)[2:]) - 1, 0, -1): self.push(alpha >> i) for i in range(len(bin(omega - 1)[2:]) - 1, 0, -1): self.push((omega - 1) >> i) while alpha < omega: if alpha & 1: if self.lazy[alpha] % 2: res += self.segsize[alpha] - self.data[alpha] else: res += self.data[alpha] alpha += 1 if omega & 1: omega -= 1 if self.lazy[omega] % 2: res += self.segsize[omega] - self.data[omega] else: res += self.data[omega] alpha >>= 1 omega >>= 1 return res def update(self, alpha, omega): """Increases all elements in the range (inclusive) by given value!""" alpha += self.size omega += self.size + 1 l, r = alpha, omega for i in range(len(bin(alpha)[2:]) - 1, 0, -1): self.push(alpha >> i) for i in range(len(bin(omega - 1)[2:]) - 1, 0, -1): self.push((omega - 1) >> i) while alpha < omega: if alpha & 1: self.lazy[alpha] += 1 alpha += 1 if omega & 1: omega -= 1 self.lazy[omega] += 1 alpha >>= 1 omega >>= 1 self.build(l) self.build(r - 1) def dfs(graph, alpha): """Depth First Search on a graph!""" n = len(graph) visited = [False] * n finished = [False] * n dp = [0] * n subtree = [0] * n order = [] stack = [alpha] while stack: v = stack[-1] if not visited[v]: visited[v] = True for u in graph[v]: if not visited[u]: stack.append(u) else: order += [stack.pop()] dp[v] = (switch[v] == 1) subtree[v] = 1 for child in graph[v]: if finished[child]: dp[v] += dp[child] subtree[v] += subtree[child] finished[v] = True return dp, order[::-1], subtree for _ in range(int(input()) if not True else 1): n = int(input()) # n, k = map(int, input().split()) # a, b = map(int, input().split()) # c, d = map(int, input().split()) a = list(map(int, input().split())) switch = [0] + list(map(int, input().split())) # s = input() graph = [[] for i in range(n + 1)] for i in range(len(a)): x, y = i + 2, a[i] graph[x] += [y] graph[y] += [x] dp, order, subtree = dfs(graph, 1) index = [0] * (n + 1) for i in range(len(order)): index[order[i]] = i + 1 st = LazySegmentTree([0] * (n+1), func=lambda a, b: a + b) for i in range(1, n + 1): if switch[i]: st.update(index[i], index[i]) for __ in range(int(input())): s = input().split() x = int(s[1]) count = subtree[x] if s[0] == 'get': print(st.query(index[x], index[x] + count - 1)) else: st.update(index[x], index[x] + count - 1) ```
95,792
Provide tags and a correct Python 3 solution for this coding contest problem. Danil decided to earn some money, so he had found a part-time job. The interview have went well, so now he is a light switcher. Danil works in a rooted tree (undirected connected acyclic graph) with n vertices, vertex 1 is the root of the tree. There is a room in each vertex, light can be switched on or off in each room. Danil's duties include switching light in all rooms of the subtree of the vertex. It means that if light is switched on in some room of the subtree, he should switch it off. Otherwise, he should switch it on. Unfortunately (or fortunately), Danil is very lazy. He knows that his boss is not going to personally check the work. Instead, he will send Danil tasks using Workforces personal messages. There are two types of tasks: 1. pow v describes a task to switch lights in the subtree of vertex v. 2. get v describes a task to count the number of rooms in the subtree of v, in which the light is turned on. Danil should send the answer to his boss using Workforces messages. A subtree of vertex v is a set of vertices for which the shortest path from them to the root passes through v. In particular, the vertex v is in the subtree of v. Danil is not going to perform his duties. He asks you to write a program, which answers the boss instead of him. Input The first line contains a single integer n (1 ≀ n ≀ 200 000) β€” the number of vertices in the tree. The second line contains n - 1 space-separated integers p2, p3, ..., pn (1 ≀ pi < i), where pi is the ancestor of vertex i. The third line contains n space-separated integers t1, t2, ..., tn (0 ≀ ti ≀ 1), where ti is 1, if the light is turned on in vertex i and 0 otherwise. The fourth line contains a single integer q (1 ≀ q ≀ 200 000) β€” the number of tasks. The next q lines are get v or pow v (1 ≀ v ≀ n) β€” the tasks described above. Output For each task get v print the number of rooms in the subtree of v, in which the light is turned on. Example Input 4 1 1 1 1 0 0 1 9 get 1 get 2 get 3 get 4 pow 1 get 1 get 2 get 3 get 4 Output 2 0 0 1 2 1 1 0 Note <image> The tree before the task pow 1. <image> The tree after the task pow 1. Tags: bitmasks, data structures, trees Correct Solution: ``` class LazySegTree: def __init__(self, init_val, seg_ide, lazy_ide, f, g, h): self.n = len(init_val) self.num = 2**(self.n-1).bit_length() self.seg_ide = seg_ide self.lazy_ide = lazy_ide self.f = f #(seg, seg) -> seg self.g = g #(seg, lazy, size) -> seg self.h = h #(lazy, lazy) -> lazy self.seg = [seg_ide]*2*self.num for i in range(self.n): self.seg[i+self.num] = init_val[i] for i in range(self.num-1, 0, -1): self.seg[i] = self.f(self.seg[2*i], self.seg[2*i+1]) self.size = [0]*2*self.num for i in range(self.n): self.size[i+self.num] = 1 for i in range(self.num-1, 0, -1): self.size[i] = self.size[2*i] + self.size[2*i+1] self.lazy = [lazy_ide]*2*self.num def update(self, i, x): i += self.num self.seg[i] = x while i: i = i >> 1 self.seg[i] = self.f(self.seg[2*i], self.seg[2*i+1]) def calc(self, i): return self.g(self.seg[i], self.lazy[i], self.size[i]) def calc_above(self, i): i = i >> 1 while i: self.seg[i] = self.f(self.calc(2*i), self.calc(2*i+1)) i = i >> 1 def propagate(self, i): self.seg[i] = self.g(self.seg[i], self.lazy[i], self.size[i]) self.lazy[2*i] = self.h(self.lazy[2*i], self.lazy[i]) self.lazy[2*i+1] = self.h(self.lazy[2*i+1], self.lazy[i]) self.lazy[i] = self.lazy_ide def propagate_above(self, i): H = i.bit_length() for h in range(H, 0, -1): self.propagate(i >> h) def query(self, l, r): l += self.num r += self.num lm = l // (l & -l) rm = r // (r & -r) -1 self.propagate_above(lm) self.propagate_above(rm) al = self.seg_ide ar = self.seg_ide while l < r: if l & 1: al = self.f(al, self.calc(l)) l += 1 if r & 1: r -= 1 ar = self.f(self.calc(r), ar) l = l >> 1 r = r >> 1 return self.f(al, ar) def oprerate_range(self, l, r, a): l += self.num r += self.num lm = l // (l & -l) rm = r // (r & -r) -1 self.propagate_above(lm) self.propagate_above(rm) while l < r: if l & 1: self.lazy[l] = self.h(self.lazy[l], a) l += 1 if r & 1: r -= 1 self.lazy[r] = self.h(self.lazy[r], a) l = l >> 1 r = r >> 1 self.calc_above(lm) self.calc_above(rm) f = lambda x, y: x+y g = lambda x, a, s: s-x if a%2 == 1 else x h = lambda a, b: a+b def EulerTour(g, root): n = len(g) root = root g = g tank = [root] eulerTour = [] left = [0]*n right = [-1]*n depth = [-1]*n parent = [-1]*n child = [[] for i in range(n)] eulerNum = -1 de = -1 while tank: v = tank.pop() if v >= 0: eulerNum += 1 eulerTour.append(v) left[v] = eulerNum right[v] = eulerNum tank.append(~v) de += 1 depth[v] = de for u in g[v]: if parent[v] == u: continue tank.append(u) parent[u] = v child[v].append(u) else: de -= 1 if ~v != root: eulerTour.append(parent[~v]) eulerNum += 1 right[parent[~v]] = eulerNum return eulerTour, left, right import bisect import sys import io, os input = sys.stdin.readline #input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline def main(): n = int(input()) P = list(map(int, input().split())) T = list(map(int, input().split())) P = [p-1 for p in P] P = [-1]+P edge = [[] for i in range(n)] for i, p in enumerate(P): if p != -1: edge[p].append(i) et, left, right = EulerTour(edge, 0) d = {} B = sorted(left) #print(B) #print(right) for i, b in enumerate(B): d[b] = i A = [0]*n for i in range(n): A[d[left[i]]] = T[i] seg = LazySegTree(A, 0, 0, f, g, h) q = int(input()) for i in range(q): query = list(map(str, input().split())) if query[0] == 'get': u = int(query[1])-1 l = d[left[u]] r = bisect.bisect_right(B, right[u]) print(seg.query(l, r)) else: u = int(query[1])-1 l = d[left[u]] r = bisect.bisect_right(B, right[u]) seg.oprerate_range(l, r, 1) if __name__ == '__main__': main() ```
95,793
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Danil decided to earn some money, so he had found a part-time job. The interview have went well, so now he is a light switcher. Danil works in a rooted tree (undirected connected acyclic graph) with n vertices, vertex 1 is the root of the tree. There is a room in each vertex, light can be switched on or off in each room. Danil's duties include switching light in all rooms of the subtree of the vertex. It means that if light is switched on in some room of the subtree, he should switch it off. Otherwise, he should switch it on. Unfortunately (or fortunately), Danil is very lazy. He knows that his boss is not going to personally check the work. Instead, he will send Danil tasks using Workforces personal messages. There are two types of tasks: 1. pow v describes a task to switch lights in the subtree of vertex v. 2. get v describes a task to count the number of rooms in the subtree of v, in which the light is turned on. Danil should send the answer to his boss using Workforces messages. A subtree of vertex v is a set of vertices for which the shortest path from them to the root passes through v. In particular, the vertex v is in the subtree of v. Danil is not going to perform his duties. He asks you to write a program, which answers the boss instead of him. Input The first line contains a single integer n (1 ≀ n ≀ 200 000) β€” the number of vertices in the tree. The second line contains n - 1 space-separated integers p2, p3, ..., pn (1 ≀ pi < i), where pi is the ancestor of vertex i. The third line contains n space-separated integers t1, t2, ..., tn (0 ≀ ti ≀ 1), where ti is 1, if the light is turned on in vertex i and 0 otherwise. The fourth line contains a single integer q (1 ≀ q ≀ 200 000) β€” the number of tasks. The next q lines are get v or pow v (1 ≀ v ≀ n) β€” the tasks described above. Output For each task get v print the number of rooms in the subtree of v, in which the light is turned on. Example Input 4 1 1 1 1 0 0 1 9 get 1 get 2 get 3 get 4 pow 1 get 1 get 2 get 3 get 4 Output 2 0 0 1 2 1 1 0 Note <image> The tree before the task pow 1. <image> The tree after the task pow 1. Submitted Solution: ``` n=int(input()) par=[int(i)-1 for i in input().split()] t=list(map(int,input().split())) qq=int(input()) tr=[[] for i in range(n)] for i in range(n-1): tr[par[i]].append(i+1) size=[1 for i in range(n)] on=[t[i] for i in range(n)] pos=[-1 for i in range(n)] m=[] i=0 s=[0] while s: x=s.pop() m.append(x) pos[x]=i i+=1 for y in tr[x]: if pos[y]!=-1:continue s.append(y) for i in range(n-1,0,-1): j=m[i] size[par[j-1]]+=size[j] on[par[j-1]]+=on[j] it=[0 for i in range(2*n)] def u(i,v): i+=n it[i]+=v while i>0: i>>=1 it[i]=it[i<<1]+it[i<<1|1] def q(i): l=n r=i+n+1 ans=0 while l<r: if l&1: ans+=it[l] l+=1 if r&1: r-=1 ans+=it[r] r>>=1 l>>=1 return(ans) for _ in range(qq): s=str(input()) v=int(s[-1])-1 i=pos[v] if s[0]=='g': if q(i)%2==0: print(on[v]) else: print(size[v]-on[v]) else: j=i+size[v] u(i,1) if j<n: u(j,-1) ``` No
95,794
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Danil decided to earn some money, so he had found a part-time job. The interview have went well, so now he is a light switcher. Danil works in a rooted tree (undirected connected acyclic graph) with n vertices, vertex 1 is the root of the tree. There is a room in each vertex, light can be switched on or off in each room. Danil's duties include switching light in all rooms of the subtree of the vertex. It means that if light is switched on in some room of the subtree, he should switch it off. Otherwise, he should switch it on. Unfortunately (or fortunately), Danil is very lazy. He knows that his boss is not going to personally check the work. Instead, he will send Danil tasks using Workforces personal messages. There are two types of tasks: 1. pow v describes a task to switch lights in the subtree of vertex v. 2. get v describes a task to count the number of rooms in the subtree of v, in which the light is turned on. Danil should send the answer to his boss using Workforces messages. A subtree of vertex v is a set of vertices for which the shortest path from them to the root passes through v. In particular, the vertex v is in the subtree of v. Danil is not going to perform his duties. He asks you to write a program, which answers the boss instead of him. Input The first line contains a single integer n (1 ≀ n ≀ 200 000) β€” the number of vertices in the tree. The second line contains n - 1 space-separated integers p2, p3, ..., pn (1 ≀ pi < i), where pi is the ancestor of vertex i. The third line contains n space-separated integers t1, t2, ..., tn (0 ≀ ti ≀ 1), where ti is 1, if the light is turned on in vertex i and 0 otherwise. The fourth line contains a single integer q (1 ≀ q ≀ 200 000) β€” the number of tasks. The next q lines are get v or pow v (1 ≀ v ≀ n) β€” the tasks described above. Output For each task get v print the number of rooms in the subtree of v, in which the light is turned on. Example Input 4 1 1 1 1 0 0 1 9 get 1 get 2 get 3 get 4 pow 1 get 1 get 2 get 3 get 4 Output 2 0 0 1 2 1 1 0 Note <image> The tree before the task pow 1. <image> The tree after the task pow 1. Submitted Solution: ``` class Node: def __init__(self): self.parent = None self.children = [] self.on = False self.count = 0 def toggle(self): self.on = not self.on diff = 1 if self.on else -1 for child in self.children: diff += child.toggle() self.count += diff return diff def calc_count(self): c = 0 for child in self.children: child.calc_count() c += child.count self.count = c+1 if self.on else c nodes = [] v = int(input()) for i in range(v): nodes.append(Node()) p = list(map(int, input().split())) for i in range(len(p)): nodes[i+1].parent = nodes[p[i]-1] nodes[p[i]-1].children.append(nodes[i+1]) t = list(input().split()) for i in range(len(t)): nodes[i].on = t[i] == '1' nodes[0].calc_count() q = int(input()) for i in range(q): command, v = input().split() v = int(v) - 1 if command == 'pow': nodes[v].toggle() if command == 'get': print(nodes[v].count) ``` No
95,795
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Danil decided to earn some money, so he had found a part-time job. The interview have went well, so now he is a light switcher. Danil works in a rooted tree (undirected connected acyclic graph) with n vertices, vertex 1 is the root of the tree. There is a room in each vertex, light can be switched on or off in each room. Danil's duties include switching light in all rooms of the subtree of the vertex. It means that if light is switched on in some room of the subtree, he should switch it off. Otherwise, he should switch it on. Unfortunately (or fortunately), Danil is very lazy. He knows that his boss is not going to personally check the work. Instead, he will send Danil tasks using Workforces personal messages. There are two types of tasks: 1. pow v describes a task to switch lights in the subtree of vertex v. 2. get v describes a task to count the number of rooms in the subtree of v, in which the light is turned on. Danil should send the answer to his boss using Workforces messages. A subtree of vertex v is a set of vertices for which the shortest path from them to the root passes through v. In particular, the vertex v is in the subtree of v. Danil is not going to perform his duties. He asks you to write a program, which answers the boss instead of him. Input The first line contains a single integer n (1 ≀ n ≀ 200 000) β€” the number of vertices in the tree. The second line contains n - 1 space-separated integers p2, p3, ..., pn (1 ≀ pi < i), where pi is the ancestor of vertex i. The third line contains n space-separated integers t1, t2, ..., tn (0 ≀ ti ≀ 1), where ti is 1, if the light is turned on in vertex i and 0 otherwise. The fourth line contains a single integer q (1 ≀ q ≀ 200 000) β€” the number of tasks. The next q lines are get v or pow v (1 ≀ v ≀ n) β€” the tasks described above. Output For each task get v print the number of rooms in the subtree of v, in which the light is turned on. Example Input 4 1 1 1 1 0 0 1 9 get 1 get 2 get 3 get 4 pow 1 get 1 get 2 get 3 get 4 Output 2 0 0 1 2 1 1 0 Note <image> The tree before the task pow 1. <image> The tree after the task pow 1. Submitted Solution: ``` class Node: def __init__(self): self.parent = None self.on = False self.children = [] self.count = -1 def toggle(self): self.on = not self.on count = 0 for child in self.children: child.toggle() count += child.count self.count = count+1 if self.on else count def calc_count(self): if self.count != -1: return self.count count = 0 for child in self.children: child.calc_count() count += child.count self.count = count+1 if self.on else count nodes = [] v = int(input()) for i in range(v): nodes.append(Node()) p = list(map(int, input().split())) for i in range(len(p)): nodes[i+1].parent = nodes[p[i]-1] nodes[p[i]-1].children.append(nodes[i+1]) t = list(map(int, input().split())) for i in range(len(t)): nodes[i].on = t[i] == 1 for i in range(v): nodes[i].calc_count() q = int(input()) for i in range(q): command, v = input().split() v = int(v) - 1 if command == 'pow': nodes[v].toggle() if command == 'get': print(nodes[v].count) ``` No
95,796
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Danil decided to earn some money, so he had found a part-time job. The interview have went well, so now he is a light switcher. Danil works in a rooted tree (undirected connected acyclic graph) with n vertices, vertex 1 is the root of the tree. There is a room in each vertex, light can be switched on or off in each room. Danil's duties include switching light in all rooms of the subtree of the vertex. It means that if light is switched on in some room of the subtree, he should switch it off. Otherwise, he should switch it on. Unfortunately (or fortunately), Danil is very lazy. He knows that his boss is not going to personally check the work. Instead, he will send Danil tasks using Workforces personal messages. There are two types of tasks: 1. pow v describes a task to switch lights in the subtree of vertex v. 2. get v describes a task to count the number of rooms in the subtree of v, in which the light is turned on. Danil should send the answer to his boss using Workforces messages. A subtree of vertex v is a set of vertices for which the shortest path from them to the root passes through v. In particular, the vertex v is in the subtree of v. Danil is not going to perform his duties. He asks you to write a program, which answers the boss instead of him. Input The first line contains a single integer n (1 ≀ n ≀ 200 000) β€” the number of vertices in the tree. The second line contains n - 1 space-separated integers p2, p3, ..., pn (1 ≀ pi < i), where pi is the ancestor of vertex i. The third line contains n space-separated integers t1, t2, ..., tn (0 ≀ ti ≀ 1), where ti is 1, if the light is turned on in vertex i and 0 otherwise. The fourth line contains a single integer q (1 ≀ q ≀ 200 000) β€” the number of tasks. The next q lines are get v or pow v (1 ≀ v ≀ n) β€” the tasks described above. Output For each task get v print the number of rooms in the subtree of v, in which the light is turned on. Example Input 4 1 1 1 1 0 0 1 9 get 1 get 2 get 3 get 4 pow 1 get 1 get 2 get 3 get 4 Output 2 0 0 1 2 1 1 0 Note <image> The tree before the task pow 1. <image> The tree after the task pow 1. Submitted Solution: ``` # ------------------- fast io -------------------- 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") # ------------------- fast io -------------------- from math import ceil def prod(a, mod=10 ** 9 + 7): ans = 1 for each in a: ans = (ans * each) % mod return ans def gcd(x, y): while y: x, y = y, x % y return x def lcm(a, b): return a * b // gcd(a, b) def binary(x, length=16): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y from math import inf, log2 class LazySegmentTree: def __init__(self, array, func=max): self.n = len(array) self.size = 2 ** (int(log2(self.n - 1)) + 1) if self.n != 1 else 1 self.func = func self.default = 0 self.data = [self.default] * (2 * self.size) self.segsize = [0] * (2 * self.size) self.lazy = [0] * (2 * self.size) self.process(array) def process(self, array): self.data[self.size: self.size + self.n] = array self.segsize[self.size: self.size + self.n] = [1] * len(array) for i in range(self.size - 1, -1, -1): self.data[i] = self.data[2 * i] + self.data[2 * i + 1] self.segsize[i] = self.segsize[2 * i] + self.segsize[2 * i + 1] def push(self, index): """Push the information of the root to it's children!""" self.lazy[2 * index] += self.lazy[index] self.lazy[2 * index + 1] += self.lazy[index] if self.lazy[index] % 2: self.data[index] = self.segsize[index] - self.data[index] self.lazy[index] = 0 def build(self, index): """Build data with the new changes!""" index >>= 1 while index: left, right = self.data[2 * index], self.data[2 * index + 1] if self.lazy[2 * index] % 2: left = self.segsize[2 * index] - left if self.lazy[2 * index + 1] % 2: right = self.segsize[2 * index + 1] - right self.data[index] = left + right index >>= 1 def query(self, alpha, omega): """Returns the result of function over the range (inclusive)!""" res = self.default alpha += self.size omega += self.size + 1 for i in range(len(bin(alpha)[2:]) - 1, 0, -1): self.push(alpha >> i) for i in range(len(bin(omega - 1)[2:]) - 1, 0, -1): self.push((omega - 1) >> i) while alpha < omega: if alpha & 1: if self.lazy[alpha] % 2: res += self.segsize[alpha] - self.data[alpha] else: res += self.data[alpha] alpha += 1 if omega & 1: omega -= 1 if self.lazy[omega] % 2: res += self.segsize[omega] - self.data[omega] else: res += self.data[omega] alpha >>= 1 omega >>= 1 return res def update(self, alpha, omega): """Increases all elements in the range (inclusive) by given value!""" alpha += self.size omega += self.size + 1 l, r = alpha, omega for i in range(len(bin(alpha)[2:]) - 1, 0, -1): self.push(alpha >> i) for i in range(len(bin(omega - 1)[2:]) - 1, 0, -1): self.push((omega - 1) >> i) while alpha < omega: if alpha & 1: self.lazy[alpha] += 1 alpha += 1 if omega & 1: omega -= 1 self.lazy[omega] += 1 alpha >>= 1 omega >>= 1 self.build(l) self.build(r - 1) def dfs(graph, alpha): """Depth First Search on a graph!""" n = len(graph) visited = [False] * n finished = [False] * n dp = [0] * n subtree = [0] * n order = [] stack = [alpha] while stack: v = stack[-1] if not visited[v]: visited[v] = True for u in graph[v]: if not visited[u]: stack.append(u) else: order += [stack.pop()] dp[v] = (switch[v] == 1) subtree[v] = 1 for child in graph[v]: if finished[child]: dp[v] += dp[child] subtree[v] += subtree[child] finished[v] = True return dp, order[::-1], subtree for _ in range(int(input()) if not True else 1): n = int(input()) # n, k = map(int, input().split()) # a, b = map(int, input().split()) # c, d = map(int, input().split()) a = list(map(int, input().split())) switch = [0] + list(map(int, input().split())) # s = input() graph = [[] for i in range(n + 1)] for i in range(len(a)): x, y = i + 2, a[i] graph[x] += [y] graph[y] += [x] dp, order, subtree = dfs(graph, 1) index = [0] * (n + 1) for i in range(len(order)): index[order[i]] = i + 1 st = LazySegmentTree(switch, func=lambda a, b: a + b) #for i in range(1, n + 1): # if switch[i]: # st.update(index[i], i) for __ in range(int(input())): s = input().split() x = int(s[1]) count = subtree[x] if s[0] == 'get': print(st.query(index[x], index[x] + count - 1)) else: st.update(index[x], index[x] + count - 1) ``` No
95,797
Provide tags and a correct Python 3 solution for this coding contest problem. Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree. Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal. The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex. Input The first line contains a single integer h (2 ≀ h ≀ 105) β€” the height of the tree. The second line contains h + 1 integers β€” the sequence a0, a1, ..., ah (1 ≀ ai ≀ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence. Output If there is only one tree matching this sequence, print "perfect". Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence. Examples Input 2 1 1 1 Output perfect Input 2 1 2 2 Output ambiguous 0 1 1 3 3 0 1 1 3 2 Note The only tree in the first example and the two printed trees from the second example are shown on the picture: <image> Tags: constructive algorithms, trees Correct Solution: ``` ''' =============================== -- @uthor : Kaleab Asfaw -- Handle : Kaleab_Asfaw -- Bio : High-School Student ===============================''' # Fast IO import sys import os 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") # Others # from math import floor, ceil, gcd # from decimal import Decimal as d mod = 10**9+7 def lcm(x, y): return (x * y) / (gcd(x, y)) def fact(x, mod=mod): ans = 1 for i in range(1, x+1): ans = (ans * i) % mod return ans def arr2D(n, m, default=0): return [[default for j in range(m)] for i in range(n)] def arr3D(n, m, r, default=0): return [[[default for k in range(r)] for j in range(m)] for i in range(n)] def sortDictV(x): return {k: v for k, v in sorted(x.items(), key = lambda item : item[1])} class DSU: def __init__(self, length): self.length = length; self.parent = [-1] * self.length # O(log(n)) def getParent(self, node, start): # O(log(n)) if node >= self.length: return False if self.parent[node] < 0: if start != node: self.parent[start] = node return node return self.getParent(self.parent[node], start) def union(self, node1, node2): # O(log(n)) parent1 = self.getParent(node1, node1); parent2 = self.getParent(node2, node2) if parent1 == parent2: return False elif self.parent[parent1] <= self.parent[parent2]: self.parent[parent1] += self.parent[parent2]; self.parent[parent2] = parent1 else: self.parent[parent2] += self.parent[parent1]; self.parent[parent1] = parent2 return True def getCount(self, node): return -self.parent[self.getParent(node, node)] # O(log(n)) def exact(num): if abs(num - round(num)) <= 10**(-9):return round(num) return num def solve(n, lst): get = False ind = -1 for i in range(n): if lst[i] > 1 and lst[i+1] > 1: get = True ind = i break if get: print("ambiguous") pre = [lst[0]] for i in lst[1:]: pre.append(pre[-1] + i) ans1 = [0] for i in range(lst[1]): ans1.append(1) prei = 0 for i in lst[2:]: ans1 += [pre[prei] + 1] * i prei += 1 print(" ".join(list(map(str, ans1)))) val = pre[ind] + 1 if val in ans1: for i in range(len(ans1)): if ans1[i] == val: ans1[i-1] += 1 else: ans1[-1] += 1 return " ".join(list(map(str, ans1))) else: return "perfect" n = int(input()) lst = list(map(int, input().split())) print(solve(n, lst)) ```
95,798
Provide tags and a correct Python 3 solution for this coding contest problem. Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree. Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal. The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex. Input The first line contains a single integer h (2 ≀ h ≀ 105) β€” the height of the tree. The second line contains h + 1 integers β€” the sequence a0, a1, ..., ah (1 ≀ ai ≀ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence. Output If there is only one tree matching this sequence, print "perfect". Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence. Examples Input 2 1 1 1 Output perfect Input 2 1 2 2 Output ambiguous 0 1 1 3 3 0 1 1 3 2 Note The only tree in the first example and the two printed trees from the second example are shown on the picture: <image> Tags: constructive algorithms, trees Correct Solution: ``` #Abhigyan Khaund - syl n = int(input()) a = list(map(int, input().split())) ambi = 0 for i in range(1,len(a)): if(a[i]>1 and a[i-1]>1): ambi = 1 ans1 = "" ans2 = "" if(ambi == 0): print ("perfect") else: print ("ambiguous") ans1+="0 " k = 0 s = sum(a) j = 1 h = 1 c = 0 st = 2 ans2+= "0" + " " k1 = 0 # s = sum(a) j1 = 1 h1 = 1 c1 = 0 st1 = 2 prev_st1 = 1 for i in range(1,s): # print j, ans1+= str(j) + " " ans2+= str(j1) + " " k+=1 c+=1 if(c>=a[h]): k = 0 h+=1 c = 0 j = st st = i+2 k1+=1 if(k1==1): k1 = 0 j1+=1 c1+=1 if(c1>=a[h1-1]): j1 = prev_st1 k1 = 0 if(c1>=a[h1]): k1 = 0 h1+=1 c1 = 0 j1 = st1 prev_st1 = st1 st1 = i+2 # print # print print (ans1) print (ans2) ```
95,799