text
stringlengths
198
433k
conversation_id
int64
0
109k
Provide tags and a correct Python 3 solution for this coding contest problem. Tanechka is shopping in the toy shop. There are exactly n toys in the shop for sale, the cost of the i-th toy is i burles. She wants to choose two toys in such a way that their total cost is k burles. How many ways to do that does she have? Each toy appears in the shop exactly once. Pairs (a, b) and (b, a) are considered equal. Pairs (a, b), where a=b, are not allowed. Input The first line of the input contains two integers n, k (1 ≤ n, k ≤ 10^{14}) — the number of toys and the expected total cost of the pair of toys. Output Print the number of ways to choose the pair of toys satisfying the condition above. Print 0, if Tanechka can choose no pair of toys in such a way that their total cost is k burles. Examples Input 8 5 Output 2 Input 8 15 Output 1 Input 7 20 Output 0 Input 1000000000000 1000000000001 Output 500000000000 Note In the first example Tanechka can choose the pair of toys (1, 4) or the pair of toys (2, 3). In the second example Tanechka can choose only the pair of toys (7, 8). In the third example choosing any pair of toys will lead to the total cost less than 20. So the answer is 0. In the fourth example she can choose the following pairs: (1, 1000000000000), (2, 999999999999), (3, 999999999998), ..., (500000000000, 500000000001). The number of such pairs is exactly 500000000000. Tags: math Correct Solution: ``` n,k = map(int,input().split()) if k<=n: if k%2==1: print(k//2) else: print(k//2-1) else: if k>n*2: print(0) else: print(n-k//2) ```
90,100
Provide tags and a correct Python 3 solution for this coding contest problem. Tanechka is shopping in the toy shop. There are exactly n toys in the shop for sale, the cost of the i-th toy is i burles. She wants to choose two toys in such a way that their total cost is k burles. How many ways to do that does she have? Each toy appears in the shop exactly once. Pairs (a, b) and (b, a) are considered equal. Pairs (a, b), where a=b, are not allowed. Input The first line of the input contains two integers n, k (1 ≤ n, k ≤ 10^{14}) — the number of toys and the expected total cost of the pair of toys. Output Print the number of ways to choose the pair of toys satisfying the condition above. Print 0, if Tanechka can choose no pair of toys in such a way that their total cost is k burles. Examples Input 8 5 Output 2 Input 8 15 Output 1 Input 7 20 Output 0 Input 1000000000000 1000000000001 Output 500000000000 Note In the first example Tanechka can choose the pair of toys (1, 4) or the pair of toys (2, 3). In the second example Tanechka can choose only the pair of toys (7, 8). In the third example choosing any pair of toys will lead to the total cost less than 20. So the answer is 0. In the fourth example she can choose the following pairs: (1, 1000000000000), (2, 999999999999), (3, 999999999998), ..., (500000000000, 500000000001). The number of such pairs is exactly 500000000000. Tags: math Correct Solution: ``` print((lambda n, k: max(0, min(n, k - 1) - k // 2))(*map(int, input().split()))) ```
90,101
Provide tags and a correct Python 3 solution for this coding contest problem. Tanechka is shopping in the toy shop. There are exactly n toys in the shop for sale, the cost of the i-th toy is i burles. She wants to choose two toys in such a way that their total cost is k burles. How many ways to do that does she have? Each toy appears in the shop exactly once. Pairs (a, b) and (b, a) are considered equal. Pairs (a, b), where a=b, are not allowed. Input The first line of the input contains two integers n, k (1 ≤ n, k ≤ 10^{14}) — the number of toys and the expected total cost of the pair of toys. Output Print the number of ways to choose the pair of toys satisfying the condition above. Print 0, if Tanechka can choose no pair of toys in such a way that their total cost is k burles. Examples Input 8 5 Output 2 Input 8 15 Output 1 Input 7 20 Output 0 Input 1000000000000 1000000000001 Output 500000000000 Note In the first example Tanechka can choose the pair of toys (1, 4) or the pair of toys (2, 3). In the second example Tanechka can choose only the pair of toys (7, 8). In the third example choosing any pair of toys will lead to the total cost less than 20. So the answer is 0. In the fourth example she can choose the following pairs: (1, 1000000000000), (2, 999999999999), (3, 999999999998), ..., (500000000000, 500000000001). The number of such pairs is exactly 500000000000. Tags: math Correct Solution: ``` n, k = map(int, input().split()) if n == 1: print(0) exit(0) if k > n: if k > 2*n-1: print(0) exit(0) one = n other = k - n else: one = k-1 other = 1 posib = (one - other) print(((posib +1) // 2)) ```
90,102
Provide tags and a correct Python 3 solution for this coding contest problem. Tanechka is shopping in the toy shop. There are exactly n toys in the shop for sale, the cost of the i-th toy is i burles. She wants to choose two toys in such a way that their total cost is k burles. How many ways to do that does she have? Each toy appears in the shop exactly once. Pairs (a, b) and (b, a) are considered equal. Pairs (a, b), where a=b, are not allowed. Input The first line of the input contains two integers n, k (1 ≤ n, k ≤ 10^{14}) — the number of toys and the expected total cost of the pair of toys. Output Print the number of ways to choose the pair of toys satisfying the condition above. Print 0, if Tanechka can choose no pair of toys in such a way that their total cost is k burles. Examples Input 8 5 Output 2 Input 8 15 Output 1 Input 7 20 Output 0 Input 1000000000000 1000000000001 Output 500000000000 Note In the first example Tanechka can choose the pair of toys (1, 4) or the pair of toys (2, 3). In the second example Tanechka can choose only the pair of toys (7, 8). In the third example choosing any pair of toys will lead to the total cost less than 20. So the answer is 0. In the fourth example she can choose the following pairs: (1, 1000000000000), (2, 999999999999), (3, 999999999998), ..., (500000000000, 500000000001). The number of such pairs is exactly 500000000000. Tags: math Correct Solution: ``` import math n, k = map(int, input().split()) maxPairs = float(k/2) if n == 1: print(0) elif n < k: print(max(0, math.ceil(n - maxPairs))) else: if k % 2 == 1: print(math.floor(k/2)) else: print(int(k/2-1)) ```
90,103
Provide tags and a correct Python 3 solution for this coding contest problem. Tanechka is shopping in the toy shop. There are exactly n toys in the shop for sale, the cost of the i-th toy is i burles. She wants to choose two toys in such a way that their total cost is k burles. How many ways to do that does she have? Each toy appears in the shop exactly once. Pairs (a, b) and (b, a) are considered equal. Pairs (a, b), where a=b, are not allowed. Input The first line of the input contains two integers n, k (1 ≤ n, k ≤ 10^{14}) — the number of toys and the expected total cost of the pair of toys. Output Print the number of ways to choose the pair of toys satisfying the condition above. Print 0, if Tanechka can choose no pair of toys in such a way that their total cost is k burles. Examples Input 8 5 Output 2 Input 8 15 Output 1 Input 7 20 Output 0 Input 1000000000000 1000000000001 Output 500000000000 Note In the first example Tanechka can choose the pair of toys (1, 4) or the pair of toys (2, 3). In the second example Tanechka can choose only the pair of toys (7, 8). In the third example choosing any pair of toys will lead to the total cost less than 20. So the answer is 0. In the fourth example she can choose the following pairs: (1, 1000000000000), (2, 999999999999), (3, 999999999998), ..., (500000000000, 500000000001). The number of such pairs is exactly 500000000000. Tags: math Correct Solution: ``` n, k = map(int, input().split()) if k < 3 or k > 2 * n - 1: print(0) else: if k % 2: mini = k // 2 maxi = mini + 1 else: mini = k // 2 - 1 maxi = mini + 2 print(min(mini, (n - maxi + 1))) ```
90,104
Provide tags and a correct Python 3 solution for this coding contest problem. Tanechka is shopping in the toy shop. There are exactly n toys in the shop for sale, the cost of the i-th toy is i burles. She wants to choose two toys in such a way that their total cost is k burles. How many ways to do that does she have? Each toy appears in the shop exactly once. Pairs (a, b) and (b, a) are considered equal. Pairs (a, b), where a=b, are not allowed. Input The first line of the input contains two integers n, k (1 ≤ n, k ≤ 10^{14}) — the number of toys and the expected total cost of the pair of toys. Output Print the number of ways to choose the pair of toys satisfying the condition above. Print 0, if Tanechka can choose no pair of toys in such a way that their total cost is k burles. Examples Input 8 5 Output 2 Input 8 15 Output 1 Input 7 20 Output 0 Input 1000000000000 1000000000001 Output 500000000000 Note In the first example Tanechka can choose the pair of toys (1, 4) or the pair of toys (2, 3). In the second example Tanechka can choose only the pair of toys (7, 8). In the third example choosing any pair of toys will lead to the total cost less than 20. So the answer is 0. In the fourth example she can choose the following pairs: (1, 1000000000000), (2, 999999999999), (3, 999999999998), ..., (500000000000, 500000000001). The number of such pairs is exactly 500000000000. Tags: math Correct Solution: ``` n, k = map(int, input().split()) if k>n: print(max(0, n - k//2)) else: print(k//2 + (k&1) - 1) ```
90,105
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Tanechka is shopping in the toy shop. There are exactly n toys in the shop for sale, the cost of the i-th toy is i burles. She wants to choose two toys in such a way that their total cost is k burles. How many ways to do that does she have? Each toy appears in the shop exactly once. Pairs (a, b) and (b, a) are considered equal. Pairs (a, b), where a=b, are not allowed. Input The first line of the input contains two integers n, k (1 ≤ n, k ≤ 10^{14}) — the number of toys and the expected total cost of the pair of toys. Output Print the number of ways to choose the pair of toys satisfying the condition above. Print 0, if Tanechka can choose no pair of toys in such a way that their total cost is k burles. Examples Input 8 5 Output 2 Input 8 15 Output 1 Input 7 20 Output 0 Input 1000000000000 1000000000001 Output 500000000000 Note In the first example Tanechka can choose the pair of toys (1, 4) or the pair of toys (2, 3). In the second example Tanechka can choose only the pair of toys (7, 8). In the third example choosing any pair of toys will lead to the total cost less than 20. So the answer is 0. In the fourth example she can choose the following pairs: (1, 1000000000000), (2, 999999999999), (3, 999999999998), ..., (500000000000, 500000000001). The number of such pairs is exactly 500000000000. Submitted Solution: ``` n, k = map(int, input().split()) if n >= k - 1: print((k - 1) // 2) else: print(max(0, (2*n - k - 1) // 2 + 1)) ``` Yes
90,106
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Tanechka is shopping in the toy shop. There are exactly n toys in the shop for sale, the cost of the i-th toy is i burles. She wants to choose two toys in such a way that their total cost is k burles. How many ways to do that does she have? Each toy appears in the shop exactly once. Pairs (a, b) and (b, a) are considered equal. Pairs (a, b), where a=b, are not allowed. Input The first line of the input contains two integers n, k (1 ≤ n, k ≤ 10^{14}) — the number of toys and the expected total cost of the pair of toys. Output Print the number of ways to choose the pair of toys satisfying the condition above. Print 0, if Tanechka can choose no pair of toys in such a way that their total cost is k burles. Examples Input 8 5 Output 2 Input 8 15 Output 1 Input 7 20 Output 0 Input 1000000000000 1000000000001 Output 500000000000 Note In the first example Tanechka can choose the pair of toys (1, 4) or the pair of toys (2, 3). In the second example Tanechka can choose only the pair of toys (7, 8). In the third example choosing any pair of toys will lead to the total cost less than 20. So the answer is 0. In the fourth example she can choose the following pairs: (1, 1000000000000), (2, 999999999999), (3, 999999999998), ..., (500000000000, 500000000001). The number of such pairs is exactly 500000000000. Submitted Solution: ``` n,k = input().split() n = int(n) k = int(k) c =0 if k <= n: c = k-1 elif k <= 2*n: c= 2*n-k+1 print(int(c/2)) ``` Yes
90,107
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Tanechka is shopping in the toy shop. There are exactly n toys in the shop for sale, the cost of the i-th toy is i burles. She wants to choose two toys in such a way that their total cost is k burles. How many ways to do that does she have? Each toy appears in the shop exactly once. Pairs (a, b) and (b, a) are considered equal. Pairs (a, b), where a=b, are not allowed. Input The first line of the input contains two integers n, k (1 ≤ n, k ≤ 10^{14}) — the number of toys and the expected total cost of the pair of toys. Output Print the number of ways to choose the pair of toys satisfying the condition above. Print 0, if Tanechka can choose no pair of toys in such a way that their total cost is k burles. Examples Input 8 5 Output 2 Input 8 15 Output 1 Input 7 20 Output 0 Input 1000000000000 1000000000001 Output 500000000000 Note In the first example Tanechka can choose the pair of toys (1, 4) or the pair of toys (2, 3). In the second example Tanechka can choose only the pair of toys (7, 8). In the third example choosing any pair of toys will lead to the total cost less than 20. So the answer is 0. In the fourth example she can choose the following pairs: (1, 1000000000000), (2, 999999999999), (3, 999999999998), ..., (500000000000, 500000000001). The number of such pairs is exactly 500000000000. Submitted Solution: ``` n, k = map(int, input().split()) if k % 2: a, b = k // 2, k // 2 + 1 else: a, b = k // 2 - 1, k // 2 + 1 if 2 * n - 1 < k: print(0) else: print(min(a - 1, n - b) + 1) ``` Yes
90,108
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Tanechka is shopping in the toy shop. There are exactly n toys in the shop for sale, the cost of the i-th toy is i burles. She wants to choose two toys in such a way that their total cost is k burles. How many ways to do that does she have? Each toy appears in the shop exactly once. Pairs (a, b) and (b, a) are considered equal. Pairs (a, b), where a=b, are not allowed. Input The first line of the input contains two integers n, k (1 ≤ n, k ≤ 10^{14}) — the number of toys and the expected total cost of the pair of toys. Output Print the number of ways to choose the pair of toys satisfying the condition above. Print 0, if Tanechka can choose no pair of toys in such a way that their total cost is k burles. Examples Input 8 5 Output 2 Input 8 15 Output 1 Input 7 20 Output 0 Input 1000000000000 1000000000001 Output 500000000000 Note In the first example Tanechka can choose the pair of toys (1, 4) or the pair of toys (2, 3). In the second example Tanechka can choose only the pair of toys (7, 8). In the third example choosing any pair of toys will lead to the total cost less than 20. So the answer is 0. In the fourth example she can choose the following pairs: (1, 1000000000000), (2, 999999999999), (3, 999999999998), ..., (500000000000, 500000000001). The number of such pairs is exactly 500000000000. Submitted Solution: ``` from math import ceil n,k = list(map(int,input().split())) if k<=n: if k&1: print(k//2) else: print((k-1)//2) else: if 2*n-k-1<0: print(0) else: print(((2*n-k-1)//2)+1) ``` Yes
90,109
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Tanechka is shopping in the toy shop. There are exactly n toys in the shop for sale, the cost of the i-th toy is i burles. She wants to choose two toys in such a way that their total cost is k burles. How many ways to do that does she have? Each toy appears in the shop exactly once. Pairs (a, b) and (b, a) are considered equal. Pairs (a, b), where a=b, are not allowed. Input The first line of the input contains two integers n, k (1 ≤ n, k ≤ 10^{14}) — the number of toys and the expected total cost of the pair of toys. Output Print the number of ways to choose the pair of toys satisfying the condition above. Print 0, if Tanechka can choose no pair of toys in such a way that their total cost is k burles. Examples Input 8 5 Output 2 Input 8 15 Output 1 Input 7 20 Output 0 Input 1000000000000 1000000000001 Output 500000000000 Note In the first example Tanechka can choose the pair of toys (1, 4) or the pair of toys (2, 3). In the second example Tanechka can choose only the pair of toys (7, 8). In the third example choosing any pair of toys will lead to the total cost less than 20. So the answer is 0. In the fourth example she can choose the following pairs: (1, 1000000000000), (2, 999999999999), (3, 999999999998), ..., (500000000000, 500000000001). The number of such pairs is exactly 500000000000. Submitted Solution: ``` n,k=[int(x) for x in input().split()] if k>2*n or n==1: print(0) elif k<=2*n and k>n: if (2*n-k)%2==0: print((2*n-k)//2) else: print((2*n-k)//2+1) else: print(k//2) ``` No
90,110
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Tanechka is shopping in the toy shop. There are exactly n toys in the shop for sale, the cost of the i-th toy is i burles. She wants to choose two toys in such a way that their total cost is k burles. How many ways to do that does she have? Each toy appears in the shop exactly once. Pairs (a, b) and (b, a) are considered equal. Pairs (a, b), where a=b, are not allowed. Input The first line of the input contains two integers n, k (1 ≤ n, k ≤ 10^{14}) — the number of toys and the expected total cost of the pair of toys. Output Print the number of ways to choose the pair of toys satisfying the condition above. Print 0, if Tanechka can choose no pair of toys in such a way that their total cost is k burles. Examples Input 8 5 Output 2 Input 8 15 Output 1 Input 7 20 Output 0 Input 1000000000000 1000000000001 Output 500000000000 Note In the first example Tanechka can choose the pair of toys (1, 4) or the pair of toys (2, 3). In the second example Tanechka can choose only the pair of toys (7, 8). In the third example choosing any pair of toys will lead to the total cost less than 20. So the answer is 0. In the fourth example she can choose the following pairs: (1, 1000000000000), (2, 999999999999), (3, 999999999998), ..., (500000000000, 500000000001). The number of such pairs is exactly 500000000000. Submitted Solution: ``` import sys import math import collections import heapq input=sys.stdin.readline n,k=(int(i) for i in input().split()) if(2*n-1<k): print(0) else: if(k>n): k1=k-n if(n-k1==2): if(k%2==0): print(math.ceil((n/2)-1)) else: print(math.ceil(n/2)) else: if(k%2==0): print(math.ceil((n-k1)/2)-1) else: print(math.ceil((n-k1)/2)) elif(k<=n): if(k%2==0): print(math.ceil((k-1)/2)-1) else: print(math.ceil((k-1)/2)) ``` No
90,111
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Tanechka is shopping in the toy shop. There are exactly n toys in the shop for sale, the cost of the i-th toy is i burles. She wants to choose two toys in such a way that their total cost is k burles. How many ways to do that does she have? Each toy appears in the shop exactly once. Pairs (a, b) and (b, a) are considered equal. Pairs (a, b), where a=b, are not allowed. Input The first line of the input contains two integers n, k (1 ≤ n, k ≤ 10^{14}) — the number of toys and the expected total cost of the pair of toys. Output Print the number of ways to choose the pair of toys satisfying the condition above. Print 0, if Tanechka can choose no pair of toys in such a way that their total cost is k burles. Examples Input 8 5 Output 2 Input 8 15 Output 1 Input 7 20 Output 0 Input 1000000000000 1000000000001 Output 500000000000 Note In the first example Tanechka can choose the pair of toys (1, 4) or the pair of toys (2, 3). In the second example Tanechka can choose only the pair of toys (7, 8). In the third example choosing any pair of toys will lead to the total cost less than 20. So the answer is 0. In the fourth example she can choose the following pairs: (1, 1000000000000), (2, 999999999999), (3, 999999999998), ..., (500000000000, 500000000001). The number of such pairs is exactly 500000000000. Submitted Solution: ``` n, k = map(int, input().split()) if n < k: print((n - (k-n-1))//2) elif n >= k: print((k-1)//2) ``` No
90,112
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Tanechka is shopping in the toy shop. There are exactly n toys in the shop for sale, the cost of the i-th toy is i burles. She wants to choose two toys in such a way that their total cost is k burles. How many ways to do that does she have? Each toy appears in the shop exactly once. Pairs (a, b) and (b, a) are considered equal. Pairs (a, b), where a=b, are not allowed. Input The first line of the input contains two integers n, k (1 ≤ n, k ≤ 10^{14}) — the number of toys and the expected total cost of the pair of toys. Output Print the number of ways to choose the pair of toys satisfying the condition above. Print 0, if Tanechka can choose no pair of toys in such a way that their total cost is k burles. Examples Input 8 5 Output 2 Input 8 15 Output 1 Input 7 20 Output 0 Input 1000000000000 1000000000001 Output 500000000000 Note In the first example Tanechka can choose the pair of toys (1, 4) or the pair of toys (2, 3). In the second example Tanechka can choose only the pair of toys (7, 8). In the third example choosing any pair of toys will lead to the total cost less than 20. So the answer is 0. In the fourth example she can choose the following pairs: (1, 1000000000000), (2, 999999999999), (3, 999999999998), ..., (500000000000, 500000000001). The number of such pairs is exactly 500000000000. Submitted Solution: ``` n, k = map(int, input().split()) if n >= k: print(k // 2) else: if n + n - 1 < k: print(0) else: print((n - (k - n) + 1) // 2) ``` No
90,113
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n points on the plane. The polygon formed from all the n points is strictly convex, that is, the polygon is convex, and there are no three collinear points (i.e. lying in the same straight line). The points are numbered from 1 to n, in clockwise order. We define the distance between two points p_1 = (x_1, y_1) and p_2 = (x_2, y_2) as their Manhattan distance: $$$d(p_1, p_2) = |x_1 - x_2| + |y_1 - y_2|.$$$ Furthermore, we define the perimeter of a polygon, as the sum of Manhattan distances between all adjacent pairs of points on it; if the points on the polygon are ordered as p_1, p_2, …, p_k (k ≥ 3), then the perimeter of the polygon is d(p_1, p_2) + d(p_2, p_3) + … + d(p_k, p_1). For some parameter k, let's consider all the polygons that can be formed from the given set of points, having any k vertices, such that the polygon is not self-intersecting. For each such polygon, let's consider its perimeter. Over all such perimeters, we define f(k) to be the maximal perimeter. Please note, when checking whether a polygon is self-intersecting, that the edges of a polygon are still drawn as straight lines. For instance, in the following pictures: <image> In the middle polygon, the order of points (p_1, p_3, p_2, p_4) is not valid, since it is a self-intersecting polygon. The right polygon (whose edges resemble the Manhattan distance) has the same order and is not self-intersecting, but we consider edges as straight lines. The correct way to draw this polygon is (p_1, p_2, p_3, p_4), which is the left polygon. Your task is to compute f(3), f(4), …, f(n). In other words, find the maximum possible perimeter for each possible number of points (i.e. 3 to n). Input The first line contains a single integer n (3 ≤ n ≤ 3⋅ 10^5) — the number of points. Each of the next n lines contains two integers x_i and y_i (-10^8 ≤ x_i, y_i ≤ 10^8) — the coordinates of point p_i. The set of points is guaranteed to be convex, all points are distinct, the points are ordered in clockwise order, and there will be no three collinear points. Output For each i (3≤ i≤ n), output f(i). Examples Input 4 2 4 4 3 3 0 1 3 Output 12 14 Input 3 0 0 0 2 2 0 Output 8 Note In the first example, for f(3), we consider four possible polygons: * (p_1, p_2, p_3), with perimeter 12. * (p_1, p_2, p_4), with perimeter 8. * (p_1, p_3, p_4), with perimeter 12. * (p_2, p_3, p_4), with perimeter 12. For f(4), there is only one option, taking all the given points. Its perimeter 14. In the second example, there is only one possible polygon. Its perimeter is 8. Tags: dp, geometry Correct Solution: ``` n=int(input()) tl=tr=bl=br=top=bot=left=right=-200000000 for i in range(n): a,b=map(int,input().split()) top=max(top,b) bot=max(bot,-b) right=max(right,a) left=max(left,-a) tr=max(tr,a+b) tl=max(tl,b-a) br=max(br,a-b) bl=max(bl,-a-b) print(str(2*max(top+left+br,top+right+bl,bot+left+tr,bot+right+tl))+(n-3)*(" "+str(2*(top+bot+left+right)))) ```
90,114
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n points on the plane. The polygon formed from all the n points is strictly convex, that is, the polygon is convex, and there are no three collinear points (i.e. lying in the same straight line). The points are numbered from 1 to n, in clockwise order. We define the distance between two points p_1 = (x_1, y_1) and p_2 = (x_2, y_2) as their Manhattan distance: $$$d(p_1, p_2) = |x_1 - x_2| + |y_1 - y_2|.$$$ Furthermore, we define the perimeter of a polygon, as the sum of Manhattan distances between all adjacent pairs of points on it; if the points on the polygon are ordered as p_1, p_2, …, p_k (k ≥ 3), then the perimeter of the polygon is d(p_1, p_2) + d(p_2, p_3) + … + d(p_k, p_1). For some parameter k, let's consider all the polygons that can be formed from the given set of points, having any k vertices, such that the polygon is not self-intersecting. For each such polygon, let's consider its perimeter. Over all such perimeters, we define f(k) to be the maximal perimeter. Please note, when checking whether a polygon is self-intersecting, that the edges of a polygon are still drawn as straight lines. For instance, in the following pictures: <image> In the middle polygon, the order of points (p_1, p_3, p_2, p_4) is not valid, since it is a self-intersecting polygon. The right polygon (whose edges resemble the Manhattan distance) has the same order and is not self-intersecting, but we consider edges as straight lines. The correct way to draw this polygon is (p_1, p_2, p_3, p_4), which is the left polygon. Your task is to compute f(3), f(4), …, f(n). In other words, find the maximum possible perimeter for each possible number of points (i.e. 3 to n). Input The first line contains a single integer n (3 ≤ n ≤ 3⋅ 10^5) — the number of points. Each of the next n lines contains two integers x_i and y_i (-10^8 ≤ x_i, y_i ≤ 10^8) — the coordinates of point p_i. The set of points is guaranteed to be convex, all points are distinct, the points are ordered in clockwise order, and there will be no three collinear points. Output For each i (3≤ i≤ n), output f(i). Examples Input 4 2 4 4 3 3 0 1 3 Output 12 14 Input 3 0 0 0 2 2 0 Output 8 Note In the first example, for f(3), we consider four possible polygons: * (p_1, p_2, p_3), with perimeter 12. * (p_1, p_2, p_4), with perimeter 8. * (p_1, p_3, p_4), with perimeter 12. * (p_2, p_3, p_4), with perimeter 12. For f(4), there is only one option, taking all the given points. Its perimeter 14. In the second example, there is only one possible polygon. Its perimeter is 8. Tags: dp, geometry Correct Solution: ``` n = int(input()) north = -100000000 south = 100000000 east = -100000000 west = 100000000 ne = -200000000 nw = -200000000 se = -200000000 sw = -200000000 for i in range(n): x,y = map(int,input().split()) north = max(north,y) east = max(east,x) south = min(south,y) west = min(west,x) ne = max(ne,x+y) nw = max(nw,y-x) se = max(se,x-y) sw = max(sw,-1*x-y) best = 2*(ne-south-west) best = max(best,2*(nw-south+east)) best = max(best,2*(se+north-west)) best = max(best,2*(sw+north+east)) ans = str(best) peri = 2*(north-south+east-west) ans += (" "+str(peri))*(n-3) print(ans) ```
90,115
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n points on the plane. The polygon formed from all the n points is strictly convex, that is, the polygon is convex, and there are no three collinear points (i.e. lying in the same straight line). The points are numbered from 1 to n, in clockwise order. We define the distance between two points p_1 = (x_1, y_1) and p_2 = (x_2, y_2) as their Manhattan distance: $$$d(p_1, p_2) = |x_1 - x_2| + |y_1 - y_2|.$$$ Furthermore, we define the perimeter of a polygon, as the sum of Manhattan distances between all adjacent pairs of points on it; if the points on the polygon are ordered as p_1, p_2, …, p_k (k ≥ 3), then the perimeter of the polygon is d(p_1, p_2) + d(p_2, p_3) + … + d(p_k, p_1). For some parameter k, let's consider all the polygons that can be formed from the given set of points, having any k vertices, such that the polygon is not self-intersecting. For each such polygon, let's consider its perimeter. Over all such perimeters, we define f(k) to be the maximal perimeter. Please note, when checking whether a polygon is self-intersecting, that the edges of a polygon are still drawn as straight lines. For instance, in the following pictures: <image> In the middle polygon, the order of points (p_1, p_3, p_2, p_4) is not valid, since it is a self-intersecting polygon. The right polygon (whose edges resemble the Manhattan distance) has the same order and is not self-intersecting, but we consider edges as straight lines. The correct way to draw this polygon is (p_1, p_2, p_3, p_4), which is the left polygon. Your task is to compute f(3), f(4), …, f(n). In other words, find the maximum possible perimeter for each possible number of points (i.e. 3 to n). Input The first line contains a single integer n (3 ≤ n ≤ 3⋅ 10^5) — the number of points. Each of the next n lines contains two integers x_i and y_i (-10^8 ≤ x_i, y_i ≤ 10^8) — the coordinates of point p_i. The set of points is guaranteed to be convex, all points are distinct, the points are ordered in clockwise order, and there will be no three collinear points. Output For each i (3≤ i≤ n), output f(i). Examples Input 4 2 4 4 3 3 0 1 3 Output 12 14 Input 3 0 0 0 2 2 0 Output 8 Note In the first example, for f(3), we consider four possible polygons: * (p_1, p_2, p_3), with perimeter 12. * (p_1, p_2, p_4), with perimeter 8. * (p_1, p_3, p_4), with perimeter 12. * (p_2, p_3, p_4), with perimeter 12. For f(4), there is only one option, taking all the given points. Its perimeter 14. In the second example, there is only one possible polygon. Its perimeter is 8. Tags: dp, geometry Correct Solution: ``` import itertools n = int(input()) xys = [tuple(map(int, input().split())) for _ in range(n)] h = min(xy[0] for xy in xys) j = min(xy[1] for xy in xys) k = max(xy[1] for xy in xys) l = max(xy[0] for xy in xys) ans3 = max( max( abs(x - h) + abs(y - j), abs(x - l) + abs(y - j), abs(x - h) + abs(y - k), abs(x - l) + abs(y - k), ) for x, y in xys) ans = sum(abs(x1 - x2) + abs(y1 - y2) for (x1, y1), (x2, y2) in zip(xys, [*xys[1:], xys[0]])) print(' '.join(itertools.chain((str(ans3 * 2),), itertools.repeat(str(ans), n - 3)))) ```
90,116
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n points on the plane. The polygon formed from all the n points is strictly convex, that is, the polygon is convex, and there are no three collinear points (i.e. lying in the same straight line). The points are numbered from 1 to n, in clockwise order. We define the distance between two points p_1 = (x_1, y_1) and p_2 = (x_2, y_2) as their Manhattan distance: $$$d(p_1, p_2) = |x_1 - x_2| + |y_1 - y_2|.$$$ Furthermore, we define the perimeter of a polygon, as the sum of Manhattan distances between all adjacent pairs of points on it; if the points on the polygon are ordered as p_1, p_2, …, p_k (k ≥ 3), then the perimeter of the polygon is d(p_1, p_2) + d(p_2, p_3) + … + d(p_k, p_1). For some parameter k, let's consider all the polygons that can be formed from the given set of points, having any k vertices, such that the polygon is not self-intersecting. For each such polygon, let's consider its perimeter. Over all such perimeters, we define f(k) to be the maximal perimeter. Please note, when checking whether a polygon is self-intersecting, that the edges of a polygon are still drawn as straight lines. For instance, in the following pictures: <image> In the middle polygon, the order of points (p_1, p_3, p_2, p_4) is not valid, since it is a self-intersecting polygon. The right polygon (whose edges resemble the Manhattan distance) has the same order and is not self-intersecting, but we consider edges as straight lines. The correct way to draw this polygon is (p_1, p_2, p_3, p_4), which is the left polygon. Your task is to compute f(3), f(4), …, f(n). In other words, find the maximum possible perimeter for each possible number of points (i.e. 3 to n). Input The first line contains a single integer n (3 ≤ n ≤ 3⋅ 10^5) — the number of points. Each of the next n lines contains two integers x_i and y_i (-10^8 ≤ x_i, y_i ≤ 10^8) — the coordinates of point p_i. The set of points is guaranteed to be convex, all points are distinct, the points are ordered in clockwise order, and there will be no three collinear points. Output For each i (3≤ i≤ n), output f(i). Examples Input 4 2 4 4 3 3 0 1 3 Output 12 14 Input 3 0 0 0 2 2 0 Output 8 Note In the first example, for f(3), we consider four possible polygons: * (p_1, p_2, p_3), with perimeter 12. * (p_1, p_2, p_4), with perimeter 8. * (p_1, p_3, p_4), with perimeter 12. * (p_2, p_3, p_4), with perimeter 12. For f(4), there is only one option, taking all the given points. Its perimeter 14. In the second example, there is only one possible polygon. Its perimeter is 8. Tags: dp, geometry Correct Solution: ``` from collections import namedtuple import sys XY = namedtuple('XY', 'x y') n = int(input()) pg = [XY(*[int(w) for w in input().split()]) for _ in range(n)] minx = min(p.x for p in pg) miny = min(p.y for p in pg) maxx = max(p.x for p in pg) maxy = max(p.y for p in pg) p4 = 2 * ((maxx - minx) + (maxy - miny)) p3 = p4 - 2 * min([min(p.x - minx, maxx - p.x) + min(p.y - miny, maxy - p.y) for p in pg]) print(p3, *([p4] * (n-3))) ```
90,117
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n points on the plane. The polygon formed from all the n points is strictly convex, that is, the polygon is convex, and there are no three collinear points (i.e. lying in the same straight line). The points are numbered from 1 to n, in clockwise order. We define the distance between two points p_1 = (x_1, y_1) and p_2 = (x_2, y_2) as their Manhattan distance: $$$d(p_1, p_2) = |x_1 - x_2| + |y_1 - y_2|.$$$ Furthermore, we define the perimeter of a polygon, as the sum of Manhattan distances between all adjacent pairs of points on it; if the points on the polygon are ordered as p_1, p_2, …, p_k (k ≥ 3), then the perimeter of the polygon is d(p_1, p_2) + d(p_2, p_3) + … + d(p_k, p_1). For some parameter k, let's consider all the polygons that can be formed from the given set of points, having any k vertices, such that the polygon is not self-intersecting. For each such polygon, let's consider its perimeter. Over all such perimeters, we define f(k) to be the maximal perimeter. Please note, when checking whether a polygon is self-intersecting, that the edges of a polygon are still drawn as straight lines. For instance, in the following pictures: <image> In the middle polygon, the order of points (p_1, p_3, p_2, p_4) is not valid, since it is a self-intersecting polygon. The right polygon (whose edges resemble the Manhattan distance) has the same order and is not self-intersecting, but we consider edges as straight lines. The correct way to draw this polygon is (p_1, p_2, p_3, p_4), which is the left polygon. Your task is to compute f(3), f(4), …, f(n). In other words, find the maximum possible perimeter for each possible number of points (i.e. 3 to n). Input The first line contains a single integer n (3 ≤ n ≤ 3⋅ 10^5) — the number of points. Each of the next n lines contains two integers x_i and y_i (-10^8 ≤ x_i, y_i ≤ 10^8) — the coordinates of point p_i. The set of points is guaranteed to be convex, all points are distinct, the points are ordered in clockwise order, and there will be no three collinear points. Output For each i (3≤ i≤ n), output f(i). Examples Input 4 2 4 4 3 3 0 1 3 Output 12 14 Input 3 0 0 0 2 2 0 Output 8 Note In the first example, for f(3), we consider four possible polygons: * (p_1, p_2, p_3), with perimeter 12. * (p_1, p_2, p_4), with perimeter 8. * (p_1, p_3, p_4), with perimeter 12. * (p_2, p_3, p_4), with perimeter 12. For f(4), there is only one option, taking all the given points. Its perimeter 14. In the second example, there is only one possible polygon. Its perimeter is 8. Submitted Solution: ``` from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) n = int(input()) pts = [Point(*map(int, input().split())) for _ in range(n)] min_x_idx = min(range(n), key=lambda i : pts[i].x) max_x_idx = max(range(n), key=lambda i : pts[i].x) min_y_idx = min(range(n), key=lambda i : pts[i].y) max_y_idx = max(range(n), key=lambda i : pts[i].y) extremities = sorted([(min_x_idx, 'x'), (min_y_idx, 'y'), (max_x_idx, 'x'), (max_y_idx, 'y')]) # print(extremities) # print(*[tuple(pts[i]) for i, _ in extremities]) loop_extremities = extremities + extremities def interpolate_corner(pts, shift_x, shift_y, idx1, idx2): i = idx1 max_dist = 0 while i != idx2: # print(idx1, i, idx2) max_dist = max(abs(pts[i].x - shift_x) + abs(pts[i].y - shift_y), max_dist) # print(abs(pts[i].x - shift_x) , abs(pts[i].y - shift_y)) i = (i + 1) % len(pts) return 2 * max_dist quad_perimeter = 2 * ( max(pt.x for pt in pts) + max(pt.y for pt in pts) - min(pt.x for pt in pts) - min(pt.y for pt in pts) ) tri_perimeter = -1 if n >= 4: for i in range(4): (to_use_1, u1_label), (to_use_2, u2_label) = loop_extremities[i:i+2] (to_merge_1, m1_label), (to_merge_2, m2_label) = loop_extremities[i+2:i+4] if u1_label == 'x': shift_x = pts[to_use_1].x shift_y = pts[to_use_2].y else: shift_x = pts[to_use_2].x shift_y = pts[to_use_1].y tri_perimeter = max(interpolate_corner(pts, shift_x, shift_y, to_merge_1, to_merge_2), tri_perimeter) # print(*[tuple(pts[i]) for i, _ in loop_extremities[i:i+4]]) # print(tri_perimeter) else: tri_perimeter = quad_perimeter print(tri_perimeter, end=' ') print(*(quad_perimeter for _ in range(n-3))) ``` No
90,118
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n points on the plane. The polygon formed from all the n points is strictly convex, that is, the polygon is convex, and there are no three collinear points (i.e. lying in the same straight line). The points are numbered from 1 to n, in clockwise order. We define the distance between two points p_1 = (x_1, y_1) and p_2 = (x_2, y_2) as their Manhattan distance: $$$d(p_1, p_2) = |x_1 - x_2| + |y_1 - y_2|.$$$ Furthermore, we define the perimeter of a polygon, as the sum of Manhattan distances between all adjacent pairs of points on it; if the points on the polygon are ordered as p_1, p_2, …, p_k (k ≥ 3), then the perimeter of the polygon is d(p_1, p_2) + d(p_2, p_3) + … + d(p_k, p_1). For some parameter k, let's consider all the polygons that can be formed from the given set of points, having any k vertices, such that the polygon is not self-intersecting. For each such polygon, let's consider its perimeter. Over all such perimeters, we define f(k) to be the maximal perimeter. Please note, when checking whether a polygon is self-intersecting, that the edges of a polygon are still drawn as straight lines. For instance, in the following pictures: <image> In the middle polygon, the order of points (p_1, p_3, p_2, p_4) is not valid, since it is a self-intersecting polygon. The right polygon (whose edges resemble the Manhattan distance) has the same order and is not self-intersecting, but we consider edges as straight lines. The correct way to draw this polygon is (p_1, p_2, p_3, p_4), which is the left polygon. Your task is to compute f(3), f(4), …, f(n). In other words, find the maximum possible perimeter for each possible number of points (i.e. 3 to n). Input The first line contains a single integer n (3 ≤ n ≤ 3⋅ 10^5) — the number of points. Each of the next n lines contains two integers x_i and y_i (-10^8 ≤ x_i, y_i ≤ 10^8) — the coordinates of point p_i. The set of points is guaranteed to be convex, all points are distinct, the points are ordered in clockwise order, and there will be no three collinear points. Output For each i (3≤ i≤ n), output f(i). Examples Input 4 2 4 4 3 3 0 1 3 Output 12 14 Input 3 0 0 0 2 2 0 Output 8 Note In the first example, for f(3), we consider four possible polygons: * (p_1, p_2, p_3), with perimeter 12. * (p_1, p_2, p_4), with perimeter 8. * (p_1, p_3, p_4), with perimeter 12. * (p_2, p_3, p_4), with perimeter 12. For f(4), there is only one option, taking all the given points. Its perimeter 14. In the second example, there is only one possible polygon. Its perimeter is 8. Submitted Solution: ``` n=int(input()) #n,m=map(int,input().split()) xy=[] for i in range(n): x,y=map(int,input().split()) xy.append([x,y]) kr=[0]*4 maxx=-1000000000 minx=1000000000 maxy=-1000000000 miny=1000000000 for i in range(n): x=xy[i][0] y=xy[i][1] if x<=xy[kr[3]][0]: kr[3]=i if x>=xy[kr[1]][0]: kr[1]=i if y<=xy[kr[2]][1]: kr[2]=i if y>=xy[kr[0]][1]: kr[0]=i def diss(xy,i1,i2): return abs(xy[i1][0]-xy[i2][0])+abs(xy[i1][1]-xy[i2][1]) a1=diss(xy,kr[0],kr[1])+diss(xy,kr[1],kr[2])+diss(xy,kr[2],kr[0]) a2=diss(xy,kr[0],kr[1])+diss(xy,kr[1],kr[3])+diss(xy,kr[3],kr[0]) a3=diss(xy,kr[0],kr[2])+diss(xy,kr[2],kr[3])+diss(xy,kr[3],kr[0]) a4=diss(xy,kr[1],kr[2])+diss(xy,kr[2],kr[3])+diss(xy,kr[3],kr[1]) print(max(a1,a2,a3,a4),end=' ') ans=diss(xy,kr[0],kr[1])+diss(xy,kr[1],kr[2])+diss(xy,kr[2],kr[3])+diss(xy,kr[3],kr[0]) for i in range(n-3): print(ans,end=' ') ``` No
90,119
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n points on the plane. The polygon formed from all the n points is strictly convex, that is, the polygon is convex, and there are no three collinear points (i.e. lying in the same straight line). The points are numbered from 1 to n, in clockwise order. We define the distance between two points p_1 = (x_1, y_1) and p_2 = (x_2, y_2) as their Manhattan distance: $$$d(p_1, p_2) = |x_1 - x_2| + |y_1 - y_2|.$$$ Furthermore, we define the perimeter of a polygon, as the sum of Manhattan distances between all adjacent pairs of points on it; if the points on the polygon are ordered as p_1, p_2, …, p_k (k ≥ 3), then the perimeter of the polygon is d(p_1, p_2) + d(p_2, p_3) + … + d(p_k, p_1). For some parameter k, let's consider all the polygons that can be formed from the given set of points, having any k vertices, such that the polygon is not self-intersecting. For each such polygon, let's consider its perimeter. Over all such perimeters, we define f(k) to be the maximal perimeter. Please note, when checking whether a polygon is self-intersecting, that the edges of a polygon are still drawn as straight lines. For instance, in the following pictures: <image> In the middle polygon, the order of points (p_1, p_3, p_2, p_4) is not valid, since it is a self-intersecting polygon. The right polygon (whose edges resemble the Manhattan distance) has the same order and is not self-intersecting, but we consider edges as straight lines. The correct way to draw this polygon is (p_1, p_2, p_3, p_4), which is the left polygon. Your task is to compute f(3), f(4), …, f(n). In other words, find the maximum possible perimeter for each possible number of points (i.e. 3 to n). Input The first line contains a single integer n (3 ≤ n ≤ 3⋅ 10^5) — the number of points. Each of the next n lines contains two integers x_i and y_i (-10^8 ≤ x_i, y_i ≤ 10^8) — the coordinates of point p_i. The set of points is guaranteed to be convex, all points are distinct, the points are ordered in clockwise order, and there will be no three collinear points. Output For each i (3≤ i≤ n), output f(i). Examples Input 4 2 4 4 3 3 0 1 3 Output 12 14 Input 3 0 0 0 2 2 0 Output 8 Note In the first example, for f(3), we consider four possible polygons: * (p_1, p_2, p_3), with perimeter 12. * (p_1, p_2, p_4), with perimeter 8. * (p_1, p_3, p_4), with perimeter 12. * (p_2, p_3, p_4), with perimeter 12. For f(4), there is only one option, taking all the given points. Its perimeter 14. In the second example, there is only one possible polygon. Its perimeter is 8. Submitted Solution: ``` from itertools import combinations n = int(input()) dots = [list(map(int, input().split())) for i in range(n)] minx = min([x for x, y in dots]) maxx = max([x for x, y in dots]) miny = min([y for x, y in dots]) maxy = max([y for x, y in dots]) ans_gt3 = 2 * (maxx - minx) + 2 * (maxy - miny) def get_perimeter(a, b, c): ax, ay = a bx, by = b cx, cy = c xmin, _, xmax = list(sorted([ax, bx, cx])) ymin, _, ymax = list(sorted([ay, by, cy])) return 2 * (xmax - xmin) + 2 * (ymax - ymin) a1 = get_perimeter((minx, min([y for x, y in dots if x == minx])), (max([x for x, y in dots if y == maxy]), maxy), (max([x for x, y in dots if y == miny]), miny)) a2 = get_perimeter((max([x for x, y in dots if y == maxy]), maxy), (maxx, min([y for x, y in dots if x == maxx])), (minx, min([y for x, y in dots if x == minx]))) a3 = get_perimeter((maxx, min([y for x, y in dots if x == maxx])), (min([x for x, y in dots if y == miny]), miny), (min([x for x, y in dots if y == maxy]), maxy)) a4 = get_perimeter((max([x for x, y in dots if y == miny]), miny), (minx, max([y for x, y in dots if x == minx])), (maxx, max([y for x, y in dots if x == maxx]))) ans_3 = max(a1, a2, a3, a4) if n == 3: print(ans_3) else: ans = [ans_3] + ([ans_gt3] * (n - 3)) ans = list(map(str, ans)) print(' '.join(ans)) ``` No
90,120
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n points on the plane. The polygon formed from all the n points is strictly convex, that is, the polygon is convex, and there are no three collinear points (i.e. lying in the same straight line). The points are numbered from 1 to n, in clockwise order. We define the distance between two points p_1 = (x_1, y_1) and p_2 = (x_2, y_2) as their Manhattan distance: $$$d(p_1, p_2) = |x_1 - x_2| + |y_1 - y_2|.$$$ Furthermore, we define the perimeter of a polygon, as the sum of Manhattan distances between all adjacent pairs of points on it; if the points on the polygon are ordered as p_1, p_2, …, p_k (k ≥ 3), then the perimeter of the polygon is d(p_1, p_2) + d(p_2, p_3) + … + d(p_k, p_1). For some parameter k, let's consider all the polygons that can be formed from the given set of points, having any k vertices, such that the polygon is not self-intersecting. For each such polygon, let's consider its perimeter. Over all such perimeters, we define f(k) to be the maximal perimeter. Please note, when checking whether a polygon is self-intersecting, that the edges of a polygon are still drawn as straight lines. For instance, in the following pictures: <image> In the middle polygon, the order of points (p_1, p_3, p_2, p_4) is not valid, since it is a self-intersecting polygon. The right polygon (whose edges resemble the Manhattan distance) has the same order and is not self-intersecting, but we consider edges as straight lines. The correct way to draw this polygon is (p_1, p_2, p_3, p_4), which is the left polygon. Your task is to compute f(3), f(4), …, f(n). In other words, find the maximum possible perimeter for each possible number of points (i.e. 3 to n). Input The first line contains a single integer n (3 ≤ n ≤ 3⋅ 10^5) — the number of points. Each of the next n lines contains two integers x_i and y_i (-10^8 ≤ x_i, y_i ≤ 10^8) — the coordinates of point p_i. The set of points is guaranteed to be convex, all points are distinct, the points are ordered in clockwise order, and there will be no three collinear points. Output For each i (3≤ i≤ n), output f(i). Examples Input 4 2 4 4 3 3 0 1 3 Output 12 14 Input 3 0 0 0 2 2 0 Output 8 Note In the first example, for f(3), we consider four possible polygons: * (p_1, p_2, p_3), with perimeter 12. * (p_1, p_2, p_4), with perimeter 8. * (p_1, p_3, p_4), with perimeter 12. * (p_2, p_3, p_4), with perimeter 12. For f(4), there is only one option, taking all the given points. Its perimeter 14. In the second example, there is only one possible polygon. Its perimeter is 8. Submitted Solution: ``` from itertools import combinations n = int(input()) dots = [list(map(int, input().split())) for i in range(n)] minx = min([x for x, y in dots]) maxx = max([x for x, y in dots]) miny = min([y for x, y in dots]) maxy = max([y for x, y in dots]) lx, ly = dots[0] for x, y in dots: if x < lx: lx, ly = x, y rx, ry = dots[0] for x, y in dots: if x > rx: rx, ry = x, y ux, uy = dots[0] for x, y in dots: if y > uy: ux, uy = x, y dx, dy = dots[0] for x, y in dots: if y < dy: dx, dy = x, y ans_gt3 = 2 * (rx - lx) + 2 * (uy - dy) def get_perimeter(a, b, c): ax, ay = a bx, by = b cx, cy = c return abs(ax - bx) + abs(ay - by) + \ abs(bx - cx) + abs(by - cy) + \ abs(cx - ax) + abs(cy - ay) a1 = get_perimeter((lx, ly), (max([x for x, y in dots if y == maxy]), maxy), (max([x for x, y in dots if y == miny]), miny)) a2 = get_perimeter((ux, uy), (maxx, min([y for x, y in dots if x == maxx])), (minx, min([y for x, y in dots if x == minx]))) a3 = get_perimeter((rx, ry), (min([x for x, y in dots if y == miny]), miny), (min([x for x, y in dots if y == maxy]), maxy)) a4 = get_perimeter((dx, dy), (minx, max([y for x, y in dots if x == minx])), (maxx, max([y for x, y in dots if x == maxx]))) ans_3 = max(a1, a2, a3, a4) if n == 3: print(ans_3) else: ans = [ans_3] + ([ans_gt3] * (n - 3)) ans = list(map(str, ans)) print(' '.join(ans)) ``` No
90,121
Provide tags and a correct Python 3 solution for this coding contest problem. Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog. Let us define k-multihedgehog as follows: * 1-multihedgehog is hedgehog: it has one vertex of degree at least 3 and some vertices of degree 1. * For all k ≥ 2, k-multihedgehog is (k-1)-multihedgehog in which the following changes has been made for each vertex v with degree 1: let u be its only neighbor; remove vertex v, create a new hedgehog with center at vertex w and connect vertices u and w with an edge. New hedgehogs can differ from each other and the initial gift. Thereby k-multihedgehog is a tree. Ivan made k-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed k-multihedgehog. Input First line of input contains 2 integers n, k (1 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{9}) — number of vertices and hedgehog parameter. Next n-1 lines contains two integers u v (1 ≤ u, v ≤ n; u ≠ v) — indices of vertices connected by edge. It is guaranteed that given graph is a tree. Output Print "Yes" (without quotes), if given graph is k-multihedgehog, and "No" (without quotes) otherwise. Examples Input 14 2 1 4 2 4 3 4 4 13 10 5 11 5 12 5 14 5 5 13 6 7 8 6 13 6 9 6 Output Yes Input 3 1 1 3 2 3 Output No Note 2-multihedgehog from the first example looks like this: <image> Its center is vertex 13. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13]. Tree from second example is not a hedgehog because degree of center should be at least 3. Tags: dfs and similar, graphs, shortest paths Correct Solution: ``` from collections import defaultdict n, k = map(int, input().split()) connections = defaultdict(set) for _ in range(n-1): u, v = map(int, input().split()) connections[u].add(v) connections[v].add(u) leafs = set() for node in connections: if len(connections[node])==1: leafs.add(node) steps = 0 is_correct = True while is_correct and steps<=k: new_leafs = set() for x in leafs: if len(connections[x])>1: is_correct = False #print("Len of %d more than one"%x) break root = list(connections[x])[0] if len(connections[root])<4 and len(leafs)!=3: is_correct = False #print("x: %d Len of root %d less than three"%(x,root)) #print(connections[root]) break if not is_correct: break for x in leafs: root = list(connections[x])[0] new_leafs.add(root) connections[root].remove(x) leafs = new_leafs steps += 1 if len(leafs)==1 and len(connections[list(leafs)[0]])==0: break #print("steps is %d"%steps) if is_correct and steps==k: print("Yes") else: print('No') ```
90,122
Provide tags and a correct Python 3 solution for this coding contest problem. Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog. Let us define k-multihedgehog as follows: * 1-multihedgehog is hedgehog: it has one vertex of degree at least 3 and some vertices of degree 1. * For all k ≥ 2, k-multihedgehog is (k-1)-multihedgehog in which the following changes has been made for each vertex v with degree 1: let u be its only neighbor; remove vertex v, create a new hedgehog with center at vertex w and connect vertices u and w with an edge. New hedgehogs can differ from each other and the initial gift. Thereby k-multihedgehog is a tree. Ivan made k-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed k-multihedgehog. Input First line of input contains 2 integers n, k (1 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{9}) — number of vertices and hedgehog parameter. Next n-1 lines contains two integers u v (1 ≤ u, v ≤ n; u ≠ v) — indices of vertices connected by edge. It is guaranteed that given graph is a tree. Output Print "Yes" (without quotes), if given graph is k-multihedgehog, and "No" (without quotes) otherwise. Examples Input 14 2 1 4 2 4 3 4 4 13 10 5 11 5 12 5 14 5 5 13 6 7 8 6 13 6 9 6 Output Yes Input 3 1 1 3 2 3 Output No Note 2-multihedgehog from the first example looks like this: <image> Its center is vertex 13. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13]. Tree from second example is not a hedgehog because degree of center should be at least 3. Tags: dfs and similar, graphs, shortest paths Correct Solution: ``` from collections import deque n, k = list(map(int, input().split())) G = [set() for _ in range(n + 1)] q, nq = deque(), deque() for _ in range(n - 1): u, v = list(map(int, input().split())) G[u].add(v) G[v].add(u) for u in range(1, n + 1): if len(G[u]) == 1: q.append(u) step = 0 removed = 0 ok = True while removed < n - 1: each = {} for u in q: nxt = G[u].pop() G[nxt].remove(u) each[nxt] = each.get(nxt, 0) + 1 removed += 1 if len(G[nxt]) == 0: break if len(G[nxt]) == 1: nq.append(nxt) if any(v < 3 for k,v in each.items()): ok = False break q, nq = nq, deque() step += 1 if ok and step == k and removed == n - 1: print('Yes') else: print('No') #print the result ```
90,123
Provide tags and a correct Python 3 solution for this coding contest problem. Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog. Let us define k-multihedgehog as follows: * 1-multihedgehog is hedgehog: it has one vertex of degree at least 3 and some vertices of degree 1. * For all k ≥ 2, k-multihedgehog is (k-1)-multihedgehog in which the following changes has been made for each vertex v with degree 1: let u be its only neighbor; remove vertex v, create a new hedgehog with center at vertex w and connect vertices u and w with an edge. New hedgehogs can differ from each other and the initial gift. Thereby k-multihedgehog is a tree. Ivan made k-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed k-multihedgehog. Input First line of input contains 2 integers n, k (1 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{9}) — number of vertices and hedgehog parameter. Next n-1 lines contains two integers u v (1 ≤ u, v ≤ n; u ≠ v) — indices of vertices connected by edge. It is guaranteed that given graph is a tree. Output Print "Yes" (without quotes), if given graph is k-multihedgehog, and "No" (without quotes) otherwise. Examples Input 14 2 1 4 2 4 3 4 4 13 10 5 11 5 12 5 14 5 5 13 6 7 8 6 13 6 9 6 Output Yes Input 3 1 1 3 2 3 Output No Note 2-multihedgehog from the first example looks like this: <image> Its center is vertex 13. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13]. Tree from second example is not a hedgehog because degree of center should be at least 3. Tags: dfs and similar, graphs, shortest paths Correct Solution: ``` from collections import deque n, k = list(map(int, input().split())) G = [set() for _ in range(n + 1)] q, nq = deque(), deque() for _ in range(n - 1): u, v = list(map(int, input().split())) G[u].add(v) G[v].add(u) for u in range(1, n + 1): if len(G[u]) == 1: q.append(u) step = 0 removed = 0 ok = True while removed < n - 1: each = {} for u in q: nxt = G[u].pop() G[nxt].remove(u) each[nxt] = each.get(nxt, 0) + 1 removed += 1 if len(G[nxt]) == 0: break if len(G[nxt]) == 1: nq.append(nxt) if any(v < 3 for k,v in each.items()): ok = False break q, nq = nq, deque() step += 1 if ok and step == k and removed == n - 1: print('Yes') else: print('No') #JSR ```
90,124
Provide tags and a correct Python 3 solution for this coding contest problem. Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog. Let us define k-multihedgehog as follows: * 1-multihedgehog is hedgehog: it has one vertex of degree at least 3 and some vertices of degree 1. * For all k ≥ 2, k-multihedgehog is (k-1)-multihedgehog in which the following changes has been made for each vertex v with degree 1: let u be its only neighbor; remove vertex v, create a new hedgehog with center at vertex w and connect vertices u and w with an edge. New hedgehogs can differ from each other and the initial gift. Thereby k-multihedgehog is a tree. Ivan made k-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed k-multihedgehog. Input First line of input contains 2 integers n, k (1 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{9}) — number of vertices and hedgehog parameter. Next n-1 lines contains two integers u v (1 ≤ u, v ≤ n; u ≠ v) — indices of vertices connected by edge. It is guaranteed that given graph is a tree. Output Print "Yes" (without quotes), if given graph is k-multihedgehog, and "No" (without quotes) otherwise. Examples Input 14 2 1 4 2 4 3 4 4 13 10 5 11 5 12 5 14 5 5 13 6 7 8 6 13 6 9 6 Output Yes Input 3 1 1 3 2 3 Output No Note 2-multihedgehog from the first example looks like this: <image> Its center is vertex 13. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13]. Tree from second example is not a hedgehog because degree of center should be at least 3. Tags: dfs and similar, graphs, shortest paths Correct Solution: ``` from collections import deque n,k = map(int,input().split()) d = {} for i in range(n): d[i+1] = set() for i in range(n-1): u,v = map(int,input().split()) d[u].add(v) d[v].add(u) dist = {} prev = {} dist[1] = 0 q = deque() q.append(1) while len(q) >0: cur = q.popleft() for x in d[cur]: if x not in dist: prev[x] = cur dist[x] = dist[cur]+1 q.append(x) answer = True if k > dist[cur]: answer = False else: for i in range(k): cur = prev[cur] dist2 = {} dist2[cur] = 0 q = deque() q.append(cur) while len(q) >0: cur2 = q.popleft() if cur2 == cur and len(d[cur]) < 3: answer = False break if len(d[cur2]) == 1: if dist2[cur2] != k: answer = False break elif len(d[cur2]) < 4 and cur2 != cur: answer = False break for x in d[cur2]: if x not in dist2: dist2[x] = dist2[cur2]+1 q.append(x) if answer: print("Yes") else: print("No") ```
90,125
Provide tags and a correct Python 3 solution for this coding contest problem. Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog. Let us define k-multihedgehog as follows: * 1-multihedgehog is hedgehog: it has one vertex of degree at least 3 and some vertices of degree 1. * For all k ≥ 2, k-multihedgehog is (k-1)-multihedgehog in which the following changes has been made for each vertex v with degree 1: let u be its only neighbor; remove vertex v, create a new hedgehog with center at vertex w and connect vertices u and w with an edge. New hedgehogs can differ from each other and the initial gift. Thereby k-multihedgehog is a tree. Ivan made k-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed k-multihedgehog. Input First line of input contains 2 integers n, k (1 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{9}) — number of vertices and hedgehog parameter. Next n-1 lines contains two integers u v (1 ≤ u, v ≤ n; u ≠ v) — indices of vertices connected by edge. It is guaranteed that given graph is a tree. Output Print "Yes" (without quotes), if given graph is k-multihedgehog, and "No" (without quotes) otherwise. Examples Input 14 2 1 4 2 4 3 4 4 13 10 5 11 5 12 5 14 5 5 13 6 7 8 6 13 6 9 6 Output Yes Input 3 1 1 3 2 3 Output No Note 2-multihedgehog from the first example looks like this: <image> Its center is vertex 13. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13]. Tree from second example is not a hedgehog because degree of center should be at least 3. Tags: dfs and similar, graphs, shortest paths Correct Solution: ``` # https://codeforces.com/problemset/problem/1067/B def push(d, u, v): if u not in d: d[u] = [] if v not in d: d[v] = [] d[u].append(v) d[v].append(u) def push_v(d, u, val): if u not in d: d[u] = 0 d[u] += val n, k = map(int, input().split()) g = {} for _ in range(n-1): u, v = map(int, input().split()) push(g, u, v) deg1 = [] used = [0] * (n+1) for u in g: if len(g[u]) == 1: used[u] = 1 deg1.append(u) flg = True while k > 0: if k >= 1 and len(deg1) < 3: flg=False break cnt = {} for u in deg1: for v in g[u]: if used[v] == 0: push_v(cnt, v, 1) for v in deg1: used[v] = 1 deg1 = [] for v, val in cnt.items(): if val < 3: flg=False break deg1.append(v) if flg==False: break k-=1 if flg==True and len(deg1) > 1: flg=False if flg==False: print('NO') else: print('YES') ```
90,126
Provide tags and a correct Python 3 solution for this coding contest problem. Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog. Let us define k-multihedgehog as follows: * 1-multihedgehog is hedgehog: it has one vertex of degree at least 3 and some vertices of degree 1. * For all k ≥ 2, k-multihedgehog is (k-1)-multihedgehog in which the following changes has been made for each vertex v with degree 1: let u be its only neighbor; remove vertex v, create a new hedgehog with center at vertex w and connect vertices u and w with an edge. New hedgehogs can differ from each other and the initial gift. Thereby k-multihedgehog is a tree. Ivan made k-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed k-multihedgehog. Input First line of input contains 2 integers n, k (1 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{9}) — number of vertices and hedgehog parameter. Next n-1 lines contains two integers u v (1 ≤ u, v ≤ n; u ≠ v) — indices of vertices connected by edge. It is guaranteed that given graph is a tree. Output Print "Yes" (without quotes), if given graph is k-multihedgehog, and "No" (without quotes) otherwise. Examples Input 14 2 1 4 2 4 3 4 4 13 10 5 11 5 12 5 14 5 5 13 6 7 8 6 13 6 9 6 Output Yes Input 3 1 1 3 2 3 Output No Note 2-multihedgehog from the first example looks like this: <image> Its center is vertex 13. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13]. Tree from second example is not a hedgehog because degree of center should be at least 3. Tags: dfs and similar, graphs, shortest paths Correct Solution: ``` from collections import deque n, k = list(map(int, input().split())) Gg = [set() for _ in range(n + 1)] q, nq = deque(), deque() for _ in range(n - 1): u, v = list(map(int, input().split())) Gg[u].add(v) Gg[v].add(u) for u in range(1, n + 1): if len(Gg[u]) == 1: q.append(u) step = 0 removed = 0 ok = True while removed < n - 1: each = {} for u in q: nxt = Gg[u].pop() Gg[nxt].remove(u) each[nxt] = each.get(nxt, 0) + 1 removed += 1 if len(Gg[nxt]) == 0: break if len(Gg[nxt]) == 1: nq.append(nxt) if any(v < 3 for k,v in each.items()): ok = False break q, nq = nq, deque() step += 1 if ok and step == k and removed == n - 1: print('Yes') else: print('No') #JSR ```
90,127
Provide tags and a correct Python 3 solution for this coding contest problem. Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog. Let us define k-multihedgehog as follows: * 1-multihedgehog is hedgehog: it has one vertex of degree at least 3 and some vertices of degree 1. * For all k ≥ 2, k-multihedgehog is (k-1)-multihedgehog in which the following changes has been made for each vertex v with degree 1: let u be its only neighbor; remove vertex v, create a new hedgehog with center at vertex w and connect vertices u and w with an edge. New hedgehogs can differ from each other and the initial gift. Thereby k-multihedgehog is a tree. Ivan made k-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed k-multihedgehog. Input First line of input contains 2 integers n, k (1 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{9}) — number of vertices and hedgehog parameter. Next n-1 lines contains two integers u v (1 ≤ u, v ≤ n; u ≠ v) — indices of vertices connected by edge. It is guaranteed that given graph is a tree. Output Print "Yes" (without quotes), if given graph is k-multihedgehog, and "No" (without quotes) otherwise. Examples Input 14 2 1 4 2 4 3 4 4 13 10 5 11 5 12 5 14 5 5 13 6 7 8 6 13 6 9 6 Output Yes Input 3 1 1 3 2 3 Output No Note 2-multihedgehog from the first example looks like this: <image> Its center is vertex 13. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13]. Tree from second example is not a hedgehog because degree of center should be at least 3. Tags: dfs and similar, graphs, shortest paths Correct Solution: ``` from sys import stdin from collections import deque n, k = map(int, stdin.readline().split()) graph = [[] for _ in range(n)] leaf = -1 for _ in range(n-1): a,b = map(int,stdin.readline().split()) graph[a - 1].append(b - 1) graph[b - 1].append(a - 1) def bfs(G, s): # la cola comienza con el vertice desde el cual hacemos bfs Q = deque() Q.append(s) # al inicio todas las distancias comienzan en infinito, por las # restricciones del problema ningun camino va a ser de ese tamanno infinite = 10 ** 6 d = [infinite]*n parent = [-1]*n valid = True # la distancia del vertice raiz es 0 d[s] = 0 while Q: # visitamos u u = Q.popleft() not_visited_count = 0 # visitamos cada adyacente de u for v in G[u]: # si no lo hemos visitado, le ponemos distancia y # lo agregamos a la cola para visitar sus adyacentes if d[v] == infinite: d[v] = d[u] + 1 parent[v] = u Q.append(v) not_visited_count += 1 if not_visited_count < 3 and d[u] != k: valid = False # retornamos el array d, que es el de las distancias del # nodo s al resto de los nodos del grafo return d, parent, valid leaf = -1 for i,v in enumerate(graph): if len(v) == 1: leaf = i break d, parent, _ = bfs(graph,leaf) center = -1 farthest_leaf = -1 path = 2*k for i,level in enumerate(d): if level == path: farthest_leaf = i break if len(graph[farthest_leaf]) != 1 or farthest_leaf == -1: print("NO") exit() for _ in range(k): center = parent[farthest_leaf] farthest_leaf = center _, _, valid = bfs(graph,center) if valid: print("YES") else: print("NO") ```
90,128
Provide tags and a correct Python 3 solution for this coding contest problem. Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog. Let us define k-multihedgehog as follows: * 1-multihedgehog is hedgehog: it has one vertex of degree at least 3 and some vertices of degree 1. * For all k ≥ 2, k-multihedgehog is (k-1)-multihedgehog in which the following changes has been made for each vertex v with degree 1: let u be its only neighbor; remove vertex v, create a new hedgehog with center at vertex w and connect vertices u and w with an edge. New hedgehogs can differ from each other and the initial gift. Thereby k-multihedgehog is a tree. Ivan made k-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed k-multihedgehog. Input First line of input contains 2 integers n, k (1 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{9}) — number of vertices and hedgehog parameter. Next n-1 lines contains two integers u v (1 ≤ u, v ≤ n; u ≠ v) — indices of vertices connected by edge. It is guaranteed that given graph is a tree. Output Print "Yes" (without quotes), if given graph is k-multihedgehog, and "No" (without quotes) otherwise. Examples Input 14 2 1 4 2 4 3 4 4 13 10 5 11 5 12 5 14 5 5 13 6 7 8 6 13 6 9 6 Output Yes Input 3 1 1 3 2 3 Output No Note 2-multihedgehog from the first example looks like this: <image> Its center is vertex 13. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13]. Tree from second example is not a hedgehog because degree of center should be at least 3. Tags: dfs and similar, graphs, shortest paths Correct Solution: ``` import math n,k=map(int,input().split()) edges=[] for i in range(n-1): edges.append(tuple(map(int,input().split()))) degreelist=[] for i in range(min(k+1,math.floor(math.log2(n))+10)): degreelist.append({}) degrees=degreelist[0] for i in range(1,n+1): degrees[i]=0 for guy in edges: degrees[guy[0]]+=1 degrees[guy[1]]+=1 small=[] center=None done=False for i in range(k): if not done: small=[] for guy in degrees: if degrees[guy]==2: print("No") done=True break if degrees[guy]==3: small.append(guy) if center==None: center=guy elif center!=guy: print("No") done=True break elif degrees[guy]>1: small.append(guy) degrees=degreelist[i+1] if center!=None and center not in small: if not done: print("No") done=True break elif len(small)==0: if not done: print("No") done=True break for guy in small: degrees[guy]=0 for guy in edges: if guy[0] in degrees and guy[1] in degrees: degrees[guy[0]]+=1 degrees[guy[1]]+=1 for guy in degrees: if degrees[guy]>1 and degreelist[i][guy]!=degrees[guy]: if not done: print("No") done=True break else: break if not done: if len(degreelist[-1])==1: print("Yes") else: print("No") ```
90,129
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog. Let us define k-multihedgehog as follows: * 1-multihedgehog is hedgehog: it has one vertex of degree at least 3 and some vertices of degree 1. * For all k ≥ 2, k-multihedgehog is (k-1)-multihedgehog in which the following changes has been made for each vertex v with degree 1: let u be its only neighbor; remove vertex v, create a new hedgehog with center at vertex w and connect vertices u and w with an edge. New hedgehogs can differ from each other and the initial gift. Thereby k-multihedgehog is a tree. Ivan made k-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed k-multihedgehog. Input First line of input contains 2 integers n, k (1 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{9}) — number of vertices and hedgehog parameter. Next n-1 lines contains two integers u v (1 ≤ u, v ≤ n; u ≠ v) — indices of vertices connected by edge. It is guaranteed that given graph is a tree. Output Print "Yes" (without quotes), if given graph is k-multihedgehog, and "No" (without quotes) otherwise. Examples Input 14 2 1 4 2 4 3 4 4 13 10 5 11 5 12 5 14 5 5 13 6 7 8 6 13 6 9 6 Output Yes Input 3 1 1 3 2 3 Output No Note 2-multihedgehog from the first example looks like this: <image> Its center is vertex 13. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13]. Tree from second example is not a hedgehog because degree of center should be at least 3. Submitted Solution: ``` from collections import deque n, h = list(map(int, input().split())) G = [set() for _ in range(n + 1)] q, nq = deque(), deque() for _ in range(n - 1): u, v = list(map(int, input().split())) G[u].add(v) G[v].add(u) for u in range(1, n + 1): if len(G[u]) == 1: q.append(u) step = 0 removed = 0 ok = True while removed < n - 1: each = {} for u in q: nxt = G[u].pop() G[nxt].remove(u) each[nxt] = each.get(nxt, 0) + 1 removed += 1 if len(G[nxt]) == 0: break if len(G[nxt]) == 1: nq.append(nxt) if any(v < 3 for h,v in each.items()): ok = False break q, nq = nq, deque() step += 1 if ok and step == h and removed == n - 1: print('Yes') else: print('No') ``` Yes
90,130
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog. Let us define k-multihedgehog as follows: * 1-multihedgehog is hedgehog: it has one vertex of degree at least 3 and some vertices of degree 1. * For all k ≥ 2, k-multihedgehog is (k-1)-multihedgehog in which the following changes has been made for each vertex v with degree 1: let u be its only neighbor; remove vertex v, create a new hedgehog with center at vertex w and connect vertices u and w with an edge. New hedgehogs can differ from each other and the initial gift. Thereby k-multihedgehog is a tree. Ivan made k-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed k-multihedgehog. Input First line of input contains 2 integers n, k (1 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{9}) — number of vertices and hedgehog parameter. Next n-1 lines contains two integers u v (1 ≤ u, v ≤ n; u ≠ v) — indices of vertices connected by edge. It is guaranteed that given graph is a tree. Output Print "Yes" (without quotes), if given graph is k-multihedgehog, and "No" (without quotes) otherwise. Examples Input 14 2 1 4 2 4 3 4 4 13 10 5 11 5 12 5 14 5 5 13 6 7 8 6 13 6 9 6 Output Yes Input 3 1 1 3 2 3 Output No Note 2-multihedgehog from the first example looks like this: <image> Its center is vertex 13. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13]. Tree from second example is not a hedgehog because degree of center should be at least 3. Submitted Solution: ``` n,k = map(int,input().split(" ")) degrees = [0] * n neighbors = [list() for x in range(n)] for i in range(n-1): first,second = map(int,input().split(" ")) degrees[first-1] += 1 degrees[second-1] += 1 neighbors[first-1] += [second] neighbors[second-1] += [first] # start at a leaf curr = 0 for i in range(n): if degrees[i] == 1: curr = i+1 break if curr == 0 or len(neighbors[curr-1]) == 0: print("No") exit() curr = neighbors[curr-1][0] def check(prev,parent,curr,level,degrees,neighbors,k): #print("curr: ",curr) #print("level: ",level) if level == 0: return len(parent) == 1 and degrees[curr-1] == 1,[] checked = [] for neighbor in neighbors[curr-1]: #print("neighbor: ",neighbor) #print("checked: ",checked) #print("parent: ",parent) if len(prev) != 0 and prev[0] == neighbor: checked += [neighbor] continue if len(parent) != 0 and parent[0] == neighbor: continue result,garbage = check([],[curr],neighbor,level-1,degrees,neighbors,k) if result: checked += [neighbor] else: #print("adding the parent") if len(parent) == 0: parent += [neighbor] else: return False,[] if len(checked) > 2 and len(parent) == 0 and level == k: #print("first check") return True,[] elif len(checked) > 2 and len(parent) == 1 and level != k: #print("second check") return True,parent else: #print("len(checked): ",len(checked)) #print("len(parent): ",len(parent)) #print("level: ",level) #print("the end fail statement") return False,[] prev = [] parent = [] counter = 1 while(counter <= k): result,parent = check(prev,[],curr,counter,degrees,neighbors,k) if not(result): print("No") exit() if counter == k: print("Yes") exit() prev = [curr] curr = parent[0] counter += 1 ``` Yes
90,131
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog. Let us define k-multihedgehog as follows: * 1-multihedgehog is hedgehog: it has one vertex of degree at least 3 and some vertices of degree 1. * For all k ≥ 2, k-multihedgehog is (k-1)-multihedgehog in which the following changes has been made for each vertex v with degree 1: let u be its only neighbor; remove vertex v, create a new hedgehog with center at vertex w and connect vertices u and w with an edge. New hedgehogs can differ from each other and the initial gift. Thereby k-multihedgehog is a tree. Ivan made k-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed k-multihedgehog. Input First line of input contains 2 integers n, k (1 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{9}) — number of vertices and hedgehog parameter. Next n-1 lines contains two integers u v (1 ≤ u, v ≤ n; u ≠ v) — indices of vertices connected by edge. It is guaranteed that given graph is a tree. Output Print "Yes" (without quotes), if given graph is k-multihedgehog, and "No" (without quotes) otherwise. Examples Input 14 2 1 4 2 4 3 4 4 13 10 5 11 5 12 5 14 5 5 13 6 7 8 6 13 6 9 6 Output Yes Input 3 1 1 3 2 3 Output No Note 2-multihedgehog from the first example looks like this: <image> Its center is vertex 13. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13]. Tree from second example is not a hedgehog because degree of center should be at least 3. Submitted Solution: ``` from collections import deque m, k = list(map(int, input().split())) G = [set() for _ in range(m + 1)] q, nq = deque(), deque() for _ in range(m - 1): u, v = list(map(int, input().split())) G[u].add(v) G[v].add(u) for u in range(1, m + 1): if len(G[u]) == 1: q.append(u) step = 0 removed = 0 ok = True while removed < m - 1: each = {} for u in q: nxt = G[u].pop() G[nxt].remove(u) each[nxt] = each.get(nxt, 0) + 1 removed += 1 if len(G[nxt]) == 0: break if len(G[nxt]) == 1: nq.append(nxt) if any(v < 3 for k,v in each.items()): ok = False break q, nq = nq, deque() step += 1 if ok and step == k and removed == m - 1: print('Yes') else: print('No') ``` Yes
90,132
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog. Let us define k-multihedgehog as follows: * 1-multihedgehog is hedgehog: it has one vertex of degree at least 3 and some vertices of degree 1. * For all k ≥ 2, k-multihedgehog is (k-1)-multihedgehog in which the following changes has been made for each vertex v with degree 1: let u be its only neighbor; remove vertex v, create a new hedgehog with center at vertex w and connect vertices u and w with an edge. New hedgehogs can differ from each other and the initial gift. Thereby k-multihedgehog is a tree. Ivan made k-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed k-multihedgehog. Input First line of input contains 2 integers n, k (1 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{9}) — number of vertices and hedgehog parameter. Next n-1 lines contains two integers u v (1 ≤ u, v ≤ n; u ≠ v) — indices of vertices connected by edge. It is guaranteed that given graph is a tree. Output Print "Yes" (without quotes), if given graph is k-multihedgehog, and "No" (without quotes) otherwise. Examples Input 14 2 1 4 2 4 3 4 4 13 10 5 11 5 12 5 14 5 5 13 6 7 8 6 13 6 9 6 Output Yes Input 3 1 1 3 2 3 Output No Note 2-multihedgehog from the first example looks like this: <image> Its center is vertex 13. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13]. Tree from second example is not a hedgehog because degree of center should be at least 3. Submitted Solution: ``` from sys import stdin from collections import deque n, k = map(int, stdin.readline().split()) graph = [[] for _ in range(n)] leaf = -1 for _ in range(n-1): a,b = map(int,stdin.readline().split()) graph[a - 1].append(b - 1) graph[b - 1].append(a - 1) def bfs(G, s): # la cola comienza con el vertice desde el cual hacemos bfs Q = deque() Q.append(s) # al inicio todas las distancias comienzan en infinito, por las # restricciones del problema ningun camino va a ser de ese tamanno infinite = 10 ** 6 d = [infinite]*n parent = [-1]*n valid = True # la distancia del vertice raiz es 0 d[s] = 0 while Q: # visitamos u u = Q.popleft() not_visited_count = 0 # visitamos cada adyacente de u for v in G[u]: # si no lo hemos visitado, le ponemos distancia y # lo agregamos a la cola para visitar sus adyacentes if d[v] == infinite: d[v] = d[u] + 1 parent[v] = u Q.append(v) not_visited_count += 1 if not_visited_count < 3 and d[u] != k: valid = False # retornamos el array d, que es el de las distancias del # nodo s al resto de los nodos del grafo return d, parent, valid leaf = -1 for i,v in enumerate(graph): if len(v) == 1: leaf = i break d, parent, _ = bfs(graph,leaf) center = -1 farthest_leaf = -1 diameter = 2*k for i,level in enumerate(d): if level == diameter: farthest_leaf = i break if len(graph[farthest_leaf]) != 1 or farthest_leaf == -1: print("NO") exit() for _ in range(k): center = parent[farthest_leaf] farthest_leaf = center if center == -1: print("NO") exit() _, _, valid = bfs(graph,center) if valid: print("YES") else: print("NO") ``` Yes
90,133
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog. Let us define k-multihedgehog as follows: * 1-multihedgehog is hedgehog: it has one vertex of degree at least 3 and some vertices of degree 1. * For all k ≥ 2, k-multihedgehog is (k-1)-multihedgehog in which the following changes has been made for each vertex v with degree 1: let u be its only neighbor; remove vertex v, create a new hedgehog with center at vertex w and connect vertices u and w with an edge. New hedgehogs can differ from each other and the initial gift. Thereby k-multihedgehog is a tree. Ivan made k-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed k-multihedgehog. Input First line of input contains 2 integers n, k (1 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{9}) — number of vertices and hedgehog parameter. Next n-1 lines contains two integers u v (1 ≤ u, v ≤ n; u ≠ v) — indices of vertices connected by edge. It is guaranteed that given graph is a tree. Output Print "Yes" (without quotes), if given graph is k-multihedgehog, and "No" (without quotes) otherwise. Examples Input 14 2 1 4 2 4 3 4 4 13 10 5 11 5 12 5 14 5 5 13 6 7 8 6 13 6 9 6 Output Yes Input 3 1 1 3 2 3 Output No Note 2-multihedgehog from the first example looks like this: <image> Its center is vertex 13. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13]. Tree from second example is not a hedgehog because degree of center should be at least 3. Submitted Solution: ``` WQ=input().split() n1=int(WQ[0]) k=int(WQ[1]) L1=[] for i in range(n1): L1.append([]) for i in range(n1-1): X=input().split() x1=int(X[0])-1 x2=int(X[1])-1 L1[x1].append(x2) L1[x2].append(x1) t=True tres=0 for i in range(n1): l=len(L1[i]) if l==1: pass elif l==3: tres+=1 elif l>3: pass else: t=False break if t: if tres>1: print("No") else: print("Yes") else: print("No") ``` No
90,134
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog. Let us define k-multihedgehog as follows: * 1-multihedgehog is hedgehog: it has one vertex of degree at least 3 and some vertices of degree 1. * For all k ≥ 2, k-multihedgehog is (k-1)-multihedgehog in which the following changes has been made for each vertex v with degree 1: let u be its only neighbor; remove vertex v, create a new hedgehog with center at vertex w and connect vertices u and w with an edge. New hedgehogs can differ from each other and the initial gift. Thereby k-multihedgehog is a tree. Ivan made k-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed k-multihedgehog. Input First line of input contains 2 integers n, k (1 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{9}) — number of vertices and hedgehog parameter. Next n-1 lines contains two integers u v (1 ≤ u, v ≤ n; u ≠ v) — indices of vertices connected by edge. It is guaranteed that given graph is a tree. Output Print "Yes" (without quotes), if given graph is k-multihedgehog, and "No" (without quotes) otherwise. Examples Input 14 2 1 4 2 4 3 4 4 13 10 5 11 5 12 5 14 5 5 13 6 7 8 6 13 6 9 6 Output Yes Input 3 1 1 3 2 3 Output No Note 2-multihedgehog from the first example looks like this: <image> Its center is vertex 13. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13]. Tree from second example is not a hedgehog because degree of center should be at least 3. Submitted Solution: ``` WQ=input().split() n1=int(WQ[0]) k=int(WQ[1]) L1=[] for i in range(n1): L1.append([]) for i in range(n1-1): X=input().split() x1=int(X[0])-1 x2=int(X[1])-1 L1[x1].append(x2) L1[x2].append(x1) t=True tres=0 for i in range(n1): l=len(L1[i]) if l==1: pass elif l==3: tres+=1 elif l>3: pass else: t=False if t: if tres>1: print("No") else: print("Yes") else: print("No") ``` No
90,135
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog. Let us define k-multihedgehog as follows: * 1-multihedgehog is hedgehog: it has one vertex of degree at least 3 and some vertices of degree 1. * For all k ≥ 2, k-multihedgehog is (k-1)-multihedgehog in which the following changes has been made for each vertex v with degree 1: let u be its only neighbor; remove vertex v, create a new hedgehog with center at vertex w and connect vertices u and w with an edge. New hedgehogs can differ from each other and the initial gift. Thereby k-multihedgehog is a tree. Ivan made k-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed k-multihedgehog. Input First line of input contains 2 integers n, k (1 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{9}) — number of vertices and hedgehog parameter. Next n-1 lines contains two integers u v (1 ≤ u, v ≤ n; u ≠ v) — indices of vertices connected by edge. It is guaranteed that given graph is a tree. Output Print "Yes" (without quotes), if given graph is k-multihedgehog, and "No" (without quotes) otherwise. Examples Input 14 2 1 4 2 4 3 4 4 13 10 5 11 5 12 5 14 5 5 13 6 7 8 6 13 6 9 6 Output Yes Input 3 1 1 3 2 3 Output No Note 2-multihedgehog from the first example looks like this: <image> Its center is vertex 13. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13]. Tree from second example is not a hedgehog because degree of center should be at least 3. Submitted Solution: ``` import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # ------------------------------ def RL(): return map(int, sys.stdin.readline().rstrip().split()) def RLL(): return list(map(int, sys.stdin.readline().rstrip().split())) def N(): return int(input()) def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0 def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0 def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2) def toord(c): return ord(c)-ord('a') def lcm(a, b): return a*b//lcm(a, b) mod = 998244353 INF = float('inf') from math import factorial, sqrt, ceil, floor, gcd from collections import Counter, defaultdict, deque from heapq import heapify, heappop, heappush # ------------------------------ # f = open('./input.txt') # sys.stdin = f def main(): n, k = RL() ind = [0]*(n+1) gp = [[] for _ in range(n+1)] for _ in range(n-1): f, t = RL() ind[f]+=1 ind[t]+=1 gp[f].append(t) gp[t].append(f) orind = ind.copy() if not any(len(gp[i]) >= 3 for i in range(n+1)): print('No') sys.exit() q = [] for i in range(1, n+1): if ind[i]==1: q.append(i) tag = False num = 0 rec = [] ct = -1 while q: nq = [] num+=1 while q: nd = q.pop() for nex in gp[nd]: ind[nex]-=1 if ind[nex]==1: rec.append(nex) nq.append(nex) q = nq if len(q)==1 and ind[q[0]]==0: ct = q[0] for i in rec: if (i!=ct and orind[i]<4) or orind[i]<3: tag = True if tag or num!=k+1 or ct==-1: print('No') else: print('Yes') if __name__ == "__main__": main() ``` No
90,136
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog. Let us define k-multihedgehog as follows: * 1-multihedgehog is hedgehog: it has one vertex of degree at least 3 and some vertices of degree 1. * For all k ≥ 2, k-multihedgehog is (k-1)-multihedgehog in which the following changes has been made for each vertex v with degree 1: let u be its only neighbor; remove vertex v, create a new hedgehog with center at vertex w and connect vertices u and w with an edge. New hedgehogs can differ from each other and the initial gift. Thereby k-multihedgehog is a tree. Ivan made k-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed k-multihedgehog. Input First line of input contains 2 integers n, k (1 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{9}) — number of vertices and hedgehog parameter. Next n-1 lines contains two integers u v (1 ≤ u, v ≤ n; u ≠ v) — indices of vertices connected by edge. It is guaranteed that given graph is a tree. Output Print "Yes" (without quotes), if given graph is k-multihedgehog, and "No" (without quotes) otherwise. Examples Input 14 2 1 4 2 4 3 4 4 13 10 5 11 5 12 5 14 5 5 13 6 7 8 6 13 6 9 6 Output Yes Input 3 1 1 3 2 3 Output No Note 2-multihedgehog from the first example looks like this: <image> Its center is vertex 13. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13]. Tree from second example is not a hedgehog because degree of center should be at least 3. Submitted Solution: ``` # ---------------------------iye ha aam zindegi--------------------------------------------- import math import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 sys.setrecursionlimit(300000) 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=0, func=lambda a, b: max(a, b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------game starts now----------------------------------------------------import math class SegmentTree: def __init__(self, data, default=0, func=lambda a, b: a + b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------------------iye ha chutiya zindegi------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD # --------------------------------------iye ha combinations ka zindegi--------------------------------- def powm(a, n, m): if a == 1 or n == 0: return 1 if n % 2 == 0: s = powm(a, n // 2, m) return s * s % m else: return a * powm(a, n - 1, m) % m # --------------------------------------iye ha power ka zindegi--------------------------------- def sort_list(list1, list2): zipped_pairs = zip(list2, list1) z = [x for _, x in sorted(zipped_pairs)] return z # --------------------------------------------------product---------------------------------------- def product(l): por = 1 for i in range(len(l)): por *= l[i] return por # --------------------------------------------------binary---------------------------------------- def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left) / 2) # Check if middle element is # less than or equal to key if (arr[mid] < key): count = mid + 1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # --------------------------------------------------binary---------------------------------------- def countdig(n): c = 0 while (n > 0): n //= 10 c += 1 return c def binary(x, length): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y def countGreater(arr, n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) if (arr[m] >= k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) # --------------------------------------------------binary------------------------------------ n,k=map(int,input().split()) graph=defaultdict(list) deg=[0]*n for i in range(n-1): a,b=map(int,input().split()) graph[a-1].append(b-1) graph[b-1].append(a-1) deg[a-1]+=1 deg[b-1]+=1 for i in range(n): if deg[i]==2: print("No") if n == 88573: print(1234) sys.exit(0) s=set() for i in range(n): if deg[i]==1: if len(s)<2: s.add(graph[i][0]) if deg[graph[i][0]]<3: if n == 88573: print(4123) print("No") sys.exit(0) f=0 e=set() for i in s: for j in graph[i]: if deg[j]==1: e.add(j) break if len(e)==2: break e=list(e) dis=[0]*n def BFS(s,des): visited = [False] * (len(graph)) pre=[-1]*n queue = [] queue.append(s) visited[s] = True while queue: s = queue.pop(0) for i in graph[s]: if visited[i] == False: visited[i]=True pre[i]=s dis[i]=dis[s]+1 queue.append(i) if i==des: return pre return pre def DFS(v,visited,dep): visited[v] = True r=0 for i in graph[v]: if visited[i] == False: r+=DFS(i, visited,dep+1) if deg[v]==1 and dep!=k: return -1 else: return r pre=BFS(e[0],e[1]) r=e[1] e=[r] er=r for i in range(dis[e[0]]): e.append(pre[er]) er=pre[er] center=e[len(e)//2] for i in range(n): if deg[i]==3 and i!=center: if n == 88573: print(1235,center,deg[center],i,deg[i]) print("No") sys.exit(0) f=DFS(center,[False]*n,0) if f==0: print("Yes") else: if n==88573: print(123) print("No") ``` No
90,137
Provide a correct Python 3 solution for this coding contest problem. The kingdom of Lazyland is the home to n idlers. These idlers are incredibly lazy and create many problems to their ruler, the mighty King of Lazyland. Today k important jobs for the kingdom (k ≤ n) should be performed. Every job should be done by one person and every person can do at most one job. The King allowed every idler to choose one job they wanted to do and the i-th idler has chosen the job a_i. Unfortunately, some jobs may not be chosen by anyone, so the King has to persuade some idlers to choose another job. The King knows that it takes b_i minutes to persuade the i-th idler. He asked his minister of labour to calculate the minimum total time he needs to spend persuading the idlers to get all the jobs done. Can you help him? Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 10^5) — the number of idlers and the number of jobs. The second line of the input contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ k) — the jobs chosen by each idler. The third line of the input contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ 10^9) — the time the King needs to spend to persuade the i-th idler. Output The only line of the output should contain one number — the minimum total time the King needs to spend persuading the idlers to get all the jobs done. Examples Input 8 7 1 1 3 1 5 3 7 1 5 7 4 8 1 3 5 2 Output 10 Input 3 3 3 1 2 5 3 4 Output 0 Note In the first example the optimal plan is to persuade idlers 1, 6, and 8 to do jobs 2, 4, and 6. In the second example each job was chosen by some idler, so there is no need to persuade anyone. "Correct Solution: ``` I = lambda: map(int, input().split()) _, k = I() B = [] C = [0]*(k+1) for a,b in zip(I(),I()): if C[a]: B.append(min(C[a],b)) else: k -= 1 C[a] = max(C[a],b) print(sum(sorted(B)[:k])) ```
90,138
Provide a correct Python 3 solution for this coding contest problem. The kingdom of Lazyland is the home to n idlers. These idlers are incredibly lazy and create many problems to their ruler, the mighty King of Lazyland. Today k important jobs for the kingdom (k ≤ n) should be performed. Every job should be done by one person and every person can do at most one job. The King allowed every idler to choose one job they wanted to do and the i-th idler has chosen the job a_i. Unfortunately, some jobs may not be chosen by anyone, so the King has to persuade some idlers to choose another job. The King knows that it takes b_i minutes to persuade the i-th idler. He asked his minister of labour to calculate the minimum total time he needs to spend persuading the idlers to get all the jobs done. Can you help him? Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 10^5) — the number of idlers and the number of jobs. The second line of the input contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ k) — the jobs chosen by each idler. The third line of the input contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ 10^9) — the time the King needs to spend to persuade the i-th idler. Output The only line of the output should contain one number — the minimum total time the King needs to spend persuading the idlers to get all the jobs done. Examples Input 8 7 1 1 3 1 5 3 7 1 5 7 4 8 1 3 5 2 Output 10 Input 3 3 3 1 2 5 3 4 Output 0 Note In the first example the optimal plan is to persuade idlers 1, 6, and 8 to do jobs 2, 4, and 6. In the second example each job was chosen by some idler, so there is no need to persuade anyone. "Correct Solution: ``` #from sys import stdin ### n, k = map(int, input().split()) jobs = list(map(int, input().split())) t = list(map(int, input().split())) exch = k - len(set(jobs)) doubleJobs = [0] * (k + 1) timeOfDouble = [] for l in range(len(jobs)): if doubleJobs[jobs[l]] < t[l]: if doubleJobs[jobs[l]] != 0: timeOfDouble.append(doubleJobs[jobs[l]]) doubleJobs[jobs[l]] = t[l] else: timeOfDouble.append(t[l]) #print("timeOfDouble", timeOfDouble) timeOfDouble.sort() #print("timeOfDouble", timeOfDouble) print(sum(timeOfDouble[:exch])) ```
90,139
Provide a correct Python 3 solution for this coding contest problem. The kingdom of Lazyland is the home to n idlers. These idlers are incredibly lazy and create many problems to their ruler, the mighty King of Lazyland. Today k important jobs for the kingdom (k ≤ n) should be performed. Every job should be done by one person and every person can do at most one job. The King allowed every idler to choose one job they wanted to do and the i-th idler has chosen the job a_i. Unfortunately, some jobs may not be chosen by anyone, so the King has to persuade some idlers to choose another job. The King knows that it takes b_i minutes to persuade the i-th idler. He asked his minister of labour to calculate the minimum total time he needs to spend persuading the idlers to get all the jobs done. Can you help him? Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 10^5) — the number of idlers and the number of jobs. The second line of the input contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ k) — the jobs chosen by each idler. The third line of the input contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ 10^9) — the time the King needs to spend to persuade the i-th idler. Output The only line of the output should contain one number — the minimum total time the King needs to spend persuading the idlers to get all the jobs done. Examples Input 8 7 1 1 3 1 5 3 7 1 5 7 4 8 1 3 5 2 Output 10 Input 3 3 3 1 2 5 3 4 Output 0 Note In the first example the optimal plan is to persuade idlers 1, 6, and 8 to do jobs 2, 4, and 6. In the second example each job was chosen by some idler, so there is no need to persuade anyone. "Correct Solution: ``` from collections import Counter n, k = map(int, input().split()) jobs = list(map(int, input().split())) time = list(map(int, input().split())) chosen = len(set(jobs)) if chosen == k: print(0) else: total = 0 c = Counter(jobs) for i in range(n): time[i] = (time[i], jobs[i]) time = sorted(time) for t in time: if c[t[1]] > 1: c[t[1]] -= 1 total += t[0] chosen += 1 if chosen == k: break print(total) ```
90,140
Provide a correct Python 3 solution for this coding contest problem. The kingdom of Lazyland is the home to n idlers. These idlers are incredibly lazy and create many problems to their ruler, the mighty King of Lazyland. Today k important jobs for the kingdom (k ≤ n) should be performed. Every job should be done by one person and every person can do at most one job. The King allowed every idler to choose one job they wanted to do and the i-th idler has chosen the job a_i. Unfortunately, some jobs may not be chosen by anyone, so the King has to persuade some idlers to choose another job. The King knows that it takes b_i minutes to persuade the i-th idler. He asked his minister of labour to calculate the minimum total time he needs to spend persuading the idlers to get all the jobs done. Can you help him? Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 10^5) — the number of idlers and the number of jobs. The second line of the input contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ k) — the jobs chosen by each idler. The third line of the input contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ 10^9) — the time the King needs to spend to persuade the i-th idler. Output The only line of the output should contain one number — the minimum total time the King needs to spend persuading the idlers to get all the jobs done. Examples Input 8 7 1 1 3 1 5 3 7 1 5 7 4 8 1 3 5 2 Output 10 Input 3 3 3 1 2 5 3 4 Output 0 Note In the first example the optimal plan is to persuade idlers 1, 6, and 8 to do jobs 2, 4, and 6. In the second example each job was chosen by some idler, so there is no need to persuade anyone. "Correct Solution: ``` n,k=(int(i)for i in input().split()) a=[int(i) for i in input().split()] b=[int(i)for i in input().split()] t=[[a[i],b[i]]for i in range(n)] t.sort(key=lambda x:[x[0],-x[1]]) now=t[0][0] time=[] chosen=1 for i in range(1,n): if t[i][0]!=now: chosen+=1 now=t[i][0] else: time.append(t[i][1]) time.sort() print(sum(time[:(k-chosen)])) ```
90,141
Provide a correct Python 3 solution for this coding contest problem. The kingdom of Lazyland is the home to n idlers. These idlers are incredibly lazy and create many problems to their ruler, the mighty King of Lazyland. Today k important jobs for the kingdom (k ≤ n) should be performed. Every job should be done by one person and every person can do at most one job. The King allowed every idler to choose one job they wanted to do and the i-th idler has chosen the job a_i. Unfortunately, some jobs may not be chosen by anyone, so the King has to persuade some idlers to choose another job. The King knows that it takes b_i minutes to persuade the i-th idler. He asked his minister of labour to calculate the minimum total time he needs to spend persuading the idlers to get all the jobs done. Can you help him? Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 10^5) — the number of idlers and the number of jobs. The second line of the input contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ k) — the jobs chosen by each idler. The third line of the input contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ 10^9) — the time the King needs to spend to persuade the i-th idler. Output The only line of the output should contain one number — the minimum total time the King needs to spend persuading the idlers to get all the jobs done. Examples Input 8 7 1 1 3 1 5 3 7 1 5 7 4 8 1 3 5 2 Output 10 Input 3 3 3 1 2 5 3 4 Output 0 Note In the first example the optimal plan is to persuade idlers 1, 6, and 8 to do jobs 2, 4, and 6. In the second example each job was chosen by some idler, so there is no need to persuade anyone. "Correct Solution: ``` from collections import defaultdict def ans(a, b): tmp = defaultdict(list) for i in range(0, n): tmp[a[i]].append(i) if(len(tmp.keys()) == k): return 0 length = k - len(tmp.keys()) dmp = [] for i in tmp.keys(): if(len(tmp[i]) > 1): dmp.append(tmp[i]) dmp = sorted(dmp, key = lambda x : len(x)) cnt = 0 temp = [] for i in dmp: max_ = [] for j in i: max_.append([b[j], j]) max_.sort(reverse=True) max_.pop(0) temp += max_[::] temp.sort() temp = temp[:length] for i in temp: cnt += i[0] return(cnt) if __name__ == '__main__': nk = list(map(int, input().strip().split())) n, k = nk[0], nk[1] a = list(map(int, input().strip().split())) b = list(map(int, input().strip().split())) print(ans(a, b)) ```
90,142
Provide a correct Python 3 solution for this coding contest problem. The kingdom of Lazyland is the home to n idlers. These idlers are incredibly lazy and create many problems to their ruler, the mighty King of Lazyland. Today k important jobs for the kingdom (k ≤ n) should be performed. Every job should be done by one person and every person can do at most one job. The King allowed every idler to choose one job they wanted to do and the i-th idler has chosen the job a_i. Unfortunately, some jobs may not be chosen by anyone, so the King has to persuade some idlers to choose another job. The King knows that it takes b_i minutes to persuade the i-th idler. He asked his minister of labour to calculate the minimum total time he needs to spend persuading the idlers to get all the jobs done. Can you help him? Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 10^5) — the number of idlers and the number of jobs. The second line of the input contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ k) — the jobs chosen by each idler. The third line of the input contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ 10^9) — the time the King needs to spend to persuade the i-th idler. Output The only line of the output should contain one number — the minimum total time the King needs to spend persuading the idlers to get all the jobs done. Examples Input 8 7 1 1 3 1 5 3 7 1 5 7 4 8 1 3 5 2 Output 10 Input 3 3 3 1 2 5 3 4 Output 0 Note In the first example the optimal plan is to persuade idlers 1, 6, and 8 to do jobs 2, 4, and 6. In the second example each job was chosen by some idler, so there is no need to persuade anyone. "Correct Solution: ``` #!/usr/bin/python3 # -*- coding: utf-8 -*- import sys def rl(proc=None): if proc is not None: return proc(sys.stdin.readline()) else: return sys.stdin.readline().rstrip() def srl(proc=None): if proc is not None: return list(map(proc, rl().split())) else: return rl().split() def main(): n, k = srl(int) A = srl(int) B = srl(int) spare = [] done = [-1] * k for i in range(n): task = A[i] - 1 if done[task] == -1: done[task] = B[i] continue spare.append(min(done[task], B[i])) done[task] = max(done[task], B[i]) spare.sort() i = 0 r = 0 for d in done: if d == -1: r += spare[i] i += 1 print(r) if __name__ == '__main__': main() ```
90,143
Provide a correct Python 3 solution for this coding contest problem. The kingdom of Lazyland is the home to n idlers. These idlers are incredibly lazy and create many problems to their ruler, the mighty King of Lazyland. Today k important jobs for the kingdom (k ≤ n) should be performed. Every job should be done by one person and every person can do at most one job. The King allowed every idler to choose one job they wanted to do and the i-th idler has chosen the job a_i. Unfortunately, some jobs may not be chosen by anyone, so the King has to persuade some idlers to choose another job. The King knows that it takes b_i minutes to persuade the i-th idler. He asked his minister of labour to calculate the minimum total time he needs to spend persuading the idlers to get all the jobs done. Can you help him? Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 10^5) — the number of idlers and the number of jobs. The second line of the input contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ k) — the jobs chosen by each idler. The third line of the input contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ 10^9) — the time the King needs to spend to persuade the i-th idler. Output The only line of the output should contain one number — the minimum total time the King needs to spend persuading the idlers to get all the jobs done. Examples Input 8 7 1 1 3 1 5 3 7 1 5 7 4 8 1 3 5 2 Output 10 Input 3 3 3 1 2 5 3 4 Output 0 Note In the first example the optimal plan is to persuade idlers 1, 6, and 8 to do jobs 2, 4, and 6. In the second example each job was chosen by some idler, so there is no need to persuade anyone. "Correct Solution: ``` n,k = map(int,input().split()) s = list(map(int,input().split())) p = list(map(int,input().split())) r = {} r2 = [] for i in range(n): if s[i] in r: if r[s[i]]>p[i]: r2.append(p[i]) else: r2.append(r[s[i]]) r[s[i]] = p[i] else: r[s[i]] = p[i] r1 = k-len(r) #print(r,r2) print(sum(sorted(r2)[:r1])) ```
90,144
Provide a correct Python 3 solution for this coding contest problem. The kingdom of Lazyland is the home to n idlers. These idlers are incredibly lazy and create many problems to their ruler, the mighty King of Lazyland. Today k important jobs for the kingdom (k ≤ n) should be performed. Every job should be done by one person and every person can do at most one job. The King allowed every idler to choose one job they wanted to do and the i-th idler has chosen the job a_i. Unfortunately, some jobs may not be chosen by anyone, so the King has to persuade some idlers to choose another job. The King knows that it takes b_i minutes to persuade the i-th idler. He asked his minister of labour to calculate the minimum total time he needs to spend persuading the idlers to get all the jobs done. Can you help him? Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 10^5) — the number of idlers and the number of jobs. The second line of the input contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ k) — the jobs chosen by each idler. The third line of the input contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ 10^9) — the time the King needs to spend to persuade the i-th idler. Output The only line of the output should contain one number — the minimum total time the King needs to spend persuading the idlers to get all the jobs done. Examples Input 8 7 1 1 3 1 5 3 7 1 5 7 4 8 1 3 5 2 Output 10 Input 3 3 3 1 2 5 3 4 Output 0 Note In the first example the optimal plan is to persuade idlers 1, 6, and 8 to do jobs 2, 4, and 6. In the second example each job was chosen by some idler, so there is no need to persuade anyone. "Correct Solution: ``` n, k = list(map(int, str(input()).split())) a = list(map(int, str(input()).split(' '))) b = list(map(int, str(input()).split(' '))) l = [] for i in range(0, k): l.append(0) for i in range(0, n): if (b[i] > l[a[i]-1]): t = b[i] b[i] = l[a[i]-1] l[a[i] - 1] = t b.sort(reverse=True) for i in range(0, n-k): b[i] = 0 print(sum(b)) ```
90,145
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The kingdom of Lazyland is the home to n idlers. These idlers are incredibly lazy and create many problems to their ruler, the mighty King of Lazyland. Today k important jobs for the kingdom (k ≤ n) should be performed. Every job should be done by one person and every person can do at most one job. The King allowed every idler to choose one job they wanted to do and the i-th idler has chosen the job a_i. Unfortunately, some jobs may not be chosen by anyone, so the King has to persuade some idlers to choose another job. The King knows that it takes b_i minutes to persuade the i-th idler. He asked his minister of labour to calculate the minimum total time he needs to spend persuading the idlers to get all the jobs done. Can you help him? Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 10^5) — the number of idlers and the number of jobs. The second line of the input contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ k) — the jobs chosen by each idler. The third line of the input contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ 10^9) — the time the King needs to spend to persuade the i-th idler. Output The only line of the output should contain one number — the minimum total time the King needs to spend persuading the idlers to get all the jobs done. Examples Input 8 7 1 1 3 1 5 3 7 1 5 7 4 8 1 3 5 2 Output 10 Input 3 3 3 1 2 5 3 4 Output 0 Note In the first example the optimal plan is to persuade idlers 1, 6, and 8 to do jobs 2, 4, and 6. In the second example each job was chosen by some idler, so there is no need to persuade anyone. Submitted Solution: ``` n, k = map(int, input().split()) a = [int(x) for x in input().split()] b = [int(x) for x in input().split()] c = [0] * k d = [] for (ai, bi) in zip(a,b): if(c[ai - 1] != 0): d.append(min(c[ai - 1], bi)) else: k -= 1 c[ai - 1] = max(c[ai - 1], bi) d.sort() print(sum(d[:k])) ``` Yes
90,146
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The kingdom of Lazyland is the home to n idlers. These idlers are incredibly lazy and create many problems to their ruler, the mighty King of Lazyland. Today k important jobs for the kingdom (k ≤ n) should be performed. Every job should be done by one person and every person can do at most one job. The King allowed every idler to choose one job they wanted to do and the i-th idler has chosen the job a_i. Unfortunately, some jobs may not be chosen by anyone, so the King has to persuade some idlers to choose another job. The King knows that it takes b_i minutes to persuade the i-th idler. He asked his minister of labour to calculate the minimum total time he needs to spend persuading the idlers to get all the jobs done. Can you help him? Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 10^5) — the number of idlers and the number of jobs. The second line of the input contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ k) — the jobs chosen by each idler. The third line of the input contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ 10^9) — the time the King needs to spend to persuade the i-th idler. Output The only line of the output should contain one number — the minimum total time the King needs to spend persuading the idlers to get all the jobs done. Examples Input 8 7 1 1 3 1 5 3 7 1 5 7 4 8 1 3 5 2 Output 10 Input 3 3 3 1 2 5 3 4 Output 0 Note In the first example the optimal plan is to persuade idlers 1, 6, and 8 to do jobs 2, 4, and 6. In the second example each job was chosen by some idler, so there is no need to persuade anyone. Submitted Solution: ``` from sys import stdin n, k = map(int, input().split()) jobs = list(map(int, next(stdin).split())) t = list(map(int, next(stdin).split())) exch = k - len(set(jobs)) doubleJobs = [0] * (k + 1) timeOfDouble = [] for l in range(len(jobs)): if doubleJobs[jobs[l]] < t[l]: if doubleJobs[jobs[l]] != 0: timeOfDouble.append(doubleJobs[jobs[l]]) doubleJobs[jobs[l]] = t[l] else: timeOfDouble.append(t[l]) #print("timeOfDouble", timeOfDouble) timeOfDouble.sort() #print("timeOfDouble", timeOfDouble) print(sum(timeOfDouble[:exch])) ``` Yes
90,147
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The kingdom of Lazyland is the home to n idlers. These idlers are incredibly lazy and create many problems to their ruler, the mighty King of Lazyland. Today k important jobs for the kingdom (k ≤ n) should be performed. Every job should be done by one person and every person can do at most one job. The King allowed every idler to choose one job they wanted to do and the i-th idler has chosen the job a_i. Unfortunately, some jobs may not be chosen by anyone, so the King has to persuade some idlers to choose another job. The King knows that it takes b_i minutes to persuade the i-th idler. He asked his minister of labour to calculate the minimum total time he needs to spend persuading the idlers to get all the jobs done. Can you help him? Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 10^5) — the number of idlers and the number of jobs. The second line of the input contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ k) — the jobs chosen by each idler. The third line of the input contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ 10^9) — the time the King needs to spend to persuade the i-th idler. Output The only line of the output should contain one number — the minimum total time the King needs to spend persuading the idlers to get all the jobs done. Examples Input 8 7 1 1 3 1 5 3 7 1 5 7 4 8 1 3 5 2 Output 10 Input 3 3 3 1 2 5 3 4 Output 0 Note In the first example the optimal plan is to persuade idlers 1, 6, and 8 to do jobs 2, 4, and 6. In the second example each job was chosen by some idler, so there is no need to persuade anyone. Submitted Solution: ``` l1 = [int(x) for x in input().split()] n,k = l1[0],l1[1] a = [int(x) for x in input().split()] b = [int(x) for x in input().split()] c = [] d= [] for x in range(len(a)): if a[x] not in c: c.append(a[x]) d.append([b[x]]) else: d[c.index(a[x])].append(b[x]) for x in d: x.remove(max(x)) f=[] for x in d: for y in x: f.append(y) f.sort() print(sum(f[:k-len(d)])) ``` Yes
90,148
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The kingdom of Lazyland is the home to n idlers. These idlers are incredibly lazy and create many problems to their ruler, the mighty King of Lazyland. Today k important jobs for the kingdom (k ≤ n) should be performed. Every job should be done by one person and every person can do at most one job. The King allowed every idler to choose one job they wanted to do and the i-th idler has chosen the job a_i. Unfortunately, some jobs may not be chosen by anyone, so the King has to persuade some idlers to choose another job. The King knows that it takes b_i minutes to persuade the i-th idler. He asked his minister of labour to calculate the minimum total time he needs to spend persuading the idlers to get all the jobs done. Can you help him? Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 10^5) — the number of idlers and the number of jobs. The second line of the input contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ k) — the jobs chosen by each idler. The third line of the input contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ 10^9) — the time the King needs to spend to persuade the i-th idler. Output The only line of the output should contain one number — the minimum total time the King needs to spend persuading the idlers to get all the jobs done. Examples Input 8 7 1 1 3 1 5 3 7 1 5 7 4 8 1 3 5 2 Output 10 Input 3 3 3 1 2 5 3 4 Output 0 Note In the first example the optimal plan is to persuade idlers 1, 6, and 8 to do jobs 2, 4, and 6. In the second example each job was chosen by some idler, so there is no need to persuade anyone. Submitted Solution: ``` n, k = map(int,input().split()) a = list(map(int,input().split())) b = list(map(int,input().split())) dic = {} for i, f in zip(a,b): if i in dic: dic[i] +=[f] else: dic[i] =[f] for _,value in dic.items(): value.sort() value.pop() k-=1 res = [] for _,value in dic.items(): for v in value: res.append(v) res.sort() print(sum(res[:k])) ``` Yes
90,149
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The kingdom of Lazyland is the home to n idlers. These idlers are incredibly lazy and create many problems to their ruler, the mighty King of Lazyland. Today k important jobs for the kingdom (k ≤ n) should be performed. Every job should be done by one person and every person can do at most one job. The King allowed every idler to choose one job they wanted to do and the i-th idler has chosen the job a_i. Unfortunately, some jobs may not be chosen by anyone, so the King has to persuade some idlers to choose another job. The King knows that it takes b_i minutes to persuade the i-th idler. He asked his minister of labour to calculate the minimum total time he needs to spend persuading the idlers to get all the jobs done. Can you help him? Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 10^5) — the number of idlers and the number of jobs. The second line of the input contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ k) — the jobs chosen by each idler. The third line of the input contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ 10^9) — the time the King needs to spend to persuade the i-th idler. Output The only line of the output should contain one number — the minimum total time the King needs to spend persuading the idlers to get all the jobs done. Examples Input 8 7 1 1 3 1 5 3 7 1 5 7 4 8 1 3 5 2 Output 10 Input 3 3 3 1 2 5 3 4 Output 0 Note In the first example the optimal plan is to persuade idlers 1, 6, and 8 to do jobs 2, 4, and 6. In the second example each job was chosen by some idler, so there is no need to persuade anyone. Submitted Solution: ``` from collections import defaultdict as dd from bisect import insort as ins def solve(a, b, n, q): jobs = dd(list) v = [] n1 = q for i in range(n): ins(jobs[a[i]], b[i]) for job in jobs: k = len(jobs[job]) for i in range(k - 1): ins(v, jobs[job][i]) n1 -= 1 return sum(v[:n1]) def bruh(): n, k = [int(i)for i in input().split()] a = [int(i)for i in input().split()] b = [int(i)for i in input().split()] print(solve(a, b, n, k)) bruh() ``` No
90,150
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The kingdom of Lazyland is the home to n idlers. These idlers are incredibly lazy and create many problems to their ruler, the mighty King of Lazyland. Today k important jobs for the kingdom (k ≤ n) should be performed. Every job should be done by one person and every person can do at most one job. The King allowed every idler to choose one job they wanted to do and the i-th idler has chosen the job a_i. Unfortunately, some jobs may not be chosen by anyone, so the King has to persuade some idlers to choose another job. The King knows that it takes b_i minutes to persuade the i-th idler. He asked his minister of labour to calculate the minimum total time he needs to spend persuading the idlers to get all the jobs done. Can you help him? Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 10^5) — the number of idlers and the number of jobs. The second line of the input contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ k) — the jobs chosen by each idler. The third line of the input contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ 10^9) — the time the King needs to spend to persuade the i-th idler. Output The only line of the output should contain one number — the minimum total time the King needs to spend persuading the idlers to get all the jobs done. Examples Input 8 7 1 1 3 1 5 3 7 1 5 7 4 8 1 3 5 2 Output 10 Input 3 3 3 1 2 5 3 4 Output 0 Note In the first example the optimal plan is to persuade idlers 1, 6, and 8 to do jobs 2, 4, and 6. In the second example each job was chosen by some idler, so there is no need to persuade anyone. Submitted Solution: ``` b=input().split( ) nas=int(b[0]) rab=int(b[1]) z=[] c=0 pred=input() time=input() pred=pred.split( ) time=time.split( ) for i in range(nas): pred[i]=int(pred[i]) time[i]=int(time[i]) z=[0]*rab for i in range(nas): z[pred[i]-1]+=1 i=0 while 0 in z: try: if z[i]>1: mac=9999999999999999999999999 for j in range(nas): if pred[j]==i+1 and time[j]<mac: mac=time[j] k=j time[k]=999999999999999999999999999 z[i]-=1 c+=mac l=z.index(0) z[l]=1 except: i=-1 i+=1 print(c) ``` No
90,151
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The kingdom of Lazyland is the home to n idlers. These idlers are incredibly lazy and create many problems to their ruler, the mighty King of Lazyland. Today k important jobs for the kingdom (k ≤ n) should be performed. Every job should be done by one person and every person can do at most one job. The King allowed every idler to choose one job they wanted to do and the i-th idler has chosen the job a_i. Unfortunately, some jobs may not be chosen by anyone, so the King has to persuade some idlers to choose another job. The King knows that it takes b_i minutes to persuade the i-th idler. He asked his minister of labour to calculate the minimum total time he needs to spend persuading the idlers to get all the jobs done. Can you help him? Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 10^5) — the number of idlers and the number of jobs. The second line of the input contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ k) — the jobs chosen by each idler. The third line of the input contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ 10^9) — the time the King needs to spend to persuade the i-th idler. Output The only line of the output should contain one number — the minimum total time the King needs to spend persuading the idlers to get all the jobs done. Examples Input 8 7 1 1 3 1 5 3 7 1 5 7 4 8 1 3 5 2 Output 10 Input 3 3 3 1 2 5 3 4 Output 0 Note In the first example the optimal plan is to persuade idlers 1, 6, and 8 to do jobs 2, 4, and 6. In the second example each job was chosen by some idler, so there is no need to persuade anyone. Submitted Solution: ``` try: n,k=map(int,input().split(' ')) inp = list(map(int,input().split())) inp2 = list(map(int,input().split())) inp2.sort() inp=set(inp) inp=list(inp) cnt=n-len(inp) ans=0 for i in range(cnt): ans=inp2[i]+ans print(ans) except: print(n,k,inp) ``` No
90,152
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The kingdom of Lazyland is the home to n idlers. These idlers are incredibly lazy and create many problems to their ruler, the mighty King of Lazyland. Today k important jobs for the kingdom (k ≤ n) should be performed. Every job should be done by one person and every person can do at most one job. The King allowed every idler to choose one job they wanted to do and the i-th idler has chosen the job a_i. Unfortunately, some jobs may not be chosen by anyone, so the King has to persuade some idlers to choose another job. The King knows that it takes b_i minutes to persuade the i-th idler. He asked his minister of labour to calculate the minimum total time he needs to spend persuading the idlers to get all the jobs done. Can you help him? Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 10^5) — the number of idlers and the number of jobs. The second line of the input contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ k) — the jobs chosen by each idler. The third line of the input contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ 10^9) — the time the King needs to spend to persuade the i-th idler. Output The only line of the output should contain one number — the minimum total time the King needs to spend persuading the idlers to get all the jobs done. Examples Input 8 7 1 1 3 1 5 3 7 1 5 7 4 8 1 3 5 2 Output 10 Input 3 3 3 1 2 5 3 4 Output 0 Note In the first example the optimal plan is to persuade idlers 1, 6, and 8 to do jobs 2, 4, and 6. In the second example each job was chosen by some idler, so there is no need to persuade anyone. Submitted Solution: ``` b=input().split( ) nas=int(b[0]) rab=int(b[1]) z=[] c=0 pred=input() time=input() pred=pred.split( ) time=time.split( ) for i in range(nas): pred[i]=int(pred[i]) time[i]=int(time[i]) z=[0]*rab for i in range(nas): z[pred[i]-1]+=1 i=0 while 0 in z: try: if z[i]>1: mac=10000000 for j in range(nas): if pred[j]==i+1 and time[j]<mac: mac=time[j] k=j time[k]=10000000000 z[i]-=1 c+=mac l=z.index(0) z[l]=1 except: i=-1 i+=1 print(c) ``` No
90,153
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions is a number of elements in the array. You are given an array a consisting of n integers. The value of the i-th element of the array is a_i. You are also given a set of m segments. The j-th segment is [l_j; r_j], where 1 ≤ l_j ≤ r_j ≤ n. You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array a = [0, 0, 0, 0, 0] and the given segments are [1; 3] and [2; 4] then you can choose both of them and the array will become b = [-1, -2, -2, -1, 0]. You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array a and obtain the array b then the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i will be maximum possible. Note that you can choose the empty set. If there are multiple answers, you can print any. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ 300) — the length of the array a and the number of segments, respectively. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^6 ≤ a_i ≤ 10^6), where a_i is the value of the i-th element of the array a. The next m lines are contain two integers each. The j-th of them contains two integers l_j and r_j (1 ≤ l_j ≤ r_j ≤ n), where l_j and r_j are the ends of the j-th segment. Output In the first line of the output print one integer d — the maximum possible value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i if b is the array obtained by applying some subset of the given segments to the array a. In the second line of the output print one integer q (0 ≤ q ≤ m) — the number of segments you apply. In the third line print q distinct integers c_1, c_2, ..., c_q in any order (1 ≤ c_k ≤ m) — indices of segments you apply to the array a in such a way that the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i of the obtained array b is maximum possible. If there are multiple answers, you can print any. Examples Input 5 4 2 -2 3 1 2 1 3 4 5 2 5 1 3 Output 6 2 4 1 Input 5 4 2 -2 3 1 4 3 5 3 4 2 4 2 5 Output 7 2 3 2 Input 1 0 1000000 Output 0 0 Note In the first example the obtained array b will be [0, -4, 1, 1, 2] so the answer is 6. In the second example the obtained array b will be [2, -3, 1, -1, 4] so the answer is 7. In the third example you cannot do anything so the answer is 0. Tags: data structures, implementation Correct Solution: ``` n, m = map(int, input().split()) A = list(map(int, input().split())) Lf = [[] for _ in range(n)] Rb = [[] for _ in range(n)] LR = [] for i in range(m): l, r = map(int, input().split()) l, r = l-1, r-1 Lf[r].append(l) Rb[l].append(r) LR.append((l, r)) minus = [0]*n INF = 10**18 ans = [-INF]*n mn = A[0] for i in range(n): ans[i] = max(ans[i], A[i]-mn) for l in Lf[i]: for j in range(l, i+1): minus[j] -= 1 mn = min(mn, A[j]+minus[j]) mn = min(mn, A[i]+minus[i]) minus = [0]*n mn = A[n-1] for i in reversed(range(n)): ans[i] = max(ans[i], A[i]-mn) for r in Rb[i]: for j in range(i, r+1): minus[j] -= 1 mn = min(mn, A[j]+minus[j]) mn = min(mn, A[i]+minus[i]) ans_ = max(ans) res = [] for i in range(n): if ans[i] == ans_: for j in range(m): l, r = LR[j] if not (l <= i and i <= r): res.append(j+1) break print(ans_) print(len(res)) print(*res) ```
90,154
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions is a number of elements in the array. You are given an array a consisting of n integers. The value of the i-th element of the array is a_i. You are also given a set of m segments. The j-th segment is [l_j; r_j], where 1 ≤ l_j ≤ r_j ≤ n. You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array a = [0, 0, 0, 0, 0] and the given segments are [1; 3] and [2; 4] then you can choose both of them and the array will become b = [-1, -2, -2, -1, 0]. You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array a and obtain the array b then the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i will be maximum possible. Note that you can choose the empty set. If there are multiple answers, you can print any. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ 300) — the length of the array a and the number of segments, respectively. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^6 ≤ a_i ≤ 10^6), where a_i is the value of the i-th element of the array a. The next m lines are contain two integers each. The j-th of them contains two integers l_j and r_j (1 ≤ l_j ≤ r_j ≤ n), where l_j and r_j are the ends of the j-th segment. Output In the first line of the output print one integer d — the maximum possible value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i if b is the array obtained by applying some subset of the given segments to the array a. In the second line of the output print one integer q (0 ≤ q ≤ m) — the number of segments you apply. In the third line print q distinct integers c_1, c_2, ..., c_q in any order (1 ≤ c_k ≤ m) — indices of segments you apply to the array a in such a way that the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i of the obtained array b is maximum possible. If there are multiple answers, you can print any. Examples Input 5 4 2 -2 3 1 2 1 3 4 5 2 5 1 3 Output 6 2 4 1 Input 5 4 2 -2 3 1 4 3 5 3 4 2 4 2 5 Output 7 2 3 2 Input 1 0 1000000 Output 0 0 Note In the first example the obtained array b will be [0, -4, 1, 1, 2] so the answer is 6. In the second example the obtained array b will be [2, -3, 1, -1, 4] so the answer is 7. In the third example you cannot do anything so the answer is 0. Tags: data structures, implementation Correct Solution: ``` # Author : nitish420 -------------------------------------------------------------------- import os import sys from io import BytesIO, IOBase def main(): n,m=map(int,input().split()) arr=list(map(int,input().split())) left=[[] for _ in range(n)] right=[[] for _ in range(n)] seg=[] for _ in range(m): l,r=map(int,input().split()) l-=1 r-=1 left[r].append(l) right[l].append(r) seg.append((l,r)) dff=[0]*n ans=[-10**10]*n mm=arr[0] for i in range(n): ans[i]=max(ans[i],arr[i]-mm) for l in left[i]: for j in range(l,i+1): dff[j]-=1 mm=min(mm,arr[j]+dff[j]) mm=min(mm,arr[i]+dff[i]) dff=[0]*n mm=arr[n-1] for i in range(n-1,-1,-1): ans[i]=max(ans[i],arr[i]-mm) for r in right[i]: for j in range(i,r+1): dff[j]-=1 mm=min(mm,arr[j]+dff[j]) mm=min(mm,arr[i]+dff[i]) final=max(ans) idx=ans.index(final) que=[] for i,item in enumerate(seg): l,r=item if l<=idx<=r: continue que.append(i+1) print(final) print(len(que)) print(*que) # 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() ```
90,155
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions is a number of elements in the array. You are given an array a consisting of n integers. The value of the i-th element of the array is a_i. You are also given a set of m segments. The j-th segment is [l_j; r_j], where 1 ≤ l_j ≤ r_j ≤ n. You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array a = [0, 0, 0, 0, 0] and the given segments are [1; 3] and [2; 4] then you can choose both of them and the array will become b = [-1, -2, -2, -1, 0]. You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array a and obtain the array b then the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i will be maximum possible. Note that you can choose the empty set. If there are multiple answers, you can print any. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ 300) — the length of the array a and the number of segments, respectively. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^6 ≤ a_i ≤ 10^6), where a_i is the value of the i-th element of the array a. The next m lines are contain two integers each. The j-th of them contains two integers l_j and r_j (1 ≤ l_j ≤ r_j ≤ n), where l_j and r_j are the ends of the j-th segment. Output In the first line of the output print one integer d — the maximum possible value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i if b is the array obtained by applying some subset of the given segments to the array a. In the second line of the output print one integer q (0 ≤ q ≤ m) — the number of segments you apply. In the third line print q distinct integers c_1, c_2, ..., c_q in any order (1 ≤ c_k ≤ m) — indices of segments you apply to the array a in such a way that the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i of the obtained array b is maximum possible. If there are multiple answers, you can print any. Examples Input 5 4 2 -2 3 1 2 1 3 4 5 2 5 1 3 Output 6 2 4 1 Input 5 4 2 -2 3 1 4 3 5 3 4 2 4 2 5 Output 7 2 3 2 Input 1 0 1000000 Output 0 0 Note In the first example the obtained array b will be [0, -4, 1, 1, 2] so the answer is 6. In the second example the obtained array b will be [2, -3, 1, -1, 4] so the answer is 7. In the third example you cannot do anything so the answer is 0. Tags: data structures, implementation Correct Solution: ``` import sys # a very nice implementation of a minimum segment tree with # some inspiration taken from https://codeforces.com/blog/entry/18051 # this implementation should be able to be modified to do pretty # much anything one would want to do with segment trees apart from # persistance. # note that especially in python this implementation is much much better # than most other approches because how slow python can be with function # calls. # currently it allows for two operations, both running in o(log n), # 'add(l,r,value)' adds value to [l,r) # 'find_min(l,r)' finds the index with the smallest value big = 10**9 class super_seg: def __init__(self,data): n = len(data) m = 1 while m<n: m *= 2 self.n = n self.m = m self.data = [big]*(2*m) for i in range(n): self.data[i+m] = data[i] for i in reversed(range(m)): self.data[i] = min(self.data[2*i], self.data[2*i+1]) self.query = [0]*(2*m) # push the query on seg_ind to its children def push(self,seg_ind): # let the children know of the queries q = self.query[seg_ind] self.query[2*seg_ind] += q self.query[2*seg_ind+1] += q self.data[2*seg_ind] += q self.data[2*seg_ind+1] += q # remove queries from seg_ind self.data[seg_ind] = min(self.data[2*seg_ind],self.data[2*seg_ind+1]) self.query[seg_ind] = 0 # updates the node seg_ind to know of all queries # applied to it via its ancestors def update(self,seg_ind): # find all indecies to be updated seg_ind //= 2 inds = [] while seg_ind>0: inds.append(seg_ind) seg_ind//=2 # push the queries down the segment tree for ind in reversed(inds): self.push(ind) # make the changes to seg_ind be known to its ancestors def build(self,seg_ind): seg_ind//=2 while seg_ind>0: self.data[seg_ind] = min(self.data[2*seg_ind], self.data[2*seg_ind+1]) + self.query[seg_ind] seg_ind //= 2 # lazily add value to [l,r) def add(self,l,r,value): l += self.m r += self.m l0 = l r0 = r while l<r: if l%2==1: self.query[l]+= value self.data[l] += value l+=1 if r%2==1: r-=1 self.query[r]+= value self.data[r] += value l//=2 r//=2 # tell all nodes above of the updated # area of the updates self.build(l0) self.build(r0-1) # min of data[l,r) def min(self,l,r): l += self.m r += self.m # apply all the lazily stored queries self.update(l) self.update(r-1) segs = [] while l<r: if l%2==1: segs.append(l) l+=1 if r%2==1: r-=1 segs.append(r) l//=2 r//=2 return min(self.data[ind] for ind in segs) # find index of smallest value in data[l,r) def find_min(self,l,r): l += self.m r += self.m # apply all the lazily stored queries self.update(l) self.update(r-1) segs = [] while l<r: if l%2==1: segs.append(l) l+=1 if r%2==1: r-=1 segs.append(r) l//=2 r//=2 ind = min(segs, key=lambda i:self.data[i]) mini = self.data[ind] # dig down in search of mini while ind<self.m: self.push(ind) if self.data[2*ind]==mini: ind *= 2 else: ind = 2*ind+1 return ind-self.m,mini n,m = [int(x) for x in input().split()] A = [int(x) for x in input().split()] inter = [] inter2 = [] for _ in range(m): l,r = [int(x) for x in input().split()] l -= 1 inter.append((l,r)) inter2.append((r,l)) inter_copy = inter[:] inter.sort() inter2.sort() Aneg = super_seg([-a for a in A]) besta = -1 besta_ind = -1 j1 = 0 j2 = 0 for i in range(n): # Only segments containing i should be active # Activate while j1<m and inter[j1][0]<=i: l,r = inter[j1] Aneg.add(l,r,1) j1 += 1 # Deactivate while j2<m and inter2[j2][0]<=i: r,l = inter2[j2] Aneg.add(l,r,-1) j2 += 1 Amax = -Aneg.data[1] Ai = A[i]-(j1-j2) if Amax-Ai>besta: besta = Amax-Ai besta_ind = i ints = [i for i in range(m) if inter_copy[i][0]<=besta_ind<inter_copy[i][1]] print(besta) print(len(ints)) print(*[x+1 for x in ints]) ```
90,156
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions is a number of elements in the array. You are given an array a consisting of n integers. The value of the i-th element of the array is a_i. You are also given a set of m segments. The j-th segment is [l_j; r_j], where 1 ≤ l_j ≤ r_j ≤ n. You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array a = [0, 0, 0, 0, 0] and the given segments are [1; 3] and [2; 4] then you can choose both of them and the array will become b = [-1, -2, -2, -1, 0]. You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array a and obtain the array b then the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i will be maximum possible. Note that you can choose the empty set. If there are multiple answers, you can print any. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ 300) — the length of the array a and the number of segments, respectively. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^6 ≤ a_i ≤ 10^6), where a_i is the value of the i-th element of the array a. The next m lines are contain two integers each. The j-th of them contains two integers l_j and r_j (1 ≤ l_j ≤ r_j ≤ n), where l_j and r_j are the ends of the j-th segment. Output In the first line of the output print one integer d — the maximum possible value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i if b is the array obtained by applying some subset of the given segments to the array a. In the second line of the output print one integer q (0 ≤ q ≤ m) — the number of segments you apply. In the third line print q distinct integers c_1, c_2, ..., c_q in any order (1 ≤ c_k ≤ m) — indices of segments you apply to the array a in such a way that the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i of the obtained array b is maximum possible. If there are multiple answers, you can print any. Examples Input 5 4 2 -2 3 1 2 1 3 4 5 2 5 1 3 Output 6 2 4 1 Input 5 4 2 -2 3 1 4 3 5 3 4 2 4 2 5 Output 7 2 3 2 Input 1 0 1000000 Output 0 0 Note In the first example the obtained array b will be [0, -4, 1, 1, 2] so the answer is 6. In the second example the obtained array b will be [2, -3, 1, -1, 4] so the answer is 7. In the third example you cannot do anything so the answer is 0. Tags: data structures, implementation Correct Solution: ``` def main(): n, m = map(int, input().split()) aa = list(map(int, input().split())) res = max(aa) - min(aa) ll, rr = [n + 1], [n + 1] segments = res_segments = [False] * (m + 1) bounds = {0, n, n + 1} for _ in range(m): l, r = map(int, input().split()) l -= 1 ll.append(l) rr.append(r) bounds.add(l) bounds.add(r) xlat = sorted(bounds) mi, ma = [], [] for l, r in zip(xlat, xlat[1:-1]): t = aa[l:r] mi.append(min(t)) ma.append(max(t)) bounds = {x: i for i, x in enumerate(xlat)} for xx in (ll, rr): for i, x in enumerate(xx): xx[i] = bounds[x] il, ir = (sorted(range(m + 1), key=xx.__getitem__, reverse=True) for xx in (ll, rr)) for i in range(len(xlat) - 1): while True: k = il[-1] lo = ll[k] if lo > i: break segments[k] = True for j in range(lo, rr[k]): mi[j] -= 1 ma[j] -= 1 del il[-1] x = max(ma) - min(mi) if res < x: res = x res_segments = segments[:] while True: k = ir[-1] hi = rr[k] if hi > i: break segments[k] = False for j in range(ll[k], hi): mi[j] += 1 ma[j] += 1 del ir[-1] print(res) segments = [i for i, f in enumerate(res_segments) if f] print(len(segments)) print(*segments) if __name__ == '__main__': main() ```
90,157
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions is a number of elements in the array. You are given an array a consisting of n integers. The value of the i-th element of the array is a_i. You are also given a set of m segments. The j-th segment is [l_j; r_j], where 1 ≤ l_j ≤ r_j ≤ n. You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array a = [0, 0, 0, 0, 0] and the given segments are [1; 3] and [2; 4] then you can choose both of them and the array will become b = [-1, -2, -2, -1, 0]. You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array a and obtain the array b then the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i will be maximum possible. Note that you can choose the empty set. If there are multiple answers, you can print any. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ 300) — the length of the array a and the number of segments, respectively. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^6 ≤ a_i ≤ 10^6), where a_i is the value of the i-th element of the array a. The next m lines are contain two integers each. The j-th of them contains two integers l_j and r_j (1 ≤ l_j ≤ r_j ≤ n), where l_j and r_j are the ends of the j-th segment. Output In the first line of the output print one integer d — the maximum possible value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i if b is the array obtained by applying some subset of the given segments to the array a. In the second line of the output print one integer q (0 ≤ q ≤ m) — the number of segments you apply. In the third line print q distinct integers c_1, c_2, ..., c_q in any order (1 ≤ c_k ≤ m) — indices of segments you apply to the array a in such a way that the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i of the obtained array b is maximum possible. If there are multiple answers, you can print any. Examples Input 5 4 2 -2 3 1 2 1 3 4 5 2 5 1 3 Output 6 2 4 1 Input 5 4 2 -2 3 1 4 3 5 3 4 2 4 2 5 Output 7 2 3 2 Input 1 0 1000000 Output 0 0 Note In the first example the obtained array b will be [0, -4, 1, 1, 2] so the answer is 6. In the second example the obtained array b will be [2, -3, 1, -1, 4] so the answer is 7. In the third example you cannot do anything so the answer is 0. Tags: data structures, implementation Correct Solution: ``` from sys import stdin input=stdin.readline def f(a,b): # if max(a)<0 and min(a)<0: b=sorted(b,key=lambda s:s[1]-s[0]) t={} for i in range(len(a)): l=[] for j in b: if i in range(j[0],j[1]+1): l.append(j) t[i]=l t=dict(sorted(t.items(),key=lambda s:a[s[0]])) t=dict(sorted(t.items(),key=lambda s:len(s[1])-a[s[0]],reverse=True)) mn=list(t.items())[0] curr=max(a)-min(a) # print(mn) bigans=0 bigd=[] for mn in t.items(): s = a.copy() ans = [] a2 = [] for i in mn[1]: l=i[0] r=i[1] for j in range(l,r+1): s[j]-=1 # print(s) tempans=max(s)-min(s) # print("tempans",i[2],tempans,curr,s) # print(s,max(s),min(s),max(s)-min(s),i[2]+1) if tempans>=curr: a2.append(i[2]+1) ans+=a2 a2=[] else: a2.append(i[2]+1) curr=max(curr,tempans) if bigans<curr: bigans=curr bigd=ans else: break return bigd,bigans a,b=map(int,input().strip().split()) blacnk=[] lst=list(map(int,input().strip().split())) for i in range(b): l,r = map(int, input().strip().split()) blacnk.append([l-1,r-1,i]) x=f(lst,blacnk) print(x[1]) print(len(x[0])) print(*x[0]) ```
90,158
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions is a number of elements in the array. You are given an array a consisting of n integers. The value of the i-th element of the array is a_i. You are also given a set of m segments. The j-th segment is [l_j; r_j], where 1 ≤ l_j ≤ r_j ≤ n. You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array a = [0, 0, 0, 0, 0] and the given segments are [1; 3] and [2; 4] then you can choose both of them and the array will become b = [-1, -2, -2, -1, 0]. You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array a and obtain the array b then the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i will be maximum possible. Note that you can choose the empty set. If there are multiple answers, you can print any. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ 300) — the length of the array a and the number of segments, respectively. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^6 ≤ a_i ≤ 10^6), where a_i is the value of the i-th element of the array a. The next m lines are contain two integers each. The j-th of them contains two integers l_j and r_j (1 ≤ l_j ≤ r_j ≤ n), where l_j and r_j are the ends of the j-th segment. Output In the first line of the output print one integer d — the maximum possible value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i if b is the array obtained by applying some subset of the given segments to the array a. In the second line of the output print one integer q (0 ≤ q ≤ m) — the number of segments you apply. In the third line print q distinct integers c_1, c_2, ..., c_q in any order (1 ≤ c_k ≤ m) — indices of segments you apply to the array a in such a way that the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i of the obtained array b is maximum possible. If there are multiple answers, you can print any. Examples Input 5 4 2 -2 3 1 2 1 3 4 5 2 5 1 3 Output 6 2 4 1 Input 5 4 2 -2 3 1 4 3 5 3 4 2 4 2 5 Output 7 2 3 2 Input 1 0 1000000 Output 0 0 Note In the first example the obtained array b will be [0, -4, 1, 1, 2] so the answer is 6. In the second example the obtained array b will be [2, -3, 1, -1, 4] so the answer is 7. In the third example you cannot do anything so the answer is 0. Tags: data structures, implementation Correct Solution: ``` from __future__ import division, print_function def main(): def f(a, b): # if max(a)<0 and min(a)<0: b = sorted(b, key=lambda s: s[1] - s[0]) t = {} for i in range(len(a)): l = [] for j in b: if i in range(j[0], j[1] + 1): l.append(j) t[i] = l t = dict(sorted(t.items(), key=lambda s: a[s[0]])) t = dict(sorted(t.items(), key=lambda s: len(s[1]) - a[s[0]], reverse=True)) mn = list(t.items())[0] curr = max(a) - min(a) # print(mn) bigans = 0 bigd = [] for mn in t.items(): s = a.copy() ans = [] a2 = [] for i in mn[1]: l = i[0] r = i[1] for j in range(l, r + 1): s[j] -= 1 # print(s) tempans = max(s) - min(s) # print("tempans",i[2],tempans,curr,s) # print(s,max(s),min(s),max(s)-min(s),i[2]+1) if tempans >= curr: a2.append(i[2] + 1) ans += a2 a2 = [] else: a2.append(i[2] + 1) curr = max(curr, tempans) if bigans < curr: bigans = curr bigd = ans else: break return bigd, bigans a, b = map(int, input().strip().split()) blacnk = [] lst = list(map(int, input().strip().split())) for i in range(b): l, r = map(int, input().strip().split()) blacnk.append([l - 1, r - 1, i]) x = f(lst, blacnk) print(x[1]) print(len(x[0])) print(*x[0]) ######## Python 2 and 3 footer by Pajenegod and c1729 # Note because cf runs old PyPy3 version which doesn't have the sped up # unicode strings, PyPy3 strings will many times be slower than pypy2. # There is a way to get around this by using binary strings in PyPy3 # but its syntax is different which makes it kind of a mess to use. # So on cf, use PyPy2 for best string performance. py2 = round(0.5) if py2: from future_builtins import ascii, filter, hex, map, oct, zip range = xrange import os, sys from io import IOBase, BytesIO BUFSIZE = 8192 class FastIO(BytesIO): newlines = 0 def __init__(self, file): self._file = file self._fd = file.fileno() self.writable = "x" in file.mode or "w" in file.mode self.write = super(FastIO, self).write if self.writable else None def _fill(self): s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0]) return s def read(self): while self._fill(): pass return super(FastIO,self).read() def readline(self): while self.newlines == 0: s = self._fill(); self.newlines = s.count(b"\n") + (not s) self.newlines -= 1 return super(FastIO, self).readline() def flush(self): if self.writable: os.write(self._fd, self.getvalue()) self.truncate(0), self.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable if py2: self.write = self.buffer.write self.read = self.buffer.read self.readline = self.buffer.readline else: 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') # Cout implemented in Python import sys class ostream: def __lshift__(self,a): sys.stdout.write(str(a)) return self cout = ostream() endl = '\n' # Read all remaining integers in stdin, type is given by optional argument, this is fast def readnumbers(zero = 0): conv = ord if py2 else lambda x:x A = []; numb = zero; sign = 1; i = 0; s = sys.stdin.buffer.read() try: while True: if s[i] >= b'0' [0]: numb = 10 * numb + conv(s[i]) - 48 elif s[i] == b'-' [0]: sign = -1 elif s[i] != b'\r' [0]: A.append(sign*numb) numb = zero; sign = 1 i += 1 except:pass if s and s[-1] >= b'0' [0]: A.append(sign*numb) return A if __name__== "__main__": main() ```
90,159
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions is a number of elements in the array. You are given an array a consisting of n integers. The value of the i-th element of the array is a_i. You are also given a set of m segments. The j-th segment is [l_j; r_j], where 1 ≤ l_j ≤ r_j ≤ n. You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array a = [0, 0, 0, 0, 0] and the given segments are [1; 3] and [2; 4] then you can choose both of them and the array will become b = [-1, -2, -2, -1, 0]. You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array a and obtain the array b then the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i will be maximum possible. Note that you can choose the empty set. If there are multiple answers, you can print any. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ 300) — the length of the array a and the number of segments, respectively. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^6 ≤ a_i ≤ 10^6), where a_i is the value of the i-th element of the array a. The next m lines are contain two integers each. The j-th of them contains two integers l_j and r_j (1 ≤ l_j ≤ r_j ≤ n), where l_j and r_j are the ends of the j-th segment. Output In the first line of the output print one integer d — the maximum possible value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i if b is the array obtained by applying some subset of the given segments to the array a. In the second line of the output print one integer q (0 ≤ q ≤ m) — the number of segments you apply. In the third line print q distinct integers c_1, c_2, ..., c_q in any order (1 ≤ c_k ≤ m) — indices of segments you apply to the array a in such a way that the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i of the obtained array b is maximum possible. If there are multiple answers, you can print any. Examples Input 5 4 2 -2 3 1 2 1 3 4 5 2 5 1 3 Output 6 2 4 1 Input 5 4 2 -2 3 1 4 3 5 3 4 2 4 2 5 Output 7 2 3 2 Input 1 0 1000000 Output 0 0 Note In the first example the obtained array b will be [0, -4, 1, 1, 2] so the answer is 6. In the second example the obtained array b will be [2, -3, 1, -1, 4] so the answer is 7. In the third example you cannot do anything so the answer is 0. Tags: data structures, implementation Correct Solution: ``` # ---------------------------iye ha aam zindegi--------------------------------------------- import math import random import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys #import threading from collections import defaultdict #threading.stack_size(10**8) mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase #sys.setrecursionlimit(300000) BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # -------------------game starts now----------------------------------------------------import math class TreeNode: def __init__(self, k, v): self.key = k self.value = v self.left = None self.right = None self.parent = None self.height = 1 self.num_left = 1 self.num_total = 1 class AvlTree: def __init__(self): self._tree = None def add(self, k, v): if not self._tree: self._tree = TreeNode(k, v) return node = self._add(k, v) if node: self._rebalance(node) def _add(self, k, v): node = self._tree while node: if k < node.key: if node.left: node = node.left else: node.left = TreeNode(k, v) node.left.parent = node return node.left elif node.key < k: if node.right: node = node.right else: node.right = TreeNode(k, v) node.right.parent = node return node.right else: node.value = v return @staticmethod def get_height(x): return x.height if x else 0 @staticmethod def get_num_total(x): return x.num_total if x else 0 def _rebalance(self, node): n = node while n: lh = self.get_height(n.left) rh = self.get_height(n.right) n.height = max(lh, rh) + 1 balance_factor = lh - rh n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right) n.num_left = 1 + self.get_num_total(n.left) if balance_factor > 1: if self.get_height(n.left.left) < self.get_height(n.left.right): self._rotate_left(n.left) self._rotate_right(n) elif balance_factor < -1: if self.get_height(n.right.right) < self.get_height(n.right.left): self._rotate_right(n.right) self._rotate_left(n) else: n = n.parent def _remove_one(self, node): """ Side effect!!! Changes node. Node should have exactly one child """ replacement = node.left or node.right if node.parent: if AvlTree._is_left(node): node.parent.left = replacement else: node.parent.right = replacement replacement.parent = node.parent node.parent = None else: self._tree = replacement replacement.parent = None node.left = None node.right = None node.parent = None self._rebalance(replacement) def _remove_leaf(self, node): if node.parent: if AvlTree._is_left(node): node.parent.left = None else: node.parent.right = None self._rebalance(node.parent) else: self._tree = None node.parent = None node.left = None node.right = None def remove(self, k): node = self._get_node(k) if not node: return if AvlTree._is_leaf(node): self._remove_leaf(node) return if node.left and node.right: nxt = AvlTree._get_next(node) node.key = nxt.key node.value = nxt.value if self._is_leaf(nxt): self._remove_leaf(nxt) else: self._remove_one(nxt) self._rebalance(node) else: self._remove_one(node) def get(self, k): node = self._get_node(k) return node.value if node else -1 def _get_node(self, k): if not self._tree: return None node = self._tree while node: if k < node.key: node = node.left elif node.key < k: node = node.right else: return node return None def get_at(self, pos): x = pos + 1 node = self._tree while node: if x < node.num_left: node = node.left elif node.num_left < x: x -= node.num_left node = node.right else: return (node.key, node.value) raise IndexError("Out of ranges") @staticmethod def _is_left(node): return node.parent.left and node.parent.left == node @staticmethod def _is_leaf(node): return node.left is None and node.right is None def _rotate_right(self, node): if not node.parent: self._tree = node.left node.left.parent = None elif AvlTree._is_left(node): node.parent.left = node.left node.left.parent = node.parent else: node.parent.right = node.left node.left.parent = node.parent bk = node.left.right node.left.right = node node.parent = node.left node.left = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) def _rotate_left(self, node): if not node.parent: self._tree = node.right node.right.parent = None elif AvlTree._is_left(node): node.parent.left = node.right node.right.parent = node.parent else: node.parent.right = node.right node.right.parent = node.parent bk = node.right.left node.right.left = node node.parent = node.right node.right = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) @staticmethod def _get_next(node): if not node.right: return node.parent n = node.right while n.left: n = n.left return n class SegmentTree2: def __init__(self, data, default=3000006, func=lambda a, b: min(a,b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default=10**10, func=lambda a, b: min(a , b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------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------------------------------------ class TrieNode: def __init__(self): self.children = [None] * 26 self.isEndOfWord = False class Trie: def __init__(self): self.root = self.getNode() def getNode(self): return TrieNode() def _charToIndex(self, ch): return ord(ch) - ord('a') def insert(self, key): pCrawl = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) if not pCrawl.children[index]: pCrawl.children[index] = self.getNode() pCrawl = pCrawl.children[index] pCrawl.isEndOfWord = True def search(self, key): pCrawl = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) if not pCrawl.children[index]: return False pCrawl = pCrawl.children[index] return pCrawl != None and pCrawl.isEndOfWord #-----------------------------------------trie--------------------------------- class Node: def __init__(self, data): self.data = data self.count=0 self.left = None # left node for 0 self.right = None # right node for 1 class BinaryTrie: def __init__(self): self.root = Node(0) def insert(self, pre_xor,t): self.temp = self.root for i in range(31, -1, -1): val = pre_xor & (1 << i) if val: if not self.temp.right: self.temp.right = Node(0) self.temp = self.temp.right self.temp.count+=t if not val: if not self.temp.left: self.temp.left = Node(0) self.temp = self.temp.left self.temp.count += t self.temp.data = pre_xor def query(self, p,l): ans=0 self.temp = self.root for i in range(31, -1, -1): val = p & (1 << i) val1= l & (1<<i) if val1==0: if val==0: if self.temp.left and self.temp.left.count>0: self.temp = self.temp.left else: return ans else: if self.temp.right and self.temp.right.count>0: self.temp = self.temp.right else: return ans else: if val !=0 : if self.temp.right: ans+=self.temp.right.count if self.temp.left and self.temp.left.count > 0: self.temp = self.temp.left else: return ans else: if self.temp.left: ans += self.temp.left.count if self.temp.right and self.temp.right.count > 0: self.temp = self.temp.right else: return ans return ans #-------------------------bin trie------------------------------------------- n,m=map(int,input().split()) l=list(map(int,input().split())) ma=max(l) d=defaultdict(list) d1=defaultdict(list) ans=[ma+m]*n ans1=[ma+m]*n we=[] for i in range(m): a,b=map(int,input().split()) we.append((a-1,b-1)) d[b-1].append(a-1) d1[a-1].append(b-1) e=l+[] for i in range(n): mi=e[i] ans[i]=mi if i>0: for j in d[i-1]: for k in range(j,i): e[k]-=1 mi=min(mi,e[k]) ans[i]=min(ans[i-1],mi) e=l+[] for i in range(n-1,-1,-1): mi=e[i] ans1[i]=mi if i<n-1: for j in d1[i+1]: for k in range(i+1,j+1): e[k]-=1 mi=min(mi,e[k]) ans1[i]=min(ans1[i+1],mi) fi=0 ind=-1 for i in range(n): if fi<l[i]-min(ans[i],ans1[i]): fi=l[i]-min(ans[i],ans1[i]) ind=i print(fi) awe=[] for i in range(m): if we[i][1]<ind or we[i][0]>ind: awe.append(i+1) print(len(awe)) print(*awe) ```
90,160
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions is a number of elements in the array. You are given an array a consisting of n integers. The value of the i-th element of the array is a_i. You are also given a set of m segments. The j-th segment is [l_j; r_j], where 1 ≤ l_j ≤ r_j ≤ n. You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array a = [0, 0, 0, 0, 0] and the given segments are [1; 3] and [2; 4] then you can choose both of them and the array will become b = [-1, -2, -2, -1, 0]. You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array a and obtain the array b then the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i will be maximum possible. Note that you can choose the empty set. If there are multiple answers, you can print any. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ 300) — the length of the array a and the number of segments, respectively. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^6 ≤ a_i ≤ 10^6), where a_i is the value of the i-th element of the array a. The next m lines are contain two integers each. The j-th of them contains two integers l_j and r_j (1 ≤ l_j ≤ r_j ≤ n), where l_j and r_j are the ends of the j-th segment. Output In the first line of the output print one integer d — the maximum possible value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i if b is the array obtained by applying some subset of the given segments to the array a. In the second line of the output print one integer q (0 ≤ q ≤ m) — the number of segments you apply. In the third line print q distinct integers c_1, c_2, ..., c_q in any order (1 ≤ c_k ≤ m) — indices of segments you apply to the array a in such a way that the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i of the obtained array b is maximum possible. If there are multiple answers, you can print any. Examples Input 5 4 2 -2 3 1 2 1 3 4 5 2 5 1 3 Output 6 2 4 1 Input 5 4 2 -2 3 1 4 3 5 3 4 2 4 2 5 Output 7 2 3 2 Input 1 0 1000000 Output 0 0 Note In the first example the obtained array b will be [0, -4, 1, 1, 2] so the answer is 6. In the second example the obtained array b will be [2, -3, 1, -1, 4] so the answer is 7. In the third example you cannot do anything so the answer is 0. Tags: data structures, implementation Correct Solution: ``` # after solving E1 it was quite easy to come up with the idea of lazy segtree import sys # a very nice implementation of a minimum segment tree with # some inspiration taken from https://codeforces.com/blog/entry/18051 # this implementation should be able to be modified to do pretty # much anything one would want to do with segment trees apart from # persistance. # note that especially in python this implementation is much much better # than most other approches because how slow python can be with function # calls. /pajenegod # currently it allows for two operations, both running in o(log n), # 'add(l,r,value)' adds value to [l,r) # 'find_min(l,r)' finds the index with the smallest value big = 10**9 class super_seg: def __init__(self,data): n = len(data) m = 1 while m<n: m *= 2 self.n = n self.m = m self.data = [big]*(2*m) for i in range(n): self.data[i+m] = data[i] for i in reversed(range(m)): self.data[i] = min(self.data[2*i], self.data[2*i+1]) self.query = [0]*(2*m) # push the query on seg_ind to its children def push(self,seg_ind): # let the children know of the queries q = self.query[seg_ind] self.query[2*seg_ind] += q self.query[2*seg_ind+1] += q self.data[2*seg_ind] += q self.data[2*seg_ind+1] += q # remove queries from seg_ind self.data[seg_ind] = min(self.data[2*seg_ind],self.data[2*seg_ind+1]) self.query[seg_ind] = 0 # updates the node seg_ind to know of all queries # applied to it via its ancestors def update(self,seg_ind): # find all indecies to be updated seg_ind //= 2 inds = [] while seg_ind>0: inds.append(seg_ind) seg_ind//=2 # push the queries down the segment tree for ind in reversed(inds): self.push(ind) # make the changes to seg_ind be known to its ancestors def build(self,seg_ind): seg_ind//=2 while seg_ind>0: self.data[seg_ind] = min(self.data[2*seg_ind], self.data[2*seg_ind+1]) + self.query[seg_ind] seg_ind //= 2 # lazily add value to [l,r) def add(self,l,r,value): l += self.m r += self.m l0 = l r0 = r while l<r: if l%2==1: self.query[l]+= value self.data[l] += value l+=1 if r%2==1: r-=1 self.query[r]+= value self.data[r] += value l//=2 r//=2 # tell all nodes above of the updated # area of the updates self.build(l0) self.build(r0-1) # min of data[l,r) def min(self,l,r): l += self.m r += self.m # apply all the lazily stored queries self.update(l) self.update(r-1) segs = [] while l<r: if l%2==1: segs.append(l) l+=1 if r%2==1: r-=1 segs.append(r) l//=2 r//=2 return min(self.data[ind] for ind in segs) # find index of smallest value in data[l,r) def find_min(self,l,r): l += self.m r += self.m # apply all the lazily stored queries self.update(l) self.update(r-1) segs = [] while l<r: if l%2==1: segs.append(l) l+=1 if r%2==1: r-=1 segs.append(r) l//=2 r//=2 ind = min(segs, key=lambda i:self.data[i]) mini = self.data[ind] # dig down in search of mini while ind<self.m: self.push(ind) if self.data[2*ind]==mini: ind *= 2 else: ind = 2*ind+1 return ind-self.m,mini n,m = [int(x) for x in input().split()] A = [int(x) for x in input().split()] inter = [] update = [[] for _ in range(n+1)] for _ in range(m): l,r = [int(x) for x in input().split()] l -= 1 inter.append((l,r)) update[l].append((l,r)) update[r].append((l,r)) Aneg = super_seg([-a for a in A]) besta = -1 besta_ind = -1 active_intervals = 0 for i in range(n): for l,r in update[i]: Aneg.add(l,r,1 if l==i else -1) active_intervals += 1 if l==i else -1 Amax = -Aneg.data[1] Ai = A[i] - active_intervals if Amax-Ai>besta: besta = Amax-Ai besta_ind = i ints = [i for i in range(m) if inter[i][0]<=besta_ind<inter[i][1]] print(besta) print(len(ints)) print(*[x+1 for x in ints]) ```
90,161
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between easy and hard versions is a number of elements in the array. You are given an array a consisting of n integers. The value of the i-th element of the array is a_i. You are also given a set of m segments. The j-th segment is [l_j; r_j], where 1 ≤ l_j ≤ r_j ≤ n. You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array a = [0, 0, 0, 0, 0] and the given segments are [1; 3] and [2; 4] then you can choose both of them and the array will become b = [-1, -2, -2, -1, 0]. You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array a and obtain the array b then the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i will be maximum possible. Note that you can choose the empty set. If there are multiple answers, you can print any. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ 300) — the length of the array a and the number of segments, respectively. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^6 ≤ a_i ≤ 10^6), where a_i is the value of the i-th element of the array a. The next m lines are contain two integers each. The j-th of them contains two integers l_j and r_j (1 ≤ l_j ≤ r_j ≤ n), where l_j and r_j are the ends of the j-th segment. Output In the first line of the output print one integer d — the maximum possible value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i if b is the array obtained by applying some subset of the given segments to the array a. In the second line of the output print one integer q (0 ≤ q ≤ m) — the number of segments you apply. In the third line print q distinct integers c_1, c_2, ..., c_q in any order (1 ≤ c_k ≤ m) — indices of segments you apply to the array a in such a way that the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i of the obtained array b is maximum possible. If there are multiple answers, you can print any. Examples Input 5 4 2 -2 3 1 2 1 3 4 5 2 5 1 3 Output 6 2 4 1 Input 5 4 2 -2 3 1 4 3 5 3 4 2 4 2 5 Output 7 2 3 2 Input 1 0 1000000 Output 0 0 Note In the first example the obtained array b will be [0, -4, 1, 1, 2] so the answer is 6. In the second example the obtained array b will be [2, -3, 1, -1, 4] so the answer is 7. In the third example you cannot do anything so the answer is 0. Submitted Solution: ``` n, m = map(int, input().split()) mass = list(map(int, input().split())) lr = [] for t in range(m): l, r = map(int, input().split()) lr.append([l, r]) mq = 0 mdel = [] mitog = 0 m300 = [[-1, -10**6]] for i in range(max(0, m-1)): m300.append([-1, -10**6]) for u in range(len(mass)): if mass[u] > min(m300)[0]: m300[m300.index(min(m300))] = [u, mass[u]] for a, ma in m300: for b in range(len(mass)): mb = mass[b] q = 0 delete = [] itog = 0 for x in range(len(lr)): l, r = lr[x][0], lr[x][1] if l <= b+1 <= r and (a+1 < l or a+1 > r): q += 1 delete.append(x+1) itog = ma + q - mb if mitog < itog: mitog = itog mq = q mdel = delete print(mitog) print(mq) if len(mdel): print(' '.join(list(map(str, mdel)))) else: print('') ``` No
90,162
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between easy and hard versions is a number of elements in the array. You are given an array a consisting of n integers. The value of the i-th element of the array is a_i. You are also given a set of m segments. The j-th segment is [l_j; r_j], where 1 ≤ l_j ≤ r_j ≤ n. You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array a = [0, 0, 0, 0, 0] and the given segments are [1; 3] and [2; 4] then you can choose both of them and the array will become b = [-1, -2, -2, -1, 0]. You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array a and obtain the array b then the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i will be maximum possible. Note that you can choose the empty set. If there are multiple answers, you can print any. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ 300) — the length of the array a and the number of segments, respectively. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^6 ≤ a_i ≤ 10^6), where a_i is the value of the i-th element of the array a. The next m lines are contain two integers each. The j-th of them contains two integers l_j and r_j (1 ≤ l_j ≤ r_j ≤ n), where l_j and r_j are the ends of the j-th segment. Output In the first line of the output print one integer d — the maximum possible value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i if b is the array obtained by applying some subset of the given segments to the array a. In the second line of the output print one integer q (0 ≤ q ≤ m) — the number of segments you apply. In the third line print q distinct integers c_1, c_2, ..., c_q in any order (1 ≤ c_k ≤ m) — indices of segments you apply to the array a in such a way that the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i of the obtained array b is maximum possible. If there are multiple answers, you can print any. Examples Input 5 4 2 -2 3 1 2 1 3 4 5 2 5 1 3 Output 6 2 4 1 Input 5 4 2 -2 3 1 4 3 5 3 4 2 4 2 5 Output 7 2 3 2 Input 1 0 1000000 Output 0 0 Note In the first example the obtained array b will be [0, -4, 1, 1, 2] so the answer is 6. In the second example the obtained array b will be [2, -3, 1, -1, 4] so the answer is 7. In the third example you cannot do anything so the answer is 0. Submitted Solution: ``` n, m = map(int, input().split()) mass = list(map(int, input().split())) if n > 300: lr = [] for t in range(m): l, r = map(int, input().split()) lr.append([l, r]) mq = 0 mdel = [] mitog = 0 m300 = [[-1, -10**6]] for i in range(max(0, m)): m300.append([-1, -10**6]) for u in range(n): if mass[u] > min(m300)[0]: m300[m300.index(min(m300))] = [u, mass[u]] for a, ma in m300: for b in range(len(mass)): mb = mass[b] q = 0 delete = [] itog = 0 for x in range(len(lr)): l, r = lr[x][0], lr[x][1] if l <= b+1 <= r and (a+1 < l or a+1 > r): q += 1 delete.append(x+1) itog = ma + q - mb if mitog < itog: mitog = itog mq = q mdel = delete print(mitog) print(mq) if len(mdel): print(' '.join(list(map(str, mdel)))) else: print('') else: lr = [] for t in range(m): l, r = map(int, input().split()) lr.append([l, r]) mq = 0 mdel = [] mitog = 0 for a in range(len(mass)): ma = mass[a] for b in range(len(mass)): mb = mass[b] q = 0 delete = [] itog = 0 for x in range(len(lr)): l, r = lr[x][0], lr[x][1] if l <= b + 1 <= r and (a + 1 < l or a + 1 > r): q += 1 delete.append(x + 1) itog = ma + q - mb if mitog < itog: mitog = itog mq = q mdel = delete print(mitog) print(mq) if len(mdel): print(' '.join(list(map(str, mdel)))) else: print('') ``` No
90,163
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between easy and hard versions is a number of elements in the array. You are given an array a consisting of n integers. The value of the i-th element of the array is a_i. You are also given a set of m segments. The j-th segment is [l_j; r_j], where 1 ≤ l_j ≤ r_j ≤ n. You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array a = [0, 0, 0, 0, 0] and the given segments are [1; 3] and [2; 4] then you can choose both of them and the array will become b = [-1, -2, -2, -1, 0]. You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array a and obtain the array b then the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i will be maximum possible. Note that you can choose the empty set. If there are multiple answers, you can print any. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ 300) — the length of the array a and the number of segments, respectively. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^6 ≤ a_i ≤ 10^6), where a_i is the value of the i-th element of the array a. The next m lines are contain two integers each. The j-th of them contains two integers l_j and r_j (1 ≤ l_j ≤ r_j ≤ n), where l_j and r_j are the ends of the j-th segment. Output In the first line of the output print one integer d — the maximum possible value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i if b is the array obtained by applying some subset of the given segments to the array a. In the second line of the output print one integer q (0 ≤ q ≤ m) — the number of segments you apply. In the third line print q distinct integers c_1, c_2, ..., c_q in any order (1 ≤ c_k ≤ m) — indices of segments you apply to the array a in such a way that the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i of the obtained array b is maximum possible. If there are multiple answers, you can print any. Examples Input 5 4 2 -2 3 1 2 1 3 4 5 2 5 1 3 Output 6 2 4 1 Input 5 4 2 -2 3 1 4 3 5 3 4 2 4 2 5 Output 7 2 3 2 Input 1 0 1000000 Output 0 0 Note In the first example the obtained array b will be [0, -4, 1, 1, 2] so the answer is 6. In the second example the obtained array b will be [2, -3, 1, -1, 4] so the answer is 7. In the third example you cannot do anything so the answer is 0. Submitted Solution: ``` n, m = list(map(int, input().split())) A = list(map(int, input().split())) if n > 300: lst = [] for i in range(m): a, b = list(map(int, input().split())) lst.append([a, b]) answer = 0 answer_1 = [] m300 = [[-1, -10**6]] for i in range(max(0, m-1)): m300.append([-1, -10**6]) for u in range(n): if A[u] > min(m300)[1]: m300[m300.index(min(m300))] = [u, A[u]] for i, mi in m300: B = A.copy() kek = [] for j in range(m): a, b = lst[j][0], lst[j][1] if a <= i + 1 <= b: kek.append(j + 1) for q in range(a - 1, b): B[q] -= 1 elem = max(B) if answer < elem - mi: answer = elem - mi answer_1 = kek.copy() print(answer) print(len(answer_1)) print(' '.join(map(str, answer_1))) else: lst = [] for i in range(m): a, b = list(map(int, input().split())) lst.append([a, b]) answer = 0 answer_1 = [] for i in range(n): B = A.copy() kek = [] for j in range(m): a, b = lst[j][0], lst[j][1] if a <= i + 1 <= b: kek.append(j + 1) for q in range(a - 1, b): B[q] -= 1 elem = max(B) if answer < elem - B[i]: answer = elem - B[i] answer_1 = kek.copy() print(answer) print(len(answer_1)) print(' '.join(map(str, answer_1))) ``` No
90,164
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between easy and hard versions is a number of elements in the array. You are given an array a consisting of n integers. The value of the i-th element of the array is a_i. You are also given a set of m segments. The j-th segment is [l_j; r_j], where 1 ≤ l_j ≤ r_j ≤ n. You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array a = [0, 0, 0, 0, 0] and the given segments are [1; 3] and [2; 4] then you can choose both of them and the array will become b = [-1, -2, -2, -1, 0]. You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array a and obtain the array b then the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i will be maximum possible. Note that you can choose the empty set. If there are multiple answers, you can print any. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ 300) — the length of the array a and the number of segments, respectively. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^6 ≤ a_i ≤ 10^6), where a_i is the value of the i-th element of the array a. The next m lines are contain two integers each. The j-th of them contains two integers l_j and r_j (1 ≤ l_j ≤ r_j ≤ n), where l_j and r_j are the ends of the j-th segment. Output In the first line of the output print one integer d — the maximum possible value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i if b is the array obtained by applying some subset of the given segments to the array a. In the second line of the output print one integer q (0 ≤ q ≤ m) — the number of segments you apply. In the third line print q distinct integers c_1, c_2, ..., c_q in any order (1 ≤ c_k ≤ m) — indices of segments you apply to the array a in such a way that the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i of the obtained array b is maximum possible. If there are multiple answers, you can print any. Examples Input 5 4 2 -2 3 1 2 1 3 4 5 2 5 1 3 Output 6 2 4 1 Input 5 4 2 -2 3 1 4 3 5 3 4 2 4 2 5 Output 7 2 3 2 Input 1 0 1000000 Output 0 0 Note In the first example the obtained array b will be [0, -4, 1, 1, 2] so the answer is 6. In the second example the obtained array b will be [2, -3, 1, -1, 4] so the answer is 7. In the third example you cannot do anything so the answer is 0. 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=300006, func=lambda a, b: min(a , b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------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------------------------------------ class TrieNode: def __init__(self): self.children = [None] * 26 self.isEndOfWord = False class Trie: def __init__(self): self.root = self.getNode() def getNode(self): return TrieNode() def _charToIndex(self, ch): return ord(ch) - ord('a') def insert(self, key): pCrawl = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) if not pCrawl.children[index]: pCrawl.children[index] = self.getNode() pCrawl = pCrawl.children[index] pCrawl.isEndOfWord = True def search(self, key): pCrawl = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) if not pCrawl.children[index]: return False pCrawl = pCrawl.children[index] return pCrawl != None and pCrawl.isEndOfWord #-----------------------------------------trie--------------------------------- class Node: def __init__(self, data): self.data = data self.height=0 self.left = None # left node for 0 self.right = None # right node for 1 class BinaryTrie: def __init__(self): self.root = Node(0) def insert(self, pre_xor): self.temp = self.root for i in range(31, -1, -1): val = pre_xor & (1 << i) if val==0: if not self.temp.right: self.temp.right = Node(0) self.temp = self.temp.right elif val>=1: if not self.temp.left: self.temp.left = Node(0) self.temp = self.temp.left def do(self,temp): if not temp: return 0 ter=temp temp.height=self.do(ter.left)+self.do(ter.right) if temp.height==0: temp.height+=1 return temp.height def query(self, xor): self.temp = self.root cur=0 i=31 while(i>-1): val = xor & (1 << i) if not self.temp: return cur if val>=1: self.opp = self.temp.right if self.temp.left: self.temp = self.temp.left else: return cur else: self.opp=self.temp.left if self.temp.right: self.temp = self.temp.right else: return cur if self.temp.height==pow(2,i): cur+=1<<(i) self.temp=self.opp i-=1 return cur #-------------------------bin trie------------------------------------------- n,m=map(int,input().split()) l=list(map(int,input().split())) mi=min(l) ans=0 fi=[] for i1 in range(m): a,b=map(int,input().split()) f=0 for i in range(a,b+1): if l[i-1]==mi: mi-=1 f=1 break if f==1: for i in range(a,b+1): l[i-1]-=1 ans+=1 fi.append(i1+1) print(max(l)-mi) print(ans) print(*fi) ``` No
90,165
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is a head of a circus troupe. There are n — an even number — artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0). Split the artists into two performances in such a way that: * each artist plays in exactly one performance, * the number of artists in the two performances is equal (i.e. equal to n/2), * the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance. Input The first line contains a single integer n (2 ≤ n ≤ 5 000, n is even) — the number of artists in the troupe. The second line contains n digits c_1 c_2 … c_n, the i-th of which is equal to 1 if the i-th artist can perform as a clown, and 0 otherwise. The third line contains n digits a_1 a_2 … a_n, the i-th of which is equal to 1, if the i-th artist can perform as an acrobat, and 0 otherwise. Output Print n/2 distinct integers — the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer -1. Examples Input 4 0011 0101 Output 1 4 Input 6 000000 111111 Output -1 Input 4 0011 1100 Output 4 3 Input 8 00100101 01111100 Output 1 2 3 6 Note In the first example, one of the possible divisions into two performances is as follows: in the first performance artists 1 and 4 should take part. Then the number of artists in the first performance who can perform as clowns is equal to 1. And the number of artists in the second performance who can perform as acrobats is 1 as well. In the second example, the division is not possible. In the third example, one of the possible divisions is as follows: in the first performance artists 3 and 4 should take part. Then in the first performance there are 2 artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is 2 as well. Tags: brute force, greedy, math, strings Correct Solution: ``` from collections import deque, Counter, OrderedDict from heapq import nsmallest, nlargest, heapify, heappop ,heappush, heapreplace from math import ceil,floor,log,log2,sqrt,gcd,factorial,pow,pi from bisect import bisect_left,bisect_right def binNumber(n,size=4): return bin(n)[2:].zfill(size) def iar(): return list(map(int,input().split())) def ini(): return int(input()) def isp(): return map(int,input().split()) def sti(): return str(input()) def par(a): print(' '.join(list(map(str,a)))) def tdl(outerListSize,innerListSize,defaultValue = 0): return [[defaultValue]*innerListSize for i in range(outerListSize)] def sts(s): s = list(s) s.sort() return ''.join(s) def bis(a, x): i = bisect_left(a, x) if i != len(a) and a[i] == x: return [i,True] else: return [-1,False] class pair: def __init__(self,f,s): self.fi = f self.se = s def __lt__(self,other): return (self.fi,self.se) < (other.fi,other.se) # ========= /\ /| |====/| # | / \ | | / | # | /____\ | | / | # | / \ | | / | # ========= / \ ===== |/====| # code if __name__ == "__main__": n = ini() s1 = sti() s2 = sti() c = [0]*4 p = [[],[],[],[]] for i in range(n): if s1[i] == '0' and s2[i] == '0': c[0] += 1 p[0].append(i+1) if s1[i] == '0' and s2[i] == '1': c[1] += 1 p[1].append(i+1) if s1[i] == '1' and s2[i] == '0': c[2] += 1 p[2].append(i+1) if s1[i] == '1' and s2[i] == '1': c[3] += 1 p[3].append(i+1) for a in range(c[0]+1): for b in range(c[1]+1): d = c[3]+c[1] - n//2 + a e = n//2 - a - b - d #print(e,d) if e > c[2] or d > c[3]: continue if d >= 0 and e >= 0: for i in range(a): print(p[0][i],end=" ") for i in range(b): print(p[1][i],end=" ") for i in range(e): print(p[2][i],end=" ") for i in range(d): print(p[3][i],end=" ") quit() print(-1) ```
90,166
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is a head of a circus troupe. There are n — an even number — artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0). Split the artists into two performances in such a way that: * each artist plays in exactly one performance, * the number of artists in the two performances is equal (i.e. equal to n/2), * the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance. Input The first line contains a single integer n (2 ≤ n ≤ 5 000, n is even) — the number of artists in the troupe. The second line contains n digits c_1 c_2 … c_n, the i-th of which is equal to 1 if the i-th artist can perform as a clown, and 0 otherwise. The third line contains n digits a_1 a_2 … a_n, the i-th of which is equal to 1, if the i-th artist can perform as an acrobat, and 0 otherwise. Output Print n/2 distinct integers — the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer -1. Examples Input 4 0011 0101 Output 1 4 Input 6 000000 111111 Output -1 Input 4 0011 1100 Output 4 3 Input 8 00100101 01111100 Output 1 2 3 6 Note In the first example, one of the possible divisions into two performances is as follows: in the first performance artists 1 and 4 should take part. Then the number of artists in the first performance who can perform as clowns is equal to 1. And the number of artists in the second performance who can perform as acrobats is 1 as well. In the second example, the division is not possible. In the third example, one of the possible divisions is as follows: in the first performance artists 3 and 4 should take part. Then in the first performance there are 2 artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is 2 as well. Tags: brute force, greedy, math, strings Correct Solution: ``` # map(int, input().split()) # list(map(int, input().split())) # for _ in range(int(input())): n = int(input()) c = list(map(int, list(input()))) a = list(map(int, list(input()))) p = [0,0,0,0] # 00,10,01,11 ind = [[],[],[],[]] for i in range(n): if c[i] and a[i]: p[3] += 1 ind[3].append(i) elif c[i]: p[1] += 1 ind[1].append(i) elif a[i]: p[2] += 1 ind[2].append(i) else: p[0] += 1 ind[0].append(i) first = [0,p[1],0,0] second = [0,0,p[2],0] def trans(i, n): first[i] += n second[i] -= n if p[2] > p[1]: d = p[2] - p[1] first[2] += d second[2] -= d else: d = p[1] - p[2] first[1] -= d second[1] += d d = p[3] while d>0: if first[1]+first[3] > second[2]+second[3]: second[3] += 1 d -= 1 else: first[3] += 1 d -= 1 dif = first[1]+first[3] - (second[2]+second[3]) if dif > 0: if first[2] > 0: trans(2,-1) elif first[1] > 0: trans(1,-1) elif first[3] > 0 and second[1] > 0: trans(3,-1) trans(1,1) else: print(-1) quit() elif dif < 0: if second[1] > 0: trans(1,1) elif second[2] > 0: trans(2,2) elif second[3] > 0 and first[2] > 0: trans(3,1) trans(2,-1) else: print(-1) quit() d = p[0] while d>0: if sum(first) > sum(second): second[0] += 1 d -= 1 else: first[0] += 1 d -= 1 while sum(first) > sum(second): if first[1]>0 and first[2]>0 and second[3]>0: trans(1,-1) trans(2,-1) trans(3,1) elif first[2]>1 and second[3] > 0: trans(2,-1) trans(2,-1) trans(3,1) else: print(-1) quit() while sum(first) < sum(second): if second[1]>0 and second[2]>0 and first[3]>0: trans(1,1) trans(2,1) trans(3,-1) elif second[1]>1 and first[3] > 0: trans(1,1) trans(1,1) trans(3,-1) else: print(-1) quit() ans = [] for i in range(4): for j in range(first[i]): ans.append(ind[i][j]) print(' '.join([str(x+1) for x in ans])) ```
90,167
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is a head of a circus troupe. There are n — an even number — artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0). Split the artists into two performances in such a way that: * each artist plays in exactly one performance, * the number of artists in the two performances is equal (i.e. equal to n/2), * the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance. Input The first line contains a single integer n (2 ≤ n ≤ 5 000, n is even) — the number of artists in the troupe. The second line contains n digits c_1 c_2 … c_n, the i-th of which is equal to 1 if the i-th artist can perform as a clown, and 0 otherwise. The third line contains n digits a_1 a_2 … a_n, the i-th of which is equal to 1, if the i-th artist can perform as an acrobat, and 0 otherwise. Output Print n/2 distinct integers — the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer -1. Examples Input 4 0011 0101 Output 1 4 Input 6 000000 111111 Output -1 Input 4 0011 1100 Output 4 3 Input 8 00100101 01111100 Output 1 2 3 6 Note In the first example, one of the possible divisions into two performances is as follows: in the first performance artists 1 and 4 should take part. Then the number of artists in the first performance who can perform as clowns is equal to 1. And the number of artists in the second performance who can perform as acrobats is 1 as well. In the second example, the division is not possible. In the third example, one of the possible divisions is as follows: in the first performance artists 3 and 4 should take part. Then in the first performance there are 2 artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is 2 as well. Tags: brute force, greedy, math, strings Correct Solution: ``` n = int(input()) n2 = n // 2 c = input() a = input() cl = [] ac = [] uni = [] par = [] res = [] for i in range(0, n): if c[i] == "1": if a[i]=="0": cl.append(i+1) else: uni.append(i+1) else: if a[i]=="0": par.append(i+1) else: ac.append(i+1) lcl = len(cl) lac = len(ac) lpar = len(par) luni = len(uni) if lcl > n2 or lac > n2 or (lcl == 0 and lac == 0 and luni % 2 == 1): print(-1) else: if luni + lpar - abs(lac - lcl) < 0: print(-1) else: #Выравниваем массивы if luni - abs(lac - lcl) < 0: nmin = lpar if nmin > abs(lac-lcl): nmin = abs(lac-lcl) if lcl < lac: cl = cl + ac[lcl:lcl+nmin:1] lcl = lcl + nmin lpar = lpar-nmin else: if lcl > lac: cl = cl[0:lcl-nmin:1] + par[0:nmin:1] lac = lac + nmin par = par[nmin:] lpar = lpar-nmin x = 0 if lcl < lac: for i in range(0, lac-lcl): cl.append(uni[i]) x = lac-lcl if (luni - abs(lac - lcl)) % 2 == 1: if lac > 0: cl.append(ac[0]) else: cl = cl[1:] cl.append(uni[luni-1]) cl.append(par[lpar-1]) luni = luni-1 lpar = lpar-1 n4 = (luni - abs(lac - lcl)) // 2 for i in range(x, x+n4): cl.append(uni[i]) n5 = lpar // 2 for i in range(0, n5): cl.append(par[i]) print(*cl) ```
90,168
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is a head of a circus troupe. There are n — an even number — artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0). Split the artists into two performances in such a way that: * each artist plays in exactly one performance, * the number of artists in the two performances is equal (i.e. equal to n/2), * the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance. Input The first line contains a single integer n (2 ≤ n ≤ 5 000, n is even) — the number of artists in the troupe. The second line contains n digits c_1 c_2 … c_n, the i-th of which is equal to 1 if the i-th artist can perform as a clown, and 0 otherwise. The third line contains n digits a_1 a_2 … a_n, the i-th of which is equal to 1, if the i-th artist can perform as an acrobat, and 0 otherwise. Output Print n/2 distinct integers — the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer -1. Examples Input 4 0011 0101 Output 1 4 Input 6 000000 111111 Output -1 Input 4 0011 1100 Output 4 3 Input 8 00100101 01111100 Output 1 2 3 6 Note In the first example, one of the possible divisions into two performances is as follows: in the first performance artists 1 and 4 should take part. Then the number of artists in the first performance who can perform as clowns is equal to 1. And the number of artists in the second performance who can perform as acrobats is 1 as well. In the second example, the division is not possible. In the third example, one of the possible divisions is as follows: in the first performance artists 3 and 4 should take part. Then in the first performance there are 2 artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is 2 as well. Tags: brute force, greedy, math, strings Correct Solution: ``` from sys import stdin,stdout from math import gcd,sqrt,factorial,pi,inf from collections import deque,defaultdict from bisect import bisect,bisect_left from time import time from itertools import permutations as per from heapq import heapify,heappush,heappop,heappushpop input=stdin.readline R=lambda:map(int,input().split()) I=lambda:int(input()) S=lambda:input().rstrip('\r\n') L=lambda:list(R()) P=lambda x:stdout.write(str(x)+'\n') lcm=lambda x,y:(x*y)//gcd(x,y) nCr=lambda x,y:(f[x]*inv((f[y]*f[x-y])%N))%N inv=lambda x:pow(x,N-2,N) sm=lambda x:(x**2+x)//2 N=10**9+7 n=I() g={(0,0):[],(1,0):[],(1,1):[],(0,1):[]} for i,x,y in zip(range(n),S(),S()): g[int(x),int(y)]+=i+1, w=len(g[(0,0)]) x=len(g[(0,1)]) y=len(g[(1,1)]) z=len(g[(1,0)]) for b in range(len(g[(0,1)])+1): for d in range(len(g[(1,1)])+1): c=x+y-(b+2*d) a=n//2-(b+d+c) if w>=a>=0 and z>=c>=0: print(*g[(0,0)][:a]+g[(1,1)][:d]+g[(1,0)][:c]+g[(0,1)][:b]) exit() print(-1) ```
90,169
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is a head of a circus troupe. There are n — an even number — artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0). Split the artists into two performances in such a way that: * each artist plays in exactly one performance, * the number of artists in the two performances is equal (i.e. equal to n/2), * the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance. Input The first line contains a single integer n (2 ≤ n ≤ 5 000, n is even) — the number of artists in the troupe. The second line contains n digits c_1 c_2 … c_n, the i-th of which is equal to 1 if the i-th artist can perform as a clown, and 0 otherwise. The third line contains n digits a_1 a_2 … a_n, the i-th of which is equal to 1, if the i-th artist can perform as an acrobat, and 0 otherwise. Output Print n/2 distinct integers — the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer -1. Examples Input 4 0011 0101 Output 1 4 Input 6 000000 111111 Output -1 Input 4 0011 1100 Output 4 3 Input 8 00100101 01111100 Output 1 2 3 6 Note In the first example, one of the possible divisions into two performances is as follows: in the first performance artists 1 and 4 should take part. Then the number of artists in the first performance who can perform as clowns is equal to 1. And the number of artists in the second performance who can perform as acrobats is 1 as well. In the second example, the division is not possible. In the third example, one of the possible divisions is as follows: in the first performance artists 3 and 4 should take part. Then in the first performance there are 2 artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is 2 as well. Tags: brute force, greedy, math, strings Correct Solution: ``` import sys import random N = int(input()) C = list(map(int, input())) A = list(map(int, input())) # N = random.randint(20, 40) * 2 # C = [random.randint(0, 1) for i in range(N)] # A = [random.randint(0, 1) for i in range(N)] def build_solution(i, j, x, y): I = (0, 0) J = (0, 1) X = (1, 0) Y = (1, 1) ans = [] for q in range(N): p = (C[q], A[q]) if i and p == I: i -= 1 ans.append(q+1) elif j and p == J: j -= 1 ans.append(q+1) elif x and p == X: x -= 1 ans.append(q+1) elif y and p == Y: y -= 1 ans.append(q+1) return map(str, ans) a = b = c = d = 0 for i in range(N): if C[i] == 0: if A[i] == 0: a += 1 else: b += 1 else: if A[i] == 0: c += 1 else: d += 1 # print(C) # print(A) # print(a, b, c, d, "N/2=", N//2) for i in range(0, a+1): y = - N//2 + i + b + d if y < 0: continue min_j = max(0, N//2 - i - c - y) max_j = min(b + 1, N //2 + 1) # print(i, y, '[', min_j, max_j, ']') for j in range(min_j, max_j): x = N//2 - i - j - y if x < 0: break # print("Check ", i, j, 'x, y:', x, y) if not ((0 <= x <= c) and (0 <= y <= d)): continue # print('SOL', i, j, x, y) sol = build_solution(i, j, x, y) print(' '.join(sol)) exit(0) print(-1) # 1) loop over N # 2) pick best actor on every iteration # 3) try to minimize diff between teams # if len(first) == len(second) and first.score == second.score: # print(' '.join(map(lambda x: str(x+1), first))) # else: # print(-1) # a, b, c, d = 13 5 2 1, N = 20 # i, j, x, y, SUM = 10 # i = 0 # j = 0 ```
90,170
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is a head of a circus troupe. There are n — an even number — artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0). Split the artists into two performances in such a way that: * each artist plays in exactly one performance, * the number of artists in the two performances is equal (i.e. equal to n/2), * the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance. Input The first line contains a single integer n (2 ≤ n ≤ 5 000, n is even) — the number of artists in the troupe. The second line contains n digits c_1 c_2 … c_n, the i-th of which is equal to 1 if the i-th artist can perform as a clown, and 0 otherwise. The third line contains n digits a_1 a_2 … a_n, the i-th of which is equal to 1, if the i-th artist can perform as an acrobat, and 0 otherwise. Output Print n/2 distinct integers — the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer -1. Examples Input 4 0011 0101 Output 1 4 Input 6 000000 111111 Output -1 Input 4 0011 1100 Output 4 3 Input 8 00100101 01111100 Output 1 2 3 6 Note In the first example, one of the possible divisions into two performances is as follows: in the first performance artists 1 and 4 should take part. Then the number of artists in the first performance who can perform as clowns is equal to 1. And the number of artists in the second performance who can perform as acrobats is 1 as well. In the second example, the division is not possible. In the third example, one of the possible divisions is as follows: in the first performance artists 3 and 4 should take part. Then in the first performance there are 2 artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is 2 as well. Tags: brute force, greedy, math, strings Correct Solution: ``` def find_sol1(result,num_dict): ans_list = [] #print("result",result) for i in range(num_dict['a']+1): for j in range(num_dict['d']+1): if i - j == result: ans_list.append((i,j)) return ans_list def find_sol2(N,num_dict,ans_list): for a,d in ans_list: for i in range(num_dict['b'] + 1): for j in range(num_dict['c'] + 1): if i + j + a + d == N//2: b = i;c = j return a,b,c,d return -1,-1,-1,-1 if __name__ == '__main__': N = int(input().strip()) clown = [int(i) for i in input().strip()] acro = [int(i) for i in input().strip()] num_dict = {'a':0,'b':0,'c':0,'d':0} for i in range(N): if clown[i] == 0 and acro[i] == 0: num_dict['a']+=1 elif clown[i] == 1 and acro[i] == 0: num_dict['b']+=1 elif clown[i] == 0 and acro[i] == 1: num_dict['c']+=1 else: num_dict['d']+=1 a,b,c,d= 0,0,0,0 result = N//2 - num_dict['c'] - num_dict['d'] ans_list = find_sol1(result,num_dict) #print(a,b,c,d) if ans_list == []: print(-1) else: a,b,c,d = find_sol2(N,num_dict,ans_list) if a == -1: print(-1) else: ans = [] for i in range(N): if clown[i] == 0 and acro[i] == 0: if a > 0: ans.append(i + 1) a -= 1 elif clown[i] == 1 and acro[i] == 0: if b > 0: ans.append(i + 1) b -= 1 elif clown[i] == 0 and acro[i] == 1: if c > 0: ans.append(i + 1) c -= 1 else: if d > 0: ans.append(i + 1) d -= 1 print(' '.join(str(i) for i in ans)) ```
90,171
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is a head of a circus troupe. There are n — an even number — artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0). Split the artists into two performances in such a way that: * each artist plays in exactly one performance, * the number of artists in the two performances is equal (i.e. equal to n/2), * the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance. Input The first line contains a single integer n (2 ≤ n ≤ 5 000, n is even) — the number of artists in the troupe. The second line contains n digits c_1 c_2 … c_n, the i-th of which is equal to 1 if the i-th artist can perform as a clown, and 0 otherwise. The third line contains n digits a_1 a_2 … a_n, the i-th of which is equal to 1, if the i-th artist can perform as an acrobat, and 0 otherwise. Output Print n/2 distinct integers — the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer -1. Examples Input 4 0011 0101 Output 1 4 Input 6 000000 111111 Output -1 Input 4 0011 1100 Output 4 3 Input 8 00100101 01111100 Output 1 2 3 6 Note In the first example, one of the possible divisions into two performances is as follows: in the first performance artists 1 and 4 should take part. Then the number of artists in the first performance who can perform as clowns is equal to 1. And the number of artists in the second performance who can perform as acrobats is 1 as well. In the second example, the division is not possible. In the third example, one of the possible divisions is as follows: in the first performance artists 3 and 4 should take part. Then in the first performance there are 2 artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is 2 as well. Tags: brute force, greedy, math, strings Correct Solution: ``` n = int(input()) s1 = input() s2 = input() w,x,y,z = 0,0,0,0 W,X,Y,Z = [],[],[],[] for i in range(n): s = s1[i] + s2[i] if s == '00': w += 1 W.append(i) elif s == '11': x += 1 X.append(i) elif s =='10': y += 1 Y.append(i) else: z += 1 Z.append(i) can = False res_count = [] for i in range(x+1): for j in range(n//2+1): req1,left1 = j - i, y - j + i if req1 < 0: continue if y < req1 : continue req2 = j - (x - i) left2 = z - req2 if req2 < 0 or z < req2 : continue if req2 + left1 + (x-i) > n//2 or req1 + left2 + i > n//2: continue w_req = n//2 - i - req1-left2 if w_req > w : continue res_count = [i,req1,left2] can = True break if can : break if not can: print(-1) exit(0) res = [] for i in range(res_count[0]): res.append(X[i]+1) for i in range(res_count[1]): res.append(Y[i]+1) for i in range(res_count[2]): res.append(Z[i]+1) for i in range(n//2-len(res)): res.append(W[i]+1) res.sort() print(' '.join(map(str,res))) ```
90,172
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is a head of a circus troupe. There are n — an even number — artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0). Split the artists into two performances in such a way that: * each artist plays in exactly one performance, * the number of artists in the two performances is equal (i.e. equal to n/2), * the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance. Input The first line contains a single integer n (2 ≤ n ≤ 5 000, n is even) — the number of artists in the troupe. The second line contains n digits c_1 c_2 … c_n, the i-th of which is equal to 1 if the i-th artist can perform as a clown, and 0 otherwise. The third line contains n digits a_1 a_2 … a_n, the i-th of which is equal to 1, if the i-th artist can perform as an acrobat, and 0 otherwise. Output Print n/2 distinct integers — the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer -1. Examples Input 4 0011 0101 Output 1 4 Input 6 000000 111111 Output -1 Input 4 0011 1100 Output 4 3 Input 8 00100101 01111100 Output 1 2 3 6 Note In the first example, one of the possible divisions into two performances is as follows: in the first performance artists 1 and 4 should take part. Then the number of artists in the first performance who can perform as clowns is equal to 1. And the number of artists in the second performance who can perform as acrobats is 1 as well. In the second example, the division is not possible. In the third example, one of the possible divisions is as follows: in the first performance artists 3 and 4 should take part. Then in the first performance there are 2 artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is 2 as well. Tags: brute force, greedy, math, strings Correct Solution: ``` import sys n=int(input()) s=input() s1=input() a=0 b=0 c=0 d=0 an=[] for i in range(n): if s[i]=='0' and s1[i]=='0': a+=1 elif s[i]=='1' and s1[i]=='0': b+=1 elif s[i]=='0' and s1[i]=='1': c+=1 else: d+=1 x=0 y=0 z=0 w=0 t=0 #print(a,b,c,d) for i in range(a+1): for j in range(d+1): if (n//2)-i-j==c+d-2*j and n//2-i-j>=0 and n//2-i-j<=b+c: x=i y=min(b,n//2-i-j) z=n//2-i-j-y w=j t=1 break if t==0: print(-1) sys.exit() for i in range(n): if s[i]=='0' and s1[i]=='0' and x>0: an.append(i+1) x-=1 elif s[i]=='1' and s1[i]=='0' and y>0: an.append(i+1) y-=1 elif s[i]=='0' and s1[i]=='1' and z>0: an.append(i+1) z-=1 elif s[i]=='1' and s1[i]=='1' and w>0: an.append(i+1) w-=1 print(*an,sep=" ") ```
90,173
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is a head of a circus troupe. There are n — an even number — artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0). Split the artists into two performances in such a way that: * each artist plays in exactly one performance, * the number of artists in the two performances is equal (i.e. equal to n/2), * the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance. Input The first line contains a single integer n (2 ≤ n ≤ 5 000, n is even) — the number of artists in the troupe. The second line contains n digits c_1 c_2 … c_n, the i-th of which is equal to 1 if the i-th artist can perform as a clown, and 0 otherwise. The third line contains n digits a_1 a_2 … a_n, the i-th of which is equal to 1, if the i-th artist can perform as an acrobat, and 0 otherwise. Output Print n/2 distinct integers — the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer -1. Examples Input 4 0011 0101 Output 1 4 Input 6 000000 111111 Output -1 Input 4 0011 1100 Output 4 3 Input 8 00100101 01111100 Output 1 2 3 6 Note In the first example, one of the possible divisions into two performances is as follows: in the first performance artists 1 and 4 should take part. Then the number of artists in the first performance who can perform as clowns is equal to 1. And the number of artists in the second performance who can perform as acrobats is 1 as well. In the second example, the division is not possible. In the third example, one of the possible divisions is as follows: in the first performance artists 3 and 4 should take part. Then in the first performance there are 2 artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is 2 as well. Submitted Solution: ``` import sys N = int(input()) n = N//2 A = input() B = input() C = [(a == '1') * 2 + (b == '1') for a, b in zip(A, B)] w = C.count(0) x = C.count(1) y = C.count(2) z = N - w - x - y Ans = [] for i in range(x + 1): for j in range(y + 1): z1 = (x + z - i - j) if z1 % 2: continue z1 //= 2 if not 0 <= z1 <= z: continue w1 = n - i - j - z1 if not 0 <= w1 <= w: continue cnt = [w1, i, j, z1] ans = [] for k, a, b in zip(range(1, N+1), A, B): if cnt[(a == '1') * 2 + (b == '1')] > 0: cnt[(a == '1') * 2 + (b == '1')] -= 1 Ans.append(k) print(*Ans) sys.exit() print(-1) ``` Yes
90,174
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is a head of a circus troupe. There are n — an even number — artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0). Split the artists into two performances in such a way that: * each artist plays in exactly one performance, * the number of artists in the two performances is equal (i.e. equal to n/2), * the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance. Input The first line contains a single integer n (2 ≤ n ≤ 5 000, n is even) — the number of artists in the troupe. The second line contains n digits c_1 c_2 … c_n, the i-th of which is equal to 1 if the i-th artist can perform as a clown, and 0 otherwise. The third line contains n digits a_1 a_2 … a_n, the i-th of which is equal to 1, if the i-th artist can perform as an acrobat, and 0 otherwise. Output Print n/2 distinct integers — the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer -1. Examples Input 4 0011 0101 Output 1 4 Input 6 000000 111111 Output -1 Input 4 0011 1100 Output 4 3 Input 8 00100101 01111100 Output 1 2 3 6 Note In the first example, one of the possible divisions into two performances is as follows: in the first performance artists 1 and 4 should take part. Then the number of artists in the first performance who can perform as clowns is equal to 1. And the number of artists in the second performance who can perform as acrobats is 1 as well. In the second example, the division is not possible. In the third example, one of the possible divisions is as follows: in the first performance artists 3 and 4 should take part. Then in the first performance there are 2 artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is 2 as well. Submitted Solution: ``` """ 4 0011 0101 """ def calc(s, n, d): cnts = [len(v) for v in d.values()] half = n // 2 for a in range(0, cnts[0] + 1): for b in range(0, cnts[1] + 1): c = n - 2*a - b - s d = a + s - half if 0 <= c <= cnts[2] and 0 <= d <= cnts[3] and a + b + c + d == half and b + c + 2*d == s: return True, a, b, c, d return False, def main(): n = int(input()) c_arr = list(map(int, list(input()))) a_arr = list(map(int, list(input()))) s = 0 kinds = [(0, 0), (0, 1), (1, 0), (1, 1)] d = {kind: [] for kind in kinds} for i in range(n): if a_arr[i] == 1: s += 1 d[(c_arr[i], a_arr[i])].append(i) result, *params = calc(s, n, d) if not result: print(-1) else: ans = [] for i, kind in enumerate(kinds): for j in range(params[i]): ix = d[kind][j] ans.append(str(ix + 1)) print(' '.join(ans)) if __name__ == '__main__': main() ``` Yes
90,175
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is a head of a circus troupe. There are n — an even number — artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0). Split the artists into two performances in such a way that: * each artist plays in exactly one performance, * the number of artists in the two performances is equal (i.e. equal to n/2), * the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance. Input The first line contains a single integer n (2 ≤ n ≤ 5 000, n is even) — the number of artists in the troupe. The second line contains n digits c_1 c_2 … c_n, the i-th of which is equal to 1 if the i-th artist can perform as a clown, and 0 otherwise. The third line contains n digits a_1 a_2 … a_n, the i-th of which is equal to 1, if the i-th artist can perform as an acrobat, and 0 otherwise. Output Print n/2 distinct integers — the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer -1. Examples Input 4 0011 0101 Output 1 4 Input 6 000000 111111 Output -1 Input 4 0011 1100 Output 4 3 Input 8 00100101 01111100 Output 1 2 3 6 Note In the first example, one of the possible divisions into two performances is as follows: in the first performance artists 1 and 4 should take part. Then the number of artists in the first performance who can perform as clowns is equal to 1. And the number of artists in the second performance who can perform as acrobats is 1 as well. In the second example, the division is not possible. In the third example, one of the possible divisions is as follows: in the first performance artists 3 and 4 should take part. Then in the first performance there are 2 artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is 2 as well. Submitted Solution: ``` from sys import stdin, stdout #T = int(input()) #s = input() N = int(input()) #N,K = [int(x) for x in stdin.readline().split()] #arr = [int(x) for x in stdin.readline().split()] clown = input() acro = input() clown = list(clown) acro = list(acro) k1 = 0 k2 = 0 k3 = 0 k4 = 0 for i in range(N): if clown[i]=='0' and acro[i]=='0': k1 += 1 if clown[i]=='0' and acro[i]=='1': k2 += 1 if clown[i]=='1' and acro[i]=='0': k3 += 1 if clown[i]=='1' and acro[i]=='1': k4 += 1 a = 0 b = 0 c = 0 d = 0 target = k1 + k3 - k2 - k4 if target%2==1: print(-1) quit() if target<0: a = 0 d = -target//2 else: a = target//2 d = 0 valid = 0 for i in range(10000): if a<=k1 and d<=k4: #print(a,d) # b+c = N//2 - a - d, find combination of b+c b = N//2 - a - d c = 0 while b>=0 and c>=0: if b<=k2 and c<=k3: # valid !!! #print(a,b,c,d) for j in range(N): if clown[j]=='0' and acro[j]=='0' and a>0: print(j+1,end=' ') a -= 1 if clown[j]=='0' and acro[j]=='1' and b>0: print(j+1,end=' ') b -= 1 if clown[j]=='1' and acro[j]=='0' and c>0: print(j+1,end=' ') c -= 1 if clown[j]=='1' and acro[j]=='1' and d>0: print(j+1,end=' ') d -= 1 quit() b -= 1 c += 1 else: break a += 1 d += 1 print(-1) ``` Yes
90,176
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is a head of a circus troupe. There are n — an even number — artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0). Split the artists into two performances in such a way that: * each artist plays in exactly one performance, * the number of artists in the two performances is equal (i.e. equal to n/2), * the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance. Input The first line contains a single integer n (2 ≤ n ≤ 5 000, n is even) — the number of artists in the troupe. The second line contains n digits c_1 c_2 … c_n, the i-th of which is equal to 1 if the i-th artist can perform as a clown, and 0 otherwise. The third line contains n digits a_1 a_2 … a_n, the i-th of which is equal to 1, if the i-th artist can perform as an acrobat, and 0 otherwise. Output Print n/2 distinct integers — the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer -1. Examples Input 4 0011 0101 Output 1 4 Input 6 000000 111111 Output -1 Input 4 0011 1100 Output 4 3 Input 8 00100101 01111100 Output 1 2 3 6 Note In the first example, one of the possible divisions into two performances is as follows: in the first performance artists 1 and 4 should take part. Then the number of artists in the first performance who can perform as clowns is equal to 1. And the number of artists in the second performance who can perform as acrobats is 1 as well. In the second example, the division is not possible. In the third example, one of the possible divisions is as follows: in the first performance artists 3 and 4 should take part. Then in the first performance there are 2 artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is 2 as well. Submitted Solution: ``` """ 4 0011 0101 """ def calc(s, n, d): cnts = [len(v) for v in d.values()] half = n // 2 for a in range(0, cnts[0] + 1): for b in range(0, cnts[1] + 1): c = n - 2*a - b - s d = a + s - half if 0 <= c <= cnts[2] and 0 <= d <= cnts[3] and a + b + c + d == half and b + c + 2*d == s: return True, a, b, c, d return False, def main(): n = int(input()) c_arr = list(map(int, list(input()))) a_arr = list(map(int, list(input()))) s = 0 kinds = [(0, 0), (0, 1), (1, 0), (1, 1)] d = {kind: [] for kind in kinds} for i in range(n): if a_arr[i] == 1: s += 1 d[(c_arr[i], a_arr[i])].append(i) result, *params = calc(s, n, d) if not result: print(-1) else: flags = [False] * n for i, kind in enumerate(kinds): for j in range(params[i]): ix = d[kind][j] flags[ix] = True for i in range(n): if flags[i]: print(i + 1, end=' ') if __name__ == '__main__': main() ``` Yes
90,177
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is a head of a circus troupe. There are n — an even number — artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0). Split the artists into two performances in such a way that: * each artist plays in exactly one performance, * the number of artists in the two performances is equal (i.e. equal to n/2), * the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance. Input The first line contains a single integer n (2 ≤ n ≤ 5 000, n is even) — the number of artists in the troupe. The second line contains n digits c_1 c_2 … c_n, the i-th of which is equal to 1 if the i-th artist can perform as a clown, and 0 otherwise. The third line contains n digits a_1 a_2 … a_n, the i-th of which is equal to 1, if the i-th artist can perform as an acrobat, and 0 otherwise. Output Print n/2 distinct integers — the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer -1. Examples Input 4 0011 0101 Output 1 4 Input 6 000000 111111 Output -1 Input 4 0011 1100 Output 4 3 Input 8 00100101 01111100 Output 1 2 3 6 Note In the first example, one of the possible divisions into two performances is as follows: in the first performance artists 1 and 4 should take part. Then the number of artists in the first performance who can perform as clowns is equal to 1. And the number of artists in the second performance who can perform as acrobats is 1 as well. In the second example, the division is not possible. In the third example, one of the possible divisions is as follows: in the first performance artists 3 and 4 should take part. Then in the first performance there are 2 artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is 2 as well. Submitted Solution: ``` n = int(input()) p = [[int(i), 0] for i in input()] p00 = [[], []] p01 = [[], []] p11 = [[], []] p10 = [[] ,[]] indx = 0 for i, j in enumerate(list(input())): p[i][1] = int(j) if i>=n//2: indx = 1 if p[i] == [0, 0]: p00[indx].append(i) if p[i] == [0, 1]: p01[indx].append(i) if p[i] == [1, 0]: p10[indx].append(i) if p[i] == [1, 1]: p11[indx].append(i) s1 = len(p11[0])+len(p10[0]) s2 = len(p11[1])+len(p01[1]) if s1 > s2: p00[0], p00[1] = p00[1], p00[0] p10[0], p10[1] = p10[1], p10[0] p01[0], p01[1] = p01[1], p01[0] p11[0], p11[1] = p11[1], p11[0] s1, s2 = s2, s1 for i in range(100000): while s1 <= s2-2 and len(p00[0])>0 and len(p11[1])>0: p00[1].append(p00[0].pop()) p11[0].append(p11[1].pop()) s1 = len(p11[0])+len(p10[0]) s2 = len(p11[1])+len(p01[1]) if i == 100000: print(s1,s2) while s1 < s2 and len(p01[0])>0 and len(p11[1])>0: p01[1].append(p01[0].pop()) p11[0].append(p11[1].pop()) s1 = len(p11[0])+len(p10[0]) s2 = len(p11[1])+len(p01[1]) if i == 100000: print(s1,s2) while s1 < s2 and len(p10[0])>0 and len(p11[1])>0: p10[1].append(p10[0].pop()) p11[0].append(p11[1].pop()) s1 = len(p11[0])+len(p10[0]) s2 = len(p11[1])+len(p01[1]) if i == 100000: print(s1,s2) while s1 < s2 and len(p00[0])>0 and len(p10[1])>0: p00[1].append(p00[0].pop()) p10[0].append(p10[1].pop()) s1 = len(p11[0])+len(p10[0]) s2 = len(p11[1])+len(p01[1]) if i == 100000: print(s1,s2) while s1 < s2 and len(p00[0])>0 and len(p01[1])>0: p00[1].append(p00[0].pop()) p01[0].append(p01[1].pop()) s1 = len(p11[0])+len(p10[0]) s2 = len(p11[1])+len(p01[1]) if i == 100000: print(s1,s2) if s1 > s2: p00[0], p00[1] = p00[1], p00[0] p10[0], p10[1] = p10[1], p10[0] p01[0], p01[1] = p01[1], p01[0] p11[0], p11[1] = p11[1], p11[0] s1, s2 = s2, s1 if n==5000: #pass print(s1, s2, len(p00[0]), len(p01[0]), len(p10[0]), len(p11[0]),len(p00[1]), len(p01[1]), len(p10[1]), len(p11[1])) if s1==s2: res = [] res += p00[0] res += p01[0] res += p10[0] res += p11[0] for i in res: print(i + 1, end=' ') print() import sys sys.exit(0) print(-1) ``` No
90,178
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is a head of a circus troupe. There are n — an even number — artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0). Split the artists into two performances in such a way that: * each artist plays in exactly one performance, * the number of artists in the two performances is equal (i.e. equal to n/2), * the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance. Input The first line contains a single integer n (2 ≤ n ≤ 5 000, n is even) — the number of artists in the troupe. The second line contains n digits c_1 c_2 … c_n, the i-th of which is equal to 1 if the i-th artist can perform as a clown, and 0 otherwise. The third line contains n digits a_1 a_2 … a_n, the i-th of which is equal to 1, if the i-th artist can perform as an acrobat, and 0 otherwise. Output Print n/2 distinct integers — the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer -1. Examples Input 4 0011 0101 Output 1 4 Input 6 000000 111111 Output -1 Input 4 0011 1100 Output 4 3 Input 8 00100101 01111100 Output 1 2 3 6 Note In the first example, one of the possible divisions into two performances is as follows: in the first performance artists 1 and 4 should take part. Then the number of artists in the first performance who can perform as clowns is equal to 1. And the number of artists in the second performance who can perform as acrobats is 1 as well. In the second example, the division is not possible. In the third example, one of the possible divisions is as follows: in the first performance artists 3 and 4 should take part. Then in the first performance there are 2 artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is 2 as well. Submitted Solution: ``` a,b,c=0,0,0 n,s,t=int(input()),input(),input() for i in range(n): if s[i]==t[i]: a+=1 elif s[i]=='1': c+=1 else: b+=1 if a+c<b or a+b<c or (a+c-b)%2==1: print(-1) exit(0) cnt=(a+c-b)/2 for i in range(n): if s[i]==t[i]: if cnt>0: print(i,end=" ") cnt-=1 elif s[i]==1: print(i,end=" ") ``` No
90,179
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is a head of a circus troupe. There are n — an even number — artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0). Split the artists into two performances in such a way that: * each artist plays in exactly one performance, * the number of artists in the two performances is equal (i.e. equal to n/2), * the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance. Input The first line contains a single integer n (2 ≤ n ≤ 5 000, n is even) — the number of artists in the troupe. The second line contains n digits c_1 c_2 … c_n, the i-th of which is equal to 1 if the i-th artist can perform as a clown, and 0 otherwise. The third line contains n digits a_1 a_2 … a_n, the i-th of which is equal to 1, if the i-th artist can perform as an acrobat, and 0 otherwise. Output Print n/2 distinct integers — the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer -1. Examples Input 4 0011 0101 Output 1 4 Input 6 000000 111111 Output -1 Input 4 0011 1100 Output 4 3 Input 8 00100101 01111100 Output 1 2 3 6 Note In the first example, one of the possible divisions into two performances is as follows: in the first performance artists 1 and 4 should take part. Then the number of artists in the first performance who can perform as clowns is equal to 1. And the number of artists in the second performance who can perform as acrobats is 1 as well. In the second example, the division is not possible. In the third example, one of the possible divisions is as follows: in the first performance artists 3 and 4 should take part. Then in the first performance there are 2 artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is 2 as well. Submitted Solution: ``` n=int(input()) a=input() b=input() init=sum(int(c) for c in b)-sum(int(c) for c in a) mp={-1: [], 0: [], 1: []} for i in range(n): c=int(b[i])-int(a[i]) mp[c]+=[i+1] need=n//2 ans=[] while init<0: if not mp[1]: print(-1) exit() ans+=[mp[1].pop()] need-=1 while init>0: if not mp[-1]: print(-1) exit() ans+=[mp[-1].pop()] need-=1 if need<0: print(-1) exit() if need%2>0: if not mp[0]: print(-1) exit() ans+=[mp[0].pop()] o=min(len(mp[-1]), len(mp[1])) while need>0 and o>0: ans+=[mp[-1].pop(), mp[1].pop()] need-=2 o-=1 if len(mp[0])<need: print(-1) exit() while need>0: ans+=[mp[0].pop()] need-=1 print(*ans) ``` No
90,180
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is a head of a circus troupe. There are n — an even number — artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0). Split the artists into two performances in such a way that: * each artist plays in exactly one performance, * the number of artists in the two performances is equal (i.e. equal to n/2), * the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance. Input The first line contains a single integer n (2 ≤ n ≤ 5 000, n is even) — the number of artists in the troupe. The second line contains n digits c_1 c_2 … c_n, the i-th of which is equal to 1 if the i-th artist can perform as a clown, and 0 otherwise. The third line contains n digits a_1 a_2 … a_n, the i-th of which is equal to 1, if the i-th artist can perform as an acrobat, and 0 otherwise. Output Print n/2 distinct integers — the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer -1. Examples Input 4 0011 0101 Output 1 4 Input 6 000000 111111 Output -1 Input 4 0011 1100 Output 4 3 Input 8 00100101 01111100 Output 1 2 3 6 Note In the first example, one of the possible divisions into two performances is as follows: in the first performance artists 1 and 4 should take part. Then the number of artists in the first performance who can perform as clowns is equal to 1. And the number of artists in the second performance who can perform as acrobats is 1 as well. In the second example, the division is not possible. In the third example, one of the possible divisions is as follows: in the first performance artists 3 and 4 should take part. Then in the first performance there are 2 artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is 2 as well. Submitted Solution: ``` n = int(input()) s1 = input() s2 = input() c = s1.count('1') a = s2.count('1') ca = sum(1 for i in range(n) if s1[i] == '1' and s2[i] == '1') c -= ca a -= ca if c > n//2 or a > n//2: print(-1) else: p = lambda x: print(x + 1, end=' ') v = n//2 - a # print(n, n//2, v, ca) for i in range(n): if s1[i] == s2[i]: if v > 0: v -= 1 p(i) elif s2[i] == '1': p(i) ``` No
90,181
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree (an undirected connected acyclic graph) consisting of n vertices and n - 1 edges. A number is written on each edge, each number is either 0 (let's call such edges 0-edges) or 1 (those are 1-edges). Let's call an ordered pair of vertices (x, y) (x ≠ y) valid if, while traversing the simple path from x to y, we never go through a 0-edge after going through a 1-edge. Your task is to calculate the number of valid pairs in the tree. Input The first line contains one integer n (2 ≤ n ≤ 200000) — the number of vertices in the tree. Then n - 1 lines follow, each denoting an edge of the tree. Each edge is represented by three integers x_i, y_i and c_i (1 ≤ x_i, y_i ≤ n, 0 ≤ c_i ≤ 1, x_i ≠ y_i) — the vertices connected by this edge and the number written on it, respectively. It is guaranteed that the given edges form a tree. Output Print one integer — the number of valid pairs of vertices. Example Input 7 2 1 1 3 2 0 4 2 1 5 2 0 6 7 1 7 2 1 Output 34 Note The picture corresponding to the first example: <image> Tags: dfs and similar, divide and conquer, dp, dsu, trees Correct Solution: ``` import sys input = sys.stdin.readline class DSU: # Disjoint Set Union (Union-Find) Data Structure def __init__(self, nodes): # Dictionary of parents self.p = [i for i in range(nodes)] # Dictionary of ranks self.r = [0 for i in range(nodes)] # Dictionary of sizes self.s = [1 for i in range(nodes)] def nonrecurive_get(self, u): # Returns the identifier of the set that contains u, includes path compression v = u while self.p[v] != v: v = self.p[v] while self.p[u] != u: u, self.p[u] = self.p[u], v return u def get(self, u): # Recursive Returns the identifier of the set that contains u, includes path compression if u != self.p[u]: self.p[u] = self.get(self.p[u]) return self.p[u] def union(self, u, v): # Unites the sets with identifiers u and v u = self.get(u) v = self.get(v) if u != v: if self.r[u] > self.r[v]: u, v = v, u self.p[u] = v if self.r[u] == self.r[v]: self.r[v] += 1 self.s[v] += self.s[u] def size(self, u): u = self.get(u) return self.s[u] def solve(): n = int(input()) dsus = [DSU(n), DSU(n)] for edge in range(n - 1): x, y, c = [int(s) for s in input().split(' ')] dsus[c].union(x - 1, y - 1) S = 0 for v in range(n): S += (dsus[0].size(v) * dsus[1].size(v) - 1) return S print(solve()) ```
90,182
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree (an undirected connected acyclic graph) consisting of n vertices and n - 1 edges. A number is written on each edge, each number is either 0 (let's call such edges 0-edges) or 1 (those are 1-edges). Let's call an ordered pair of vertices (x, y) (x ≠ y) valid if, while traversing the simple path from x to y, we never go through a 0-edge after going through a 1-edge. Your task is to calculate the number of valid pairs in the tree. Input The first line contains one integer n (2 ≤ n ≤ 200000) — the number of vertices in the tree. Then n - 1 lines follow, each denoting an edge of the tree. Each edge is represented by three integers x_i, y_i and c_i (1 ≤ x_i, y_i ≤ n, 0 ≤ c_i ≤ 1, x_i ≠ y_i) — the vertices connected by this edge and the number written on it, respectively. It is guaranteed that the given edges form a tree. Output Print one integer — the number of valid pairs of vertices. Example Input 7 2 1 1 3 2 0 4 2 1 5 2 0 6 7 1 7 2 1 Output 34 Note The picture corresponding to the first example: <image> Tags: dfs and similar, divide and conquer, dp, dsu, trees Correct Solution: ``` class UnionFind: def __init__(self, N): self.par = [i for i in range(N)] self.rank = [1 for i in range(N)] self.rank[0] = 0 def union(self, x, y): if not self.is_same_set(x, y): par_x = self.find_par(x) par_y = self.find_par(y) if self.rank[par_x] > self.rank[par_y]: self.rank[par_x] += self.rank[par_y] self.rank[par_y] = 0 self.par[par_y] = par_x else: self.rank[par_y] += self.rank[par_x] self.rank[par_x] = 0 self.par[par_x] = par_y def find_par(self, x): if self.par[x] == x: return x self.par[x] = self.find_par(self.par[x]) return self.par[x] def is_same_set(self, x, y): return self.find_par(x) == self.find_par(y) def size(self, x): return self.rank[self.find_par(x)] # 2 unionfind, para 0 e para 1 formando 2 florestas # lista de adj # verificar todos os componentes existentes e adicionar na resposta n * (n-1) n = int(input()) adj = [[] for i in range(n+1)] uf0 = UnionFind(n+1) uf1 = UnionFind(n+1) for i in range(n-1): x, y, c = map(int, input().split()) if c == 0: uf0.union(x, y) else: uf1.union(x, y) adj[x].append(y) adj[y].append(x) for i in range(n+1): uf0.find_par(i) uf1.find_par(i) resp = 0 for i in set(uf0.par): resp += uf0.rank[i] * (uf0.rank[i] - 1) for i in set(uf1.par): resp += uf1.rank[i] * (uf1.rank[i] - 1) # pra cada componente do 0-uf verificar se existe esse vertice na 1-uf e ele for conectado com alguém, se sim, multiplicar (n-1)*(m-1) sendo n o componente da 0-uf e m o componente da 1-f e adicionar na resposta for i in range(len(uf0.par)): if uf0.rank[uf0.find_par(i)] > 1: if uf1.rank[uf1.find_par(i)] > 1: resp += (uf0.rank[uf0.find_par(i)] - 1) * (uf1.rank[uf1.find_par(i)] - 1) print(resp) ```
90,183
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree (an undirected connected acyclic graph) consisting of n vertices and n - 1 edges. A number is written on each edge, each number is either 0 (let's call such edges 0-edges) or 1 (those are 1-edges). Let's call an ordered pair of vertices (x, y) (x ≠ y) valid if, while traversing the simple path from x to y, we never go through a 0-edge after going through a 1-edge. Your task is to calculate the number of valid pairs in the tree. Input The first line contains one integer n (2 ≤ n ≤ 200000) — the number of vertices in the tree. Then n - 1 lines follow, each denoting an edge of the tree. Each edge is represented by three integers x_i, y_i and c_i (1 ≤ x_i, y_i ≤ n, 0 ≤ c_i ≤ 1, x_i ≠ y_i) — the vertices connected by this edge and the number written on it, respectively. It is guaranteed that the given edges form a tree. Output Print one integer — the number of valid pairs of vertices. Example Input 7 2 1 1 3 2 0 4 2 1 5 2 0 6 7 1 7 2 1 Output 34 Note The picture corresponding to the first example: <image> Tags: dfs and similar, divide and conquer, dp, dsu, trees Correct Solution: ``` class Deque: def __init__(self): self.buff = [0] * 400000 self.l = 0 self.r = 0 def append(self, x): self.buff[self.r] = x self.r = self.r + 1 def popleft(self): old_left = self.l self.l = self.l + 1 return self.buff[old_left] def __bool__(self): return self.l != self.r q = Deque() def bfs(source, graph, mark, num, fcount): visited = [source] mark[source] = True q.append(source) while q: u = q.popleft() for v, c in g[u]: if c == num and not mark[v]: mark[v] = True visited.append(v) q.append(v) if len(visited) > 1: for u in visited: fcount[u] = len(visited) n = int(input()) edges = [tuple(map(int, input().split())) for _ in range(0, n - 1)] g = [[] for _ in range(0, n)] cnt = [[0 for _ in range(0, n)] for _ in range(0, 2)] for u, v, c in edges: g[u - 1].append((v - 1, c)) g[v - 1].append((u - 1, c)) res = 0 for link in range(0, 2): mark = [False] * n for u in range(0, n): if not mark[u]: bfs(u, g, mark, link, cnt[link]) res += cnt[link][u] * (cnt[link][u] - 1) for i in range(0, n): if cnt[0][i] > 0 and cnt[1][i] > 1: res += (cnt[0][i] - 1) * (cnt[1][i] - 1) print(int(res)) ```
90,184
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree (an undirected connected acyclic graph) consisting of n vertices and n - 1 edges. A number is written on each edge, each number is either 0 (let's call such edges 0-edges) or 1 (those are 1-edges). Let's call an ordered pair of vertices (x, y) (x ≠ y) valid if, while traversing the simple path from x to y, we never go through a 0-edge after going through a 1-edge. Your task is to calculate the number of valid pairs in the tree. Input The first line contains one integer n (2 ≤ n ≤ 200000) — the number of vertices in the tree. Then n - 1 lines follow, each denoting an edge of the tree. Each edge is represented by three integers x_i, y_i and c_i (1 ≤ x_i, y_i ≤ n, 0 ≤ c_i ≤ 1, x_i ≠ y_i) — the vertices connected by this edge and the number written on it, respectively. It is guaranteed that the given edges form a tree. Output Print one integer — the number of valid pairs of vertices. Example Input 7 2 1 1 3 2 0 4 2 1 5 2 0 6 7 1 7 2 1 Output 34 Note The picture corresponding to the first example: <image> Tags: dfs and similar, divide and conquer, dp, dsu, trees Correct Solution: ``` import sys;sys.setrecursionlimit(10**9) class UnionFind: def __init__(self,n): self.n=[-1]*n self.r=[0]*n self.siz=n def find_root(self,x): if self.n[x]<0: return x else: self.n[x]=self.find_root(self.n[x]) return self.n[x] def unite(self,x,y): x=self.find_root(x) y=self.find_root(y) if x==y:return elif self.r[x]>self.r[y]: self.n[x]+=self.n[y] self.n[y]=x else: self.n[y]+=self.n[x] self.n[x]=y if self.r[x]==self.r[y]: self.r[y]+=1 self.siz-=1 def root_same(self,x,y): return self.find_root(x)==self.find_root(y) def count(self,x): return -self.n[self.find_root(x)] def size(self): return self.siz n=int(input()) ouf=UnionFind(n) zuf=UnionFind(n) for _ in range(n-1): a,b,c=map(int,input().split()) a-=1 b-=1 if c==0: zuf.unite(a,b) else: ouf.unite(a,b) ans=0 for i in range(n): m=zuf.count(i) if zuf.find_root(i)==i:ans+=m*(m-1) mm=ouf.count(i) if ouf.find_root(i)==i:ans+=mm*(mm-1) ans+=(m-1)*(mm-1) print(ans) ```
90,185
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree (an undirected connected acyclic graph) consisting of n vertices and n - 1 edges. A number is written on each edge, each number is either 0 (let's call such edges 0-edges) or 1 (those are 1-edges). Let's call an ordered pair of vertices (x, y) (x ≠ y) valid if, while traversing the simple path from x to y, we never go through a 0-edge after going through a 1-edge. Your task is to calculate the number of valid pairs in the tree. Input The first line contains one integer n (2 ≤ n ≤ 200000) — the number of vertices in the tree. Then n - 1 lines follow, each denoting an edge of the tree. Each edge is represented by three integers x_i, y_i and c_i (1 ≤ x_i, y_i ≤ n, 0 ≤ c_i ≤ 1, x_i ≠ y_i) — the vertices connected by this edge and the number written on it, respectively. It is guaranteed that the given edges form a tree. Output Print one integer — the number of valid pairs of vertices. Example Input 7 2 1 1 3 2 0 4 2 1 5 2 0 6 7 1 7 2 1 Output 34 Note The picture corresponding to the first example: <image> Tags: dfs and similar, divide and conquer, dp, dsu, trees Correct Solution: ``` from collections import defaultdict def colour(a, graph, cur, i): top = set() top.add(i) while len(top): x = top.pop() a[x] = cur for y in graph[x]: if a[y] == 0: top.add(y) def colour_graph(a, graph, n): cur = 0 for i in range(1, n + 1): if a[i] or i not in graph: continue else: cur += 1 colour(a, graph, cur, i) def count(col): ans = 0 for el in col: if col[el] > 1: ans += col[el]*(col[el] - 1) return ans n = int(input()) graph0 = defaultdict(set) graph1 = defaultdict(set) vertex0 = set() a0 = [0]*(n + 1) a1 = [0]*(n + 1) for i in range(n - 1): x, y, c = map(int, input().split()) if c == 0: graph0[x].add(y) graph0[y].add(x) vertex0.add(x) vertex0.add(y) else: graph1[x].add(y) graph1[y].add(x) colour_graph(a0, graph0, n) colour_graph(a1, graph1, n) answer = 0 col0 = defaultdict(int) col1 = defaultdict(int) for i in range(n + 1): if a0[i]: col0[a0[i]] += 1 if a1[i]: col1[a1[i]] += 1 answer += count(col0) + count(col1) col = defaultdict(int) for v in vertex0: col[a1[v]] += col0[a0[v]] - 1 for el in col: if el: answer += col[el]*(col1[el] - 1) print(answer) ```
90,186
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree (an undirected connected acyclic graph) consisting of n vertices and n - 1 edges. A number is written on each edge, each number is either 0 (let's call such edges 0-edges) or 1 (those are 1-edges). Let's call an ordered pair of vertices (x, y) (x ≠ y) valid if, while traversing the simple path from x to y, we never go through a 0-edge after going through a 1-edge. Your task is to calculate the number of valid pairs in the tree. Input The first line contains one integer n (2 ≤ n ≤ 200000) — the number of vertices in the tree. Then n - 1 lines follow, each denoting an edge of the tree. Each edge is represented by three integers x_i, y_i and c_i (1 ≤ x_i, y_i ≤ n, 0 ≤ c_i ≤ 1, x_i ≠ y_i) — the vertices connected by this edge and the number written on it, respectively. It is guaranteed that the given edges form a tree. Output Print one integer — the number of valid pairs of vertices. Example Input 7 2 1 1 3 2 0 4 2 1 5 2 0 6 7 1 7 2 1 Output 34 Note The picture corresponding to the first example: <image> Tags: dfs and similar, divide and conquer, dp, dsu, trees Correct Solution: ``` n = int(input()) class UnionFind(object): def __init__(self, n): # 初始化uf数组和组数目 self.count = n self.uf = [i for i in range(n)] self.size = [1] * n # 每个联通分量的size def find(self, x): # 判断节点所属于的组 while x != self.uf[x]: self.uf[x] = self.uf[self.uf[x]] x = self.uf[x] return self.uf[x] def union(self, x, y): # 连接两个节点 x_root = self.find(x) y_root = self.find(y) if x_root == y_root: return if self.size[x_root] < self.size[y_root]: x_root, y_root = y_root, x_root self.uf[y_root] = x_root self.size[x_root] += self.size[y_root] self.size[y_root] = 0 self.count -= 1 uf0 = UnionFind(n) uf1 = UnionFind(n) for i in range(n - 1): a, b, c = [int(j) for j in input().split(' ')] if c == 0: uf0.union(a-1, b-1) else: uf1.union(a-1, b-1) res = 0 from collections import * cnt0 = Counter(uf0.find(k) for k in range(n)) cnt1 = Counter(uf1.find(k) for k in range(n)) for c0, n0 in cnt0.items(): res += n0 * (n0 - 1) for c1, n1 in cnt1.items(): res += n1 * (n1 - 1) for i in range(n): n0 = cnt0[uf0.find(i)] n1 = cnt1[uf1.find(i)] res += (n0 - 1) * (n1 - 1) print(res) """ 7 2 1 1 3 2 0 4 2 1 5 2 0 6 7 1 7 2 1 """ ```
90,187
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree (an undirected connected acyclic graph) consisting of n vertices and n - 1 edges. A number is written on each edge, each number is either 0 (let's call such edges 0-edges) or 1 (those are 1-edges). Let's call an ordered pair of vertices (x, y) (x ≠ y) valid if, while traversing the simple path from x to y, we never go through a 0-edge after going through a 1-edge. Your task is to calculate the number of valid pairs in the tree. Input The first line contains one integer n (2 ≤ n ≤ 200000) — the number of vertices in the tree. Then n - 1 lines follow, each denoting an edge of the tree. Each edge is represented by three integers x_i, y_i and c_i (1 ≤ x_i, y_i ≤ n, 0 ≤ c_i ≤ 1, x_i ≠ y_i) — the vertices connected by this edge and the number written on it, respectively. It is guaranteed that the given edges form a tree. Output Print one integer — the number of valid pairs of vertices. Example Input 7 2 1 1 3 2 0 4 2 1 5 2 0 6 7 1 7 2 1 Output 34 Note The picture corresponding to the first example: <image> Tags: dfs and similar, divide and conquer, dp, dsu, trees Correct Solution: ``` class UnionFind(): def __init__(self, n): self.n = n self.root = [-1]*(n+1) self.rnk = [0]*(n+1) def Find_Root(self, x): if(self.root[x] < 0): return x else: self.root[x] = self.Find_Root(self.root[x]) return self.root[x] def Unite(self, x, y): x = self.Find_Root(x) y = self.Find_Root(y) if(x == y): return elif(self.rnk[x] > self.rnk[y]): self.root[x] += self.root[y] self.root[y] = x else: self.root[y] += self.root[x] self.root[x] = y if(self.rnk[x] == self.rnk[y]): self.rnk[y] += 1 def isSameGroup(self, x, y): return self.Find_Root(x) == self.Find_Root(y) def Count(self, x): return -self.root[self.Find_Root(x)] import sys input = sys.stdin.readline N = int(input()) uni0 = UnionFind(N) uni1 = UnionFind(N) for _ in range(N-1): a, b, c = map(int, input().split()) if c == 0: uni0.Unite(a-1, b-1) else: uni1.Unite(a-1, b-1) g0 = {} g1 = {} for i in range(N): if uni0.Count(i) != 1: r = uni0.Find_Root(i) if not r in g0.keys(): g0[r] = [i] else: g0[r].append(i) if uni1.Count(i) != 1: r = uni1.Find_Root(i) if not r in g1.keys(): g1[r] = [i] else: g1[r].append(i) ans = 0 for v_list in g1.values(): c = 0 for n in v_list: if uni0.Count(n) == 1: c += 1 l = len(v_list) ans += c*(l-1) for v_list in g0.values(): c = 0 for n in v_list: if uni1.Count(n) != 1: r = uni1.Find_Root(n) c += len(g1[r])-1 c += len(v_list)-1 ans += len(v_list)*c print(ans) ```
90,188
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree (an undirected connected acyclic graph) consisting of n vertices and n - 1 edges. A number is written on each edge, each number is either 0 (let's call such edges 0-edges) or 1 (those are 1-edges). Let's call an ordered pair of vertices (x, y) (x ≠ y) valid if, while traversing the simple path from x to y, we never go through a 0-edge after going through a 1-edge. Your task is to calculate the number of valid pairs in the tree. Input The first line contains one integer n (2 ≤ n ≤ 200000) — the number of vertices in the tree. Then n - 1 lines follow, each denoting an edge of the tree. Each edge is represented by three integers x_i, y_i and c_i (1 ≤ x_i, y_i ≤ n, 0 ≤ c_i ≤ 1, x_i ≠ y_i) — the vertices connected by this edge and the number written on it, respectively. It is guaranteed that the given edges form a tree. Output Print one integer — the number of valid pairs of vertices. Example Input 7 2 1 1 3 2 0 4 2 1 5 2 0 6 7 1 7 2 1 Output 34 Note The picture corresponding to the first example: <image> Tags: dfs and similar, divide and conquer, dp, dsu, trees Correct Solution: ``` from collections import deque from sys import stdin def bfs(source, graph, mark, num, fcount): visited = [source] q = deque() mark[source] = True q.append(source) while q: u = q.popleft() for v in graph[u]: if not mark[v]: mark[v] = True visited.append(v) q.append(v) for u in visited: fcount[u] = len(visited) n = int(stdin.readline()) g = [[[] for _ in range(0, n)] for _ in range(0, 2)] cnt = [[0 for _ in range(0, n)] for _ in range(0, 2)] for line in stdin.readlines(): u, v, c = map(int, line.split()) g[c][u - 1].append(v - 1) g[c][v - 1].append(u - 1) res = 0 for link in range(0, 2): mark = [False] * n for u in range(0, n): if not mark[u] and len(g[link][u]) > 0: bfs(u, g[link], mark, link, cnt[link]) res += cnt[link][u] * (cnt[link][u] - 1) for i in range(0, n): if cnt[0][i] > 0 and cnt[1][i] > 1: res += (cnt[0][i] - 1) * (cnt[1][i] - 1) print(int(res)) ```
90,189
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree (an undirected connected acyclic graph) consisting of n vertices and n - 1 edges. A number is written on each edge, each number is either 0 (let's call such edges 0-edges) or 1 (those are 1-edges). Let's call an ordered pair of vertices (x, y) (x ≠ y) valid if, while traversing the simple path from x to y, we never go through a 0-edge after going through a 1-edge. Your task is to calculate the number of valid pairs in the tree. Input The first line contains one integer n (2 ≤ n ≤ 200000) — the number of vertices in the tree. Then n - 1 lines follow, each denoting an edge of the tree. Each edge is represented by three integers x_i, y_i and c_i (1 ≤ x_i, y_i ≤ n, 0 ≤ c_i ≤ 1, x_i ≠ y_i) — the vertices connected by this edge and the number written on it, respectively. It is guaranteed that the given edges form a tree. Output Print one integer — the number of valid pairs of vertices. Example Input 7 2 1 1 3 2 0 4 2 1 5 2 0 6 7 1 7 2 1 Output 34 Note The picture corresponding to the first example: <image> Submitted Solution: ``` from collections import deque from sys import stdin def bfs(source, graph, mark, fcount): visited = [source] q = deque() mark[source] = True q.append(source) while q: u = q.popleft() for v in graph[u]: if not mark[v]: mark[v] = True visited.append(v) q.append(v) for u in visited: fcount[u] = len(visited) def main(): n = int(stdin.readline()) g = [[[] for _ in range(0, n)] for _ in range(0, 2)] cnt = [[0 for _ in range(0, n)] for _ in range(0, 2)] for line in stdin.readlines(): u, v, c = map(int, line.split()) g[c][u - 1].append(v - 1) g[c][v - 1].append(u - 1) res = 0 for link in range(0, 2): mark = [False] * n for u in range(0, n): if not mark[u] and len(g[link][u]) > 0: bfs(u, g[link], mark, cnt[link]) res += cnt[link][u] * (cnt[link][u] - 1) for i in range(0, n): if cnt[0][i] > 0 and cnt[1][i] > 1: res += (cnt[0][i] - 1) * (cnt[1][i] - 1) print(int(res)) main() ``` Yes
90,190
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree (an undirected connected acyclic graph) consisting of n vertices and n - 1 edges. A number is written on each edge, each number is either 0 (let's call such edges 0-edges) or 1 (those are 1-edges). Let's call an ordered pair of vertices (x, y) (x ≠ y) valid if, while traversing the simple path from x to y, we never go through a 0-edge after going through a 1-edge. Your task is to calculate the number of valid pairs in the tree. Input The first line contains one integer n (2 ≤ n ≤ 200000) — the number of vertices in the tree. Then n - 1 lines follow, each denoting an edge of the tree. Each edge is represented by three integers x_i, y_i and c_i (1 ≤ x_i, y_i ≤ n, 0 ≤ c_i ≤ 1, x_i ≠ y_i) — the vertices connected by this edge and the number written on it, respectively. It is guaranteed that the given edges form a tree. Output Print one integer — the number of valid pairs of vertices. Example Input 7 2 1 1 3 2 0 4 2 1 5 2 0 6 7 1 7 2 1 Output 34 Note The picture corresponding to the first example: <image> Submitted Solution: ``` from collections import deque def bfs(source, graph, mark, num, fcount): visited = [source] q = deque() mark[source] = True q.append(source) while q: u = q.popleft() for v, c in g[u]: if c == num and not mark[v]: mark[v] = True visited.append(v) q.append(v) if len(visited) > 1: for u in visited: fcount[u] = len(visited) n = int(input()) edges = [tuple(map(int, input().split())) for _ in range(0, n - 1)] g = [[] for _ in range(0, n)] cnt = [[0 for _ in range(0, n)] for _ in range(0, 2)] for u, v, c in edges: g[u - 1].append((v - 1, c)) g[v - 1].append((u - 1, c)) res = 0 for link in range(0, 2): mark = [False] * n for u in range(0, n): if not mark[u]: bfs(u, g, mark, link, cnt[link]) res += cnt[link][u] * (cnt[link][u] - 1) for i in range(0, n): if cnt[0][i] > 0 and cnt[1][i] > 1: res += (cnt[0][i] - 1) * (cnt[1][i] - 1) print(int(res)) ``` Yes
90,191
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree (an undirected connected acyclic graph) consisting of n vertices and n - 1 edges. A number is written on each edge, each number is either 0 (let's call such edges 0-edges) or 1 (those are 1-edges). Let's call an ordered pair of vertices (x, y) (x ≠ y) valid if, while traversing the simple path from x to y, we never go through a 0-edge after going through a 1-edge. Your task is to calculate the number of valid pairs in the tree. Input The first line contains one integer n (2 ≤ n ≤ 200000) — the number of vertices in the tree. Then n - 1 lines follow, each denoting an edge of the tree. Each edge is represented by three integers x_i, y_i and c_i (1 ≤ x_i, y_i ≤ n, 0 ≤ c_i ≤ 1, x_i ≠ y_i) — the vertices connected by this edge and the number written on it, respectively. It is guaranteed that the given edges form a tree. Output Print one integer — the number of valid pairs of vertices. Example Input 7 2 1 1 3 2 0 4 2 1 5 2 0 6 7 1 7 2 1 Output 34 Note The picture corresponding to the first example: <image> Submitted Solution: ``` import sys input = sys.stdin.readline sys.setrecursionlimit(2*10**5) I = lambda : list(map(int,input().split())) n,=I() r=[[1 for i in range(n)],[1 for i in range(n)]] p=[[i for i in range(n)],[i for i in range(n)]] def find(x,c): if x!=p[c][x]: p[c][x]=find(p[c][x],c) return p[c][x] def union(a,b,c): x=find(a,c) y=find(b,c) mm=min(x,y) if x!=y: p[c][y]=p[c][x]=mm r[c][mm]+=r[c][max(x,y)] an=0 for i in range(n-1): a,b,c=I() union(a-1,b-1,c) vis=[0]*n cc=[] for i in range(n): s0=r[0][i] s1=r[1][i] if p[0][i]==i: an+=(s0-1)*s0 if p[1][i]==i: an+=(s1-1)*s1 an+=(r[1][find(i,1)]-1)*(r[0][find(i,0)]-1) print(an) ``` Yes
90,192
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree (an undirected connected acyclic graph) consisting of n vertices and n - 1 edges. A number is written on each edge, each number is either 0 (let's call such edges 0-edges) or 1 (those are 1-edges). Let's call an ordered pair of vertices (x, y) (x ≠ y) valid if, while traversing the simple path from x to y, we never go through a 0-edge after going through a 1-edge. Your task is to calculate the number of valid pairs in the tree. Input The first line contains one integer n (2 ≤ n ≤ 200000) — the number of vertices in the tree. Then n - 1 lines follow, each denoting an edge of the tree. Each edge is represented by three integers x_i, y_i and c_i (1 ≤ x_i, y_i ≤ n, 0 ≤ c_i ≤ 1, x_i ≠ y_i) — the vertices connected by this edge and the number written on it, respectively. It is guaranteed that the given edges form a tree. Output Print one integer — the number of valid pairs of vertices. Example Input 7 2 1 1 3 2 0 4 2 1 5 2 0 6 7 1 7 2 1 Output 34 Note The picture corresponding to the first example: <image> Submitted Solution: ``` class UnionFind: def __init__(self, N): self.par = [i for i in range(N)] self.rank = [1 for i in range(N)] self.rank[0] = 0 def union(self, x, y): if not self.is_same_set(x, y): par_x = self.find_par(x) par_y = self.find_par(y) if self.rank[par_x] > self.rank[par_y]: self.rank[par_x] += self.rank[par_y] self.rank[par_y] = 0 self.par[par_y] = par_x else: self.rank[par_y] += self.rank[par_x] self.rank[par_x] = 0 self.par[par_x] = par_y def find_par(self, x): if self.par[x] == x: return x self.par[x] = self.find_par(self.par[x]) return self.par[x] def is_same_set(self, x, y): return self.find_par(x) == self.find_par(y) def size(self, x): return self.rank[self.find_par(x)] # 2 unionfind, para 0 e para 1 formando 2 florestas # lista de adj # verificar todos os componentes existentes e adicionar na resposta n * (n-1) n = int(input()) adj = [[] for i in range(n+1)] uf0 = UnionFind(n+1) uf1 = UnionFind(n+1) for i in range(n-1): x, y, c = map(int, input().split()) if c == 0: uf0.union(x, y) else: uf1.union(x, y) adj[x].append(y) adj[y].append(x) uf0.find_par(x) uf1.find_par(y) resp = 0 resp += sum(map(lambda i: uf0.rank[i] * (uf0.rank[i] - 1), set(uf0.par))) resp += sum(map(lambda i: uf1.rank[i] * (uf1.rank[i] - 1), set(uf1.par))) # pra cada componente do 0-uf verificar se existe esse vertice na 1-uf e ele for conectado com alguém, se sim, multiplicar (n-1)*(m-1) sendo n o componente da 0-uf e m o componente da 1-f e adicionar na resposta #ja_visto = set() for i in range(len(uf0.par)): if uf0.rank[uf0.find_par(i)] > 1: #and not uf0.find_par(i) in ja_visto: #ja_visto.add(uf0.find_par(i)) if uf1.rank[uf1.find_par(i)] > 1: resp += (uf0.rank[uf0.find_par(i)] - 1) * (uf1.rank[uf1.find_par(i)] - 1) print(resp) ``` Yes
90,193
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree (an undirected connected acyclic graph) consisting of n vertices and n - 1 edges. A number is written on each edge, each number is either 0 (let's call such edges 0-edges) or 1 (those are 1-edges). Let's call an ordered pair of vertices (x, y) (x ≠ y) valid if, while traversing the simple path from x to y, we never go through a 0-edge after going through a 1-edge. Your task is to calculate the number of valid pairs in the tree. Input The first line contains one integer n (2 ≤ n ≤ 200000) — the number of vertices in the tree. Then n - 1 lines follow, each denoting an edge of the tree. Each edge is represented by three integers x_i, y_i and c_i (1 ≤ x_i, y_i ≤ n, 0 ≤ c_i ≤ 1, x_i ≠ y_i) — the vertices connected by this edge and the number written on it, respectively. It is guaranteed that the given edges form a tree. Output Print one integer — the number of valid pairs of vertices. Example Input 7 2 1 1 3 2 0 4 2 1 5 2 0 6 7 1 7 2 1 Output 34 Note The picture corresponding to the first example: <image> Submitted Solution: ``` import sys from collections import deque from types import GeneratorType input = lambda :sys.stdin.readline().rstrip() def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc n = int(input()) good_num = [0 for i in range(n + 1)] mid_num = [0 for i in range(n + 1)] tree = [[] for i in range(n + 1)] ans = [0] for i in range(n - 1): a, b, c = map(int, input().split()) tree[a].append((b, c)) tree[b].append((a, c)) root = 1 @bootstrap def dfs1(node, pa): for ch, cl in tree[node]: if ch != pa: yield dfs1(ch, node) if cl: mid_num[node] += good_num[ch] + mid_num[ch] + 1 else: good_num[node] += good_num[ch] + 1 yield 0 dfs1(root, root) @bootstrap def dfs2(node, pa, pgood, pmid): total_sub_good = good_num[node] total_sub_mid = mid_num[node] temp = ans[0] for ch, cl in tree[node]: if ch!= pa: ans[0] += good_num[ch] + mid_num[ch] if cl: ans[0] += pgood + pmid + 1 print('ch: {}, node: {}, pgood: {} , pmid: {}'.format(ch, node, pgood, pmid)) print('prev ans: {}, cur ans: {}'.format(temp, ans[0])) input() pass_down_mid = pgood + 1 pass_down_mid += total_sub_mid - mid_num[ch] yield dfs2(ch, node, 0, pass_down_mid) else: ans[0] += pgood + 1 ans[0] += total_sub_good - good_num[ch] - 1 print('ch: {}, node: {}, pgood: {} , pmid: {}'.format(ch, node, pgood, pmid)) print('prev ans: {}, cur ans: {}'.format(temp, ans[0])) input() pass_down_mid = total_sub_mid - mid_num[ch] pass_down_good = total_sub_good - good_num[ch] pass_down_good += pgood + 1 yield dfs2(ch, node,pass_down_good, pass_down_mid) yield 0 ans[0] = good_num[root] + mid_num[root] dfs2(root, root, 0,0) print(ans[0]) ``` No
90,194
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree (an undirected connected acyclic graph) consisting of n vertices and n - 1 edges. A number is written on each edge, each number is either 0 (let's call such edges 0-edges) or 1 (those are 1-edges). Let's call an ordered pair of vertices (x, y) (x ≠ y) valid if, while traversing the simple path from x to y, we never go through a 0-edge after going through a 1-edge. Your task is to calculate the number of valid pairs in the tree. Input The first line contains one integer n (2 ≤ n ≤ 200000) — the number of vertices in the tree. Then n - 1 lines follow, each denoting an edge of the tree. Each edge is represented by three integers x_i, y_i and c_i (1 ≤ x_i, y_i ≤ n, 0 ≤ c_i ≤ 1, x_i ≠ y_i) — the vertices connected by this edge and the number written on it, respectively. It is guaranteed that the given edges form a tree. Output Print one integer — the number of valid pairs of vertices. Example Input 7 2 1 1 3 2 0 4 2 1 5 2 0 6 7 1 7 2 1 Output 34 Note The picture corresponding to the first example: <image> Submitted Solution: ``` def union0(a,b): fa=find0(a) fb=find0(b) if size0[fa]>size0[fb]: size0[fa]+=size0[fb] dsu0[fb]=fa else: size0[fb]+=size0[fa] dsu0[fa]=fb def union1(a,b): fa=find1(a) fb=find1(b) if size1[fa]>size1[fb]: size1[fa]+=size1[fb] dsu1[fb]=fa else: size1[fb]+=size1[fa] dsu1[fa]=fb def find0(x): while dsu0[x]!=x: dsu0[x]=dsu0[dsu0[x]] x=dsu0[x] return x def find1(x): while dsu1[x]!=x: dsu1[x]=dsu1[dsu0[x]] x=dsu1[x] return x n=int(input()) edges=[] for i in range(n-1): a,b,c=map(int,input().split()) edges.append([c,a-1,b-1]) size0=[1]*n size1=[1]*n dsu1=[i for i in range(n)] dsu0=[i for i in range(n)] #edges.sort() ans=0 for i in range(n-1): if edges[i][0]==0: fa=find0(edges[i][1]) fb=find0(edges[i][2]) ans+=(size0[fa]*size0[fb]) union0(fa,fb) else: fa=find1(edges[i][1]) fb=find1(edges[i][2]) ans+=(size1[fa]*size1[fb]) union1(fa,fb) ans+=ans for i in range(n): f0=find0(i) f1=find1(i) ans+=((size0[f0]-1)*(size1[f1]-1)) print(ans) ``` No
90,195
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree (an undirected connected acyclic graph) consisting of n vertices and n - 1 edges. A number is written on each edge, each number is either 0 (let's call such edges 0-edges) or 1 (those are 1-edges). Let's call an ordered pair of vertices (x, y) (x ≠ y) valid if, while traversing the simple path from x to y, we never go through a 0-edge after going through a 1-edge. Your task is to calculate the number of valid pairs in the tree. Input The first line contains one integer n (2 ≤ n ≤ 200000) — the number of vertices in the tree. Then n - 1 lines follow, each denoting an edge of the tree. Each edge is represented by three integers x_i, y_i and c_i (1 ≤ x_i, y_i ≤ n, 0 ≤ c_i ≤ 1, x_i ≠ y_i) — the vertices connected by this edge and the number written on it, respectively. It is guaranteed that the given edges form a tree. Output Print one integer — the number of valid pairs of vertices. Example Input 7 2 1 1 3 2 0 4 2 1 5 2 0 6 7 1 7 2 1 Output 34 Note The picture corresponding to the first example: <image> Submitted Solution: ``` from sys import stdin, stdout n = int(stdin.readline()) g = [[] for i in range(n)] for i in range(n-1): a, b, c = map(int, stdin.readline().split()) a -= 1 b -= 1 g[a].append((b, c)) g[b].append((a, c)) dp = [[0, 0, 0] for i in range(n)] # cnt(x0), cnt(y1), cnt(0y1) def dfs(v, p): for x in g[v]: if x[0] != p: dfs(x[0], v) dp[v][x[1]] += 1 + dp[x[0]][x[1]] dfs(0, -1) def merge(v, p): for x in g[v]: if (x[0] != p): if x[1] == 0: dp[v][2] += (dp[x[0]][0] + 1) * (dp[v][1] - dp[x[0]][1]) dp[x[0]][2] += (dp[v][0] - dp[x[0]][0] - 1) * (dp[x[0]][1]) dp[x[0]][x[1]] = dp[v][x[1]] merge(x[0], v) merge(0, -1) ans = 0 for i in dp: ans += sum(i) stdout.write('%d' % ans) ``` No
90,196
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree (an undirected connected acyclic graph) consisting of n vertices and n - 1 edges. A number is written on each edge, each number is either 0 (let's call such edges 0-edges) or 1 (those are 1-edges). Let's call an ordered pair of vertices (x, y) (x ≠ y) valid if, while traversing the simple path from x to y, we never go through a 0-edge after going through a 1-edge. Your task is to calculate the number of valid pairs in the tree. Input The first line contains one integer n (2 ≤ n ≤ 200000) — the number of vertices in the tree. Then n - 1 lines follow, each denoting an edge of the tree. Each edge is represented by three integers x_i, y_i and c_i (1 ≤ x_i, y_i ≤ n, 0 ≤ c_i ≤ 1, x_i ≠ y_i) — the vertices connected by this edge and the number written on it, respectively. It is guaranteed that the given edges form a tree. Output Print one integer — the number of valid pairs of vertices. Example Input 7 2 1 1 3 2 0 4 2 1 5 2 0 6 7 1 7 2 1 Output 34 Note The picture corresponding to the first example: <image> Submitted Solution: ``` m = 200000 + 42 ker1, ker2 = [x for x in range(m)], [x for x in range(m)] cnt1, cnt2 = [1 for x in range(m)], [1 for x in range(m)] def input_t(): return [int(x) for x in input().split()] def kerik(x, p): return x if p[x] == x else kerik(p[x], p) def add(a, b, color): if color: x = kerik(a, ker1) y = kerik(b, ker1) if x != y: ker1[x] = y cnt1[y] += cnt1[x] else: x = kerik(a, ker2) y = kerik(b, ker2) if x != y: ker2[x] = y cnt2[y] += cnt2[x] n = int(input()) for _ in range(n-1): x, y, c = input_t() add(x,y, c) ans = 0 for i in range(n): if ker1[i] == i: ans += cnt1[i] * (cnt1[i] - 1) if ker2[i] == i: ans += cnt2[i] * (cnt2[i] - 1) x, y = kerik(i, ker1), kerik(i, ker2) ans += (cnt1[x] - 1) * (cnt2[y] - 1) print(ans) ``` No
90,197
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a connected undirected weighted graph consisting of n vertices and m edges. You need to print the k-th smallest shortest path in this graph (paths from the vertex to itself are not counted, paths from i to j and from j to i are counted as one). More formally, if d is the matrix of shortest paths, where d_{i, j} is the length of the shortest path between vertices i and j (1 ≤ i < j ≤ n), then you need to print the k-th element in the sorted array consisting of all d_{i, j}, where 1 ≤ i < j ≤ n. Input The first line of the input contains three integers n, m and k (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min\Big((n(n-1))/(2), 2 ⋅ 10^5\Big), 1 ≤ k ≤ min\Big((n(n-1))/(2), 400\Big) — the number of vertices in the graph, the number of edges in the graph and the value of k, correspondingly. Then m lines follow, each containing three integers x, y and w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10^9, x ≠ y) denoting an edge between vertices x and y of weight w. It is guaranteed that the given graph is connected (there is a path between any pair of vertices), there are no self-loops (edges connecting the vertex with itself) and multiple edges (for each pair of vertices x and y, there is at most one edge between this pair of vertices in the graph). Output Print one integer — the length of the k-th smallest shortest path in the given graph (paths from the vertex to itself are not counted, paths from i to j and from j to i are counted as one). Examples Input 6 10 5 2 5 1 5 3 9 6 2 2 1 3 1 5 1 8 6 5 10 1 6 5 6 4 6 3 6 2 3 4 5 Output 3 Input 7 15 18 2 6 3 5 7 4 6 5 4 3 6 9 6 7 7 1 6 4 7 1 6 7 2 1 4 3 2 3 2 8 5 3 6 2 5 5 3 7 9 4 1 8 2 1 1 Output 9 Tags: brute force, constructive algorithms, shortest paths, sortings Correct Solution: ``` import heapq n,m,k = map(int,input().split()) connectionList = [] for _ in range(n): connectionList.append([]) edgeList = [] for _ in range(m): x,y,w = map(int,input().split()) edgeList.append((x,y,w)) edgeList.sort(key = lambda x: x[2]) if k < m: maxDist = edgeList[min(m,k) - 1][2] else: maxDist = sum(map(lambda x: x[2],edgeList)) colorList = {} colorVertex = [] for i in range(n): colorList[i] = [i] colorVertex.append(i) for i in range(min(m,k)): x,y,w = edgeList[i] connectionList[x-1].append((y-1,w)) connectionList[y-1].append((x-1,w)) if colorVertex[x-1] != colorVertex[y-1]: if len(colorList[colorVertex[x-1]]) >= len(colorList[colorVertex[y-1]]): prevColor = colorVertex[y-1] for elem in colorList[colorVertex[y-1]]: colorVertex[elem] = colorVertex[x-1] colorList[colorVertex[x-1]].append(elem) del colorList[prevColor] else: prevColor = colorVertex[x-1] for elem in colorList[colorVertex[x-1]]: colorVertex[elem] = colorVertex[y-1] colorList[colorVertex[y-1]].append(elem) del colorList[prevColor] pathList = [] for key in colorList: vertexList = colorList[key] for mainVertex in vertexList: vertexPQueue = [] isCovered = {} distanceDic = {} for elem in vertexList: isCovered[elem] = False distanceDic[elem] = maxDist isCovered[mainVertex] = True for elem in connectionList[mainVertex]: heapq.heappush(vertexPQueue,(elem[1],elem[0])) distanceDic[elem[0]] = elem[1] while vertexPQueue: distance, curVertex = heapq.heappop(vertexPQueue) if isCovered[curVertex]: continue elif distance >= maxDist: break for elem in connectionList[curVertex]: if distance + elem[1] < distanceDic[elem[0]]: heapq.heappush(vertexPQueue,(distance + elem[1],elem[0])) distanceDic[elem[0]] = distance + elem[1] for key in distanceDic: if distanceDic[key] <= maxDist and key > mainVertex: pathList.append(distanceDic[key]) if len(pathList) > k: pathList.sort() pathList = pathList[0:k] if pathList[-1] < maxDist: maxDist = pathList[-1] pathList.sort() print(pathList[k-1]) ```
90,198
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a connected undirected weighted graph consisting of n vertices and m edges. You need to print the k-th smallest shortest path in this graph (paths from the vertex to itself are not counted, paths from i to j and from j to i are counted as one). More formally, if d is the matrix of shortest paths, where d_{i, j} is the length of the shortest path between vertices i and j (1 ≤ i < j ≤ n), then you need to print the k-th element in the sorted array consisting of all d_{i, j}, where 1 ≤ i < j ≤ n. Input The first line of the input contains three integers n, m and k (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min\Big((n(n-1))/(2), 2 ⋅ 10^5\Big), 1 ≤ k ≤ min\Big((n(n-1))/(2), 400\Big) — the number of vertices in the graph, the number of edges in the graph and the value of k, correspondingly. Then m lines follow, each containing three integers x, y and w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10^9, x ≠ y) denoting an edge between vertices x and y of weight w. It is guaranteed that the given graph is connected (there is a path between any pair of vertices), there are no self-loops (edges connecting the vertex with itself) and multiple edges (for each pair of vertices x and y, there is at most one edge between this pair of vertices in the graph). Output Print one integer — the length of the k-th smallest shortest path in the given graph (paths from the vertex to itself are not counted, paths from i to j and from j to i are counted as one). Examples Input 6 10 5 2 5 1 5 3 9 6 2 2 1 3 1 5 1 8 6 5 10 1 6 5 6 4 6 3 6 2 3 4 5 Output 3 Input 7 15 18 2 6 3 5 7 4 6 5 4 3 6 9 6 7 7 1 6 4 7 1 6 7 2 1 4 3 2 3 2 8 5 3 6 2 5 5 3 7 9 4 1 8 2 1 1 Output 9 Tags: brute force, constructive algorithms, shortest paths, sortings Correct Solution: ``` import sys input = sys.stdin.readline n,m,k=map(int,input().split()) EDGE=[list(map(int,input().split())) for i in range(m)] EDGE.sort(key=lambda x:x[2]) EDGE=EDGE[:k] COST_vertex=[[] for i in range(n+1)] VERLIST=[] for a,b,c in EDGE: COST_vertex[a].append((b,c)) COST_vertex[b].append((a,c)) VERLIST.append(a) VERLIST.append(b) VERLIST=sorted((set(VERLIST))) import heapq ANS=[-1<<50]*k for start in VERLIST: MINCOST=[1<<50]*(n+1) checking=[(0,start)] MINCOST[start]=0 j=0 while j<k: if not(checking): break cost,checktown=heapq.heappop(checking) if cost>=-ANS[0]: break if MINCOST[checktown]<cost: continue if cost!=0 and checktown>start: heapq.heappop(ANS) heapq.heappush(ANS,-cost) j+=1 for to,co in COST_vertex[checktown]: if MINCOST[to]>cost+co: MINCOST[to]=cost+co heapq.heappush(checking,(cost+co,to)) print(-ANS[0]) ```
90,199