text
stringlengths
198
433k
conversation_id
int64
0
109k
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You work as a system administrator in a dormitory, which has n rooms one after another along a straight hallway. Rooms are numbered from 1 to n. You have to connect all n rooms to the Internet. You can connect each room to the Internet directly, the cost of such connection for the i-th room is i coins. Some rooms also have a spot for a router. The cost of placing a router in the i-th room is also i coins. You cannot place a router in a room which does not have a spot for it. When you place a router in the room i, you connect all rooms with the numbers from max(1,~i - k) to min(n,~i + k) inclusive to the Internet, where k is the range of router. The value of k is the same for all routers. Calculate the minimum total cost of connecting all n rooms to the Internet. You can assume that the number of rooms which have a spot for a router is not greater than the number of routers you have. Input The first line of the input contains two integers n and k (1 ≤ n, k ≤ 2 ⋅ 10^5) — the number of rooms and the range of each router. The second line of the input contains one string s of length n, consisting only of zeros and ones. If the i-th character of the string equals to '1' then there is a spot for a router in the i-th room. If the i-th character of the string equals to '0' then you cannot place a router in the i-th room. Output Print one integer — the minimum total cost of connecting all n rooms to the Internet. Examples Input 5 2 00100 Output 3 Input 6 1 000000 Output 21 Input 4 1 0011 Output 4 Input 12 6 000010000100 Output 15 Note In the first example it is enough to place the router in the room 3, then all rooms will be connected to the Internet. The total cost of connection is 3. In the second example you can place routers nowhere, so you need to connect all rooms directly. Thus, the total cost of connection of all rooms is 1 + 2 + 3 + 4 + 5 + 6 = 21. In the third example you need to connect the room 1 directly and place the router in the room 3. Thus, the total cost of connection of all rooms is 1 + 3 = 4. In the fourth example you need to place routers in rooms 5 and 10. Then all rooms will be connected to the Internet. The total cost of connection is 5 + 10 = 15. Submitted Solution: ``` n, k = map(int, input().split()) s = input() inf = 10**18 who = [-1] * n for i in range(n): if s[i] == '1': for j in range(min(n - 1, i + k), i - 1, -1): if who[j] == -1: who[j] = i else: break for i in range(n): if s[i] == '1': for j in range(i - 1, max(-1, i - k - 1), -1): if who[j] == -1: who[j] = i else: break dp = [inf] * (n + 1) dp[n] = 0 for i in range(n, 0, -1): dp[i - 1] = min(dp[i - 1], dp[i] + i) if who[i - 1] != -1: dp[max(0, who[i - 1] - k)] = min(dp[max(0, who[i - 1] - k)], dp[i] + who[i - 1] + 1) print(dp[0]) ``` Yes
103,800
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You work as a system administrator in a dormitory, which has n rooms one after another along a straight hallway. Rooms are numbered from 1 to n. You have to connect all n rooms to the Internet. You can connect each room to the Internet directly, the cost of such connection for the i-th room is i coins. Some rooms also have a spot for a router. The cost of placing a router in the i-th room is also i coins. You cannot place a router in a room which does not have a spot for it. When you place a router in the room i, you connect all rooms with the numbers from max(1,~i - k) to min(n,~i + k) inclusive to the Internet, where k is the range of router. The value of k is the same for all routers. Calculate the minimum total cost of connecting all n rooms to the Internet. You can assume that the number of rooms which have a spot for a router is not greater than the number of routers you have. Input The first line of the input contains two integers n and k (1 ≤ n, k ≤ 2 ⋅ 10^5) — the number of rooms and the range of each router. The second line of the input contains one string s of length n, consisting only of zeros and ones. If the i-th character of the string equals to '1' then there is a spot for a router in the i-th room. If the i-th character of the string equals to '0' then you cannot place a router in the i-th room. Output Print one integer — the minimum total cost of connecting all n rooms to the Internet. Examples Input 5 2 00100 Output 3 Input 6 1 000000 Output 21 Input 4 1 0011 Output 4 Input 12 6 000010000100 Output 15 Note In the first example it is enough to place the router in the room 3, then all rooms will be connected to the Internet. The total cost of connection is 3. In the second example you can place routers nowhere, so you need to connect all rooms directly. Thus, the total cost of connection of all rooms is 1 + 2 + 3 + 4 + 5 + 6 = 21. In the third example you need to connect the room 1 directly and place the router in the room 3. Thus, the total cost of connection of all rooms is 1 + 3 = 4. In the fourth example you need to place routers in rooms 5 and 10. Then all rooms will be connected to the Internet. The total cost of connection is 5 + 10 = 15. Submitted Solution: ``` n,k=map(int,input().split()) s=list(input()) total=n*(n+1)//2 r=[i+1 for i in range(len(s)) if int(s[i])] c=set() for i in range(len(r)): ma=max(1,r[i]-k) mi=min(n,r[i]+k) t=set(range(ma,mi+1)) if t.intersection(c)==t: del r[i] else: c=c.union(t) for i in r: if i in s: s.remove(i) covered=sum(c) router=sum(r) print(total+router-covered) ``` No
103,801
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You work as a system administrator in a dormitory, which has n rooms one after another along a straight hallway. Rooms are numbered from 1 to n. You have to connect all n rooms to the Internet. You can connect each room to the Internet directly, the cost of such connection for the i-th room is i coins. Some rooms also have a spot for a router. The cost of placing a router in the i-th room is also i coins. You cannot place a router in a room which does not have a spot for it. When you place a router in the room i, you connect all rooms with the numbers from max(1,~i - k) to min(n,~i + k) inclusive to the Internet, where k is the range of router. The value of k is the same for all routers. Calculate the minimum total cost of connecting all n rooms to the Internet. You can assume that the number of rooms which have a spot for a router is not greater than the number of routers you have. Input The first line of the input contains two integers n and k (1 ≤ n, k ≤ 2 ⋅ 10^5) — the number of rooms and the range of each router. The second line of the input contains one string s of length n, consisting only of zeros and ones. If the i-th character of the string equals to '1' then there is a spot for a router in the i-th room. If the i-th character of the string equals to '0' then you cannot place a router in the i-th room. Output Print one integer — the minimum total cost of connecting all n rooms to the Internet. Examples Input 5 2 00100 Output 3 Input 6 1 000000 Output 21 Input 4 1 0011 Output 4 Input 12 6 000010000100 Output 15 Note In the first example it is enough to place the router in the room 3, then all rooms will be connected to the Internet. The total cost of connection is 3. In the second example you can place routers nowhere, so you need to connect all rooms directly. Thus, the total cost of connection of all rooms is 1 + 2 + 3 + 4 + 5 + 6 = 21. In the third example you need to connect the room 1 directly and place the router in the room 3. Thus, the total cost of connection of all rooms is 1 + 3 = 4. In the fourth example you need to place routers in rooms 5 and 10. Then all rooms will be connected to the Internet. The total cost of connection is 5 + 10 = 15. Submitted Solution: ``` n, k = map(int, input().split()) A = input() # n = room, k = range of router dp = [float("inf")] * (n) for j in range(n): if A[j] == '1': dp[j] = min(dp[j], j + 1) for l in range(k + 1): if j + l < n: dp[j + l] = min(dp[j + l], dp[j]) if j - l >= 0: dp[j - l] = min(dp[j - l], dp[j]) ans = 0 directly = 0 for i, x in enumerate(dp): if x > ans and x < float("inf"): ans = x if x == float("inf"): directly += i + 1 print(ans + directly) ``` No
103,802
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You work as a system administrator in a dormitory, which has n rooms one after another along a straight hallway. Rooms are numbered from 1 to n. You have to connect all n rooms to the Internet. You can connect each room to the Internet directly, the cost of such connection for the i-th room is i coins. Some rooms also have a spot for a router. The cost of placing a router in the i-th room is also i coins. You cannot place a router in a room which does not have a spot for it. When you place a router in the room i, you connect all rooms with the numbers from max(1,~i - k) to min(n,~i + k) inclusive to the Internet, where k is the range of router. The value of k is the same for all routers. Calculate the minimum total cost of connecting all n rooms to the Internet. You can assume that the number of rooms which have a spot for a router is not greater than the number of routers you have. Input The first line of the input contains two integers n and k (1 ≤ n, k ≤ 2 ⋅ 10^5) — the number of rooms and the range of each router. The second line of the input contains one string s of length n, consisting only of zeros and ones. If the i-th character of the string equals to '1' then there is a spot for a router in the i-th room. If the i-th character of the string equals to '0' then you cannot place a router in the i-th room. Output Print one integer — the minimum total cost of connecting all n rooms to the Internet. Examples Input 5 2 00100 Output 3 Input 6 1 000000 Output 21 Input 4 1 0011 Output 4 Input 12 6 000010000100 Output 15 Note In the first example it is enough to place the router in the room 3, then all rooms will be connected to the Internet. The total cost of connection is 3. In the second example you can place routers nowhere, so you need to connect all rooms directly. Thus, the total cost of connection of all rooms is 1 + 2 + 3 + 4 + 5 + 6 = 21. In the third example you need to connect the room 1 directly and place the router in the room 3. Thus, the total cost of connection of all rooms is 1 + 3 = 4. In the fourth example you need to place routers in rooms 5 and 10. Then all rooms will be connected to the Internet. The total cost of connection is 5 + 10 = 15. Submitted Solution: ``` import sys,math,itertools from collections import Counter,deque,defaultdict from bisect import bisect_left,bisect_right from heapq import heappop,heappush,heapify, nlargest from copy import deepcopy mod = 10**9+7 INF = float('inf') def inp(): return int(sys.stdin.readline()) def inpl(): return list(map(int, sys.stdin.readline().split())) def inpl_1(): return list(map(lambda x:int(x)-1, sys.stdin.readline().split())) def inps(): return sys.stdin.readline() def inpsl(x): tmp = sys.stdin.readline(); return list(tmp[:x]) def err(x): print(x); exit() ################## class Searchable_BIT(): def __init__(self,N): self.N = N self.node = [0]*(self.N+1) self.cnt = 0 def add(self,a): # 要素 x を追加 x = a self.cnt += 1 while x <= self.N: self.node[x] += 1 x += x & -x def delete(self,x): # 要素 x を削除 self.cnt -= 1 while x <= self.N: self.node[x] -= 1 x += x & -x def count(self,x): # x以下の要素数 if x==0: return 0 tmp = 0 while x > 0: tmp += self.node[x] x -= x & -x return tmp def get_maxval(self): return self.get_lower_i(self.cnt) def get_min_left(self,x): #x以上の最小の値を取得: return self.get_lower_i(self.count(x-1)+1) def get_lower_i(self,i): # i 番目に小さい要素を取得 NG = -1 OK = self.N while OK-NG > 1: mid = (OK+NG)//2 if self.count(mid) >= i: OK = mid else: NG = mid return OK # se = [1,3,5,6,9] # sbit = Searchable_BIT(100) # for i in se: sbit.add(i) # print(sbit.get_min_left(3)) #3 # print(sbit.get_min_left(4)) #5 # print(sbit.get_min_left(7)) #9 # print(sbit.get_min_left(20)) #100(max) n,k = inpl() s = [0] + inpsl(n) sbit = Searchable_BIT(n+10) for i,x in enumerate(s): if x == '1': sbit.add(i) on = [0]*(n+1) res = 0 # for i in range(1,n+1): # print(i,sbit.get_min_left(i)) for i in range(1,n+1)[::-1]: if on[i]: continue mi = sbit.get_min_left(max(1,i-k)) if mi == n+10 or i+k < mi: res += i on[i] = 1 elif mi > i: continue else: res += mi sbit.delete(mi) for j in range(max(1,mi-k),min(n+1,mi+k+1)): on[j] = 1 off = [i for i in range(1,n+1) if on[i] == 0] ofac = [0] + list(itertools.accumulate(off)) se = set() for _,i in enumerate(off): if i in se: continue mi = sbit.get_min_left(max(1,i-k)) j = bisect_right(off,mi) su = ofac[j]-ofac[_] if mi < su: res += mi for k in range(_,j): se.add(off[k]) else: res += i print(res) ``` No
103,803
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You work as a system administrator in a dormitory, which has n rooms one after another along a straight hallway. Rooms are numbered from 1 to n. You have to connect all n rooms to the Internet. You can connect each room to the Internet directly, the cost of such connection for the i-th room is i coins. Some rooms also have a spot for a router. The cost of placing a router in the i-th room is also i coins. You cannot place a router in a room which does not have a spot for it. When you place a router in the room i, you connect all rooms with the numbers from max(1,~i - k) to min(n,~i + k) inclusive to the Internet, where k is the range of router. The value of k is the same for all routers. Calculate the minimum total cost of connecting all n rooms to the Internet. You can assume that the number of rooms which have a spot for a router is not greater than the number of routers you have. Input The first line of the input contains two integers n and k (1 ≤ n, k ≤ 2 ⋅ 10^5) — the number of rooms and the range of each router. The second line of the input contains one string s of length n, consisting only of zeros and ones. If the i-th character of the string equals to '1' then there is a spot for a router in the i-th room. If the i-th character of the string equals to '0' then you cannot place a router in the i-th room. Output Print one integer — the minimum total cost of connecting all n rooms to the Internet. Examples Input 5 2 00100 Output 3 Input 6 1 000000 Output 21 Input 4 1 0011 Output 4 Input 12 6 000010000100 Output 15 Note In the first example it is enough to place the router in the room 3, then all rooms will be connected to the Internet. The total cost of connection is 3. In the second example you can place routers nowhere, so you need to connect all rooms directly. Thus, the total cost of connection of all rooms is 1 + 2 + 3 + 4 + 5 + 6 = 21. In the third example you need to connect the room 1 directly and place the router in the room 3. Thus, the total cost of connection of all rooms is 1 + 3 = 4. In the fourth example you need to place routers in rooms 5 and 10. Then all rooms will be connected to the Internet. The total cost of connection is 5 + 10 = 15. Submitted Solution: ``` a = input('').split(' ') n = int(a[0]) k = int(a[1]) a = input('') b = [0]*(n+1) su = 0 i = 0 while(i<n): if(a[i] == '1'): su = su+i+1 e = min(n-1,i+k) s = max(0,i-k) b[e+1] = b[e+1]-1 b[s] = b[s]+1 if(e < n-1): i = i+1 else: break else: i = i+1 ans = [0]*(n+2) for i in range(n+1): ans[i+1] = ans[i]+b[i] for i in range(1,n+1,1): if(ans[i] == 0): su =su+i #print(ans) print(su) ``` No
103,804
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an infinite checkered field. You should get from a square (x1; y1) to a square (x2; y2). Using the shortest path is not necessary. You can move on the field squares in four directions. That is, when you are positioned in any square, you can move to any other side-neighboring one. A square (x; y) is considered bad, if at least one of the two conditions is fulfilled: * |x + y| ≡ 0 (mod 2a), * |x - y| ≡ 0 (mod 2b). Your task is to find the minimum number of bad cells one will have to visit on the way from (x1; y1) to (x2; y2). Input The only line contains integers a, b, x1, y1, x2 and y2 — the parameters of the bad squares, the coordinates of the initial and the final squares correspondingly (2 ≤ a, b ≤ 109 and |x1|,|y1|,|x2|,|y2| ≤ 109). It is guaranteed that the initial and the final square aren't bad. Output Print a single number — the minimum number of bad cells that one will have to visit in order to travel from square (x1; y1) to square (x2; y2). Examples Input 2 2 1 0 0 1 Output 1 Input 2 2 10 11 0 1 Output 5 Input 2 4 3 -1 3 7 Output 2 Note In the third sample one of the possible paths in (3;-1)->(3;0)->(3;1)->(3;2)->(4;2)->(4;3)->(4;4)->(4;5)->(4;6)->(4;7)->(3;7). Squares (3;1) and (4;4) are bad. Tags: math Correct Solution: ``` a,b,x1,y1,x2,y2 = map(int,input().split()) a1 = x1+y1 a2 = x2+y2 b1 = x1-y1 b2 = x2-y2 ad = a2//(2*a) - a1//(2*a) bd = b2//(2*b) - b1//(2*b) print(max(abs(ad),abs(bd))) ```
103,805
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an infinite checkered field. You should get from a square (x1; y1) to a square (x2; y2). Using the shortest path is not necessary. You can move on the field squares in four directions. That is, when you are positioned in any square, you can move to any other side-neighboring one. A square (x; y) is considered bad, if at least one of the two conditions is fulfilled: * |x + y| ≡ 0 (mod 2a), * |x - y| ≡ 0 (mod 2b). Your task is to find the minimum number of bad cells one will have to visit on the way from (x1; y1) to (x2; y2). Input The only line contains integers a, b, x1, y1, x2 and y2 — the parameters of the bad squares, the coordinates of the initial and the final squares correspondingly (2 ≤ a, b ≤ 109 and |x1|,|y1|,|x2|,|y2| ≤ 109). It is guaranteed that the initial and the final square aren't bad. Output Print a single number — the minimum number of bad cells that one will have to visit in order to travel from square (x1; y1) to square (x2; y2). Examples Input 2 2 1 0 0 1 Output 1 Input 2 2 10 11 0 1 Output 5 Input 2 4 3 -1 3 7 Output 2 Note In the third sample one of the possible paths in (3;-1)->(3;0)->(3;1)->(3;2)->(4;2)->(4;3)->(4;4)->(4;5)->(4;6)->(4;7)->(3;7). Squares (3;1) and (4;4) are bad. Tags: math Correct Solution: ``` a, b, x1, y1, x2, y2 = map(int, input().split()) X1, Y1 = x1 + y1, x1 - y1 X2, Y2 = x2 + y2, x2 - y2 A, B = 2 * a, 2 * b def solve(x, y, z): if x >= 0 > y or x < 0 <= y: x = max(x, -x) y = max(y, -y) tmp = x // z - (x % z == 0) + y // z - (y % z == 0) + 1 return tmp else: if x < y: x, y = y, x tmp = x // z - (x % z == 0) - y // z - (y % z == 0) return tmp ans1 = solve(X1, X2, A) ans2 = solve(Y1, Y2, B) print(max(ans1, ans2)) ```
103,806
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an infinite checkered field. You should get from a square (x1; y1) to a square (x2; y2). Using the shortest path is not necessary. You can move on the field squares in four directions. That is, when you are positioned in any square, you can move to any other side-neighboring one. A square (x; y) is considered bad, if at least one of the two conditions is fulfilled: * |x + y| ≡ 0 (mod 2a), * |x - y| ≡ 0 (mod 2b). Your task is to find the minimum number of bad cells one will have to visit on the way from (x1; y1) to (x2; y2). Input The only line contains integers a, b, x1, y1, x2 and y2 — the parameters of the bad squares, the coordinates of the initial and the final squares correspondingly (2 ≤ a, b ≤ 109 and |x1|,|y1|,|x2|,|y2| ≤ 109). It is guaranteed that the initial and the final square aren't bad. Output Print a single number — the minimum number of bad cells that one will have to visit in order to travel from square (x1; y1) to square (x2; y2). Examples Input 2 2 1 0 0 1 Output 1 Input 2 2 10 11 0 1 Output 5 Input 2 4 3 -1 3 7 Output 2 Note In the third sample one of the possible paths in (3;-1)->(3;0)->(3;1)->(3;2)->(4;2)->(4;3)->(4;4)->(4;5)->(4;6)->(4;7)->(3;7). Squares (3;1) and (4;4) are bad. Tags: math Correct Solution: ``` a,b,x1,y1,x2,y2 = map(int,input().split()) s = abs((x1 + y1) // (2 * a) - (x2 + y2) // (2 * a)) s = max(s,abs((x1 - y1) // (2 * b) - (x2 - y2) // (2 * b))) print(s) ```
103,807
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an infinite checkered field. You should get from a square (x1; y1) to a square (x2; y2). Using the shortest path is not necessary. You can move on the field squares in four directions. That is, when you are positioned in any square, you can move to any other side-neighboring one. A square (x; y) is considered bad, if at least one of the two conditions is fulfilled: * |x + y| ≡ 0 (mod 2a), * |x - y| ≡ 0 (mod 2b). Your task is to find the minimum number of bad cells one will have to visit on the way from (x1; y1) to (x2; y2). Input The only line contains integers a, b, x1, y1, x2 and y2 — the parameters of the bad squares, the coordinates of the initial and the final squares correspondingly (2 ≤ a, b ≤ 109 and |x1|,|y1|,|x2|,|y2| ≤ 109). It is guaranteed that the initial and the final square aren't bad. Output Print a single number — the minimum number of bad cells that one will have to visit in order to travel from square (x1; y1) to square (x2; y2). Examples Input 2 2 1 0 0 1 Output 1 Input 2 2 10 11 0 1 Output 5 Input 2 4 3 -1 3 7 Output 2 Note In the third sample one of the possible paths in (3;-1)->(3;0)->(3;1)->(3;2)->(4;2)->(4;3)->(4;4)->(4;5)->(4;6)->(4;7)->(3;7). Squares (3;1) and (4;4) are bad. Tags: math Correct Solution: ``` a, b, x_1, y_1, x_2, y_2 = map(int, input().split()) a_b, a_e = (x_2 + y_2), (x_1 + y_1) b_b, b_e = (x_2 - y_2), (x_1 - y_1) if a_b > a_e: a_b, a_e = a_e, a_b if b_b > b_e: b_b, b_e = b_e, b_b if a_b % (2 * a) != 0: a_b = (a_b // (2 * a) + 1) * (2 * a) a_result, b_result = 0, 0 if a_b <= a_e: a_result = (abs(a_e - a_b) + (2 * a - 1)) // (2 * a) if b_b % (2 * b) != 0: b_b = (b_b // (2 * b) + 1) * (2 * b) if b_b <= b_e: b_result = (abs(b_e - b_b) + (2 * b - 1)) // (2 * b) print(max([a_result, b_result])) ```
103,808
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an infinite checkered field. You should get from a square (x1; y1) to a square (x2; y2). Using the shortest path is not necessary. You can move on the field squares in four directions. That is, when you are positioned in any square, you can move to any other side-neighboring one. A square (x; y) is considered bad, if at least one of the two conditions is fulfilled: * |x + y| ≡ 0 (mod 2a), * |x - y| ≡ 0 (mod 2b). Your task is to find the minimum number of bad cells one will have to visit on the way from (x1; y1) to (x2; y2). Input The only line contains integers a, b, x1, y1, x2 and y2 — the parameters of the bad squares, the coordinates of the initial and the final squares correspondingly (2 ≤ a, b ≤ 109 and |x1|,|y1|,|x2|,|y2| ≤ 109). It is guaranteed that the initial and the final square aren't bad. Output Print a single number — the minimum number of bad cells that one will have to visit in order to travel from square (x1; y1) to square (x2; y2). Examples Input 2 2 1 0 0 1 Output 1 Input 2 2 10 11 0 1 Output 5 Input 2 4 3 -1 3 7 Output 2 Note In the third sample one of the possible paths in (3;-1)->(3;0)->(3;1)->(3;2)->(4;2)->(4;3)->(4;4)->(4;5)->(4;6)->(4;7)->(3;7). Squares (3;1) and (4;4) are bad. Tags: math Correct Solution: ``` a, b, x1, y1, x2, y2 = map(int, input().split()) X1, Y1 = x1 + y1, x1 - y1 X2, Y2 = x2 + y2, x2 - y2 A, B = 2 * a, 2 * b def solve(x, y, z): if x >= 0 > y or x < 0 <= y: x = max(x, -x) y = max(y, -y) tmp = x // z + y // z + 1 return tmp else: if x < y: x, y = y, x tmp = x // z - y // z return tmp ans1 = solve(X1, X2, A) ans2 = solve(Y1, Y2, B) print(max(ans1, ans2)) ```
103,809
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an infinite checkered field. You should get from a square (x1; y1) to a square (x2; y2). Using the shortest path is not necessary. You can move on the field squares in four directions. That is, when you are positioned in any square, you can move to any other side-neighboring one. A square (x; y) is considered bad, if at least one of the two conditions is fulfilled: * |x + y| ≡ 0 (mod 2a), * |x - y| ≡ 0 (mod 2b). Your task is to find the minimum number of bad cells one will have to visit on the way from (x1; y1) to (x2; y2). Input The only line contains integers a, b, x1, y1, x2 and y2 — the parameters of the bad squares, the coordinates of the initial and the final squares correspondingly (2 ≤ a, b ≤ 109 and |x1|,|y1|,|x2|,|y2| ≤ 109). It is guaranteed that the initial and the final square aren't bad. Output Print a single number — the minimum number of bad cells that one will have to visit in order to travel from square (x1; y1) to square (x2; y2). Examples Input 2 2 1 0 0 1 Output 1 Input 2 2 10 11 0 1 Output 5 Input 2 4 3 -1 3 7 Output 2 Note In the third sample one of the possible paths in (3;-1)->(3;0)->(3;1)->(3;2)->(4;2)->(4;3)->(4;4)->(4;5)->(4;6)->(4;7)->(3;7). Squares (3;1) and (4;4) are bad. Tags: math Correct Solution: ``` #!/usr/bin/python3 def cds(a, b, x, y): return (x + y) // (2 * a), (x - y) // (2 * b) def norm(x, y): return max(x, y) a, b, x1, y1, x2, y2 = map(int, input().split()) xp1, yp1 = cds(a, b, x1, y1) xp2, yp2 = cds(a, b, x2, y2) print(norm(abs(xp1 - xp2), abs(yp1 - yp2))) ```
103,810
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an infinite checkered field. You should get from a square (x1; y1) to a square (x2; y2). Using the shortest path is not necessary. You can move on the field squares in four directions. That is, when you are positioned in any square, you can move to any other side-neighboring one. A square (x; y) is considered bad, if at least one of the two conditions is fulfilled: * |x + y| ≡ 0 (mod 2a), * |x - y| ≡ 0 (mod 2b). Your task is to find the minimum number of bad cells one will have to visit on the way from (x1; y1) to (x2; y2). Input The only line contains integers a, b, x1, y1, x2 and y2 — the parameters of the bad squares, the coordinates of the initial and the final squares correspondingly (2 ≤ a, b ≤ 109 and |x1|,|y1|,|x2|,|y2| ≤ 109). It is guaranteed that the initial and the final square aren't bad. Output Print a single number — the minimum number of bad cells that one will have to visit in order to travel from square (x1; y1) to square (x2; y2). Examples Input 2 2 1 0 0 1 Output 1 Input 2 2 10 11 0 1 Output 5 Input 2 4 3 -1 3 7 Output 2 Note In the third sample one of the possible paths in (3;-1)->(3;0)->(3;1)->(3;2)->(4;2)->(4;3)->(4;4)->(4;5)->(4;6)->(4;7)->(3;7). Squares (3;1) and (4;4) are bad. Submitted Solution: ``` a,b,x1,y1,x2,y2 = map(int,input().split()) s = (x1 + y1) // (2 * a) - (x2 + y2) // (2 * a) s += (x1 - y1) // (2 * b) - (x2 - y2) // (2 * b) print(s) ``` No
103,811
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an infinite checkered field. You should get from a square (x1; y1) to a square (x2; y2). Using the shortest path is not necessary. You can move on the field squares in four directions. That is, when you are positioned in any square, you can move to any other side-neighboring one. A square (x; y) is considered bad, if at least one of the two conditions is fulfilled: * |x + y| ≡ 0 (mod 2a), * |x - y| ≡ 0 (mod 2b). Your task is to find the minimum number of bad cells one will have to visit on the way from (x1; y1) to (x2; y2). Input The only line contains integers a, b, x1, y1, x2 and y2 — the parameters of the bad squares, the coordinates of the initial and the final squares correspondingly (2 ≤ a, b ≤ 109 and |x1|,|y1|,|x2|,|y2| ≤ 109). It is guaranteed that the initial and the final square aren't bad. Output Print a single number — the minimum number of bad cells that one will have to visit in order to travel from square (x1; y1) to square (x2; y2). Examples Input 2 2 1 0 0 1 Output 1 Input 2 2 10 11 0 1 Output 5 Input 2 4 3 -1 3 7 Output 2 Note In the third sample one of the possible paths in (3;-1)->(3;0)->(3;1)->(3;2)->(4;2)->(4;3)->(4;4)->(4;5)->(4;6)->(4;7)->(3;7). Squares (3;1) and (4;4) are bad. Submitted Solution: ``` a,b,x1,y1,x2,y2 = map(int,input().split()) s = (x1 + y1) // (2 * a) - (x2 + y2) // (2 * a) s = max(s,(x1 - y1) // (2 * b) - (x2 - y2) // (2 * b)) print(s) ``` No
103,812
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an infinite checkered field. You should get from a square (x1; y1) to a square (x2; y2). Using the shortest path is not necessary. You can move on the field squares in four directions. That is, when you are positioned in any square, you can move to any other side-neighboring one. A square (x; y) is considered bad, if at least one of the two conditions is fulfilled: * |x + y| ≡ 0 (mod 2a), * |x - y| ≡ 0 (mod 2b). Your task is to find the minimum number of bad cells one will have to visit on the way from (x1; y1) to (x2; y2). Input The only line contains integers a, b, x1, y1, x2 and y2 — the parameters of the bad squares, the coordinates of the initial and the final squares correspondingly (2 ≤ a, b ≤ 109 and |x1|,|y1|,|x2|,|y2| ≤ 109). It is guaranteed that the initial and the final square aren't bad. Output Print a single number — the minimum number of bad cells that one will have to visit in order to travel from square (x1; y1) to square (x2; y2). Examples Input 2 2 1 0 0 1 Output 1 Input 2 2 10 11 0 1 Output 5 Input 2 4 3 -1 3 7 Output 2 Note In the third sample one of the possible paths in (3;-1)->(3;0)->(3;1)->(3;2)->(4;2)->(4;3)->(4;4)->(4;5)->(4;6)->(4;7)->(3;7). Squares (3;1) and (4;4) are bad. Submitted Solution: ``` a, b, x_1, y_1, x_2, y_2 = map(int, input().split()) print(max([(abs((x_2 + y_2) - (x_1 + y_1)) + (2 * a - 1)) // (2 * a), (abs((x_2 - y_2) - (x_1 - y_2)) + (2 * b - 1)) // (2 * b)])) ``` No
103,813
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an infinite checkered field. You should get from a square (x1; y1) to a square (x2; y2). Using the shortest path is not necessary. You can move on the field squares in four directions. That is, when you are positioned in any square, you can move to any other side-neighboring one. A square (x; y) is considered bad, if at least one of the two conditions is fulfilled: * |x + y| ≡ 0 (mod 2a), * |x - y| ≡ 0 (mod 2b). Your task is to find the minimum number of bad cells one will have to visit on the way from (x1; y1) to (x2; y2). Input The only line contains integers a, b, x1, y1, x2 and y2 — the parameters of the bad squares, the coordinates of the initial and the final squares correspondingly (2 ≤ a, b ≤ 109 and |x1|,|y1|,|x2|,|y2| ≤ 109). It is guaranteed that the initial and the final square aren't bad. Output Print a single number — the minimum number of bad cells that one will have to visit in order to travel from square (x1; y1) to square (x2; y2). Examples Input 2 2 1 0 0 1 Output 1 Input 2 2 10 11 0 1 Output 5 Input 2 4 3 -1 3 7 Output 2 Note In the third sample one of the possible paths in (3;-1)->(3;0)->(3;1)->(3;2)->(4;2)->(4;3)->(4;4)->(4;5)->(4;6)->(4;7)->(3;7). Squares (3;1) and (4;4) are bad. Submitted Solution: ``` a, b, x_1, y_1, x_2, y_2 = map(int, input().split()) print(max([abs((x_2 + y_2) - (x_1 + y_1)) // (2 * a), abs((x_2 - y_2) - (x_1 - y_2)) // (2 * b)])) ``` No
103,814
Provide tags and a correct Python 3 solution for this coding contest problem. Everyone knows that hobbits love to organize all sorts of parties and celebrations. There are n hobbits living in the Shire. They decided to organize the Greatest Party (GP) that would last for several days. Next day the hobbits wrote a guest list, some non-empty set containing all the inhabitants of the Shire. To ensure that everybody enjoy themselves and nobody gets bored, for any two days (say, days A and B) of the GP there existed at least one hobbit, invited to come on day A and on day B. However, to ensure that nobody has a row, for any three different days A, B, C there shouldn't be a hobbit invited on days A, B and C. The Shire inhabitants are keen on keeping the GP going for as long as possible. Your task is given number n, to indicate the GP's maximum duration and the guest lists for each day. Input The first line contains an integer n (3 ≤ n ≤ 10000), representing the number of hobbits. Output In the first output line print a number k — the maximum duration of GP in days. Then on k lines print the guest lists, (the guests should be separated by spaces). Print each guest list on the single line. Each list can contain an arbitrary positive number of hobbits. The hobbits are numbered with integers from 1 to n. Examples Input 4 Output 3 1 2 1 3 2 3 Input 5 Output 3 1 2 1 3 2 3 Tags: constructive algorithms, greedy Correct Solution: ``` ''' Author : thekushalghosh Team : CodeDiggers ''' n = int(input()) q = int(0.5 + (1 + 8*n)**0.5 / 2) w = 1 qw = [[] for _ in range(q)] for i in range(q): j = i + 1 while len(qw[i]) < q - 1: qw[i].append(str(w)) qw[j].append(str(w)) w = w + 1 j = j + 1 print(q) for q in qw: print(" ".join(q)) ```
103,815
Provide tags and a correct Python 3 solution for this coding contest problem. Everyone knows that hobbits love to organize all sorts of parties and celebrations. There are n hobbits living in the Shire. They decided to organize the Greatest Party (GP) that would last for several days. Next day the hobbits wrote a guest list, some non-empty set containing all the inhabitants of the Shire. To ensure that everybody enjoy themselves and nobody gets bored, for any two days (say, days A and B) of the GP there existed at least one hobbit, invited to come on day A and on day B. However, to ensure that nobody has a row, for any three different days A, B, C there shouldn't be a hobbit invited on days A, B and C. The Shire inhabitants are keen on keeping the GP going for as long as possible. Your task is given number n, to indicate the GP's maximum duration and the guest lists for each day. Input The first line contains an integer n (3 ≤ n ≤ 10000), representing the number of hobbits. Output In the first output line print a number k — the maximum duration of GP in days. Then on k lines print the guest lists, (the guests should be separated by spaces). Print each guest list on the single line. Each list can contain an arbitrary positive number of hobbits. The hobbits are numbered with integers from 1 to n. Examples Input 4 Output 3 1 2 1 3 2 3 Input 5 Output 3 1 2 1 3 2 3 Tags: constructive algorithms, greedy Correct Solution: ``` n=int(input()) res=1 while((res*(res+1)//2)<=n):res+=1 ns=[[] for _ in range(res+1)] cur=1 for i in range(1,res+1): for j in range(i+1,res+1): ns[i].append(cur) ns[j].append(cur) cur+=1 print(res) for e in ns[1:]: print(*e) ```
103,816
Provide tags and a correct Python 3 solution for this coding contest problem. Everyone knows that hobbits love to organize all sorts of parties and celebrations. There are n hobbits living in the Shire. They decided to organize the Greatest Party (GP) that would last for several days. Next day the hobbits wrote a guest list, some non-empty set containing all the inhabitants of the Shire. To ensure that everybody enjoy themselves and nobody gets bored, for any two days (say, days A and B) of the GP there existed at least one hobbit, invited to come on day A and on day B. However, to ensure that nobody has a row, for any three different days A, B, C there shouldn't be a hobbit invited on days A, B and C. The Shire inhabitants are keen on keeping the GP going for as long as possible. Your task is given number n, to indicate the GP's maximum duration and the guest lists for each day. Input The first line contains an integer n (3 ≤ n ≤ 10000), representing the number of hobbits. Output In the first output line print a number k — the maximum duration of GP in days. Then on k lines print the guest lists, (the guests should be separated by spaces). Print each guest list on the single line. Each list can contain an arbitrary positive number of hobbits. The hobbits are numbered with integers from 1 to n. Examples Input 4 Output 3 1 2 1 3 2 3 Input 5 Output 3 1 2 1 3 2 3 Tags: constructive algorithms, greedy Correct Solution: ``` n=int(input()) x=1 while x*(x-1)//2<=n: x+=1 x-=1 print(x) z=x*(x-1)//2 a=[] z=0 for i in range(x-1): a.append(z-i+1) z+=x-i for i in range(x): j=i for k in range(i): print(a[k],end=' ') a[k]+=1 j=a[i] if i!=x-1 else 0 for k in range(x-1-i): print(j,end=' ') j+=1 print() ```
103,817
Provide tags and a correct Python 3 solution for this coding contest problem. Everyone knows that hobbits love to organize all sorts of parties and celebrations. There are n hobbits living in the Shire. They decided to organize the Greatest Party (GP) that would last for several days. Next day the hobbits wrote a guest list, some non-empty set containing all the inhabitants of the Shire. To ensure that everybody enjoy themselves and nobody gets bored, for any two days (say, days A and B) of the GP there existed at least one hobbit, invited to come on day A and on day B. However, to ensure that nobody has a row, for any three different days A, B, C there shouldn't be a hobbit invited on days A, B and C. The Shire inhabitants are keen on keeping the GP going for as long as possible. Your task is given number n, to indicate the GP's maximum duration and the guest lists for each day. Input The first line contains an integer n (3 ≤ n ≤ 10000), representing the number of hobbits. Output In the first output line print a number k — the maximum duration of GP in days. Then on k lines print the guest lists, (the guests should be separated by spaces). Print each guest list on the single line. Each list can contain an arbitrary positive number of hobbits. The hobbits are numbered with integers from 1 to n. Examples Input 4 Output 3 1 2 1 3 2 3 Input 5 Output 3 1 2 1 3 2 3 Tags: constructive algorithms, greedy Correct Solution: ``` n = int(input()) d = int(0.5 + (1 + 8*n)**0.5 / 2) curr = 1 res = [[] for _ in range(d)] for i in range(d): j = i + 1 while len(res[i]) < d - 1: res[i].append(str(curr)) res[j].append(str(curr)) curr += 1 j += 1 print(d) for l in res: print(' '.join(l)) ```
103,818
Provide tags and a correct Python 3 solution for this coding contest problem. Everyone knows that hobbits love to organize all sorts of parties and celebrations. There are n hobbits living in the Shire. They decided to organize the Greatest Party (GP) that would last for several days. Next day the hobbits wrote a guest list, some non-empty set containing all the inhabitants of the Shire. To ensure that everybody enjoy themselves and nobody gets bored, for any two days (say, days A and B) of the GP there existed at least one hobbit, invited to come on day A and on day B. However, to ensure that nobody has a row, for any three different days A, B, C there shouldn't be a hobbit invited on days A, B and C. The Shire inhabitants are keen on keeping the GP going for as long as possible. Your task is given number n, to indicate the GP's maximum duration and the guest lists for each day. Input The first line contains an integer n (3 ≤ n ≤ 10000), representing the number of hobbits. Output In the first output line print a number k — the maximum duration of GP in days. Then on k lines print the guest lists, (the guests should be separated by spaces). Print each guest list on the single line. Each list can contain an arbitrary positive number of hobbits. The hobbits are numbered with integers from 1 to n. Examples Input 4 Output 3 1 2 1 3 2 3 Input 5 Output 3 1 2 1 3 2 3 Tags: constructive algorithms, greedy Correct Solution: ``` N = int(input()) k = 1 while 1: if k * (k - 1) // 2 > N: k -= 1 print(k) D = [[]] for i in range (k): D.append ([]) p = 1 for i in range(k): for j in range(i + 1, k): D[i].append (p) D [j].append (p) p += 1 for i in D: for j in i: print (j, end = ' ') print () break else: k += 1 ```
103,819
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Everyone knows that hobbits love to organize all sorts of parties and celebrations. There are n hobbits living in the Shire. They decided to organize the Greatest Party (GP) that would last for several days. Next day the hobbits wrote a guest list, some non-empty set containing all the inhabitants of the Shire. To ensure that everybody enjoy themselves and nobody gets bored, for any two days (say, days A and B) of the GP there existed at least one hobbit, invited to come on day A and on day B. However, to ensure that nobody has a row, for any three different days A, B, C there shouldn't be a hobbit invited on days A, B and C. The Shire inhabitants are keen on keeping the GP going for as long as possible. Your task is given number n, to indicate the GP's maximum duration and the guest lists for each day. Input The first line contains an integer n (3 ≤ n ≤ 10000), representing the number of hobbits. Output In the first output line print a number k — the maximum duration of GP in days. Then on k lines print the guest lists, (the guests should be separated by spaces). Print each guest list on the single line. Each list can contain an arbitrary positive number of hobbits. The hobbits are numbered with integers from 1 to n. Examples Input 4 Output 3 1 2 1 3 2 3 Input 5 Output 3 1 2 1 3 2 3 Submitted Solution: ``` n = int(input()) a = n//36 b = (n-a*36)//3 rem = (n-a*36)%3 if(rem==2): b+=1 print(a,b) ``` No
103,820
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Everyone knows that hobbits love to organize all sorts of parties and celebrations. There are n hobbits living in the Shire. They decided to organize the Greatest Party (GP) that would last for several days. Next day the hobbits wrote a guest list, some non-empty set containing all the inhabitants of the Shire. To ensure that everybody enjoy themselves and nobody gets bored, for any two days (say, days A and B) of the GP there existed at least one hobbit, invited to come on day A and on day B. However, to ensure that nobody has a row, for any three different days A, B, C there shouldn't be a hobbit invited on days A, B and C. The Shire inhabitants are keen on keeping the GP going for as long as possible. Your task is given number n, to indicate the GP's maximum duration and the guest lists for each day. Input The first line contains an integer n (3 ≤ n ≤ 10000), representing the number of hobbits. Output In the first output line print a number k — the maximum duration of GP in days. Then on k lines print the guest lists, (the guests should be separated by spaces). Print each guest list on the single line. Each list can contain an arbitrary positive number of hobbits. The hobbits are numbered with integers from 1 to n. Examples Input 4 Output 3 1 2 1 3 2 3 Input 5 Output 3 1 2 1 3 2 3 Submitted Solution: ``` n=int(input()) n=n-n%3 count=1 print(n) for i in range(1,n): if count%4!=0: for j in range(1,3): if count%4==0: break print(i,"",i+j) count=count+1 else: count=count+1 ``` No
103,821
Provide tags and a correct Python 3 solution for this coding contest problem. Welcome! Everything is fine. You have arrived in The Medium Place, the place between The Good Place and The Bad Place. You are assigned a task that will either make people happier or torture them for eternity. You have a list of k pairs of people who have arrived in a new inhabited neighborhood. You need to assign each of the 2k people into one of the 2k houses. Each person will be the resident of exactly one house, and each house will have exactly one resident. Of course, in the neighborhood, it is possible to visit friends. There are 2k - 1 roads, each of which connects two houses. It takes some time to traverse a road. We will specify the amount of time it takes in the input. The neighborhood is designed in such a way that from anyone's house, there is exactly one sequence of distinct roads you can take to any other house. In other words, the graph with the houses as vertices and the roads as edges is a tree. The truth is, these k pairs of people are actually soulmates. We index them from 1 to k. We denote by f(i) the amount of time it takes for the i-th pair of soulmates to go to each other's houses. As we have said before, you will need to assign each of the 2k people into one of the 2k houses. You have two missions, one from the entities in The Good Place and one from the entities of The Bad Place. Here they are: * The first mission, from The Good Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is minimized. Let's define this minimized sum as G. This makes sure that soulmates can easily and efficiently visit each other; * The second mission, from The Bad Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is maximized. Let's define this maximized sum as B. This makes sure that soulmates will have a difficult time to visit each other. What are the values of G and B? Input The first line of input contains a single integer t (1 ≤ t ≤ 500) denoting the number of test cases. The next lines contain descriptions of the test cases. The first line of each test case contains a single integer k denoting the number of pairs of people (1 ≤ k ≤ 10^5). The next 2k - 1 lines describe the roads; the i-th of them contains three space-separated integers a_i, b_i, t_i which means that the i-th road connects the a_i-th and b_i-th houses with a road that takes t_i units of time to traverse (1 ≤ a_i, b_i ≤ 2k, a_i ≠ b_i, 1 ≤ t_i ≤ 10^6). It is guaranteed that the given roads define a tree structure. It is guaranteed that the sum of the k in a single file is at most 3 ⋅ 10^5. Output For each test case, output a single line containing two space-separated integers G and B. Example Input 2 3 1 2 3 3 2 4 2 4 3 4 5 6 5 6 5 2 1 2 1 1 3 2 1 4 3 Output 15 33 6 6 Note For the sample test case, we have a minimum sum equal to G = 15. One way this can be achieved is with the following assignment: * The first pair of people get assigned to houses 5 and 6, giving us f(1) = 5; * The second pair of people get assigned to houses 1 and 4, giving us f(2) = 6; * The third pair of people get assigned to houses 3 and 2, giving us f(3) = 4. Note that the sum of the f(i) is 5 + 6 + 4 = 15. We also have a maximum sum equal to B = 33. One way this can be achieved is with the following assignment: * The first pair of people get assigned to houses 1 and 4, giving us f(1) = 6; * The second pair of people get assigned to houses 6 and 2, giving us f(2) = 14; * The third pair of people get assigned to houses 3 and 5, giving us f(3) = 13. Note that the sum of the f(i) is 6 + 14 + 13 = 33. Tags: dfs and similar, graphs, greedy, trees Correct Solution: ``` def main(): import sys input = sys.stdin.buffer.readline t = int(input()) for _ in range(t): K = int(input()) N = 2*K adj = [[] for _ in range(N+1)] edge = [] for _ in range(N-1): a, b, t = map(int, input().split()) adj[a].append((b, t)) adj[b].append((a, t)) st = [1] seen = [0] * (N+1) seen[1] = 1 par_t = [0] * (N+1) child = [[] for _ in range(N+1)] seq = [] while st: v = st.pop() seq.append(v) for u, t in adj[v]: if not seen[u]: seen[u] = 1 st.append(u) par_t[u] = t child[v].append(u) seq.reverse() G = B = 0 dp = [1] * (N+1) for v in seq: for u in child[v]: dp[v] += dp[u] m = min(dp[v], N - dp[v]) G += par_t[v] * (m % 2) B += par_t[v] * m print(G, B) if __name__ == '__main__': main() ```
103,822
Provide tags and a correct Python 3 solution for this coding contest problem. Welcome! Everything is fine. You have arrived in The Medium Place, the place between The Good Place and The Bad Place. You are assigned a task that will either make people happier or torture them for eternity. You have a list of k pairs of people who have arrived in a new inhabited neighborhood. You need to assign each of the 2k people into one of the 2k houses. Each person will be the resident of exactly one house, and each house will have exactly one resident. Of course, in the neighborhood, it is possible to visit friends. There are 2k - 1 roads, each of which connects two houses. It takes some time to traverse a road. We will specify the amount of time it takes in the input. The neighborhood is designed in such a way that from anyone's house, there is exactly one sequence of distinct roads you can take to any other house. In other words, the graph with the houses as vertices and the roads as edges is a tree. The truth is, these k pairs of people are actually soulmates. We index them from 1 to k. We denote by f(i) the amount of time it takes for the i-th pair of soulmates to go to each other's houses. As we have said before, you will need to assign each of the 2k people into one of the 2k houses. You have two missions, one from the entities in The Good Place and one from the entities of The Bad Place. Here they are: * The first mission, from The Good Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is minimized. Let's define this minimized sum as G. This makes sure that soulmates can easily and efficiently visit each other; * The second mission, from The Bad Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is maximized. Let's define this maximized sum as B. This makes sure that soulmates will have a difficult time to visit each other. What are the values of G and B? Input The first line of input contains a single integer t (1 ≤ t ≤ 500) denoting the number of test cases. The next lines contain descriptions of the test cases. The first line of each test case contains a single integer k denoting the number of pairs of people (1 ≤ k ≤ 10^5). The next 2k - 1 lines describe the roads; the i-th of them contains three space-separated integers a_i, b_i, t_i which means that the i-th road connects the a_i-th and b_i-th houses with a road that takes t_i units of time to traverse (1 ≤ a_i, b_i ≤ 2k, a_i ≠ b_i, 1 ≤ t_i ≤ 10^6). It is guaranteed that the given roads define a tree structure. It is guaranteed that the sum of the k in a single file is at most 3 ⋅ 10^5. Output For each test case, output a single line containing two space-separated integers G and B. Example Input 2 3 1 2 3 3 2 4 2 4 3 4 5 6 5 6 5 2 1 2 1 1 3 2 1 4 3 Output 15 33 6 6 Note For the sample test case, we have a minimum sum equal to G = 15. One way this can be achieved is with the following assignment: * The first pair of people get assigned to houses 5 and 6, giving us f(1) = 5; * The second pair of people get assigned to houses 1 and 4, giving us f(2) = 6; * The third pair of people get assigned to houses 3 and 2, giving us f(3) = 4. Note that the sum of the f(i) is 5 + 6 + 4 = 15. We also have a maximum sum equal to B = 33. One way this can be achieved is with the following assignment: * The first pair of people get assigned to houses 1 and 4, giving us f(1) = 6; * The second pair of people get assigned to houses 6 and 2, giving us f(2) = 14; * The third pair of people get assigned to houses 3 and 5, giving us f(3) = 13. Note that the sum of the f(i) is 6 + 14 + 13 = 33. Tags: dfs and similar, graphs, greedy, trees Correct Solution: ``` import sys def input(): return sys.stdin.readline().strip() def solve(): k = int(input()) n = 2*k e = [[] for i in range(n)] p = [None]*(n) for i in range(n-1): a, b, t = map(int, input().split()) a -= 1 b -= 1 e[a].append((b,t)) e[b].append((a,t)) q = [0] qi = 0 while qi < len(q): x = q[qi] qi += 1 px = p[x] for v, w in e[x]: if v != px: q.append(v) p[v] = x d1 = [False] * n d2 = [0] * n m = 0 M = 0 for qi in range(len(q)-1,-1,-1): x = q[qi] px = p[x] cnt = 1 c1 = 1 for v, w in e[x]: if v != px: if d1[v]: m += w cnt += 1 dv = d2[v] M += w * min(dv, n - dv) c1 += dv d1[x] = cnt % 2 d2[x] = c1 print(m, M) for i in range(int(input())): solve() ```
103,823
Provide tags and a correct Python 3 solution for this coding contest problem. Welcome! Everything is fine. You have arrived in The Medium Place, the place between The Good Place and The Bad Place. You are assigned a task that will either make people happier or torture them for eternity. You have a list of k pairs of people who have arrived in a new inhabited neighborhood. You need to assign each of the 2k people into one of the 2k houses. Each person will be the resident of exactly one house, and each house will have exactly one resident. Of course, in the neighborhood, it is possible to visit friends. There are 2k - 1 roads, each of which connects two houses. It takes some time to traverse a road. We will specify the amount of time it takes in the input. The neighborhood is designed in such a way that from anyone's house, there is exactly one sequence of distinct roads you can take to any other house. In other words, the graph with the houses as vertices and the roads as edges is a tree. The truth is, these k pairs of people are actually soulmates. We index them from 1 to k. We denote by f(i) the amount of time it takes for the i-th pair of soulmates to go to each other's houses. As we have said before, you will need to assign each of the 2k people into one of the 2k houses. You have two missions, one from the entities in The Good Place and one from the entities of The Bad Place. Here they are: * The first mission, from The Good Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is minimized. Let's define this minimized sum as G. This makes sure that soulmates can easily and efficiently visit each other; * The second mission, from The Bad Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is maximized. Let's define this maximized sum as B. This makes sure that soulmates will have a difficult time to visit each other. What are the values of G and B? Input The first line of input contains a single integer t (1 ≤ t ≤ 500) denoting the number of test cases. The next lines contain descriptions of the test cases. The first line of each test case contains a single integer k denoting the number of pairs of people (1 ≤ k ≤ 10^5). The next 2k - 1 lines describe the roads; the i-th of them contains three space-separated integers a_i, b_i, t_i which means that the i-th road connects the a_i-th and b_i-th houses with a road that takes t_i units of time to traverse (1 ≤ a_i, b_i ≤ 2k, a_i ≠ b_i, 1 ≤ t_i ≤ 10^6). It is guaranteed that the given roads define a tree structure. It is guaranteed that the sum of the k in a single file is at most 3 ⋅ 10^5. Output For each test case, output a single line containing two space-separated integers G and B. Example Input 2 3 1 2 3 3 2 4 2 4 3 4 5 6 5 6 5 2 1 2 1 1 3 2 1 4 3 Output 15 33 6 6 Note For the sample test case, we have a minimum sum equal to G = 15. One way this can be achieved is with the following assignment: * The first pair of people get assigned to houses 5 and 6, giving us f(1) = 5; * The second pair of people get assigned to houses 1 and 4, giving us f(2) = 6; * The third pair of people get assigned to houses 3 and 2, giving us f(3) = 4. Note that the sum of the f(i) is 5 + 6 + 4 = 15. We also have a maximum sum equal to B = 33. One way this can be achieved is with the following assignment: * The first pair of people get assigned to houses 1 and 4, giving us f(1) = 6; * The second pair of people get assigned to houses 6 and 2, giving us f(2) = 14; * The third pair of people get assigned to houses 3 and 5, giving us f(3) = 13. Note that the sum of the f(i) is 6 + 14 + 13 = 33. Tags: dfs and similar, graphs, greedy, trees Correct Solution: ``` import sys # inf = open('input.txt', 'r') # reader = (map(int, line.split()) for line in inf) reader = (map(int, line.split()) for line in sys.stdin) def minmaxPairs(g, costDict, n): G = B = 0 s = 1 stack = [s] traversal = [] visited = [False] * (n + 1) subtreeSize = [1 for _ in range(n + 1)] while stack: v = stack.pop() if not visited[v]: visited[v] = True for to in g[v]: if not visited[to]: stack.append(v) stack.append(to) else: to = traversal[-1] if (v, to) in costDict: cost = costDict[(v, to)] else: cost = costDict[(to, v)] toSize = subtreeSize[to] subtreeSize[v] += toSize minComp = min(toSize, n - toSize) G += (minComp % 2) * cost B += minComp * cost traversal.append(v) return G, B t, = next(reader) for _ in range(t): k, = next(reader) n = 2 * k g = [[] for i in range(n + 1)] costDict = {} for i in range(n - 1): v, to, cost = next(reader) costDict[(v, to)] = cost g[v].append(to) g[to].append(v) G, B = minmaxPairs(g, costDict, n) print(G, B) # inf.close() ```
103,824
Provide tags and a correct Python 3 solution for this coding contest problem. Welcome! Everything is fine. You have arrived in The Medium Place, the place between The Good Place and The Bad Place. You are assigned a task that will either make people happier or torture them for eternity. You have a list of k pairs of people who have arrived in a new inhabited neighborhood. You need to assign each of the 2k people into one of the 2k houses. Each person will be the resident of exactly one house, and each house will have exactly one resident. Of course, in the neighborhood, it is possible to visit friends. There are 2k - 1 roads, each of which connects two houses. It takes some time to traverse a road. We will specify the amount of time it takes in the input. The neighborhood is designed in such a way that from anyone's house, there is exactly one sequence of distinct roads you can take to any other house. In other words, the graph with the houses as vertices and the roads as edges is a tree. The truth is, these k pairs of people are actually soulmates. We index them from 1 to k. We denote by f(i) the amount of time it takes for the i-th pair of soulmates to go to each other's houses. As we have said before, you will need to assign each of the 2k people into one of the 2k houses. You have two missions, one from the entities in The Good Place and one from the entities of The Bad Place. Here they are: * The first mission, from The Good Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is minimized. Let's define this minimized sum as G. This makes sure that soulmates can easily and efficiently visit each other; * The second mission, from The Bad Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is maximized. Let's define this maximized sum as B. This makes sure that soulmates will have a difficult time to visit each other. What are the values of G and B? Input The first line of input contains a single integer t (1 ≤ t ≤ 500) denoting the number of test cases. The next lines contain descriptions of the test cases. The first line of each test case contains a single integer k denoting the number of pairs of people (1 ≤ k ≤ 10^5). The next 2k - 1 lines describe the roads; the i-th of them contains three space-separated integers a_i, b_i, t_i which means that the i-th road connects the a_i-th and b_i-th houses with a road that takes t_i units of time to traverse (1 ≤ a_i, b_i ≤ 2k, a_i ≠ b_i, 1 ≤ t_i ≤ 10^6). It is guaranteed that the given roads define a tree structure. It is guaranteed that the sum of the k in a single file is at most 3 ⋅ 10^5. Output For each test case, output a single line containing two space-separated integers G and B. Example Input 2 3 1 2 3 3 2 4 2 4 3 4 5 6 5 6 5 2 1 2 1 1 3 2 1 4 3 Output 15 33 6 6 Note For the sample test case, we have a minimum sum equal to G = 15. One way this can be achieved is with the following assignment: * The first pair of people get assigned to houses 5 and 6, giving us f(1) = 5; * The second pair of people get assigned to houses 1 and 4, giving us f(2) = 6; * The third pair of people get assigned to houses 3 and 2, giving us f(3) = 4. Note that the sum of the f(i) is 5 + 6 + 4 = 15. We also have a maximum sum equal to B = 33. One way this can be achieved is with the following assignment: * The first pair of people get assigned to houses 1 and 4, giving us f(1) = 6; * The second pair of people get assigned to houses 6 and 2, giving us f(2) = 14; * The third pair of people get assigned to houses 3 and 5, giving us f(3) = 13. Note that the sum of the f(i) is 6 + 14 + 13 = 33. Tags: dfs and similar, graphs, greedy, trees Correct Solution: ``` # ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # ------------------- fast io -------------------- from math import gcd, ceil def prod(a, mod=10**9+7): ans = 1 for each in a: ans = (ans * each) % mod return ans def lcm(a, b): return a * b // gcd(a, b) def binary(x, length=16): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y def dfs(graph, alpha): """Depth First Search on a graph!""" n = len(graph) visited = [False]*n finished = [False]*n parents = [-1]*n stack = [alpha] dp = [0]*n while stack: v = stack[-1] if not visited[v]: visited[v] = True for u in graph[v]: if parents[u] == -1: parents[u] = v if not visited[u]: stack.append(u) else: stack.pop() dp[v] += 1 for u in graph[v]: if finished[u]: dp[v] += dp[u] finished[v] = True return visited, dp, parents for _ in range(int(input()) if True else 1): n = int(input()) #n, k = map(int, input().split()) #a, b = map(int, input().split()) #c, d = map(int, input().split()) #a = list(map(int, input().split())) #b = list(map(int, input().split())) #s = input() n *= 2 graph = [[] for i in range(n+1)] edges = {} for i in range(n-1): x, y, k = map(int, input().split()) graph[x] += [y] graph[y] += [x] edges[(x,y)] = edges[(y,x)] = k visited, dp, parents = dfs(graph, 1) mi, ma = 0, 0 for i in range(2, n+1): mi += (dp[i] % 2) * edges[(i, parents[i])] ma += min(dp[i], n-dp[i]) * edges[(i, parents[i])] print(mi, ma) ```
103,825
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Welcome! Everything is fine. You have arrived in The Medium Place, the place between The Good Place and The Bad Place. You are assigned a task that will either make people happier or torture them for eternity. You have a list of k pairs of people who have arrived in a new inhabited neighborhood. You need to assign each of the 2k people into one of the 2k houses. Each person will be the resident of exactly one house, and each house will have exactly one resident. Of course, in the neighborhood, it is possible to visit friends. There are 2k - 1 roads, each of which connects two houses. It takes some time to traverse a road. We will specify the amount of time it takes in the input. The neighborhood is designed in such a way that from anyone's house, there is exactly one sequence of distinct roads you can take to any other house. In other words, the graph with the houses as vertices and the roads as edges is a tree. The truth is, these k pairs of people are actually soulmates. We index them from 1 to k. We denote by f(i) the amount of time it takes for the i-th pair of soulmates to go to each other's houses. As we have said before, you will need to assign each of the 2k people into one of the 2k houses. You have two missions, one from the entities in The Good Place and one from the entities of The Bad Place. Here they are: * The first mission, from The Good Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is minimized. Let's define this minimized sum as G. This makes sure that soulmates can easily and efficiently visit each other; * The second mission, from The Bad Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is maximized. Let's define this maximized sum as B. This makes sure that soulmates will have a difficult time to visit each other. What are the values of G and B? Input The first line of input contains a single integer t (1 ≤ t ≤ 500) denoting the number of test cases. The next lines contain descriptions of the test cases. The first line of each test case contains a single integer k denoting the number of pairs of people (1 ≤ k ≤ 10^5). The next 2k - 1 lines describe the roads; the i-th of them contains three space-separated integers a_i, b_i, t_i which means that the i-th road connects the a_i-th and b_i-th houses with a road that takes t_i units of time to traverse (1 ≤ a_i, b_i ≤ 2k, a_i ≠ b_i, 1 ≤ t_i ≤ 10^6). It is guaranteed that the given roads define a tree structure. It is guaranteed that the sum of the k in a single file is at most 3 ⋅ 10^5. Output For each test case, output a single line containing two space-separated integers G and B. Example Input 2 3 1 2 3 3 2 4 2 4 3 4 5 6 5 6 5 2 1 2 1 1 3 2 1 4 3 Output 15 33 6 6 Note For the sample test case, we have a minimum sum equal to G = 15. One way this can be achieved is with the following assignment: * The first pair of people get assigned to houses 5 and 6, giving us f(1) = 5; * The second pair of people get assigned to houses 1 and 4, giving us f(2) = 6; * The third pair of people get assigned to houses 3 and 2, giving us f(3) = 4. Note that the sum of the f(i) is 5 + 6 + 4 = 15. We also have a maximum sum equal to B = 33. One way this can be achieved is with the following assignment: * The first pair of people get assigned to houses 1 and 4, giving us f(1) = 6; * The second pair of people get assigned to houses 6 and 2, giving us f(2) = 14; * The third pair of people get assigned to houses 3 and 5, giving us f(3) = 13. Note that the sum of the f(i) is 6 + 14 + 13 = 33. Submitted Solution: ``` # ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # ------------------- fast io -------------------- from math import gcd, ceil def prod(a, mod=10**9+7): ans = 1 for each in a: ans = (ans * each) % mod return ans def lcm(a, b): return a * b // gcd(a, b) def binary(x, length=16): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y def dfs(graph, alpha): """Depth First Search on a graph!""" n = len(graph) visited = [False]*n finished = [False]*n parents = [-1]*n stack = [alpha] dp = [0]*n while stack: v = stack[-1] if not visited[v]: visited[v] = True for u in graph[v]: if parents[v] == -1: parents[v] = u if not visited[u]: stack.append(u) else: stack.pop() dp[v] += 1 for u in graph[v]: if finished[u]: dp[v] += dp[u] finished[v] = True return visited, dp, parents for _ in range(int(input()) if True else 1): n = int(input()) #n, k = map(int, input().split()) #a, b = map(int, input().split()) #c, d = map(int, input().split()) #a = list(map(int, input().split())) #b = list(map(int, input().split())) #s = input() n *= 2 graph = [[] for i in range(n+1)] edges = {} for i in range(n-1): x, y, k = map(int, input().split()) graph[x] += [y] graph[y] += [x] edges[(x,y)] = edges[(y,x)] = k visited, dp, parents = dfs(graph, 1) mi, ma = 0, 0 for i in range(2, n+1): mi += (dp[i] % 2) * edges[(i, parents[i])] ma += min(dp[i], n-dp[i]) * edges[(i, parents[i])] print(mi, ma) ``` No
103,826
Provide tags and a correct Python 3 solution for this coding contest problem. Warawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building. The logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored with red, the top right square is colored with green, the bottom left square is colored with yellow and the bottom right square is colored with blue. An Example of some correct logos: <image> An Example of some incorrect logos: <image> Warawreh went to Adhami's store in order to buy the needed picture. Although Adhami's store is very large he has only one picture that can be described as a grid of n rows and m columns. The color of every cell in the picture will be green (the symbol 'G'), red (the symbol 'R'), yellow (the symbol 'Y') or blue (the symbol 'B'). Adhami gave Warawreh q options, in every option he gave him a sub-rectangle from that picture and told him that he can cut that sub-rectangle for him. To choose the best option, Warawreh needs to know for every option the maximum area of sub-square inside the given sub-rectangle that can be a Nanosoft logo. If there are no such sub-squares, the answer is 0. Warawreh couldn't find the best option himself so he asked you for help, can you help him? Input The first line of input contains three integers n, m and q (1 ≤ n , m ≤ 500, 1 ≤ q ≤ 3 ⋅ 10^{5}) — the number of row, the number columns and the number of options. For the next n lines, every line will contain m characters. In the i-th line the j-th character will contain the color of the cell at the i-th row and j-th column of the Adhami's picture. The color of every cell will be one of these: {'G','Y','R','B'}. For the next q lines, the input will contain four integers r_1, c_1, r_2 and c_2 (1 ≤ r_1 ≤ r_2 ≤ n, 1 ≤ c_1 ≤ c_2 ≤ m). In that option, Adhami gave to Warawreh a sub-rectangle of the picture with the upper-left corner in the cell (r_1, c_1) and with the bottom-right corner in the cell (r_2, c_2). Output For every option print the maximum area of sub-square inside the given sub-rectangle, which can be a NanoSoft Logo. If there are no such sub-squares, print 0. Examples Input 5 5 5 RRGGB RRGGY YYBBG YYBBR RBBRG 1 1 5 5 2 2 5 5 2 2 3 3 1 1 3 5 4 4 5 5 Output 16 4 4 4 0 Input 6 10 5 RRRGGGRRGG RRRGGGRRGG RRRGGGYYBB YYYBBBYYBB YYYBBBRGRG YYYBBBYBYB 1 1 6 10 1 3 3 10 2 2 6 6 1 7 6 10 2 1 5 10 Output 36 4 16 16 16 Input 8 8 8 RRRRGGGG RRRRGGGG RRRRGGGG RRRRGGGG YYYYBBBB YYYYBBBB YYYYBBBB YYYYBBBB 1 1 8 8 5 2 5 7 3 1 8 6 2 3 5 8 1 2 6 8 2 1 5 5 2 1 7 7 6 5 7 5 Output 64 0 16 4 16 4 36 0 Note Picture for the first test: <image> The pictures from the left to the right corresponds to the options. The border of the sub-rectangle in the option is marked with black, the border of the sub-square with the maximal possible size, that can be cut is marked with gray. Tags: binary search, data structures, dp, implementation Correct Solution: ``` import io, os import sys input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline n,m,q=map(int,input().split()) C=[input().strip() for i in range(n)] ATABLE=[[0]*m for i in range(n)] for i in range(n-1): for j in range(m-1): if C[i][j]==82 and C[i+1][j]==89 and C[i][j+1]==71 and C[i+1][j+1]==66: for l in range(1,5000): if 0<=i-l and 0<=j-l and i+l+1<n and j+l+1<m: True else: break flag=1 for k in range(i-l,i+1): if C[k][j-l]!=82: flag=0 break if C[k][j+l+1]!=71: flag=0 break if flag==0: break for k in range(j-l,j+1): if C[i-l][k]!=82: flag=0 break if C[i+l+1][k]!=89: flag=0 break if flag==0: break for k in range(i+1,i+l+2): if C[k][j-l]!=89: flag=0 break if C[k][j+l+1]!=66: flag=0 break if flag==0: break for k in range(j+1,j+l+2): if C[i-l][k]!=71: flag=0 break if C[i+l+1][k]!=66: flag=0 break if flag==0: break ATABLE[i][j]=l #for i in range(n): # print(ATABLE[i]) Sparse_table1 = [[ATABLE[i]] for i in range(n)] for r in range(n): for i in range(m.bit_length()-1): j = 1<<i B = [] for k in range(len(Sparse_table1[r][-1])-j): B.append(max(Sparse_table1[r][-1][k], Sparse_table1[r][-1][k+j])) Sparse_table1[r].append(B) #for i in range(n): # print(Sparse_table1[i]) Sparse_table2 = [[[[Sparse_table1[i][j][k] for i in range(n)]] for k in range(len(Sparse_table1[0][j]))] for j in range(m.bit_length())] for d in range(m.bit_length()): for c in range(len(Sparse_table1[0][d])): for i in range(n.bit_length()-1): #print(d,c,Sparse_table2[d][c]) j = 1<<i B = [] for k in range(len(Sparse_table2[d][c][-1])-j): B.append(max(Sparse_table2[d][c][-1][k], Sparse_table2[d][c][-1][k+j])) Sparse_table2[d][c].append(B) #print("!",B) for query in range(q): r1,c1,r2,c2=map(int,input().split()) r1-=1 c1-=1 r2-=1 c2-=1 if r1==r2 or c1==c2: print(0) continue OK=0 rd=(r2-r1).bit_length()-1 cd=(c2-c1).bit_length()-1 NG=1+max(Sparse_table2[cd][c1][rd][r1],Sparse_table2[cd][c1][rd][r2-(1<<rd)],Sparse_table2[cd][c2-(1<<cd)][rd][r1],Sparse_table2[cd][c2-(1<<cd)][rd][r2-(1<<rd)]) #print(r1,r2,c1,c2) while NG-OK>1: mid=(NG+OK)//2 rr1=r1+mid-1 cc1=c1+mid-1 rr2=r2-mid+1 cc2=c2-mid+1 #print("!",NG,OK,mid,rr1,rr2,cc1,cc2) if rr1>=rr2 or cc1>=cc2: NG=mid continue rd=(rr2-rr1).bit_length()-1 cd=(cc2-cc1).bit_length()-1 #print(rr1,rr2,cc1,cc2,mid,cd,rd) #print(Sparse_table2[cd][cc1][rd][rr1],Sparse_table2[cd][cc2-(1<<cd)][rd][rr2-(1<<rd)]) if mid<=max(Sparse_table2[cd][cc1][rd][rr1],Sparse_table2[cd][cc1][rd][rr2-(1<<rd)],Sparse_table2[cd][cc2-(1<<cd)][rd][rr1],Sparse_table2[cd][cc2-(1<<cd)][rd][rr2-(1<<rd)]): OK=mid else: NG=mid sys.stdout.write(str((OK*2)**2)+"\n") ```
103,827
Provide tags and a correct Python 3 solution for this coding contest problem. Warawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building. The logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored with red, the top right square is colored with green, the bottom left square is colored with yellow and the bottom right square is colored with blue. An Example of some correct logos: <image> An Example of some incorrect logos: <image> Warawreh went to Adhami's store in order to buy the needed picture. Although Adhami's store is very large he has only one picture that can be described as a grid of n rows and m columns. The color of every cell in the picture will be green (the symbol 'G'), red (the symbol 'R'), yellow (the symbol 'Y') or blue (the symbol 'B'). Adhami gave Warawreh q options, in every option he gave him a sub-rectangle from that picture and told him that he can cut that sub-rectangle for him. To choose the best option, Warawreh needs to know for every option the maximum area of sub-square inside the given sub-rectangle that can be a Nanosoft logo. If there are no such sub-squares, the answer is 0. Warawreh couldn't find the best option himself so he asked you for help, can you help him? Input The first line of input contains three integers n, m and q (1 ≤ n , m ≤ 500, 1 ≤ q ≤ 3 ⋅ 10^{5}) — the number of row, the number columns and the number of options. For the next n lines, every line will contain m characters. In the i-th line the j-th character will contain the color of the cell at the i-th row and j-th column of the Adhami's picture. The color of every cell will be one of these: {'G','Y','R','B'}. For the next q lines, the input will contain four integers r_1, c_1, r_2 and c_2 (1 ≤ r_1 ≤ r_2 ≤ n, 1 ≤ c_1 ≤ c_2 ≤ m). In that option, Adhami gave to Warawreh a sub-rectangle of the picture with the upper-left corner in the cell (r_1, c_1) and with the bottom-right corner in the cell (r_2, c_2). Output For every option print the maximum area of sub-square inside the given sub-rectangle, which can be a NanoSoft Logo. If there are no such sub-squares, print 0. Examples Input 5 5 5 RRGGB RRGGY YYBBG YYBBR RBBRG 1 1 5 5 2 2 5 5 2 2 3 3 1 1 3 5 4 4 5 5 Output 16 4 4 4 0 Input 6 10 5 RRRGGGRRGG RRRGGGRRGG RRRGGGYYBB YYYBBBYYBB YYYBBBRGRG YYYBBBYBYB 1 1 6 10 1 3 3 10 2 2 6 6 1 7 6 10 2 1 5 10 Output 36 4 16 16 16 Input 8 8 8 RRRRGGGG RRRRGGGG RRRRGGGG RRRRGGGG YYYYBBBB YYYYBBBB YYYYBBBB YYYYBBBB 1 1 8 8 5 2 5 7 3 1 8 6 2 3 5 8 1 2 6 8 2 1 5 5 2 1 7 7 6 5 7 5 Output 64 0 16 4 16 4 36 0 Note Picture for the first test: <image> The pictures from the left to the right corresponds to the options. The border of the sub-rectangle in the option is marked with black, the border of the sub-square with the maximal possible size, that can be cut is marked with gray. Tags: binary search, data structures, dp, implementation Correct Solution: ``` import sys readline = sys.stdin.readline def accumulate2d(X): N = len(X) M = len(X[0]) for i in range(0, N): for j in range(1, M): X[i][j] += X[i][j-1] for j in range(0, M): for i in range(1, N): X[i][j] += X[i-1][j] return X N, M, Q = map(int, readline().split()) table = [None]*100 table[ord('R')] = 0 table[ord('G')] = 1 table[ord('B')] = 2 table[ord('Y')] = 3 INF = 10**3 D = [[table[ord(s)] for s in readline().strip()] for _ in range(N)] G = [[0]*M for _ in range(N)] BS = 25 candi = [] geta = M for i in range(N-1): for j in range(M-1): if D[i][j] == 0 and D[i][j+1] == 1 and D[i+1][j+1] == 2 and D[i+1][j] == 3: G[i][j] = 1 nh, nw = i, j while True: k = G[nh][nw] fh, fw = nh-k, nw-k k2 = 2*(k+1) kh = k+1 if fh < 0 or fw < 0 or N < fh+k2-1 or M < fw+k2-1: break if any(D[fh][j] != 0 for j in range(fw, fw+kh)) or\ any(D[j][fw] != 0 for j in range(fh, fh+kh)) or\ any(D[fh][j] != 1 for j in range(fw+kh, fw+k2)) or\ any(D[j][fw+k2-1] != 1 for j in range(fh, fh+kh)) or\ any(D[j][fw+k2-1] != 2 for j in range(fh+kh, fh+k2)) or\ any(D[fh+k2-1][j] != 2 for j in range(fw+kh, fw+k2)) or\ any(D[fh+k2-1][j] != 3 for j in range(fw, fw+kh)) or\ any(D[j][fw] != 3 for j in range(fh+kh, fh+k2)): break G[nh][nw] += 1 if G[nh][nw] > BS: candi.append((nh, nw)) Gnum = [None] + [[[0]*M for _ in range(N)] for _ in range(BS)] for h in range(N): for w in range(M): if G[h][w] > 0: for k in range(1, min(BS, G[h][w])+1): Gnum[k][h][w] = 1 Gnum = [None] + [accumulate2d(g) for g in Gnum[1:]] Ans = [None]*Q for qu in range(Q): h1, w1, h2, w2 = map(lambda x: int(x)-1, readline().split()) res = 0 for k in range(min(BS, h2-h1+1, w2-w1+1), 0, -1): hs, ws = h1+k-1, w1+k-1 he, we = h2-k, w2-k if hs <= he and ws <= we: cnt = Gnum[k][he][we] if hs: cnt -= Gnum[k][hs-1][we] if ws: cnt -= Gnum[k][he][ws-1] if hs and ws: cnt += Gnum[k][hs-1][ws-1] if cnt: res = k break for nh, nw in candi: if h1 <= nh <= h2 and w1 <= nw <= w2: res = max(res, min(nh-h1+1, h2-nh, nw-w1+1, w2-nw, G[nh][nw])) Ans[qu] = 4*res**2 print('\n'.join(map(str, Ans))) ```
103,828
Provide tags and a correct Python 3 solution for this coding contest problem. Warawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building. The logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored with red, the top right square is colored with green, the bottom left square is colored with yellow and the bottom right square is colored with blue. An Example of some correct logos: <image> An Example of some incorrect logos: <image> Warawreh went to Adhami's store in order to buy the needed picture. Although Adhami's store is very large he has only one picture that can be described as a grid of n rows and m columns. The color of every cell in the picture will be green (the symbol 'G'), red (the symbol 'R'), yellow (the symbol 'Y') or blue (the symbol 'B'). Adhami gave Warawreh q options, in every option he gave him a sub-rectangle from that picture and told him that he can cut that sub-rectangle for him. To choose the best option, Warawreh needs to know for every option the maximum area of sub-square inside the given sub-rectangle that can be a Nanosoft logo. If there are no such sub-squares, the answer is 0. Warawreh couldn't find the best option himself so he asked you for help, can you help him? Input The first line of input contains three integers n, m and q (1 ≤ n , m ≤ 500, 1 ≤ q ≤ 3 ⋅ 10^{5}) — the number of row, the number columns and the number of options. For the next n lines, every line will contain m characters. In the i-th line the j-th character will contain the color of the cell at the i-th row and j-th column of the Adhami's picture. The color of every cell will be one of these: {'G','Y','R','B'}. For the next q lines, the input will contain four integers r_1, c_1, r_2 and c_2 (1 ≤ r_1 ≤ r_2 ≤ n, 1 ≤ c_1 ≤ c_2 ≤ m). In that option, Adhami gave to Warawreh a sub-rectangle of the picture with the upper-left corner in the cell (r_1, c_1) and with the bottom-right corner in the cell (r_2, c_2). Output For every option print the maximum area of sub-square inside the given sub-rectangle, which can be a NanoSoft Logo. If there are no such sub-squares, print 0. Examples Input 5 5 5 RRGGB RRGGY YYBBG YYBBR RBBRG 1 1 5 5 2 2 5 5 2 2 3 3 1 1 3 5 4 4 5 5 Output 16 4 4 4 0 Input 6 10 5 RRRGGGRRGG RRRGGGRRGG RRRGGGYYBB YYYBBBYYBB YYYBBBRGRG YYYBBBYBYB 1 1 6 10 1 3 3 10 2 2 6 6 1 7 6 10 2 1 5 10 Output 36 4 16 16 16 Input 8 8 8 RRRRGGGG RRRRGGGG RRRRGGGG RRRRGGGG YYYYBBBB YYYYBBBB YYYYBBBB YYYYBBBB 1 1 8 8 5 2 5 7 3 1 8 6 2 3 5 8 1 2 6 8 2 1 5 5 2 1 7 7 6 5 7 5 Output 64 0 16 4 16 4 36 0 Note Picture for the first test: <image> The pictures from the left to the right corresponds to the options. The border of the sub-rectangle in the option is marked with black, the border of the sub-square with the maximal possible size, that can be cut is marked with gray. Tags: binary search, data structures, dp, implementation Correct Solution: ``` def main(): import sys input = sys.stdin.buffer.readline # max def STfunc(a, b): if a > b: return a else: return b # クエリは0-indexedで[(r1, c1), (r2, c2)) class SparseTable(): def __init__(self, grid): # A: 処理したい2D配列 self.N = len(grid) self.M = len(grid[0]) self.KN = self.N.bit_length() - 1 self.KM = self.M.bit_length() - 1 self.flatten = lambda n, m, kn, km: \ (n * self.M + m) * ((self.KN + 1) * (self.KM + 1)) + (kn * (self.KM + 1) + km) self.table = [0] * (self.flatten(self.N - 1, self.M - 1, self.KN, self.KM) + 1) for i, line in enumerate(grid): for j, val in enumerate(line): self.table[self.flatten(i, j, 0, 0)] = val for km in range(1, self.KM + 1): for i in range(self.N): for j in range(self.M): j2 = j + (1 << (km - 1)) if j2 <= self.M - 1: self.table[self.flatten(i, j, 0, km)] = \ STfunc(self.table[self.flatten(i, j, 0, km - 1)], self.table[self.flatten(i, j2, 0, km - 1)]) for kn in range(1, self.KN + 1): for km in range(self.KM + 1): for i in range(self.N): i2 = i + (1 << (kn - 1)) for j in range(self.M): if i2 <= self.N - 1: self.table[self.flatten(i, j, kn, km)] = \ STfunc(self.table[self.flatten(i, j, kn - 1, km)], self.table[self.flatten(i2, j, kn - 1, km)]) def query(self, r1, c1, r2, c2): # [(r1, c1), (r2, c2))の最小値を求める kr = (r2 - r1).bit_length() - 1 kc = (c2 - c1).bit_length() - 1 r2 -= (1 << kr) c2 -= (1 << kc) return STfunc(STfunc(self.table[self.flatten(r1, c1, kr, kc)], self.table[self.flatten(r2, c1, kr, kc)]), STfunc(self.table[self.flatten(r1, c2, kr, kc)], self.table[self.flatten(r2, c2, kr, kc)])) H, W, Q = map(int, input().split()) grid = [] for _ in range(H): grid.append(input()) #print(grid) R = [[0] * W for _ in range(H)] G = [[0] * W for _ in range(H)] Y = [[0] * W for _ in range(H)] B = [[0] * W for _ in range(H)] R_enc = ord('R') G_enc = ord('G') Y_enc = ord('Y') B_enc = ord('B') for h in range(H): for w in range(W): if grid[h][w] == R_enc: R[h][w] = 1 elif grid[h][w] == G_enc: G[h][w] = 1 elif grid[h][w] == Y_enc: Y[h][w] = 1 else: B[h][w] = 1 for h in range(1, H): for w in range(1, W): if R[h][w]: tmp = min(R[h-1][w-1], R[h-1][w], R[h][w-1]) + 1 if tmp > 1: R[h][w] = tmp for h in range(1, H): for w in range(W-2, -1, -1): if G[h][w]: tmp = min(G[h-1][w+1], G[h-1][w], G[h][w+1]) + 1 if tmp > 1: G[h][w] = tmp for h in range(H-2, -1, -1): for w in range(1, W): if Y[h][w]: tmp = min(Y[h+1][w-1], Y[h+1][w], Y[h][w-1]) + 1 if tmp > 1: Y[h][w] = tmp for h in range(H-2, -1, -1): for w in range(W-2, -1, -1): if B[h][w]: tmp = min(B[h+1][w+1], B[h+1][w], B[h][w+1]) + 1 if tmp > 1: B[h][w] = tmp M = [[0] * W for _ in range(H)] for h in range(H): for w in range(W): if h < H-1 and w < W-1: M[h][w] = min(R[h][w], G[h][w+1], Y[h+1][w], B[h+1][w+1]) ST = SparseTable(M) ans = [None] * Q for q in range(Q): r1, c1, r2, c2 = map(int, input().split()) r1 -= 1 c1 -= 1 r2 -= 1 c2 -= 1 ok = 0 ng = 501 mid = 250 while ng - ok > 1: R1 = r1 + mid - 1 C1 = c1 + mid - 1 R2 = r2 - mid + 1 C2 = c2 - mid + 1 if R1 >= R2 or C1 >= C2: ng = mid mid = (ok + ng)//2 continue #print(ST.query(R1, C1, R2, C2), mid, [R1, C1, R2, C2]) if ST.query(R1, C1, R2, C2) >= mid: ok = mid else: ng = mid mid = (ok+ng)//2 #[print(M[h]) for h in range(H)] ans[q] = (2*ok)**2 sys.stdout.write('\n'.join(map(str, ans))) if __name__ == '__main__': main() ```
103,829
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Warawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building. The logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored with red, the top right square is colored with green, the bottom left square is colored with yellow and the bottom right square is colored with blue. An Example of some correct logos: <image> An Example of some incorrect logos: <image> Warawreh went to Adhami's store in order to buy the needed picture. Although Adhami's store is very large he has only one picture that can be described as a grid of n rows and m columns. The color of every cell in the picture will be green (the symbol 'G'), red (the symbol 'R'), yellow (the symbol 'Y') or blue (the symbol 'B'). Adhami gave Warawreh q options, in every option he gave him a sub-rectangle from that picture and told him that he can cut that sub-rectangle for him. To choose the best option, Warawreh needs to know for every option the maximum area of sub-square inside the given sub-rectangle that can be a Nanosoft logo. If there are no such sub-squares, the answer is 0. Warawreh couldn't find the best option himself so he asked you for help, can you help him? Input The first line of input contains three integers n, m and q (1 ≤ n , m ≤ 500, 1 ≤ q ≤ 3 ⋅ 10^{5}) — the number of row, the number columns and the number of options. For the next n lines, every line will contain m characters. In the i-th line the j-th character will contain the color of the cell at the i-th row and j-th column of the Adhami's picture. The color of every cell will be one of these: {'G','Y','R','B'}. For the next q lines, the input will contain four integers r_1, c_1, r_2 and c_2 (1 ≤ r_1 ≤ r_2 ≤ n, 1 ≤ c_1 ≤ c_2 ≤ m). In that option, Adhami gave to Warawreh a sub-rectangle of the picture with the upper-left corner in the cell (r_1, c_1) and with the bottom-right corner in the cell (r_2, c_2). Output For every option print the maximum area of sub-square inside the given sub-rectangle, which can be a NanoSoft Logo. If there are no such sub-squares, print 0. Examples Input 5 5 5 RRGGB RRGGY YYBBG YYBBR RBBRG 1 1 5 5 2 2 5 5 2 2 3 3 1 1 3 5 4 4 5 5 Output 16 4 4 4 0 Input 6 10 5 RRRGGGRRGG RRRGGGRRGG RRRGGGYYBB YYYBBBYYBB YYYBBBRGRG YYYBBBYBYB 1 1 6 10 1 3 3 10 2 2 6 6 1 7 6 10 2 1 5 10 Output 36 4 16 16 16 Input 8 8 8 RRRRGGGG RRRRGGGG RRRRGGGG RRRRGGGG YYYYBBBB YYYYBBBB YYYYBBBB YYYYBBBB 1 1 8 8 5 2 5 7 3 1 8 6 2 3 5 8 1 2 6 8 2 1 5 5 2 1 7 7 6 5 7 5 Output 64 0 16 4 16 4 36 0 Note Picture for the first test: <image> The pictures from the left to the right corresponds to the options. The border of the sub-rectangle in the option is marked with black, the border of the sub-square with the maximal possible size, that can be cut is marked with gray. Submitted Solution: ``` # SUBMIT SOURCE # https://gist.github.com/raikuma/6109943d493d3ba825ba995bae70b90c import sys from pprint import pprint if not 'DEBUG' in globals(): readline = sys.stdin.readline def read(map_func): return map_func(readline().rstrip()) def reads(map_func): return list(map(map_func, readline().rstrip().split())) def readn(map_func, n): return [map_func(readline().rstrip()) for _ in range(n)] def readint(): return read(int) def readints(): return reads(int) def readcol(n): return readn(int) def readmat(n): return [readints() for _ in range(n)] def readmap(n): return readn(list, n) def makemat(n, m, v): return [[v for _ in range(m)] for _ in range(n)] def zeromat(n, m=None): return makemat(n, m if m else n, 0) def listmat(n, m=None): return [[[] for _ in range(m if m else n)] for _ in range(n)] def crosslist(y, x, n=None, m=None): return [(p,q) for (p,q) in [(y,x+1),(y-1,x),(y,x-1),(y+1, x)] if (n==None or 0 <= p < n) and (m==None or 0 <= q < m)] def roundlist(y, x, n=None, m=None): return [(p,q) for (p,q) in [(y,x+1),(y-1,x+1),(y-1,x),(y-1,x-1),(y,x-1),(y+1,x-1),(y+1, x),(y+1,x+1)] if (n==None or 0 <= p < n) and (m==None or 0 <= q < m)] def plog(obj): pprint(obj) if 'DEBUG' in globals() else None def log(msg, label=None): print((label+': ' if label else '')+str(msg)) if 'DEBUG' in globals() else None def _logmat(mat, label=None): fmt='{:'+str(max(max(len(str(s)) for s in m) for m in mat))+'d}'; f=lambda row: '['+' '.join(fmt.format(x) for x in row)+']'; [log('['+f(row),label) if i == 0 else log((' '*(len(label)+3) if label else ' ')+f(row)+']',None) if i == len(mat)-1 else log((' '*(len(label)+3) if label else ' ')+f(row),None) for i, row in enumerate(mat)] def logmat(mat, label=None): _logmat(mat, label) if 'DEBUG' in globals() else None # endregion BOJ # LOGIC HERE # def _check(A, V, Ry, Rx, x): for i in Ry: for j in Rx: if V[i][j] == 1 or A[i][j] != x: return False return True def check(A, N, M, y, x, V, e): if not _check(A, V, range(y, y+e//2), range(x, x+e//2), 'R'): return False if not _check(A, V, range(y, y+e//2), range(x+e//2, x+e), 'G'): return False if not _check(A, V, range(y+e//2, y+e), range(x, x+e//2), 'Y'): return False if not _check(A, V, range(y+e//2, y+e), range(x+e//2, x+e), 'B'): return False return True def visit(A, N, M, y, x, V, e): for i in range(y, y+e): for j in range(x, x+e): V[i][j] = 1 def mapping(A, N, M): V = zeromat(N, M) L = zeromat(N, M) for e in range((min(N, M)//2)*2, 1, -2): for i in range(N-e+1): for j in range(M-e+1): if V[i][j] == 0: if check(A, N, M, i, j, V, e): visit(A, N, M, i, j, V, e) L[i][j] = e for i in range(N): for j in range(M): if L[i][j] > 0: e = L[i][j] y, x = i, j for k in range(e//2-1): y += 1 x += 1 e -= 2 L[y][x] = e return L N, M, Q = readints() A = readmap(N) O = readmat(Q) L = mapping(A, N, M) # logmat(L) for (r1, c1, r2, c2) in O: r1 -= 1 c1 -= 1 m = 0 # log((r1, c1, r2, c2)) for i in range(r1, r2): for j in range(c1, c2): if L[i][j] > 0: if L[i][j] <= r2-i and L[i][j] <= c2-j: m = L[i][j] break else: continue break print(m*m) ``` No
103,830
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Warawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building. The logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored with red, the top right square is colored with green, the bottom left square is colored with yellow and the bottom right square is colored with blue. An Example of some correct logos: <image> An Example of some incorrect logos: <image> Warawreh went to Adhami's store in order to buy the needed picture. Although Adhami's store is very large he has only one picture that can be described as a grid of n rows and m columns. The color of every cell in the picture will be green (the symbol 'G'), red (the symbol 'R'), yellow (the symbol 'Y') or blue (the symbol 'B'). Adhami gave Warawreh q options, in every option he gave him a sub-rectangle from that picture and told him that he can cut that sub-rectangle for him. To choose the best option, Warawreh needs to know for every option the maximum area of sub-square inside the given sub-rectangle that can be a Nanosoft logo. If there are no such sub-squares, the answer is 0. Warawreh couldn't find the best option himself so he asked you for help, can you help him? Input The first line of input contains three integers n, m and q (1 ≤ n , m ≤ 500, 1 ≤ q ≤ 3 ⋅ 10^{5}) — the number of row, the number columns and the number of options. For the next n lines, every line will contain m characters. In the i-th line the j-th character will contain the color of the cell at the i-th row and j-th column of the Adhami's picture. The color of every cell will be one of these: {'G','Y','R','B'}. For the next q lines, the input will contain four integers r_1, c_1, r_2 and c_2 (1 ≤ r_1 ≤ r_2 ≤ n, 1 ≤ c_1 ≤ c_2 ≤ m). In that option, Adhami gave to Warawreh a sub-rectangle of the picture with the upper-left corner in the cell (r_1, c_1) and with the bottom-right corner in the cell (r_2, c_2). Output For every option print the maximum area of sub-square inside the given sub-rectangle, which can be a NanoSoft Logo. If there are no such sub-squares, print 0. Examples Input 5 5 5 RRGGB RRGGY YYBBG YYBBR RBBRG 1 1 5 5 2 2 5 5 2 2 3 3 1 1 3 5 4 4 5 5 Output 16 4 4 4 0 Input 6 10 5 RRRGGGRRGG RRRGGGRRGG RRRGGGYYBB YYYBBBYYBB YYYBBBRGRG YYYBBBYBYB 1 1 6 10 1 3 3 10 2 2 6 6 1 7 6 10 2 1 5 10 Output 36 4 16 16 16 Input 8 8 8 RRRRGGGG RRRRGGGG RRRRGGGG RRRRGGGG YYYYBBBB YYYYBBBB YYYYBBBB YYYYBBBB 1 1 8 8 5 2 5 7 3 1 8 6 2 3 5 8 1 2 6 8 2 1 5 5 2 1 7 7 6 5 7 5 Output 64 0 16 4 16 4 36 0 Note Picture for the first test: <image> The pictures from the left to the right corresponds to the options. The border of the sub-rectangle in the option is marked with black, the border of the sub-square with the maximal possible size, that can be cut is marked with gray. Submitted Solution: ``` import sys reader = (s.rstrip() for s in sys.stdin) input = reader.__next__ def make_array(dims, fill): if len(dims) == 1: return [fill]*dims[0] nxt = dims[1:] ret = [make_array(nxt,fill) for i in range(dims[0])] return ret class Sparse_Table_2D(): def __init__(self,n,m,F=min): self.n = n self.m = m self.ln = n.bit_length() self.lm = m.bit_length() self.data = make_array((self.ln,n,self.lm,m), 0) self.F = F log_table = [0]*(max(n,m)+1) for i in range(2,max(n,m)+1): log_table[i] = log_table[i>>1] + 1 self.log_table = log_table def construct(self, matrix): for i in range(self.n): for j in range(self.m): self.data[0][i][0][j] = matrix[i][j] for jc in range(1, self.lm): for ic in range(self.m): self.data[0][i][jc][ic] = self.F(self.data[0][i][jc-1][ic], self.data[0][i][jc-1][min(ic+(1<<(jc-1)), self.m-1)]) for jr in range(1,self.ln): for ir in range(self.n): for jc in range(self.lm): for ic in range(self.m): self.data[jr][ir][jc][ic] = self.F(self.data[jr-1][ir][jc][ic], self.data[jr-1][min(ir+(1<<(jr-1)), self.n-1)][jc][ic]) def get(self, x1,y1,x2,y2): lx = self.log_table[x2-x1] ly = self.log_table[y2-y1] R1 = self.F(self.data[lx][x1][ly][y1], self.data[lx][x1][ly][y2-(1<<ly)]) R2 = self.F(self.data[lx][x2-(1<<lx)][ly][y1], self.data[lx][x2-(1<<lx)][ly][y2-(1<<ly)]) R = self.F(R1, R2) return R def solve(): n,m,q = map(int, input().split()) board = [list(map(ord, input())) for i in range(n)] temp = [[0]*m for i in range(n)] hoge = [ [ord("R"), (-1,0), (-1,1), (-1,1), (-1,0)], [ord("G"), (-1,0), (1,0), (-1,1), (1,1)], [ord("Y"), (1,1), (-1,1), (1,0), (-1,0)], [ord("B"), (1,1), (1,0), (1,0), (1,1)], ] def search(i,j): temp[i][j] = 1 for k in range(2, n): for col, tatex, tatey, yokox, yokoy in hoge: for dx in range(k): nx, ny = i+tatex[0]*dx+tatex[1], j+tatey[0]*k+tatey[1] if not(0<=nx<n and 0<=ny<m and board[nx][ny] == col): return for dy in range(k): nx, ny = i+yokox[0]*k+yokox[1], j+yokoy[0]*dy+yokoy[1] if not(0<=nx<n and 0<=ny<m and board[nx][ny] == col): return temp[i][j] = k R = ord("R") G = ord("G") Y = ord("Y") B = ord("B") for i in range(n-1): for j in range(m-1): if board[i][j] == R and board[i][j+1] == G and board[i+1][j] == Y and board[i+1][j+1] == B: search(i,j) ST2D = Sparse_Table_2D(n,m,max) ST2D.construct(temp) ans = [] for _ in range(q): r1,c1,r2,c2 = map(int, input().split()) r1,c1,r2,c2 = r1-1,c1-1,r2, c2 left = 0 right = min(r2-r1, c2-c1)//2 + 1 while right-left>1: mid = (right+left)//2 if ST2D.get(r1+mid-1, c1+mid-1, r2-mid, c2-mid) >= mid: left = mid else: right = mid ans.append(4*left*left) sys.stdout.writelines(map(str, ans)) solve() ``` No
103,831
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Warawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building. The logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored with red, the top right square is colored with green, the bottom left square is colored with yellow and the bottom right square is colored with blue. An Example of some correct logos: <image> An Example of some incorrect logos: <image> Warawreh went to Adhami's store in order to buy the needed picture. Although Adhami's store is very large he has only one picture that can be described as a grid of n rows and m columns. The color of every cell in the picture will be green (the symbol 'G'), red (the symbol 'R'), yellow (the symbol 'Y') or blue (the symbol 'B'). Adhami gave Warawreh q options, in every option he gave him a sub-rectangle from that picture and told him that he can cut that sub-rectangle for him. To choose the best option, Warawreh needs to know for every option the maximum area of sub-square inside the given sub-rectangle that can be a Nanosoft logo. If there are no such sub-squares, the answer is 0. Warawreh couldn't find the best option himself so he asked you for help, can you help him? Input The first line of input contains three integers n, m and q (1 ≤ n , m ≤ 500, 1 ≤ q ≤ 3 ⋅ 10^{5}) — the number of row, the number columns and the number of options. For the next n lines, every line will contain m characters. In the i-th line the j-th character will contain the color of the cell at the i-th row and j-th column of the Adhami's picture. The color of every cell will be one of these: {'G','Y','R','B'}. For the next q lines, the input will contain four integers r_1, c_1, r_2 and c_2 (1 ≤ r_1 ≤ r_2 ≤ n, 1 ≤ c_1 ≤ c_2 ≤ m). In that option, Adhami gave to Warawreh a sub-rectangle of the picture with the upper-left corner in the cell (r_1, c_1) and with the bottom-right corner in the cell (r_2, c_2). Output For every option print the maximum area of sub-square inside the given sub-rectangle, which can be a NanoSoft Logo. If there are no such sub-squares, print 0. Examples Input 5 5 5 RRGGB RRGGY YYBBG YYBBR RBBRG 1 1 5 5 2 2 5 5 2 2 3 3 1 1 3 5 4 4 5 5 Output 16 4 4 4 0 Input 6 10 5 RRRGGGRRGG RRRGGGRRGG RRRGGGYYBB YYYBBBYYBB YYYBBBRGRG YYYBBBYBYB 1 1 6 10 1 3 3 10 2 2 6 6 1 7 6 10 2 1 5 10 Output 36 4 16 16 16 Input 8 8 8 RRRRGGGG RRRRGGGG RRRRGGGG RRRRGGGG YYYYBBBB YYYYBBBB YYYYBBBB YYYYBBBB 1 1 8 8 5 2 5 7 3 1 8 6 2 3 5 8 1 2 6 8 2 1 5 5 2 1 7 7 6 5 7 5 Output 64 0 16 4 16 4 36 0 Note Picture for the first test: <image> The pictures from the left to the right corresponds to the options. The border of the sub-rectangle in the option is marked with black, the border of the sub-square with the maximal possible size, that can be cut is marked with gray. Submitted Solution: ``` import sys reader = (s.rstrip() for s in sys.stdin) input = reader.__next__ def make_array(dims, fill): if len(dims) == 1: return [fill]*dims[0] nxt = dims[1:] ret = [make_array(nxt,fill) for i in range(dims[0])] return ret class Sparse_Table_2D(): def __init__(self,n,m): self.n = n self.m = m self.ln = n.bit_length() self.lm = m.bit_length() self.data = make_array((self.ln,n,self.lm,m), 0) log_table = [0]*(max(n,m)+1) for i in range(2,max(n,m)+1): log_table[i] = log_table[i>>1] + 1 self.log_table = log_table def construct(self, matrix): for i in range(self.n): for j in range(self.m): self.data[0][i][0][j] = matrix[i][j] for jc in range(1, self.lm): for ic in range(self.m): self.data[0][i][jc][ic] = max(self.data[0][i][jc-1][ic], self.data[0][i][jc-1][min(ic+(1<<(jc-1)), self.m-1)]) for jr in range(1,self.ln): for ir in range(self.n): for jc in range(self.lm): for ic in range(self.m): self.data[jr][ir][jc][ic] = max(self.data[jr-1][ir][jc][ic], self.data[jr-1][min(ir+(1<<(jr-1)), self.n-1)][jc][ic]) def get(self, x1,y1,x2,y2): lx = self.log_table[x2-x1] ly = self.log_table[y2-y1] R1 = max(self.data[lx][x1][ly][y1], self.data[lx][x1][ly][y2-(1<<ly)]) R2 = max(self.data[lx][x2-(1<<lx)][ly][y1], self.data[lx][x2-(1<<lx)][ly][y2-(1<<ly)]) R = max(R1, R2) return R def solve(): n,m,q = map(int, input().split()) board = [list(map(ord, input())) for i in range(n)] temp = [[0]*m for i in range(n)] R = ord("R") G = ord("G") Y = ord("Y") B = ord("B") hoge = [ [R, (-1,0), (-1,1), (-1,1), (-1,0)], [G, (-1,0), (1,0), (-1,1), (1,1)], [Y, (1,1), (-1,1), (1,0), (-1,0)], [B, (1,1), (1,0), (1,0), (1,1)], ] def search(i,j): temp[i][j] = 1 for k in range(2, n): for col, tatex, tatey, yokox, yokoy in hoge: for dx in range(k): nx, ny = i+tatex[0]*dx+tatex[1], j+tatey[0]*k+tatey[1] if not(0<=nx<n and 0<=ny<m and board[nx][ny] == col): return for dy in range(k): nx, ny = i+yokox[0]*k+yokox[1], j+yokoy[0]*dy+yokoy[1] if not(0<=nx<n and 0<=ny<m and board[nx][ny] == col): return temp[i][j] = k for i in range(n-1): for j in range(m-1): if board[i][j] == R and board[i][j+1] == G and board[i+1][j] == Y and board[i+1][j+1] == B: search(i,j) ST2D = Sparse_Table_2D(n,m) ST2D.construct(temp) ans = [] for _ in range(q): r1,c1,r2,c2 = map(int, input().split()) r1,c1,r2,c2 = r1-1,c1-1,r2, c2 left = 0 right = min(r2-r1, c2-c1)//2 + 1 while right-left>1: mid = (right+left)//2 if ST2D.get(r1+mid-1, c1+mid-1, r2-mid, c2-mid) >= mid: left = mid else: right = mid ans.append(4*left*left) print(*ans, sep="\n") ``` No
103,832
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Warawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building. The logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored with red, the top right square is colored with green, the bottom left square is colored with yellow and the bottom right square is colored with blue. An Example of some correct logos: <image> An Example of some incorrect logos: <image> Warawreh went to Adhami's store in order to buy the needed picture. Although Adhami's store is very large he has only one picture that can be described as a grid of n rows and m columns. The color of every cell in the picture will be green (the symbol 'G'), red (the symbol 'R'), yellow (the symbol 'Y') or blue (the symbol 'B'). Adhami gave Warawreh q options, in every option he gave him a sub-rectangle from that picture and told him that he can cut that sub-rectangle for him. To choose the best option, Warawreh needs to know for every option the maximum area of sub-square inside the given sub-rectangle that can be a Nanosoft logo. If there are no such sub-squares, the answer is 0. Warawreh couldn't find the best option himself so he asked you for help, can you help him? Input The first line of input contains three integers n, m and q (1 ≤ n , m ≤ 500, 1 ≤ q ≤ 3 ⋅ 10^{5}) — the number of row, the number columns and the number of options. For the next n lines, every line will contain m characters. In the i-th line the j-th character will contain the color of the cell at the i-th row and j-th column of the Adhami's picture. The color of every cell will be one of these: {'G','Y','R','B'}. For the next q lines, the input will contain four integers r_1, c_1, r_2 and c_2 (1 ≤ r_1 ≤ r_2 ≤ n, 1 ≤ c_1 ≤ c_2 ≤ m). In that option, Adhami gave to Warawreh a sub-rectangle of the picture with the upper-left corner in the cell (r_1, c_1) and with the bottom-right corner in the cell (r_2, c_2). Output For every option print the maximum area of sub-square inside the given sub-rectangle, which can be a NanoSoft Logo. If there are no such sub-squares, print 0. Examples Input 5 5 5 RRGGB RRGGY YYBBG YYBBR RBBRG 1 1 5 5 2 2 5 5 2 2 3 3 1 1 3 5 4 4 5 5 Output 16 4 4 4 0 Input 6 10 5 RRRGGGRRGG RRRGGGRRGG RRRGGGYYBB YYYBBBYYBB YYYBBBRGRG YYYBBBYBYB 1 1 6 10 1 3 3 10 2 2 6 6 1 7 6 10 2 1 5 10 Output 36 4 16 16 16 Input 8 8 8 RRRRGGGG RRRRGGGG RRRRGGGG RRRRGGGG YYYYBBBB YYYYBBBB YYYYBBBB YYYYBBBB 1 1 8 8 5 2 5 7 3 1 8 6 2 3 5 8 1 2 6 8 2 1 5 5 2 1 7 7 6 5 7 5 Output 64 0 16 4 16 4 36 0 Note Picture for the first test: <image> The pictures from the left to the right corresponds to the options. The border of the sub-rectangle in the option is marked with black, the border of the sub-square with the maximal possible size, that can be cut is marked with gray. Submitted Solution: ``` print(16) print(4) print(4) print(4) print(0) ``` No
103,833
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a of length n that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square. A sequence a is a subsequence of an array b if a can be obtained from b by deletion of several (possibly, zero or all) elements. Input The first line contains an integer n (1 ≤ n ≤ 10^5) — the length of a. The second line contains n integers a_1, a_2, …, a_{n} (1 ≤ a_i ≤ 10^6) — the elements of the array a. Output Output the length of the shortest non-empty subsequence of a product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1". Examples Input 3 1 4 6 Output 1 Input 4 2 3 6 6 Output 2 Input 3 6 15 10 Output 3 Input 4 2 3 5 7 Output -1 Note In the first sample, you can choose a subsequence [1]. In the second sample, you can choose a subsequence [6, 6]. In the third sample, you can choose a subsequence [6, 15, 10]. In the fourth sample, there is no such subsequence. Tags: brute force, dfs and similar, graphs, number theory, shortest paths Correct Solution: ``` import sys input = sys.stdin.readline n=int(input()) A=list(map(int,input().split())) Primes=(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997) E=[[] for i in range(10**6)] U=set() for i in range(n): a=A[i] X=[] for p in Primes: while a%(p*p)==0: a//=p*p if a%p==0: a//=p X.append(p) if a!=1: X.append(a) if a==1 and X==[]: print(1) sys.exit() elif len(X)==1: E[1].append(X[0]) E[X[0]].append(1) U.add(X[0]) else: E[X[0]].append(X[1]) E[X[1]].append(X[0]) U.add(X[0]*X[1]) if len(A)!=len(U): ANS=2 else: ANS=n+5 D=[] E2=[] for i in range(10**6): if E[i]==[]: continue D.append(i) E2.append(E[i]) DD={x:i for i,x in enumerate(D)} for i in range(len(E2)): for k in range(len(E2[i])): E2[i][k]=DD[E2[i][k]] from collections import deque for start in range(min(170,len(E2))): if E2[start]==[]: continue Q=deque([start]) D=[0]*len(E2) FROM=[0]*len(E2) D[start]=1 while Q: x=Q.popleft() if D[x]*2-2>=ANS: break for to in E2[x]: if to==FROM[x]: continue elif D[to]==0: Q.append(to) FROM[to]=x D[to]=D[x]+1 else: #print(start,x,to,D[x],D[to]) ANS=min(ANS,D[x]+D[to]-1) if ANS>len(A): print(-1) else: print(ANS) ```
103,834
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a of length n that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square. A sequence a is a subsequence of an array b if a can be obtained from b by deletion of several (possibly, zero or all) elements. Input The first line contains an integer n (1 ≤ n ≤ 10^5) — the length of a. The second line contains n integers a_1, a_2, …, a_{n} (1 ≤ a_i ≤ 10^6) — the elements of the array a. Output Output the length of the shortest non-empty subsequence of a product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1". Examples Input 3 1 4 6 Output 1 Input 4 2 3 6 6 Output 2 Input 3 6 15 10 Output 3 Input 4 2 3 5 7 Output -1 Note In the first sample, you can choose a subsequence [1]. In the second sample, you can choose a subsequence [6, 6]. In the third sample, you can choose a subsequence [6, 15, 10]. In the fourth sample, there is no such subsequence. Tags: brute force, dfs and similar, graphs, number theory, shortest paths Correct Solution: ``` from collections import deque,defaultdict import sys input=sys.stdin.readline def make_mf(): res=[-1]*(mxa+5) ptoi=[0]*(mxa+5) pn=1 for i in range(2,mxa+5): if res[i]==-1: res[i]=i ptoi[i]=pn pn+=1 for j in range(i**2,mxa+5,i): if res[j]==-1:res[j]=i return res,ptoi,pn def make_to(): to=[[] for _ in range(pn)] ss=set() for a in aa: pp=[] while a>1: p=mf[a] e=0 while p==mf[a]: a//=p e^=1 if e:pp.append(p) if len(pp)==0:ext(1) elif len(pp)==1:pp.append(1) u,v=ptoi[pp[0]],ptoi[pp[1]] to[u].append(v) to[v].append(u) if pp[0]**2<=mxa:ss.add(u) if pp[1]**2<=mxa:ss.add(v) return to,ss def ext(ans): print(ans) exit() def solve(): ans=inf for u in ss: ans=bfs(u,ans) if ans==inf:ans=-1 return ans def bfs(u,ans): dist=[-1]*pn q=deque() q.append((u,0,-1)) dist[u]=0 while q: u,d,pu=q.popleft() if d*2>=ans:break for v in to[u]: if v==pu:continue if dist[v]!=-1:ans=min(ans,d+dist[v]+1) dist[v]=d+1 q.append((v,d+1,u)) return ans inf=10**9 n=int(input()) aa=list(map(int,input().split())) mxa=max(aa) mf,ptoi,pn=make_mf() to,ss=make_to() print(solve()) ```
103,835
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a of length n that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square. A sequence a is a subsequence of an array b if a can be obtained from b by deletion of several (possibly, zero or all) elements. Input The first line contains an integer n (1 ≤ n ≤ 10^5) — the length of a. The second line contains n integers a_1, a_2, …, a_{n} (1 ≤ a_i ≤ 10^6) — the elements of the array a. Output Output the length of the shortest non-empty subsequence of a product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1". Examples Input 3 1 4 6 Output 1 Input 4 2 3 6 6 Output 2 Input 3 6 15 10 Output 3 Input 4 2 3 5 7 Output -1 Note In the first sample, you can choose a subsequence [1]. In the second sample, you can choose a subsequence [6, 6]. In the third sample, you can choose a subsequence [6, 15, 10]. In the fourth sample, there is no such subsequence. Tags: brute force, dfs and similar, graphs, number theory, shortest paths Correct Solution: ``` from collections import deque import sys input=sys.stdin.readline def make_mf(): res=[-1]*(mxa+5) ptoi=[0]*(mxa+5) pn=1 for i in range(2,mxa+5): if res[i]==-1: res[i]=i ptoi[i]=pn pn+=1 for j in range(i**2,mxa+5,i): if res[j]==-1:res[j]=i return res,ptoi,pn def make_to(): to=[[] for _ in range(pn)] ss=set() for a in aa: pp=[] while a>1: p=mf[a] e=0 while p==mf[a]: a//=p e^=1 if e:pp.append(p) if len(pp)==0:ext(1) elif len(pp)==1:pp.append(1) u,v=ptoi[pp[0]],ptoi[pp[1]] to[u].append(v) to[v].append(u) if pp[0]**2<=mxa:ss.add(u) if pp[1]**2<=mxa:ss.add(v) return to,ss def ext(ans): print(ans) exit() def solve(): ans=inf for u in ss: ans=bfs(u,ans) if ans==inf:ans=-1 return ans def bfs(u,ans): dist=[-1]*pn q=deque() q.append((u,0,-1)) dist[u]=0 while q: u,d,pu=q.popleft() if d*2>=ans:break for v in to[u]: if v==pu:continue if dist[v]!=-1:ans=min(ans,d+dist[v]+1) dist[v]=d+1 q.append((v,d+1,u)) return ans inf=10**9 n=int(input()) aa=list(map(int,input().split())) mxa=max(aa) mf,ptoi,pn=make_mf() to,ss=make_to() print(solve()) ```
103,836
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a of length n that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square. A sequence a is a subsequence of an array b if a can be obtained from b by deletion of several (possibly, zero or all) elements. Input The first line contains an integer n (1 ≤ n ≤ 10^5) — the length of a. The second line contains n integers a_1, a_2, …, a_{n} (1 ≤ a_i ≤ 10^6) — the elements of the array a. Output Output the length of the shortest non-empty subsequence of a product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1". Examples Input 3 1 4 6 Output 1 Input 4 2 3 6 6 Output 2 Input 3 6 15 10 Output 3 Input 4 2 3 5 7 Output -1 Note In the first sample, you can choose a subsequence [1]. In the second sample, you can choose a subsequence [6, 6]. In the third sample, you can choose a subsequence [6, 15, 10]. In the fourth sample, there is no such subsequence. Submitted Solution: ``` from collections import deque,defaultdict import sys input=sys.stdin.readline def make_mf(): res=[-1]*mxa for i in range(2,mxa): if res[i]==-1: res[i]=i for j in range(i**2,mxa,i): if res[j]==-1:res[j]=i return res def make_to(): to=defaultdict(set) ss=set() ans=inf for a in aa: pp=[] while a>1: p=mf[a] e=0 while p==mf[a]: a//=p e^=1 if e:pp.append(p) if len(pp)==0:ext(1) elif len(pp)==1:pp.append(1) u,v=pp if v in to[u]:ans=2 to[u].add(v) to[v].add(u) if u**2<=mxa:ss.add(u) if v**2<=mxa:ss.add(v) return to,ss,ans def ext(ans): print(ans) exit() def solve(ans): for u in ss: ans=bfs(u,ans) if ans==inf:ans=-1 return ans def bfs(u,ans): dist=defaultdict(int) q=deque() q.append((u,0,-1)) dist[u]=0 while q: u,d,pu=q.popleft() if d*2>=ans:break for v in to[u]: if v==pu:continue if v in dist: ans=min(ans,d+dist[v]+1) dist[v]=d+1 q.append((v,d+1,u)) return ans inf=10**9 n=int(input()) aa=map(int,input().split()) mxa=max(aa) mf=make_mf() to,ss,ans=make_to() if ans==2:ext(2) print(solve(ans)) ``` No
103,837
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a of length n that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square. A sequence a is a subsequence of an array b if a can be obtained from b by deletion of several (possibly, zero or all) elements. Input The first line contains an integer n (1 ≤ n ≤ 10^5) — the length of a. The second line contains n integers a_1, a_2, …, a_{n} (1 ≤ a_i ≤ 10^6) — the elements of the array a. Output Output the length of the shortest non-empty subsequence of a product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1". Examples Input 3 1 4 6 Output 1 Input 4 2 3 6 6 Output 2 Input 3 6 15 10 Output 3 Input 4 2 3 5 7 Output -1 Note In the first sample, you can choose a subsequence [1]. In the second sample, you can choose a subsequence [6, 6]. In the third sample, you can choose a subsequence [6, 15, 10]. In the fourth sample, there is no such subsequence. Submitted Solution: ``` import sys readline = sys.stdin.readline ns = lambda: readline().rstrip() ni = lambda: int(readline().rstrip()) nm = lambda: map(int, readline().split()) nl = lambda: list(map(int, readline().split())) n = 10**6 + 5 p = [-1] * n for i in range(2, n): if p[i] < 0: for j in range(i*2, n, i): if p[j] < 0: p[j] = i def solve(): mod = 998244353 n = ni() a = nl() c = 0 d = dict() d[0] = -1 ans = n + 5 for i in range(n): x = a[i] while p[x] > 0: c ^= p[x] x //= p[x] if x > 1: c ^= x if c in d: ans = min(ans, i - d[c]) d[c] = i print(-1 if ans > n else ans) return solve() # T = ni() # for _ in range(T): # solve() ``` No
103,838
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a of length n that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square. A sequence a is a subsequence of an array b if a can be obtained from b by deletion of several (possibly, zero or all) elements. Input The first line contains an integer n (1 ≤ n ≤ 10^5) — the length of a. The second line contains n integers a_1, a_2, …, a_{n} (1 ≤ a_i ≤ 10^6) — the elements of the array a. Output Output the length of the shortest non-empty subsequence of a product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1". Examples Input 3 1 4 6 Output 1 Input 4 2 3 6 6 Output 2 Input 3 6 15 10 Output 3 Input 4 2 3 5 7 Output -1 Note In the first sample, you can choose a subsequence [1]. In the second sample, you can choose a subsequence [6, 6]. In the third sample, you can choose a subsequence [6, 15, 10]. In the fourth sample, there is no such subsequence. Submitted Solution: ``` def prime_numbers(): numbers = list() p = 2 while (p < 1000): for n in numbers: if p % n == 0: break else: numbers.append(p) p += 1 return numbers def solve(): primes = prime_numbers() n = int(input()) A = list(map(int, input().split())) #n = 4 #A = [2, 3, 6, 6] A_primes_more1000 = list() B = [set() for i in range(n)] D = set() solved = False for i in range(n): a = A[i] if a == 1: solved = True break for d in primes: count = 0 while (a % d == 0): a //= d count += 1 count = count % 2 if count: B[i].add(d) D.add(d) if a > 1: B[i].add(a) D.add(a) if len(B[i]) == 0: solved = True break if solved: print(1) return if len(A_primes_more1000) > len(set(A_primes_more1000)): print(2) return D = sorted(list(D)) len_D = len(D) Matrix = [[0 for j in range(len_D)] for i in range(n)] for i in range(n): for j in range(len_D): if D[j] in B[i]: Matrix[i][j] = 1 V = [0 for i in range(n)] for j in range(min(len_D, n)): if Matrix[j][j] == 0: swapped = False for k in range(j + 1, n): if Matrix[k][j] != 0: Matrix[k], Matrix[j] = Matrix[j], Matrix[k] V[j], V[k] = V[k], V[j] swapped = True break else: solved = j + 1 break for k in range(j + 1, n): for i in range(len_D): Matrix[k][i] = (Matrix[k][i] + Matrix[j][i]) % 2 V[k] = (V[k] + V[j]) % 2 j = min(len_D, n) if solved: print(solved) return #print(Matrix) #print(j) #print(V) for k in range(j, n): if V[k] != 0: solved = -1 break if solved: print(solved) return print(j) solve() ``` No
103,839
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a of length n that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square. A sequence a is a subsequence of an array b if a can be obtained from b by deletion of several (possibly, zero or all) elements. Input The first line contains an integer n (1 ≤ n ≤ 10^5) — the length of a. The second line contains n integers a_1, a_2, …, a_{n} (1 ≤ a_i ≤ 10^6) — the elements of the array a. Output Output the length of the shortest non-empty subsequence of a product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1". Examples Input 3 1 4 6 Output 1 Input 4 2 3 6 6 Output 2 Input 3 6 15 10 Output 3 Input 4 2 3 5 7 Output -1 Note In the first sample, you can choose a subsequence [1]. In the second sample, you can choose a subsequence [6, 6]. In the third sample, you can choose a subsequence [6, 15, 10]. In the fourth sample, there is no such subsequence. Submitted Solution: ``` import math n=int(input()) a=list(map(int,(input().split()))) k=0 count=0 for i in range(n): sum=1 k=a[i] for j in range(1,k+1): if(a[i]%j==0): sum=sum*j root = math.sqrt(sum) if(root ==k): count=count+1 if(count==0): print(-1) else: print(count) ``` No
103,840
Provide tags and a correct Python 3 solution for this coding contest problem. Uh oh! Applications to tech companies are due soon, and you've been procrastinating by doing contests instead! (Let's pretend for now that it is actually possible to get a job in these uncertain times.) You have completed many programming projects. In fact, there are exactly n types of programming projects, and you have completed a_i projects of type i. Your résumé has limited space, but you want to carefully choose them in such a way that maximizes your chances of getting hired. You want to include several projects of the same type to emphasize your expertise, but you also don't want to include so many that the low-quality projects start slipping in. Specifically, you determine the following quantity to be a good indicator of your chances of getting hired: $$$ f(b_1,…,b_n)=∑_{i=1}^n b_i(a_i-b_i^2). $$$ Here, b_i denotes the number of projects of type i you include in your résumé. Of course, you cannot include more projects than you have completed, so you require 0≤ b_i ≤ a_i for all i. Your résumé only has enough room for k projects, and you will absolutely not be hired if your résumé has empty space, so you require ∑_{i=1}^n b_i=k. Find values for b_1,…, b_n that maximize the value of f(b_1,…,b_n) while satisfying the above two constraints. Input The first line contains two integers n and k (1≤ n≤ 10^5, 1≤ k≤ ∑_{i=1}^n a_i) — the number of types of programming projects and the résumé size, respectively. The next line contains n integers a_1,…,a_n (1≤ a_i≤ 10^9) — a_i is equal to the number of completed projects of type i. Output In a single line, output n integers b_1,…, b_n that achieve the maximum value of f(b_1,…,b_n), while satisfying the requirements 0≤ b_i≤ a_i and ∑_{i=1}^n b_i=k. If there are multiple solutions, output any. Note that you do not have to output the value f(b_1,…,b_n). Examples Input 10 32 1 2 3 4 5 5 5 5 5 5 Output 1 2 3 3 3 4 4 4 4 4 Input 5 8 4 4 8 2 1 Output 2 2 2 1 1 Note For the first test, the optimal answer is f=-269. Note that a larger f value is possible if we ignored the constraint ∑_{i=1}^n b_i=k. For the second test, the optimal answer is f=9. Tags: binary search, greedy, math Correct Solution: ``` import os import sys #sys.setrecursionlimit(int(2e5)) from collections import deque import math readline = sys.stdin.readline ##################################################################################### class CF(object): def __init__(self): self.eps = 1e-7 self.n, self.k = list(map(int, readline().split())) self.a = list(map(int, readline().split())) assert(len(self.a) == self.n) def fd(self, i): return 3*i*(i+1) + 1 def find_le(self, x, ca): if(self.fd(0) > x): return 0, 0 ans = int(((12*x-3) **.5 - 3)/6 + self.eps) ans = int(min(ans, ca-1)) return int(ans + 1), int(3*ans*(ans+1) + 1 == x) def get_num(self, x): st = 0 se = 0 for ca in self.a: t1,t2 = self.find_le(x+ca, ca) st += t1 se += t2 pass return st,se def find_k(self, k): l = int(-4e18) r = int(4e18) while(l != r): mid = int((l+r+1)//2) #print(mid) st, se = self.get_num(mid) the_max = st the_min = the_max - se # if(k>= the_min and k <= the_max): # temp = the_max - k # ans = [] # for pos in range(self.n): # if(eq[pos] == 1): # if(temp > 0): # ans.append(int(tot[pos] - 1)) # temp -= 1 # else: # ans.append(int(tot[pos])) # else: # ans.append(int(tot[pos])) # pass # print(' '.join(map(str, ans))) # return if(k < the_max): r = mid - 1 else: l = mid pass ck = [] eq = [] for ca in self.a: t1,t2 = self.find_le(l+ca, ca) ck.append(t1) ck1 = [] eq1 = 0 for ca in self.a: t1,t2 = self.find_le(l+1+ca, ca) ck1.append(t1) eq1 += t2 the_max = sum(ck1) the_min = the_max - eq1 #assert(k<the_max and k>= the_min) res = k - sum(ck) for i in range(self.n): if(ck1[i]>ck[i]): if(res>0): res-=1 ck[i] += 1 pass print(' '.join(map(str, ck))) def main(self): self.find_k(self.k) pass if __name__ == "__main__": cf = CF() cf.main() pass ```
103,841
Provide tags and a correct Python 3 solution for this coding contest problem. Uh oh! Applications to tech companies are due soon, and you've been procrastinating by doing contests instead! (Let's pretend for now that it is actually possible to get a job in these uncertain times.) You have completed many programming projects. In fact, there are exactly n types of programming projects, and you have completed a_i projects of type i. Your résumé has limited space, but you want to carefully choose them in such a way that maximizes your chances of getting hired. You want to include several projects of the same type to emphasize your expertise, but you also don't want to include so many that the low-quality projects start slipping in. Specifically, you determine the following quantity to be a good indicator of your chances of getting hired: $$$ f(b_1,…,b_n)=∑_{i=1}^n b_i(a_i-b_i^2). $$$ Here, b_i denotes the number of projects of type i you include in your résumé. Of course, you cannot include more projects than you have completed, so you require 0≤ b_i ≤ a_i for all i. Your résumé only has enough room for k projects, and you will absolutely not be hired if your résumé has empty space, so you require ∑_{i=1}^n b_i=k. Find values for b_1,…, b_n that maximize the value of f(b_1,…,b_n) while satisfying the above two constraints. Input The first line contains two integers n and k (1≤ n≤ 10^5, 1≤ k≤ ∑_{i=1}^n a_i) — the number of types of programming projects and the résumé size, respectively. The next line contains n integers a_1,…,a_n (1≤ a_i≤ 10^9) — a_i is equal to the number of completed projects of type i. Output In a single line, output n integers b_1,…, b_n that achieve the maximum value of f(b_1,…,b_n), while satisfying the requirements 0≤ b_i≤ a_i and ∑_{i=1}^n b_i=k. If there are multiple solutions, output any. Note that you do not have to output the value f(b_1,…,b_n). Examples Input 10 32 1 2 3 4 5 5 5 5 5 5 Output 1 2 3 3 3 4 4 4 4 4 Input 5 8 4 4 8 2 1 Output 2 2 2 1 1 Note For the first test, the optimal answer is f=-269. Note that a larger f value is possible if we ignored the constraint ∑_{i=1}^n b_i=k. For the second test, the optimal answer is f=9. Tags: binary search, greedy, math Correct Solution: ``` import sys import heapq as hq readline = sys.stdin.readline ns = lambda: readline().rstrip() ni = lambda: int(readline().rstrip()) nm = lambda: map(int, readline().split()) nl = lambda: list(map(int, readline().split())) eps = 10**-7 def solve(): n, k = nm() a = nl() ans = [0]*n ok = 10**9; ng = -4*10**18 while ok - ng > 1: mid = (ok + ng) // 2 ck = 0 for i in range(n): d = 9 - 12 * (mid + 1 - a[i]) if d < 0: continue ck += min(a[i], int((3 + d**.5) / 6 + eps)) # print(mid, ck) if ck > k: ng = mid else: ok = mid for i in range(n): d = 9 - 12 * (ok + 1 - a[i]) if d < 0: continue ans[i] = min(a[i], int((3 + d**.5) / 6 + eps)) # print(ans) rk = k - sum(ans) l = list() for i in range(n): if ans[i] < a[i]: hq.heappush(l, (-a[i] + 3 * ans[i]**2 - 3 * ans[i] + 1, i)) for _ in range(rk): v, i = hq.heappop(l) ans[i] += 1 if ans[i] < a[i]: hq.heappush(l, (-a[i] + 3 * ans[i]**2 - 3 * ans[i] + 1, i)) print(*ans) return solve() ```
103,842
Provide tags and a correct Python 3 solution for this coding contest problem. Uh oh! Applications to tech companies are due soon, and you've been procrastinating by doing contests instead! (Let's pretend for now that it is actually possible to get a job in these uncertain times.) You have completed many programming projects. In fact, there are exactly n types of programming projects, and you have completed a_i projects of type i. Your résumé has limited space, but you want to carefully choose them in such a way that maximizes your chances of getting hired. You want to include several projects of the same type to emphasize your expertise, but you also don't want to include so many that the low-quality projects start slipping in. Specifically, you determine the following quantity to be a good indicator of your chances of getting hired: $$$ f(b_1,…,b_n)=∑_{i=1}^n b_i(a_i-b_i^2). $$$ Here, b_i denotes the number of projects of type i you include in your résumé. Of course, you cannot include more projects than you have completed, so you require 0≤ b_i ≤ a_i for all i. Your résumé only has enough room for k projects, and you will absolutely not be hired if your résumé has empty space, so you require ∑_{i=1}^n b_i=k. Find values for b_1,…, b_n that maximize the value of f(b_1,…,b_n) while satisfying the above two constraints. Input The first line contains two integers n and k (1≤ n≤ 10^5, 1≤ k≤ ∑_{i=1}^n a_i) — the number of types of programming projects and the résumé size, respectively. The next line contains n integers a_1,…,a_n (1≤ a_i≤ 10^9) — a_i is equal to the number of completed projects of type i. Output In a single line, output n integers b_1,…, b_n that achieve the maximum value of f(b_1,…,b_n), while satisfying the requirements 0≤ b_i≤ a_i and ∑_{i=1}^n b_i=k. If there are multiple solutions, output any. Note that you do not have to output the value f(b_1,…,b_n). Examples Input 10 32 1 2 3 4 5 5 5 5 5 5 Output 1 2 3 3 3 4 4 4 4 4 Input 5 8 4 4 8 2 1 Output 2 2 2 1 1 Note For the first test, the optimal answer is f=-269. Note that a larger f value is possible if we ignored the constraint ∑_{i=1}^n b_i=k. For the second test, the optimal answer is f=9. Tags: binary search, greedy, math Correct Solution: ``` import os import sys input = sys.stdin.readline #sys.setrecursionlimit(int(2e5)) from collections import deque import math ##################################################################################### class CF(object): def __init__(self): self.eps = 1e-7 self.n, self.k = list(map(int, input().split())) self.a = list(map(int, input().split())) assert(len(self.a) == self.n) pass def fd(self, i): return 3*i*(i+1) + 1 def find_le(self, x, ca): if(self.fd(0) > x): return 0 #, 0 ans = ((12*x-3) **.5 - 3)/6 l = int(max(ans - 1.0, 0)) r = int(min(ans+1.5, ca-1)) while(l<r): mid = (l+r+1)//2 if(self.fd(mid)<=x): l = mid else: r = mid - 1 pass ans = r return int(ans + 1) #, int(3*ans*(ans+1) + 1 == x) def get_num(self, x): st = 0 for ca in self.a: t1 = self.find_le(x+ca, ca) st += t1 pass return st def find_k(self, k): l = int(-1e10) r = int(4e18) while(l != r): mid = int((l+r+1)//2) st = self.get_num(mid) the_max = st if(k < the_max): r = mid - 1 else: l = mid pass ck = [] for ca in self.a: t1 = self.find_le(l+ca, ca) ck.append(t1) ck1 = [] for ca in self.a: t1 = self.find_le(l+1+ca, ca) ck1.append(t1) #the_max = sum(ck1) #the_min = the_max - eq1 #assert(k<=the_max) #assert(k>=the_min) #assert(sum(ck) == the_min) res = k - sum(ck) for i in range(self.n): if(ck1[i]>ck[i]): if(res>0): res-=1 ck[i] += 1 pass print(*ck) def main(self): self.find_k(self.k) pass if __name__ == "__main__": cf = CF() cf.main() pass ```
103,843
Provide tags and a correct Python 3 solution for this coding contest problem. Uh oh! Applications to tech companies are due soon, and you've been procrastinating by doing contests instead! (Let's pretend for now that it is actually possible to get a job in these uncertain times.) You have completed many programming projects. In fact, there are exactly n types of programming projects, and you have completed a_i projects of type i. Your résumé has limited space, but you want to carefully choose them in such a way that maximizes your chances of getting hired. You want to include several projects of the same type to emphasize your expertise, but you also don't want to include so many that the low-quality projects start slipping in. Specifically, you determine the following quantity to be a good indicator of your chances of getting hired: $$$ f(b_1,…,b_n)=∑_{i=1}^n b_i(a_i-b_i^2). $$$ Here, b_i denotes the number of projects of type i you include in your résumé. Of course, you cannot include more projects than you have completed, so you require 0≤ b_i ≤ a_i for all i. Your résumé only has enough room for k projects, and you will absolutely not be hired if your résumé has empty space, so you require ∑_{i=1}^n b_i=k. Find values for b_1,…, b_n that maximize the value of f(b_1,…,b_n) while satisfying the above two constraints. Input The first line contains two integers n and k (1≤ n≤ 10^5, 1≤ k≤ ∑_{i=1}^n a_i) — the number of types of programming projects and the résumé size, respectively. The next line contains n integers a_1,…,a_n (1≤ a_i≤ 10^9) — a_i is equal to the number of completed projects of type i. Output In a single line, output n integers b_1,…, b_n that achieve the maximum value of f(b_1,…,b_n), while satisfying the requirements 0≤ b_i≤ a_i and ∑_{i=1}^n b_i=k. If there are multiple solutions, output any. Note that you do not have to output the value f(b_1,…,b_n). Examples Input 10 32 1 2 3 4 5 5 5 5 5 5 Output 1 2 3 3 3 4 4 4 4 4 Input 5 8 4 4 8 2 1 Output 2 2 2 1 1 Note For the first test, the optimal answer is f=-269. Note that a larger f value is possible if we ignored the constraint ∑_{i=1}^n b_i=k. For the second test, the optimal answer is f=9. Tags: binary search, greedy, math Correct Solution: ``` import os import sys #sys.setrecursionlimit(int(2e5)) from collections import deque import math readline = sys.stdin.readline ##################################################################################### class CF(object): def __init__(self): self.eps = 1e-7 self.n, self.k = list(map(int, readline().split())) self.a = list(map(int, readline().split())) assert(len(self.a) == self.n) def fd(self, i): return 3*i*(i+1) + 1 def find_le(self, x, ca): if(self.fd(0) > x): return 0, 0 ans = int(((12*x-3) **.5 - 3)/6 + self.eps) ans = int(min(ans, ca-1)) return int(ans + 1), int(3*ans*(ans+1) + 1 == x) def get_num(self, x): st = 0 se = 0 for ca in self.a: t1,t2 = self.find_le(x+ca, ca) st += t1 se += t2 pass return st,se def find_k(self, k): l = int(-4e18) r = int(4e18) while(l != r): mid = int((l+r+1)//2) #print(mid) st, se = self.get_num(mid) the_max = st the_min = the_max - se # if(k>= the_min and k <= the_max): # temp = the_max - k # ans = [] # for pos in range(self.n): # if(eq[pos] == 1): # if(temp > 0): # ans.append(int(tot[pos] - 1)) # temp -= 1 # else: # ans.append(int(tot[pos])) # else: # ans.append(int(tot[pos])) # pass # print(' '.join(map(str, ans))) # return if(k < the_max): r = mid - 1 else: l = mid pass ck = [] eq = [] for ca in self.a: t1,t2 = self.find_le(l+ca, ca) ck.append(t1) ck1 = [] for ca in self.a: t1,t2 = self.find_le(l+1+ca, ca) ck1.append(t1) res = k - sum(ck) for i in range(self.n): if(ck1[i]>ck[i]): if(res>0): res-=1 ck[i] += 1 pass print(' '.join(map(str, ck))) def main(self): self.find_k(self.k) pass if __name__ == "__main__": cf = CF() cf.main() pass ```
103,844
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Uh oh! Applications to tech companies are due soon, and you've been procrastinating by doing contests instead! (Let's pretend for now that it is actually possible to get a job in these uncertain times.) You have completed many programming projects. In fact, there are exactly n types of programming projects, and you have completed a_i projects of type i. Your résumé has limited space, but you want to carefully choose them in such a way that maximizes your chances of getting hired. You want to include several projects of the same type to emphasize your expertise, but you also don't want to include so many that the low-quality projects start slipping in. Specifically, you determine the following quantity to be a good indicator of your chances of getting hired: $$$ f(b_1,…,b_n)=∑_{i=1}^n b_i(a_i-b_i^2). $$$ Here, b_i denotes the number of projects of type i you include in your résumé. Of course, you cannot include more projects than you have completed, so you require 0≤ b_i ≤ a_i for all i. Your résumé only has enough room for k projects, and you will absolutely not be hired if your résumé has empty space, so you require ∑_{i=1}^n b_i=k. Find values for b_1,…, b_n that maximize the value of f(b_1,…,b_n) while satisfying the above two constraints. Input The first line contains two integers n and k (1≤ n≤ 10^5, 1≤ k≤ ∑_{i=1}^n a_i) — the number of types of programming projects and the résumé size, respectively. The next line contains n integers a_1,…,a_n (1≤ a_i≤ 10^9) — a_i is equal to the number of completed projects of type i. Output In a single line, output n integers b_1,…, b_n that achieve the maximum value of f(b_1,…,b_n), while satisfying the requirements 0≤ b_i≤ a_i and ∑_{i=1}^n b_i=k. If there are multiple solutions, output any. Note that you do not have to output the value f(b_1,…,b_n). Examples Input 10 32 1 2 3 4 5 5 5 5 5 5 Output 1 2 3 3 3 4 4 4 4 4 Input 5 8 4 4 8 2 1 Output 2 2 2 1 1 Note For the first test, the optimal answer is f=-269. Note that a larger f value is possible if we ignored the constraint ∑_{i=1}^n b_i=k. For the second test, the optimal answer is f=9. Submitted Solution: ``` #!/usr/bin/env python from __future__ import division, print_function import os import sys from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip #sys.setrecursionlimit(int(2e5)) from collections import deque import math ##################################################################################### class CF(object): def __init__(self): #super().__init__() self.n, self.k = list(map(int, input().split())) self.a = list(map(int, input().split())) def fd(self, i): return 3*i*(i+1) + 1 def find_le(self, x, ca): ans = int((math.sqrt(12*x-3) - 3)//6) ans = min(ans, ca-1) return int(ans + 1), int(3*ans*(ans+1) + 1 == x) def get_num(self, x): tot = [] eq = [] st = 0 se = 0 for ca in self.a: t1,t2 = self.find_le(x+ca, ca) tot.append(t1) eq.append(t2) st += t1 se += t2 pass return tot, eq, int(st), int(se) def find_k(self, k): l = int(-1e20) r = int(1e20) while(l<=r): mid = int((l+r)//2) #print(mid) tot, eq, st, se = self.get_num(mid) the_max = st the_min = the_max - se if(k>= the_min and k <= the_max): temp = the_max - k ans = [] for pos in range(self.n): if(eq[pos] == 1): if(temp > 0): ans.append(int(tot[pos] - 1)) temp -= 1 else: ans.append(int(tot[pos])) else: ans.append(int(tot[pos])) pass if(k == 20071483408634): for xx in ans: print(1, end=' ') else: print(' '.join(map(str, ans))) return elif(k < the_min): r = mid - 1 elif(k > the_max): l = mid + 1 else: assert(False) pass pass def main(self): self.find_k(self.k) pass # #################################################################################### # # 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") # # def print(*args, **kwargs): # # """Prints the values to a stream, or to sys.stdout by default.""" # # sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) # # at_start = True # # for x in args: # # if not at_start: # # file.write(sep) # # file.write(str(x)) # # at_start = False # # file.write(kwargs.pop("end", "\n")) # # if kwargs.pop("flush", False): # # file.flush() # if sys.version_info[0] < 3: # sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) # else: # sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) # input = lambda: sys.stdin.readline().rstrip("\r\n") # # endregion ############################################################################## if __name__ == "__main__": cf = CF() cf.main() pass ``` No
103,845
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Uh oh! Applications to tech companies are due soon, and you've been procrastinating by doing contests instead! (Let's pretend for now that it is actually possible to get a job in these uncertain times.) You have completed many programming projects. In fact, there are exactly n types of programming projects, and you have completed a_i projects of type i. Your résumé has limited space, but you want to carefully choose them in such a way that maximizes your chances of getting hired. You want to include several projects of the same type to emphasize your expertise, but you also don't want to include so many that the low-quality projects start slipping in. Specifically, you determine the following quantity to be a good indicator of your chances of getting hired: $$$ f(b_1,…,b_n)=∑_{i=1}^n b_i(a_i-b_i^2). $$$ Here, b_i denotes the number of projects of type i you include in your résumé. Of course, you cannot include more projects than you have completed, so you require 0≤ b_i ≤ a_i for all i. Your résumé only has enough room for k projects, and you will absolutely not be hired if your résumé has empty space, so you require ∑_{i=1}^n b_i=k. Find values for b_1,…, b_n that maximize the value of f(b_1,…,b_n) while satisfying the above two constraints. Input The first line contains two integers n and k (1≤ n≤ 10^5, 1≤ k≤ ∑_{i=1}^n a_i) — the number of types of programming projects and the résumé size, respectively. The next line contains n integers a_1,…,a_n (1≤ a_i≤ 10^9) — a_i is equal to the number of completed projects of type i. Output In a single line, output n integers b_1,…, b_n that achieve the maximum value of f(b_1,…,b_n), while satisfying the requirements 0≤ b_i≤ a_i and ∑_{i=1}^n b_i=k. If there are multiple solutions, output any. Note that you do not have to output the value f(b_1,…,b_n). Examples Input 10 32 1 2 3 4 5 5 5 5 5 5 Output 1 2 3 3 3 4 4 4 4 4 Input 5 8 4 4 8 2 1 Output 2 2 2 1 1 Note For the first test, the optimal answer is f=-269. Note that a larger f value is possible if we ignored the constraint ∑_{i=1}^n b_i=k. For the second test, the optimal answer is f=9. Submitted Solution: ``` #!/usr/bin/env python from __future__ import division, print_function import os import sys from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip #sys.setrecursionlimit(int(2e5)) from collections import deque import math ##################################################################################### class CF(object): def __init__(self): self.n, self.k = list(map(int, input().split())) self.a = list(map(int, input().split())) def fd(self, i): return 3*i*(i+1) + 1 def find_le(self, x, ca): ans = int((math.sqrt(12*x-3) - 3)//6) ans = int(min(ans, ca-1)) return int(ans + 1), int(3*ans*(ans+1) + 1 == x) def get_num(self, x): tot = [] eq = [] st = 0 se = 0 for ca in self.a: t1,t2 = self.find_le(x+ca, ca) tot.append(t1) eq.append(t2) st += t1 se += t2 pass return tot, eq, int(st), int(se) def find_k(self, k): l = int(-1e20) r = int(1e20) while(l<=r): mid = int((l+r)//2) #print(mid) tot, eq, st, se = self.get_num(mid) the_max = st the_min = the_max - se if(k>= the_min and k <= the_max): temp = the_max - k ans = [] for pos in range(self.n): if(eq[pos] == 1): if(temp > 0): ans.append(int(tot[pos] - 1)) temp -= 1 else: ans.append(int(tot[pos])) else: ans.append(int(tot[pos])) pass print(' '.join(map(str, ans))) return elif(k < the_min): r = mid - 1 elif(k > the_max): l = mid + 1 else: assert(False) pass print('???????') pass def main(self): self.find_k(self.k) pass # #################################################################################### # # 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") # # def print(*args, **kwargs): # # """Prints the values to a stream, or to sys.stdout by default.""" # # sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) # # at_start = True # # for x in args: # # if not at_start: # # file.write(sep) # # file.write(str(x)) # # at_start = False # # file.write(kwargs.pop("end", "\n")) # # if kwargs.pop("flush", False): # # file.flush() # if sys.version_info[0] < 3: # sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) # else: # sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) # input = lambda: sys.stdin.readline().rstrip("\r\n") # # endregion ############################################################################## if __name__ == "__main__": cf = CF() cf.main() pass ``` No
103,846
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Uh oh! Applications to tech companies are due soon, and you've been procrastinating by doing contests instead! (Let's pretend for now that it is actually possible to get a job in these uncertain times.) You have completed many programming projects. In fact, there are exactly n types of programming projects, and you have completed a_i projects of type i. Your résumé has limited space, but you want to carefully choose them in such a way that maximizes your chances of getting hired. You want to include several projects of the same type to emphasize your expertise, but you also don't want to include so many that the low-quality projects start slipping in. Specifically, you determine the following quantity to be a good indicator of your chances of getting hired: $$$ f(b_1,…,b_n)=∑_{i=1}^n b_i(a_i-b_i^2). $$$ Here, b_i denotes the number of projects of type i you include in your résumé. Of course, you cannot include more projects than you have completed, so you require 0≤ b_i ≤ a_i for all i. Your résumé only has enough room for k projects, and you will absolutely not be hired if your résumé has empty space, so you require ∑_{i=1}^n b_i=k. Find values for b_1,…, b_n that maximize the value of f(b_1,…,b_n) while satisfying the above two constraints. Input The first line contains two integers n and k (1≤ n≤ 10^5, 1≤ k≤ ∑_{i=1}^n a_i) — the number of types of programming projects and the résumé size, respectively. The next line contains n integers a_1,…,a_n (1≤ a_i≤ 10^9) — a_i is equal to the number of completed projects of type i. Output In a single line, output n integers b_1,…, b_n that achieve the maximum value of f(b_1,…,b_n), while satisfying the requirements 0≤ b_i≤ a_i and ∑_{i=1}^n b_i=k. If there are multiple solutions, output any. Note that you do not have to output the value f(b_1,…,b_n). Examples Input 10 32 1 2 3 4 5 5 5 5 5 5 Output 1 2 3 3 3 4 4 4 4 4 Input 5 8 4 4 8 2 1 Output 2 2 2 1 1 Note For the first test, the optimal answer is f=-269. Note that a larger f value is possible if we ignored the constraint ∑_{i=1}^n b_i=k. For the second test, the optimal answer is f=9. Submitted Solution: ``` #!/usr/bin/env python from __future__ import division, print_function import os import sys from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip #sys.setrecursionlimit(int(2e5)) from collections import deque import math ##################################################################################### class CF(object): def __init__(self): #super().__init__() self.n, self.k = list(map(int, input().split())) self.a = list(map(int, input().split())) def fd(self, i): return 3*i*(i+1) + 1 def find_le(self, x, ca): ans = int((math.sqrt(12*x-3) - 3)//6) ans = min(ans, ca-1) return int(ans + 1), int(3*ans*(ans+1) + 1 == x) def get_num(self, x): tot = [] eq = [] st = 0 se = 0 for ca in self.a: t1,t2 = self.find_le(x+ca, ca) tot.append(t1) eq.append(t2) st += t1 se += t2 pass return tot, eq, int(st), int(se) def find_k(self, k): l = int(-1e20) r = int(1e20) while(l<=r): mid = int((l+r)//2) #print(mid) tot, eq, st, se = self.get_num(mid) the_max = st the_min = the_max - se if(k>= the_min and k <= the_max): temp = the_max - k ans = [] for pos in range(self.n): if(eq[pos] == 1): if(temp > 0): ans.append(int(tot[pos] - 1)) temp -= 1 else: ans.append(int(tot[pos])) else: ans.append(int(tot[pos])) pass print(' '.join(map(str, ans))) return elif(k < the_min): r = mid - 1 elif(k > the_max): l = mid + 1 else: assert(False) pass pass def main(self): self.find_k(self.k) pass #################################################################################### # 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") # def print(*args, **kwargs): # """Prints the values to a stream, or to sys.stdout by default.""" # sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) # at_start = True # for x in args: # if not at_start: # file.write(sep) # file.write(str(x)) # at_start = False # file.write(kwargs.pop("end", "\n")) # if kwargs.pop("flush", False): # file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion ############################################################################## if __name__ == "__main__": cf = CF() cf.main() pass ``` No
103,847
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Uh oh! Applications to tech companies are due soon, and you've been procrastinating by doing contests instead! (Let's pretend for now that it is actually possible to get a job in these uncertain times.) You have completed many programming projects. In fact, there are exactly n types of programming projects, and you have completed a_i projects of type i. Your résumé has limited space, but you want to carefully choose them in such a way that maximizes your chances of getting hired. You want to include several projects of the same type to emphasize your expertise, but you also don't want to include so many that the low-quality projects start slipping in. Specifically, you determine the following quantity to be a good indicator of your chances of getting hired: $$$ f(b_1,…,b_n)=∑_{i=1}^n b_i(a_i-b_i^2). $$$ Here, b_i denotes the number of projects of type i you include in your résumé. Of course, you cannot include more projects than you have completed, so you require 0≤ b_i ≤ a_i for all i. Your résumé only has enough room for k projects, and you will absolutely not be hired if your résumé has empty space, so you require ∑_{i=1}^n b_i=k. Find values for b_1,…, b_n that maximize the value of f(b_1,…,b_n) while satisfying the above two constraints. Input The first line contains two integers n and k (1≤ n≤ 10^5, 1≤ k≤ ∑_{i=1}^n a_i) — the number of types of programming projects and the résumé size, respectively. The next line contains n integers a_1,…,a_n (1≤ a_i≤ 10^9) — a_i is equal to the number of completed projects of type i. Output In a single line, output n integers b_1,…, b_n that achieve the maximum value of f(b_1,…,b_n), while satisfying the requirements 0≤ b_i≤ a_i and ∑_{i=1}^n b_i=k. If there are multiple solutions, output any. Note that you do not have to output the value f(b_1,…,b_n). Examples Input 10 32 1 2 3 4 5 5 5 5 5 5 Output 1 2 3 3 3 4 4 4 4 4 Input 5 8 4 4 8 2 1 Output 2 2 2 1 1 Note For the first test, the optimal answer is f=-269. Note that a larger f value is possible if we ignored the constraint ∑_{i=1}^n b_i=k. For the second test, the optimal answer is f=9. Submitted Solution: ``` #!/usr/bin/env python from __future__ import division, print_function import os import sys from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip #sys.setrecursionlimit(int(2e5)) from collections import deque import math ##################################################################################### class CF(object): def __init__(self): #super().__init__() self.n, self.k = list(map(int, input().split())) self.a = list(map(int, input().split())) def fd(self, i): return 3*i*(i+1) + 1 def find_le(self, x, ca): ans = int((math.sqrt(12*x-3) - 3)//6) ans = min(ans, ca-1) return int(ans + 1), int(3*ans*(ans+1) + 1 == x) def get_num(self, x): tot = [] eq = [] st = 0 se = 0 for ca in self.a: t1,t2 = self.find_le(x+ca, ca) tot.append(t1) eq.append(t2) st += t1 se += t2 pass return tot, eq, int(st), int(se) def find_k(self, k): l = int(-1e20) r = int(1e20) while(l<=r): mid = int((l+r)//2) #print(mid) tot, eq, st, se = self.get_num(mid) the_max = st the_min = the_max - se if(k>= the_min and k <= the_max): temp = the_max - k ans = [] for pos in range(self.n): if(eq[pos] == 1): if(temp > 0): ans.append(int(tot[pos] - 1)) temp -= 1 else: ans.append(int(tot[pos])) else: ans.append(int(tot[pos])) pass if(k == 20071483408634): for xx in ans: print(1, end=' ') else: print(' '.join(map(str, ans))) return elif(k < the_min): r = mid - 1 elif(k > the_max): l = mid + 1 else: assert(False) pass pass def main(self): self.find_k(self.k) pass #################################################################################### # 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") # def print(*args, **kwargs): # """Prints the values to a stream, or to sys.stdout by default.""" # sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) # at_start = True # for x in args: # if not at_start: # file.write(sep) # file.write(str(x)) # at_start = False # file.write(kwargs.pop("end", "\n")) # if kwargs.pop("flush", False): # file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion ############################################################################## if __name__ == "__main__": cf = CF() cf.main() pass ``` No
103,848
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n integers a_1, a_2, ..., a_n. For each a_i find its two divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 (where \gcd(a, b) is the greatest common divisor of a and b) or say that there is no such pair. Input The first line contains single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the size of the array a. The second line contains n integers a_1, a_2, ..., a_n (2 ≤ a_i ≤ 10^7) — the array a. Output To speed up the output, print two lines with n integers in each line. The i-th integers in the first and second lines should be corresponding divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 or -1 and -1 if there is no such pair. If there are multiple answers, print any of them. Example Input 10 2 3 4 5 6 7 8 9 10 24 Output -1 -1 -1 -1 3 -1 -1 -1 2 2 -1 -1 -1 -1 2 -1 -1 -1 5 3 Note Let's look at a_7 = 8. It has 3 divisors greater than 1: 2, 4, 8. As you can see, the sum of any pair of divisors is divisible by 2 as well as a_7. There are other valid pairs of d_1 and d_2 for a_{10}=24, like (3, 4) or (8, 3). You can print any of them. Tags: constructive algorithms, math, number theory Correct Solution: ``` import math import sys from collections import deque from fractions import Fraction # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # -------------------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): # At least (mid + 1) elements are there # whose values are less than # or equal to key count = mid + 1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count #--------------------------------------------------binary---------------------------------------- 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 mid element is greater than # k update leftGreater and r 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=int(input()) l=list(map(int,input().split())) m=max(l)+1 small=[1]*m for i in range(2,m): if small[i]==1: small[i]=i for j in range(i*i,m,i): if small[j]==1: small[j]=i ans1=[-1]*n ans2=[-1]*n for i in range(n): t=l[i] x=small[l[i]] c=1 while(l[i]%x==0): l[i]//=x c*=x l[i]=t if c==l[i]: ans1[i]=-1 ans2[i]=-1 else: ans1[i]=c ans2[i]=l[i]//c print(*ans1,sep=" ") print(*ans2,sep=" ") ```
103,849
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n integers a_1, a_2, ..., a_n. For each a_i find its two divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 (where \gcd(a, b) is the greatest common divisor of a and b) or say that there is no such pair. Input The first line contains single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the size of the array a. The second line contains n integers a_1, a_2, ..., a_n (2 ≤ a_i ≤ 10^7) — the array a. Output To speed up the output, print two lines with n integers in each line. The i-th integers in the first and second lines should be corresponding divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 or -1 and -1 if there is no such pair. If there are multiple answers, print any of them. Example Input 10 2 3 4 5 6 7 8 9 10 24 Output -1 -1 -1 -1 3 -1 -1 -1 2 2 -1 -1 -1 -1 2 -1 -1 -1 5 3 Note Let's look at a_7 = 8. It has 3 divisors greater than 1: 2, 4, 8. As you can see, the sum of any pair of divisors is divisible by 2 as well as a_7. There are other valid pairs of d_1 and d_2 for a_{10}=24, like (3, 4) or (8, 3). You can print any of them. Tags: constructive algorithms, math, number theory Correct Solution: ``` import math as mt def sieve(MAXN): spf = [0 for i in range(MAXN)] spf[1] = 1 for i in range(2, MAXN): # marking smallest prime factor # for every number to be itself. spf[i] = i # separately marking spf for # every even number as 2 for i in range(4, MAXN, 2): spf[i] = 2 for i in range(3, mt.ceil(mt.sqrt(MAXN))): # checking if i is prime if (spf[i] == i): # marking SPF for all numbers # divisible by i for j in range(i * i, MAXN, i): # marking spf[j] if it is # not previously marked if (spf[j] == j): spf[j] = i return spf def getFactorization(x): ret = list() while (x != 1): ret.append(spf[x]) x = x // spf[x] return ret # Driver code # precalculating Smallest Prime Factor n = int(input()) l = list(map(int,input().split())) spf = sieve(max(l)+2) ans1 = [] ans2 = [] for i in range(n): num = l[i] sp = spf[num] while sp==spf[num]: num = num//sp if num==1: ans1.append(-1) ans2.append(-1) else: ans1.append(num) ans2.append(sp) print(*ans1) print(*ans2) ```
103,850
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n integers a_1, a_2, ..., a_n. For each a_i find its two divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 (where \gcd(a, b) is the greatest common divisor of a and b) or say that there is no such pair. Input The first line contains single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the size of the array a. The second line contains n integers a_1, a_2, ..., a_n (2 ≤ a_i ≤ 10^7) — the array a. Output To speed up the output, print two lines with n integers in each line. The i-th integers in the first and second lines should be corresponding divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 or -1 and -1 if there is no such pair. If there are multiple answers, print any of them. Example Input 10 2 3 4 5 6 7 8 9 10 24 Output -1 -1 -1 -1 3 -1 -1 -1 2 2 -1 -1 -1 -1 2 -1 -1 -1 5 3 Note Let's look at a_7 = 8. It has 3 divisors greater than 1: 2, 4, 8. As you can see, the sum of any pair of divisors is divisible by 2 as well as a_7. There are other valid pairs of d_1 and d_2 for a_{10}=24, like (3, 4) or (8, 3). You can print any of them. Tags: constructive algorithms, math, number theory Correct Solution: ``` from sys import stdout, stdin import os,io # input = stdin.readline # input_all = stdin.read input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline # input_all = io.BytesIO(os.read(0,os.fstat(0).st_size)).read def read_int(): return map(int, input().split()) def read_list(): return list(map(int, input().split())) def print_list(l): print(' '.join(map(str,l))) # import heapq as hq # import bisect as bs # from collections import deque as dq # from collections import defaultdict as dc import math # from collections import Counter # f = open('test.py') # input = f.readline # input_all = f.read def getPrimes(n): if n < 2: return [] else: output = [1] * n output[0],output[1] = 0,0 for i in range(2,int(n**0.5)+1): if output[i] == 1: output[i*i:n:i] = [0] * len(output[i*i:n:i]) return [i for i in range(n) if output[i]==1] primes = getPrimes(3170) s = set(primes) n = int(input()) nums = read_list() r1,r2 = [],[] for a in nums: if a&1==0: while a&1==0: a>>=1 if a>1: r1.append(2) r2.append(a) else: r1.append(-1) r2.append(-1) else: tmp = int(math.sqrt(a)) first = -1 for p in primes: if p>tmp: break if a%p==0: first = p break if first==-1: r1.append(-1) r2.append(-1) else: while a%first==0: a//=first if a>1: r1.append(first) r2.append(a) else: r1.append(-1) r2.append(-1) print_list(r1) print_list(r2) ```
103,851
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n integers a_1, a_2, ..., a_n. For each a_i find its two divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 (where \gcd(a, b) is the greatest common divisor of a and b) or say that there is no such pair. Input The first line contains single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the size of the array a. The second line contains n integers a_1, a_2, ..., a_n (2 ≤ a_i ≤ 10^7) — the array a. Output To speed up the output, print two lines with n integers in each line. The i-th integers in the first and second lines should be corresponding divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 or -1 and -1 if there is no such pair. If there are multiple answers, print any of them. Example Input 10 2 3 4 5 6 7 8 9 10 24 Output -1 -1 -1 -1 3 -1 -1 -1 2 2 -1 -1 -1 -1 2 -1 -1 -1 5 3 Note Let's look at a_7 = 8. It has 3 divisors greater than 1: 2, 4, 8. As you can see, the sum of any pair of divisors is divisible by 2 as well as a_7. There are other valid pairs of d_1 and d_2 for a_{10}=24, like (3, 4) or (8, 3). You can print any of them. Tags: constructive algorithms, math, number theory Correct Solution: ``` import io import math import os from collections import Counter """ def primeFactors(n): assert n >= 1 factors = Counter() while n % 2 == 0: factors[2] += 1 n //= 2 x = 3 while x * x <= n: while n % x == 0: factors[x] += 1 n //= x x += 2 if n != 1: factors[n] += 1 return factors """ def primes(n): # Sieve of Eratosthenes: Returns all the primes up to n (exclusive) is_prime = [True] * n is_prime[0] = False is_prime[1] = False for i in range(2, n): if is_prime[i]: for j in range(2 * i, n, i): # Multiples of a prime are not prime is_prime[j] = False return [i for i in range(n) if is_prime[i]] # want the smallest two odd prime factor of x. Don't need primes above 10**3.5. smallPrimes = primes(int(10 ** 3.5) + 10)[1:] cache = {} def getAns(x): key = x if key not in cache: if x % 2 == 0: # If x is even, the divisors must be odd and even (otherwise will sum to even) # Choosing 2 and the largest odd divisor should always work p = 2 while x % (2 * p) == 0: p *= 2 odd = x // p if odd == 1: ret = (-1, -1) else: ret = (2, odd) else: # Two smallest odd prime factors? TLE # p = sorted(primeFactors(x).keys())[-2:] # Smallest odd prime factor and remaining odd factor that doesn't contain that prime? p = [] for d in smallPrimes: if x % d == 0: p.append(d) while x % d == 0: x //= d break if d * d >= x: break if p and x != 1: p.append(x) if len(p) <= 1: ret = (-1, -1) else: ret = tuple(p) # if ret[0] != -1: # assert math.gcd(sum(ret), key) == 1 cache[key] = ret return cache[key] def solve(N, A): ans1 = [] ans2 = [] for x in A: d1, d2 = getAns(x) ans1.append(d1) ans2.append(d2) return " ".join(map(str, ans1)) + "\n" + " ".join(map(str, ans2)) if False: N = 5 * 10 ** 5 M = 10 ** 7 A = list(range(M - 1, M - 2 * N - 1, -2)) assert len(A) == N solve(len(A), A) if __name__ == "__main__": input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline (N,) = [int(x) for x in input().split()] A = [int(x) for x in input().split()] ans = solve(N, A) print(ans) ```
103,852
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n integers a_1, a_2, ..., a_n. For each a_i find its two divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 (where \gcd(a, b) is the greatest common divisor of a and b) or say that there is no such pair. Input The first line contains single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the size of the array a. The second line contains n integers a_1, a_2, ..., a_n (2 ≤ a_i ≤ 10^7) — the array a. Output To speed up the output, print two lines with n integers in each line. The i-th integers in the first and second lines should be corresponding divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 or -1 and -1 if there is no such pair. If there are multiple answers, print any of them. Example Input 10 2 3 4 5 6 7 8 9 10 24 Output -1 -1 -1 -1 3 -1 -1 -1 2 2 -1 -1 -1 -1 2 -1 -1 -1 5 3 Note Let's look at a_7 = 8. It has 3 divisors greater than 1: 2, 4, 8. As you can see, the sum of any pair of divisors is divisible by 2 as well as a_7. There are other valid pairs of d_1 and d_2 for a_{10}=24, like (3, 4) or (8, 3). You can print any of them. Tags: constructive algorithms, math, number theory Correct Solution: ``` import sys, os, io def rs(): return sys.stdin.readline().rstrip() def ri(): return int(sys.stdin.readline()) def ria(): return list(map(int, sys.stdin.readline().split())) def ws(s): sys.stdout.write(s + '\n') def wi(n): sys.stdout.write(str(n) + '\n') def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n') import math as mt # stores smallest prime factor for # every number # Calculating SPF (Smallest Prime Factor) # for every number till MAXN. # Time Complexity : O(nloglogn) def main(): n=ri() a=ria() MAXN=max(a)+1 spf = [0 for i in range(MAXN)] spf[1] = 1 for i in range(2, MAXN): # marking smallest prime factor # for every number to be itself. spf[i] = i # separately marking spf for # every even number as 2 for i in range(4, MAXN, 2): spf[i] = 2 for i in range(3, mt.ceil(mt.sqrt(MAXN))): # checking if i is prime if (spf[i] == i): # marking SPF for all numbers # divisible by i for j in range(i * i, MAXN, i): # marking spf[j] if it is # not previously marked if (spf[j] == j): spf[j] = i # A O(log n) function returning prime d1a=[] d2a=[] for e in a: k=spf[e] #print(e,k) l=1 r=0 z=e while True: if z%k==0: z=z/k l=l*k else: break r=e//l if r==1: d1a.append(-1) d2a.append(-1) else: d1a.append(l) d2a.append(r) wia(d1a) wia(d2a) class FastReader(io.IOBase): newlines = 0 def __init__(self, fd, chunk_size=1024 * 8): self._fd = fd self._chunk_size = chunk_size self.buffer = io.BytesIO() def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self, size=-1): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() class FastWriter(io.IOBase): def __init__(self, fd): self._fd = fd self.buffer = io.BytesIO() self.write = self.buffer.write def flush(self): os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class FastStdin(io.IOBase): def __init__(self, fd=0): self.buffer = FastReader(fd) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") class FastStdout(io.IOBase): def __init__(self, fd=1): self.buffer = FastWriter(fd) self.write = lambda s: self.buffer.write(s.encode("ascii")) self.flush = self.buffer.flush if __name__ == '__main__': sys.stdin = FastStdin() sys.stdout = FastStdout() main() ```
103,853
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n integers a_1, a_2, ..., a_n. For each a_i find its two divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 (where \gcd(a, b) is the greatest common divisor of a and b) or say that there is no such pair. Input The first line contains single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the size of the array a. The second line contains n integers a_1, a_2, ..., a_n (2 ≤ a_i ≤ 10^7) — the array a. Output To speed up the output, print two lines with n integers in each line. The i-th integers in the first and second lines should be corresponding divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 or -1 and -1 if there is no such pair. If there are multiple answers, print any of them. Example Input 10 2 3 4 5 6 7 8 9 10 24 Output -1 -1 -1 -1 3 -1 -1 -1 2 2 -1 -1 -1 -1 2 -1 -1 -1 5 3 Note Let's look at a_7 = 8. It has 3 divisors greater than 1: 2, 4, 8. As you can see, the sum of any pair of divisors is divisible by 2 as well as a_7. There are other valid pairs of d_1 and d_2 for a_{10}=24, like (3, 4) or (8, 3). You can print any of them. Tags: constructive algorithms, math, number theory Correct Solution: ``` n=int(input()) al=list(map(int,input().split())) MX=max(al)+5 seive=MX*[-1] for i in range(2,MX): if (seive[i]==-1): seive[i]=i j=i*i while (j<MX): if (seive[j]==-1): seive[j]=i j+=i #print("seive = ",seive) ans_d1=[] ans_d2=[] for i in al: k=i while (k%seive[i]==0): k=k//seive[i] if (k==1): ans_d1.append(-1) ans_d2.append(-1) else: ans_d1.append(seive[i]) ans_d2.append(k) print(*ans_d1) print(*ans_d2) ```
103,854
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n integers a_1, a_2, ..., a_n. For each a_i find its two divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 (where \gcd(a, b) is the greatest common divisor of a and b) or say that there is no such pair. Input The first line contains single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the size of the array a. The second line contains n integers a_1, a_2, ..., a_n (2 ≤ a_i ≤ 10^7) — the array a. Output To speed up the output, print two lines with n integers in each line. The i-th integers in the first and second lines should be corresponding divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 or -1 and -1 if there is no such pair. If there are multiple answers, print any of them. Example Input 10 2 3 4 5 6 7 8 9 10 24 Output -1 -1 -1 -1 3 -1 -1 -1 2 2 -1 -1 -1 -1 2 -1 -1 -1 5 3 Note Let's look at a_7 = 8. It has 3 divisors greater than 1: 2, 4, 8. As you can see, the sum of any pair of divisors is divisible by 2 as well as a_7. There are other valid pairs of d_1 and d_2 for a_{10}=24, like (3, 4) or (8, 3). You can print any of them. Tags: constructive algorithms, math, number theory Correct Solution: ``` import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") mod = 10**9 + 7 n = int(input()) a = [int(x) for x in input().split()] primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209, 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271, 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331, 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, 3499] ans1 = [-1]*n ans2 = [-1]*n for i, j in enumerate(a): for k in primes: if j % k == 0: while j % k == 0: j //= k if j != 1: ans1[i] = j ans2[i] = k break else: break print(*ans1) print(*ans2) ```
103,855
Provide tags and a correct Python 3 solution for this coding contest problem. You are given n integers a_1, a_2, ..., a_n. For each a_i find its two divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 (where \gcd(a, b) is the greatest common divisor of a and b) or say that there is no such pair. Input The first line contains single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the size of the array a. The second line contains n integers a_1, a_2, ..., a_n (2 ≤ a_i ≤ 10^7) — the array a. Output To speed up the output, print two lines with n integers in each line. The i-th integers in the first and second lines should be corresponding divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 or -1 and -1 if there is no such pair. If there are multiple answers, print any of them. Example Input 10 2 3 4 5 6 7 8 9 10 24 Output -1 -1 -1 -1 3 -1 -1 -1 2 2 -1 -1 -1 -1 2 -1 -1 -1 5 3 Note Let's look at a_7 = 8. It has 3 divisors greater than 1: 2, 4, 8. As you can see, the sum of any pair of divisors is divisible by 2 as well as a_7. There are other valid pairs of d_1 and d_2 for a_{10}=24, like (3, 4) or (8, 3). You can print any of them. Tags: constructive algorithms, math, number theory Correct Solution: ``` import sys from collections import deque, Counter from itertools import product from functools import reduce input = sys.stdin.buffer.readline n = int(input()) ls = list(map(int, input().split())) mx = max(ls) pr = [i for i in range(mx+1)] for u in range(2, mx+1): if u*u > mx: break if pr[u] == u: for v in range(u*2, mx+1, u): pr[v] = min(pr[v], u) def get_fac(n): fac = [] while n > 1: p = pr[n] if not fac or fac[-1] != p: fac.append(p) n //= p return fac d1, d2 = [], [] for u in ls: f = get_fac(u) if len(f) < 2: d1.append(-1) d2.append(-1) else: d1.append(f[0]) d2.append(reduce(lambda x, y: x*y, f[1:])) print(*d1) print(*d2) ```
103,856
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n integers a_1, a_2, ..., a_n. For each a_i find its two divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 (where \gcd(a, b) is the greatest common divisor of a and b) or say that there is no such pair. Input The first line contains single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the size of the array a. The second line contains n integers a_1, a_2, ..., a_n (2 ≤ a_i ≤ 10^7) — the array a. Output To speed up the output, print two lines with n integers in each line. The i-th integers in the first and second lines should be corresponding divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 or -1 and -1 if there is no such pair. If there are multiple answers, print any of them. Example Input 10 2 3 4 5 6 7 8 9 10 24 Output -1 -1 -1 -1 3 -1 -1 -1 2 2 -1 -1 -1 -1 2 -1 -1 -1 5 3 Note Let's look at a_7 = 8. It has 3 divisors greater than 1: 2, 4, 8. As you can see, the sum of any pair of divisors is divisible by 2 as well as a_7. There are other valid pairs of d_1 and d_2 for a_{10}=24, like (3, 4) or (8, 3). You can print any of them. Submitted Solution: ``` def leastPrimeFactor(n , least_prime) : #least_prime = [0] * (n + 1) least_prime[1] = 1 for i in range(2, n + 1) : if (least_prime[i] == 0) : least_prime[i] = i for j in range(2 * i, n + 1, i) : if (least_prime[j] == 0) : least_prime[j] = i n = int(input()) a = list(map(int , input().split())) maxn = max(a) lp = [0]*(maxn + 1) leastPrimeFactor(maxn , lp) one = [0 for _ in range(n)] two = [0 for _ in range(n)] for i in range(n): sp = lp[a[i]] while a[i] % sp == 0 and a[i] > 0: a[i] = a[i]//sp if a[i] == 1: one[i] = -1 two[i] = -1 else: one[i] = sp two[i] = a[i] print(*one) print(*two) ``` Yes
103,857
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n integers a_1, a_2, ..., a_n. For each a_i find its two divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 (where \gcd(a, b) is the greatest common divisor of a and b) or say that there is no such pair. Input The first line contains single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the size of the array a. The second line contains n integers a_1, a_2, ..., a_n (2 ≤ a_i ≤ 10^7) — the array a. Output To speed up the output, print two lines with n integers in each line. The i-th integers in the first and second lines should be corresponding divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 or -1 and -1 if there is no such pair. If there are multiple answers, print any of them. Example Input 10 2 3 4 5 6 7 8 9 10 24 Output -1 -1 -1 -1 3 -1 -1 -1 2 2 -1 -1 -1 -1 2 -1 -1 -1 5 3 Note Let's look at a_7 = 8. It has 3 divisors greater than 1: 2, 4, 8. As you can see, the sum of any pair of divisors is divisible by 2 as well as a_7. There are other valid pairs of d_1 and d_2 for a_{10}=24, like (3, 4) or (8, 3). You can print any of them. Submitted Solution: ``` # ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # ------------------- fast io -------------------- import math import bisect n=int(input()) vals=list(map(int,input().split())) maxy=max(vals) #now we construct the primes primes=[2] for j in range(3,math.ceil(math.sqrt(maxy))+1): indy=min(bisect.bisect_left(primes,math.ceil(math.sqrt(j))),len(primes)-1) broke=False for s in range(indy+1): if j%primes[s]==0: broke=True break if broke==False: primes.append(j) #primes constructed outyd1=[] outyd2=[] for j in range(n): val=vals[j] divs=[] fac=1 #now we find the prime divisiors of vals[j] isprime=True indy=min(bisect.bisect_left(primes,math.ceil(math.sqrt(val))),len(primes)-1) for s in range(indy+1): if val%primes[s]==0: divs.append(primes[s]) if isprime==True: fac=val//primes[s] isprime=False facfree=fac for s in range(len(divs)): if facfree%divs[s]==0: while facfree%divs[s]==0: facfree=facfree//divs[s] if len(divs)>=1: if facfree>divs[-1]: divs.append(facfree) if isprime==True or len(divs)==1: outyd1.append(-1) outyd2.append(-1) else: #ok now we have all the prime divisors #finding d1 and d2 d1=divs[0] d2=1 for s in range(1,len(divs)): d2*=divs[s] outyd1.append(d1) outyd2.append(d2) outyd1=[str(k) for k in outyd1] outyd2=[str(k) for k in outyd2] print(" ".join(outyd1)) print(" ".join(outyd2)) ``` Yes
103,858
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n integers a_1, a_2, ..., a_n. For each a_i find its two divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 (where \gcd(a, b) is the greatest common divisor of a and b) or say that there is no such pair. Input The first line contains single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the size of the array a. The second line contains n integers a_1, a_2, ..., a_n (2 ≤ a_i ≤ 10^7) — the array a. Output To speed up the output, print two lines with n integers in each line. The i-th integers in the first and second lines should be corresponding divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 or -1 and -1 if there is no such pair. If there are multiple answers, print any of them. Example Input 10 2 3 4 5 6 7 8 9 10 24 Output -1 -1 -1 -1 3 -1 -1 -1 2 2 -1 -1 -1 -1 2 -1 -1 -1 5 3 Note Let's look at a_7 = 8. It has 3 divisors greater than 1: 2, 4, 8. As you can see, the sum of any pair of divisors is divisible by 2 as well as a_7. There are other valid pairs of d_1 and d_2 for a_{10}=24, like (3, 4) or (8, 3). You can print any of them. Submitted Solution: ``` import io import os input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline sieve = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, 3163] n = int(input()) a = list(map(int, input().split())) out1 = [int(-1) for _ in range(n)] out2 = [int(-1) for _ in range(n)] for i in range(n): m = a[i] for p in sieve: if a[i] % p: continue while not m % p: m //= p if m != 1: out1[i] = m out2[i] = a[i]//m break print(' '.join(map(str, out1))) print(' '.join(map(str, out2))) ``` Yes
103,859
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n integers a_1, a_2, ..., a_n. For each a_i find its two divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 (where \gcd(a, b) is the greatest common divisor of a and b) or say that there is no such pair. Input The first line contains single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the size of the array a. The second line contains n integers a_1, a_2, ..., a_n (2 ≤ a_i ≤ 10^7) — the array a. Output To speed up the output, print two lines with n integers in each line. The i-th integers in the first and second lines should be corresponding divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 or -1 and -1 if there is no such pair. If there are multiple answers, print any of them. Example Input 10 2 3 4 5 6 7 8 9 10 24 Output -1 -1 -1 -1 3 -1 -1 -1 2 2 -1 -1 -1 -1 2 -1 -1 -1 5 3 Note Let's look at a_7 = 8. It has 3 divisors greater than 1: 2, 4, 8. As you can see, the sum of any pair of divisors is divisible by 2 as well as a_7. There are other valid pairs of d_1 and d_2 for a_{10}=24, like (3, 4) or (8, 3). You can print any of them. Submitted Solution: ``` from sys import stdin, stdout # 10 # 2 3 4 5 6 7 8 9 10 24 # 6 = 2,3 # 10 = 2,5 # 24 = 2,3 # 30 = 2,3,5 # a = 30 # 1. get all prime numbers # 2. put into two groups, {p1}, {p2*p3*p4...pn} # 3. then p1 and p2*p3*p4...pn are the answer # proof: # then (p1 + p2*p3*p4...pn)%p1 != 0 # then (p1 + p2*p3*p4...pn)%p2 != 0 # then (p1 + p2*p3*p4...pn)%p3 != 0 # ..... # then (p1 + p2*p3*p4...pn)%pn != 0 def two_divisors(a, div): r1 = [] r2 = [] for v in a: p = getprimelist(v, div) if len(p) < 2: r1.append(-1) r2.append(-1) else: r1.append(p[0]) d = 1 for i in range(1, len(p)): d *= p[i] r2.append(d) return [r1, r2] def getprimelist(a, div): p = [] while a > 1: if len(p) == 0 or p[-1] != div[a]: p.append(div[a]) a //= div[a] return p def getmindiv(max): max += 1 div = [i for i in range(max)] for k in range(2, max): if div[k] != k: continue curv = k while curv < max: div[curv] = k curv += k return div if __name__ == '__main__': n = int(stdin.readline()) a = list(map(int, stdin.readline().split())) div = getmindiv(max(a)) r = two_divisors(a, div) print(' '.join(map(str, r[0]))) print(' '.join(map(str, r[1]))) #stdin.write(' '.join(r[1]) + '\n') ``` Yes
103,860
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n integers a_1, a_2, ..., a_n. For each a_i find its two divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 (where \gcd(a, b) is the greatest common divisor of a and b) or say that there is no such pair. Input The first line contains single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the size of the array a. The second line contains n integers a_1, a_2, ..., a_n (2 ≤ a_i ≤ 10^7) — the array a. Output To speed up the output, print two lines with n integers in each line. The i-th integers in the first and second lines should be corresponding divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 or -1 and -1 if there is no such pair. If there are multiple answers, print any of them. Example Input 10 2 3 4 5 6 7 8 9 10 24 Output -1 -1 -1 -1 3 -1 -1 -1 2 2 -1 -1 -1 -1 2 -1 -1 -1 5 3 Note Let's look at a_7 = 8. It has 3 divisors greater than 1: 2, 4, 8. As you can see, the sum of any pair of divisors is divisible by 2 as well as a_7. There are other valid pairs of d_1 and d_2 for a_{10}=24, like (3, 4) or (8, 3). You can print any of them. Submitted Solution: ``` import math def is_power_of_two(ai): i = 1 while (2 ** i) <= ai: if ai == 2 ** i: return True i += 1 return False #  Gotten from https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n/3035188#3035188 def get_primes(n): """ Returns a list of primes < n """ sieve = [True] * n for i in range(3, int(n ** 0.5) + 1, 2): if sieve[i]: sieve[i * i :: 2 * i] = [False] * ((n - i * i - 1) // (2 * i) + 1) return [2] + [i for i in range(3, n, 2) if sieve[i]] n = int(input()) max_ai = 10 ** 7 + 1 s = int(math.sqrt(max_ai)) + 1 primes = get_primes(s) np = len(primes) set_primes = set(primes) a = list(map(int, input().split())) d1 = [-1 for i in range(n)] d2 = [-1 for i in range(n)] for i in range(n): ai = a[i] if ai in set_primes: r1 = -1 r2 = -1 elif is_power_of_two(ai): r1 = -1 r2 = -1 else: # print(ai) try: if (ai % 2) == 0: for i1 in range(1, np): p1 = primes[i1] if (ai % p1) == 0: r1 = 2 r2 = p1 assert False else: for i1 in range(1, np - 1): p1 = primes[i1] for i2 in range(i1 + 1, np): p2 = primes[i2] if (ai % i1) == 0 and (ai % p2) == 0: r1 = p1 r2 = p2 assert False except AssertionError: pass d1[i] = r1 d2[i] = r2 print(" ".join((map(str, d1)))) print(" ".join((map(str, d2)))) ``` No
103,861
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n integers a_1, a_2, ..., a_n. For each a_i find its two divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 (where \gcd(a, b) is the greatest common divisor of a and b) or say that there is no such pair. Input The first line contains single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the size of the array a. The second line contains n integers a_1, a_2, ..., a_n (2 ≤ a_i ≤ 10^7) — the array a. Output To speed up the output, print two lines with n integers in each line. The i-th integers in the first and second lines should be corresponding divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 or -1 and -1 if there is no such pair. If there are multiple answers, print any of them. Example Input 10 2 3 4 5 6 7 8 9 10 24 Output -1 -1 -1 -1 3 -1 -1 -1 2 2 -1 -1 -1 -1 2 -1 -1 -1 5 3 Note Let's look at a_7 = 8. It has 3 divisors greater than 1: 2, 4, 8. As you can see, the sum of any pair of divisors is divisible by 2 as well as a_7. There are other valid pairs of d_1 and d_2 for a_{10}=24, like (3, 4) or (8, 3). You can print any of them. Submitted Solution: ``` from math import log,gcd def get_divisor(number): i = 2 divisor = [] while i*i <=number: if number % i == 0: if i == number//i: divisor.append(i) else: divisor.append(i) divisor.append(number//i) i = i + 1 return divisor def main(): first = [] second = [] n = int(input()) number = list(map(int,input().split())) for k in range(n): divisors = get_divisor(number[k]) if gcd(number[k],sum(divisors)) != 1: first.append(-1) second.append(-1) else: for i in range(len(divisors)): for j in range(i,len(divisors)): if gcd(divisors[i] + divisors[j],number[k]) == 1: first.append(divisors[i]) second.append(divisors[j]) break; print(*first) print(*second) main() ``` No
103,862
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n integers a_1, a_2, ..., a_n. For each a_i find its two divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 (where \gcd(a, b) is the greatest common divisor of a and b) or say that there is no such pair. Input The first line contains single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the size of the array a. The second line contains n integers a_1, a_2, ..., a_n (2 ≤ a_i ≤ 10^7) — the array a. Output To speed up the output, print two lines with n integers in each line. The i-th integers in the first and second lines should be corresponding divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 or -1 and -1 if there is no such pair. If there are multiple answers, print any of them. Example Input 10 2 3 4 5 6 7 8 9 10 24 Output -1 -1 -1 -1 3 -1 -1 -1 2 2 -1 -1 -1 -1 2 -1 -1 -1 5 3 Note Let's look at a_7 = 8. It has 3 divisors greater than 1: 2, 4, 8. As you can see, the sum of any pair of divisors is divisible by 2 as well as a_7. There are other valid pairs of d_1 and d_2 for a_{10}=24, like (3, 4) or (8, 3). You can print any of them. Submitted Solution: ``` from sys import stdin, stdout import math from random import randint def primes(n): """ Returns a list of primes < n """ sieve = [True] * (n//2) for i in range(3,int(n**0.5)+1,2): if sieve[i//2]: sieve[i*i//2::i] = [False] * ((n-i*i-1)//(2*i)+1) return [2] + [2*i+1 for i in range(1,n//2) if sieve[i]] def solve(n, P): ori = n s = set() for i in P: if n == 1: break if i > math.sqrt(n): i = n first = True while n % i == 0: if first: first = False for x in s: if gcd(x+i, ori) == 1: return x, i s.add(i) n //= i return -1, -1 def gcd(a, b): while b: a, b = b, a%b return a n = int(stdin.readline()) l = list(map(int, stdin.readline().strip().split())) #l = [randint(2, 10**7) for _ in range(n)] #print(l) a1, a2 = [-1]*n, [-1]*n P = primes(max(l)) for i in range(len(l)): a1[i], a2[i] = solve(l[i], P) # print("=====================") # print(l[i]%a1[i], l[i]%a2[i], gcd(a1[i]+a2[i], l[i])) # primeFactors(l[i]) # if a1[i] > 0: # primeFactors(a1[i]+a2[i]) stdout.write(" ".join(map(str, a1))+"\n") stdout.write(" ".join(map(str, a2))+"\n") ``` No
103,863
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given n integers a_1, a_2, ..., a_n. For each a_i find its two divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 (where \gcd(a, b) is the greatest common divisor of a and b) or say that there is no such pair. Input The first line contains single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the size of the array a. The second line contains n integers a_1, a_2, ..., a_n (2 ≤ a_i ≤ 10^7) — the array a. Output To speed up the output, print two lines with n integers in each line. The i-th integers in the first and second lines should be corresponding divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 or -1 and -1 if there is no such pair. If there are multiple answers, print any of them. Example Input 10 2 3 4 5 6 7 8 9 10 24 Output -1 -1 -1 -1 3 -1 -1 -1 2 2 -1 -1 -1 -1 2 -1 -1 -1 5 3 Note Let's look at a_7 = 8. It has 3 divisors greater than 1: 2, 4, 8. As you can see, the sum of any pair of divisors is divisible by 2 as well as a_7. There are other valid pairs of d_1 and d_2 for a_{10}=24, like (3, 4) or (8, 3). You can print any of them. Submitted Solution: ``` # Contest No.: Edu89 # Problem No.: D # Solver: JEMINI # Date: 20200611 import sys import heapq def gcd(a, b): if a < b: a, b = b, a if b == 0: return a return gcd(b, a % b) def main(): temp = [True] * (10 ** 4) temp[0] = False temp[1] = False for i in range(10 ** 4): if temp[i]: cnt = 2 * i while cnt < 10 ** 4: temp[cnt] = False cnt += i prime = set() for i in range(10 ** 4): if temp[i]: prime.add(i) n = int(input()) nums = list(map(int, sys.stdin.readline().split())) ans1 = [] ans2 = [] for i in range(n): flag = False tempAns = None num = nums[i] fprime = None for j in range(2, int(num ** 0.5) + 2): #print(num, fprime, j) if num % j == 0: if not fprime: fprime = j elif j in prime and gcd(j + fprime, num) == 1: flag = True tempAns = [j, fprime] break if fprime and num // j in prime and gcd(num // j + fprime, num) == 1: flag = True tempAns = [num // j, fprime] break if flag: ans1.append(tempAns[0]) ans2.append(tempAns[1]) else: ans1.append(-1) ans2.append(-1) for i in ans1: print(i, end= " ") print("") for i in ans2: print(i, end= " ") return if __name__ == "__main__": main() ``` No
103,864
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected graph where each edge has one of two colors: black or red. Your task is to assign a real number to each node so that: * for each black edge the sum of values at its endpoints is 1; * for each red edge the sum of values at its endpoints is 2; * the sum of the absolute values of all assigned numbers is the smallest possible. Otherwise, if it is not possible, report that there is no feasible assignment of the numbers. Input The first line contains two integers N (1 ≤ N ≤ 100 000) and M (0 ≤ M ≤ 200 000): the number of nodes and the number of edges, respectively. The nodes are numbered by consecutive integers: 1, 2, …, N. The next M lines describe the edges. Each line contains three integers a, b and c denoting that there is an edge between nodes a and b (1 ≤ a, b ≤ N) with color c (1 denotes black, 2 denotes red). Output If there is a solution, the first line should contain the word "YES" and the second line should contain N space-separated numbers. For each i (1 ≤ i ≤ N), the i-th number should be the number assigned to the node i. Output should be such that: * the sum of the numbers at the endpoints of each edge differs from the precise value by less than 10^{-6}; * the sum of the absolute values of all assigned numbers differs from the smallest possible by less than 10^{-6}. If there are several valid solutions, output any of them. If there is no solution, the only line should contain the word "NO". Scoring Subtasks: 1. (5 points) N ≤ 5, M ≤ 14 2. (12 points) N ≤ 100 3. (17 points) N ≤ 1000 4. (24 points) N ≤ 10 000 5. (42 points) No further constraints Examples Input 4 4 1 2 1 2 3 2 1 3 2 3 4 1 Output YES 0.5 0.5 1.5 -0.5 Input 2 1 1 2 1 Output YES 0.3 0.7 Input 3 2 1 2 2 2 3 2 Output YES 0 2 0 Input 3 4 1 2 2 2 2 1 2 1 1 1 2 2 Output NO Note Note that in the second example the solution is not unique. Tags: *special, binary search, dfs and similar, dp, math, ternary search Correct Solution: ``` # SOLUTION CREDITS: https://codeforces.com/profile/TheVan 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() # ------------------------------ def RL(): return map(int, sys.stdin.readline().split()) def RLL(): return list(map(int, sys.stdin.readline().split())) def N(): return int(input()) def print_list(l): print(' '.join(map(str,l))) # import heapq as hq # import bisect as bs # from collections import deque as dq # from collections import defaultdict as dc # from math import ceil,floor,sqrt # from collections import Counter n,m = RL() dic = [[] for _ in range(n+1)] for _ in range(m): u,v,t = RL() dic[u].append((v,t)) dic[v].append((u,t)) v = [None] * (n+1) f = [True] * (n+1) key = {} color = [0]*(n+1) flag = True for s in range(1,n+1): if v[s] is not None: continue v[s] = 0 color[s] = s now = [s] ss = [0] while now and flag: p = now.pop() for child,t in dic[p]: if v[child] is not None: if f[child]!=f[p]: if v[child]+v[p]!=t: flag = False break elif f[child] is True: if s not in key: key[s] = (v[child]+v[p]-t)/(-2) elif v[child]+v[p]+key[s]*2!=t: flag = False break else: if s not in key: key[s] = (v[child]+v[p]-t)/2 elif v[child]+v[p]-key[s]*2!=t: flag = False break else: v[child] = t-v[p] f[child] = not f[p] if f[child]: ss.append(-1*v[child]) else: ss.append(v[child]) color[child] = s now.append(child) if not flag: break if s not in key: ss.sort() nn = len(ss) key[s] = (ss[nn>>1]+ss[nn-1>>1])/2 if flag: print("YES") res = [] for i in range(1,n+1): if f[i]: res.append(v[i]+key[color[i]]) else: res.append(v[i]-key[color[i]]) print_list(res) else: print("NO") '''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() # ------------------------------ def RL(): return map(int, sys.stdin.readline().split()) def RLL(): return list(map(int, sys.stdin.readline().split())) def N(): return int(input()) def print_list(l): print(' '.join(map(str,l)))''' ''' import heapq as hq import bisect as bs from collections import deque as dq from collections import defaultdict as dc from math import ceil, floor, sqrt from collections import Counter n, m = map(int, input().split()) dic = [[] for _ in range(n + 1)] for _ in range(m): u, v, t = map(int, input().split()) dic[u].append((v, t)) dic[v].append((u, t)) v = [None for _ in range(n + 1)] f = [True for _ in range(n + 1)] key = {} color = [0 for _ in range(n + 1)] flag = True for s in range(1, n + 1): if v[s]: continue v[s] = 0 color[s] = s now = [s] ss = [0] while now and flag: p = now.pop() for child,t in dic[p]: if v[child]: if f[child] != f[p]: if v[child] + v[p] != t: flag = False break elif f[child]: if s not in key: key[s] = (v[child] + v[p] - t) / (-2) elif v[child] + v[p] + key[s] * 2 != t: flag = False break else: if s not in key: key[s] = (v[child] + v[p] - t) / 2 elif v[child] + v[p] - key[s] * 2 != t: flag = False break else: v[child] = t - v[p] f[child] = not f[p] if f[child]: ss.append(-v[child]) else: ss.append(v[child]) color[child] = s now.append(child) if not flag: break if s not in key: ss.sort() nn = len(ss) key[s] = (ss[nn >> 1] + ss[nn - 1 >> 1]) / 2 if flag: print("YES") res = [] for i in range(1, n + 1): if f[i]: res.append(v[i] + key[color[i]]) else: res.append(v[i] - key[color[i]]) print(' '.join(map(str, res))) else: print("NO")''' ```
103,865
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected graph where each edge has one of two colors: black or red. Your task is to assign a real number to each node so that: * for each black edge the sum of values at its endpoints is 1; * for each red edge the sum of values at its endpoints is 2; * the sum of the absolute values of all assigned numbers is the smallest possible. Otherwise, if it is not possible, report that there is no feasible assignment of the numbers. Input The first line contains two integers N (1 ≤ N ≤ 100 000) and M (0 ≤ M ≤ 200 000): the number of nodes and the number of edges, respectively. The nodes are numbered by consecutive integers: 1, 2, …, N. The next M lines describe the edges. Each line contains three integers a, b and c denoting that there is an edge between nodes a and b (1 ≤ a, b ≤ N) with color c (1 denotes black, 2 denotes red). Output If there is a solution, the first line should contain the word "YES" and the second line should contain N space-separated numbers. For each i (1 ≤ i ≤ N), the i-th number should be the number assigned to the node i. Output should be such that: * the sum of the numbers at the endpoints of each edge differs from the precise value by less than 10^{-6}; * the sum of the absolute values of all assigned numbers differs from the smallest possible by less than 10^{-6}. If there are several valid solutions, output any of them. If there is no solution, the only line should contain the word "NO". Scoring Subtasks: 1. (5 points) N ≤ 5, M ≤ 14 2. (12 points) N ≤ 100 3. (17 points) N ≤ 1000 4. (24 points) N ≤ 10 000 5. (42 points) No further constraints Examples Input 4 4 1 2 1 2 3 2 1 3 2 3 4 1 Output YES 0.5 0.5 1.5 -0.5 Input 2 1 1 2 1 Output YES 0.3 0.7 Input 3 2 1 2 2 2 3 2 Output YES 0 2 0 Input 3 4 1 2 2 2 2 1 2 1 1 1 2 2 Output NO Note Note that in the second example the solution is not unique. Tags: *special, binary search, dfs and similar, dp, math, ternary search Correct 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() # ------------------------------ def RL(): return map(int, sys.stdin.readline().split()) def RLL(): return list(map(int, sys.stdin.readline().split())) def N(): return int(input()) def print_list(l): print(' '.join(map(str,l))) # import heapq as hq # import bisect as bs # from collections import deque as dq # from collections import defaultdict as dc # from math import ceil,floor,sqrt # from collections import Counter n,m = RL() dic = [[] for _ in range(n+1)] for _ in range(m): u,v,t = RL() dic[u].append((v,t)) dic[v].append((u,t)) v = [None] * (n+1) f = [True] * (n+1) key = {} color = [0]*(n+1) flag = True for s in range(1,n+1): if v[s] is not None: continue v[s] = 0 color[s] = s now = [s] ss = [0] while now and flag: p = now.pop() for child,t in dic[p]: if v[child] is not None: if f[child]!=f[p]: if v[child]+v[p]!=t: flag = False break elif f[child] is True: if s not in key: key[s] = (v[child]+v[p]-t)/(-2) elif v[child]+v[p]+key[s]*2!=t: flag = False break else: if s not in key: key[s] = (v[child]+v[p]-t)/2 elif v[child]+v[p]-key[s]*2!=t: flag = False break else: v[child] = t-v[p] f[child] = not f[p] if f[child]: ss.append(-1*v[child]) else: ss.append(v[child]) color[child] = s now.append(child) if not flag: break if s not in key: ss.sort() nn = len(ss) key[s] = (ss[nn>>1]+ss[nn-1>>1])/2 if flag: print("YES") res = [] for i in range(1,n+1): if f[i]: res.append(v[i]+key[color[i]]) else: res.append(v[i]-key[color[i]]) print_list(res) else: print("NO") ```
103,866
Provide tags and a correct Python 3 solution for this coding contest problem. There are n robbers at coordinates (a_1, b_1), (a_2, b_2), ..., (a_n, b_n) and m searchlight at coordinates (c_1, d_1), (c_2, d_2), ..., (c_m, d_m). In one move you can move each robber to the right (increase a_i of each robber by one) or move each robber up (increase b_i of each robber by one). Note that you should either increase all a_i or all b_i, you can't increase a_i for some points and b_i for some other points. Searchlight j can see a robber i if a_i ≤ c_j and b_i ≤ d_j. A configuration of robbers is safe if no searchlight can see a robber (i.e. if there is no pair i,j such that searchlight j can see a robber i). What is the minimum number of moves you need to perform to reach a safe configuration? Input The first line of input contains two integers n and m (1 ≤ n, m ≤ 2000): the number of robbers and the number of searchlight. Each of the next n lines contains two integers a_i, b_i (0 ≤ a_i, b_i ≤ 10^6), coordinates of robbers. Each of the next m lines contains two integers c_i, d_i (0 ≤ c_i, d_i ≤ 10^6), coordinates of searchlights. Output Print one integer: the minimum number of moves you need to perform to reach a safe configuration. Examples Input 1 1 0 0 2 3 Output 3 Input 2 3 1 6 6 1 10 1 1 10 7 7 Output 4 Input 1 2 0 0 0 0 0 0 Output 1 Input 7 3 0 8 3 8 2 7 0 10 5 5 7 0 3 5 6 6 3 11 11 5 Output 6 Note In the first test, you can move each robber to the right three times. After that there will be one robber in the coordinates (3, 0). The configuration of the robbers is safe, because the only searchlight can't see the robber, because it is in the coordinates (2, 3) and 3 > 2. In the second test, you can move each robber to the right two times and two times up. After that robbers will be in the coordinates (3, 8), (8, 3). It's easy the see that the configuration of the robbers is safe. It can be proved that you can't reach a safe configuration using no more than 3 moves. Tags: binary search, brute force, data structures, dp, implementation, sortings, two pointers Correct Solution: ``` '''Author- Akshit Monga''' from sys import stdin,stdout input=stdin.readline n,m=map(int,input().split()) a=[] b=[] for _ in range(n): x,y=map(int,input().split()) a.append((x,y)) for _ in range(m): x,y=map(int,input().split()) b.append((x,y)) all=[] dict={} for j in range(m): for i in range(n): if b[j][0]-a[i][0]>=0 and b[j][1]-a[i][1]>=0: if b[j][0]-a[i][0] in dict: dict[b[j][0]-a[i][0]]=max(dict[b[j][0]-a[i][0]],b[j][1]-a[i][1]) else: dict[b[j][0]-a[i][0]]=b[j][1]-a[i][1] ans=float('inf') all=sorted(dict.keys(),reverse=True) y_max=-1 for i in all: ans=min(ans,i+1+y_max+1) y_max=max(y_max,dict[i]) ans=min(ans,y_max+1) stdout.write(str(ans)+'\n') ```
103,867
Provide tags and a correct Python 3 solution for this coding contest problem. There are n robbers at coordinates (a_1, b_1), (a_2, b_2), ..., (a_n, b_n) and m searchlight at coordinates (c_1, d_1), (c_2, d_2), ..., (c_m, d_m). In one move you can move each robber to the right (increase a_i of each robber by one) or move each robber up (increase b_i of each robber by one). Note that you should either increase all a_i or all b_i, you can't increase a_i for some points and b_i for some other points. Searchlight j can see a robber i if a_i ≤ c_j and b_i ≤ d_j. A configuration of robbers is safe if no searchlight can see a robber (i.e. if there is no pair i,j such that searchlight j can see a robber i). What is the minimum number of moves you need to perform to reach a safe configuration? Input The first line of input contains two integers n and m (1 ≤ n, m ≤ 2000): the number of robbers and the number of searchlight. Each of the next n lines contains two integers a_i, b_i (0 ≤ a_i, b_i ≤ 10^6), coordinates of robbers. Each of the next m lines contains two integers c_i, d_i (0 ≤ c_i, d_i ≤ 10^6), coordinates of searchlights. Output Print one integer: the minimum number of moves you need to perform to reach a safe configuration. Examples Input 1 1 0 0 2 3 Output 3 Input 2 3 1 6 6 1 10 1 1 10 7 7 Output 4 Input 1 2 0 0 0 0 0 0 Output 1 Input 7 3 0 8 3 8 2 7 0 10 5 5 7 0 3 5 6 6 3 11 11 5 Output 6 Note In the first test, you can move each robber to the right three times. After that there will be one robber in the coordinates (3, 0). The configuration of the robbers is safe, because the only searchlight can't see the robber, because it is in the coordinates (2, 3) and 3 > 2. In the second test, you can move each robber to the right two times and two times up. After that robbers will be in the coordinates (3, 8), (8, 3). It's easy the see that the configuration of the robbers is safe. It can be proved that you can't reach a safe configuration using no more than 3 moves. Tags: binary search, brute force, data structures, dp, implementation, sortings, two pointers Correct Solution: ``` n, m = map(int, input().split()) robbers = [] lights = [] for i in range(n): a, b = map(int, input().split()) robbers.append((a, b)) for i in range(m): c, d = map(int, input().split()) lights.append((c, d)) C = [0] * 1000002 for a, b in robbers: for c, d in lights: if a <= c: C[c - a] = max(C[c - a], d - b + 1) result = 1000001 max_value = 0 for i in range(1000001, -1, -1): max_value = max(max_value, C[i]) result = min(result, i + max_value) print(result) ```
103,868
Provide tags and a correct Python 3 solution for this coding contest problem. There are n robbers at coordinates (a_1, b_1), (a_2, b_2), ..., (a_n, b_n) and m searchlight at coordinates (c_1, d_1), (c_2, d_2), ..., (c_m, d_m). In one move you can move each robber to the right (increase a_i of each robber by one) or move each robber up (increase b_i of each robber by one). Note that you should either increase all a_i or all b_i, you can't increase a_i for some points and b_i for some other points. Searchlight j can see a robber i if a_i ≤ c_j and b_i ≤ d_j. A configuration of robbers is safe if no searchlight can see a robber (i.e. if there is no pair i,j such that searchlight j can see a robber i). What is the minimum number of moves you need to perform to reach a safe configuration? Input The first line of input contains two integers n and m (1 ≤ n, m ≤ 2000): the number of robbers and the number of searchlight. Each of the next n lines contains two integers a_i, b_i (0 ≤ a_i, b_i ≤ 10^6), coordinates of robbers. Each of the next m lines contains two integers c_i, d_i (0 ≤ c_i, d_i ≤ 10^6), coordinates of searchlights. Output Print one integer: the minimum number of moves you need to perform to reach a safe configuration. Examples Input 1 1 0 0 2 3 Output 3 Input 2 3 1 6 6 1 10 1 1 10 7 7 Output 4 Input 1 2 0 0 0 0 0 0 Output 1 Input 7 3 0 8 3 8 2 7 0 10 5 5 7 0 3 5 6 6 3 11 11 5 Output 6 Note In the first test, you can move each robber to the right three times. After that there will be one robber in the coordinates (3, 0). The configuration of the robbers is safe, because the only searchlight can't see the robber, because it is in the coordinates (2, 3) and 3 > 2. In the second test, you can move each robber to the right two times and two times up. After that robbers will be in the coordinates (3, 8), (8, 3). It's easy the see that the configuration of the robbers is safe. It can be proved that you can't reach a safe configuration using no more than 3 moves. Tags: binary search, brute force, data structures, dp, implementation, sortings, two pointers Correct Solution: ``` n, m = map(int, input().split()) g = [] c = [] for i in range(n): x, y = map(int, input().split()) g.append((x, y)) for i in range(m): x, y = map(int, input().split()) c.append((x, y)) g.sort() c.sort() kek = [] mi = 1e10 mx = 0 for i in range(n): buf1 = 1e10 buf2 = 1e10 for j in range(m): if c[j][0] - g[i][0] < 0 or c[j][1] - g[i][1] < 0: continue mx = max(mx, c[j][1] - g[i][1]) mi = min(mi , c[j][0] - g[i][0]) kek.append((c[j][0] - g[i][0], c[j][1] - g[i][1])) if len(kek) > 0: kek.sort() res = min(kek[-1][0], mx) + 1 buf = kek[0][0] pref = [0]*(len(kek) + 1) for i in range(len(kek)-1, -1, -1): pref[i] = max(pref[i + 1], kek[i][1] + 1) for i in range(len(kek)): if kek[i][0] == buf: continue res = min(res, buf + 1 + pref[i]) buf = kek[i][0] print(res) else: print(0) ```
103,869
Provide tags and a correct Python 3 solution for this coding contest problem. There are n robbers at coordinates (a_1, b_1), (a_2, b_2), ..., (a_n, b_n) and m searchlight at coordinates (c_1, d_1), (c_2, d_2), ..., (c_m, d_m). In one move you can move each robber to the right (increase a_i of each robber by one) or move each robber up (increase b_i of each robber by one). Note that you should either increase all a_i or all b_i, you can't increase a_i for some points and b_i for some other points. Searchlight j can see a robber i if a_i ≤ c_j and b_i ≤ d_j. A configuration of robbers is safe if no searchlight can see a robber (i.e. if there is no pair i,j such that searchlight j can see a robber i). What is the minimum number of moves you need to perform to reach a safe configuration? Input The first line of input contains two integers n and m (1 ≤ n, m ≤ 2000): the number of robbers and the number of searchlight. Each of the next n lines contains two integers a_i, b_i (0 ≤ a_i, b_i ≤ 10^6), coordinates of robbers. Each of the next m lines contains two integers c_i, d_i (0 ≤ c_i, d_i ≤ 10^6), coordinates of searchlights. Output Print one integer: the minimum number of moves you need to perform to reach a safe configuration. Examples Input 1 1 0 0 2 3 Output 3 Input 2 3 1 6 6 1 10 1 1 10 7 7 Output 4 Input 1 2 0 0 0 0 0 0 Output 1 Input 7 3 0 8 3 8 2 7 0 10 5 5 7 0 3 5 6 6 3 11 11 5 Output 6 Note In the first test, you can move each robber to the right three times. After that there will be one robber in the coordinates (3, 0). The configuration of the robbers is safe, because the only searchlight can't see the robber, because it is in the coordinates (2, 3) and 3 > 2. In the second test, you can move each robber to the right two times and two times up. After that robbers will be in the coordinates (3, 8), (8, 3). It's easy the see that the configuration of the robbers is safe. It can be proved that you can't reach a safe configuration using no more than 3 moves. Tags: binary search, brute force, data structures, dp, implementation, sortings, two pointers Correct Solution: ``` import sys,math from collections import Counter,deque,defaultdict from bisect import bisect_left,bisect_right mod = 10**9+7 INF = float('inf') def inp(): return int(sys.stdin.readline()) def inpl(): return list(map(int, sys.stdin.readline().split())) n,m = inpl() ab = [inpl() for _ in range(n)] cd = [inpl() for _ in range(m)] up = [0] * 1000010 for a,b in ab: for c,d in cd: if a > c: continue #right:c-a+1 or up:d-b+1 up[c-a] = max(up[c-a], d-b+1) mx = 0 res = INF for right in range(1000010)[::-1]: mx = max(mx, up[right]) res = min(res, right+mx) print(res) ```
103,870
Provide tags and a correct Python 3 solution for this coding contest problem. There are n robbers at coordinates (a_1, b_1), (a_2, b_2), ..., (a_n, b_n) and m searchlight at coordinates (c_1, d_1), (c_2, d_2), ..., (c_m, d_m). In one move you can move each robber to the right (increase a_i of each robber by one) or move each robber up (increase b_i of each robber by one). Note that you should either increase all a_i or all b_i, you can't increase a_i for some points and b_i for some other points. Searchlight j can see a robber i if a_i ≤ c_j and b_i ≤ d_j. A configuration of robbers is safe if no searchlight can see a robber (i.e. if there is no pair i,j such that searchlight j can see a robber i). What is the minimum number of moves you need to perform to reach a safe configuration? Input The first line of input contains two integers n and m (1 ≤ n, m ≤ 2000): the number of robbers and the number of searchlight. Each of the next n lines contains two integers a_i, b_i (0 ≤ a_i, b_i ≤ 10^6), coordinates of robbers. Each of the next m lines contains two integers c_i, d_i (0 ≤ c_i, d_i ≤ 10^6), coordinates of searchlights. Output Print one integer: the minimum number of moves you need to perform to reach a safe configuration. Examples Input 1 1 0 0 2 3 Output 3 Input 2 3 1 6 6 1 10 1 1 10 7 7 Output 4 Input 1 2 0 0 0 0 0 0 Output 1 Input 7 3 0 8 3 8 2 7 0 10 5 5 7 0 3 5 6 6 3 11 11 5 Output 6 Note In the first test, you can move each robber to the right three times. After that there will be one robber in the coordinates (3, 0). The configuration of the robbers is safe, because the only searchlight can't see the robber, because it is in the coordinates (2, 3) and 3 > 2. In the second test, you can move each robber to the right two times and two times up. After that robbers will be in the coordinates (3, 8), (8, 3). It's easy the see that the configuration of the robbers is safe. It can be proved that you can't reach a safe configuration using no more than 3 moves. Tags: binary search, brute force, data structures, dp, implementation, sortings, two pointers Correct Solution: ``` '''Author- Akshit Monga''' from sys import stdin,stdout input=stdin.readline n,m=map(int,input().split()) a=[] b=[] for _ in range(n): x,y=map(int,input().split()) a.append((x,y)) for _ in range(m): x,y=map(int,input().split()) b.append((x,y)) all=[] dict={} for j in range(m): for i in range(n): if b[j][0]-a[i][0]>=0 and b[j][1]-a[i][1]>=0: if b[j][0]-a[i][0] in dict: dict[b[j][0]-a[i][0]]=max(dict[b[j][0]-a[i][0]],b[j][1]-a[i][1]) else: dict[b[j][0]-a[i][0]]=b[j][1]-a[i][1] ans=float('inf') all=sorted(dict.keys(),reverse=True) y_max=-1 for i in all: ans=min(ans,i+1+y_max+1) y_max=max(y_max,dict[i]) ans=min(ans,y_max+1) if ans==float('inf'): ans=0 stdout.write(str(ans)+'\n') ```
103,871
Provide tags and a correct Python 3 solution for this coding contest problem. There are n robbers at coordinates (a_1, b_1), (a_2, b_2), ..., (a_n, b_n) and m searchlight at coordinates (c_1, d_1), (c_2, d_2), ..., (c_m, d_m). In one move you can move each robber to the right (increase a_i of each robber by one) or move each robber up (increase b_i of each robber by one). Note that you should either increase all a_i or all b_i, you can't increase a_i for some points and b_i for some other points. Searchlight j can see a robber i if a_i ≤ c_j and b_i ≤ d_j. A configuration of robbers is safe if no searchlight can see a robber (i.e. if there is no pair i,j such that searchlight j can see a robber i). What is the minimum number of moves you need to perform to reach a safe configuration? Input The first line of input contains two integers n and m (1 ≤ n, m ≤ 2000): the number of robbers and the number of searchlight. Each of the next n lines contains two integers a_i, b_i (0 ≤ a_i, b_i ≤ 10^6), coordinates of robbers. Each of the next m lines contains two integers c_i, d_i (0 ≤ c_i, d_i ≤ 10^6), coordinates of searchlights. Output Print one integer: the minimum number of moves you need to perform to reach a safe configuration. Examples Input 1 1 0 0 2 3 Output 3 Input 2 3 1 6 6 1 10 1 1 10 7 7 Output 4 Input 1 2 0 0 0 0 0 0 Output 1 Input 7 3 0 8 3 8 2 7 0 10 5 5 7 0 3 5 6 6 3 11 11 5 Output 6 Note In the first test, you can move each robber to the right three times. After that there will be one robber in the coordinates (3, 0). The configuration of the robbers is safe, because the only searchlight can't see the robber, because it is in the coordinates (2, 3) and 3 > 2. In the second test, you can move each robber to the right two times and two times up. After that robbers will be in the coordinates (3, 8), (8, 3). It's easy the see that the configuration of the robbers is safe. It can be proved that you can't reach a safe configuration using no more than 3 moves. Tags: binary search, brute force, data structures, dp, implementation, sortings, two pointers Correct Solution: ``` #1800 practice n, m = map(int, input().split()) robs = [tuple(map(int, input().split())) for i in range(n)] light = [tuple(map(int, input().split())) for i in range(m)] limitation = [0]*(10**6+10) for i in range(n): for j in range(m): a, b = robs[i] c, d = light[j] x, y = c-a, d-b if x >= 0: limitation[x] = max(limitation[x], y+1) for i in range(10**6, -1, -1): limitation[i] = max(limitation[i+1], limitation[i]) ans = min(i+limitation[i] for i in range(10**6+1)) print(ans) ```
103,872
Provide tags and a correct Python 3 solution for this coding contest problem. There are n robbers at coordinates (a_1, b_1), (a_2, b_2), ..., (a_n, b_n) and m searchlight at coordinates (c_1, d_1), (c_2, d_2), ..., (c_m, d_m). In one move you can move each robber to the right (increase a_i of each robber by one) or move each robber up (increase b_i of each robber by one). Note that you should either increase all a_i or all b_i, you can't increase a_i for some points and b_i for some other points. Searchlight j can see a robber i if a_i ≤ c_j and b_i ≤ d_j. A configuration of robbers is safe if no searchlight can see a robber (i.e. if there is no pair i,j such that searchlight j can see a robber i). What is the minimum number of moves you need to perform to reach a safe configuration? Input The first line of input contains two integers n and m (1 ≤ n, m ≤ 2000): the number of robbers and the number of searchlight. Each of the next n lines contains two integers a_i, b_i (0 ≤ a_i, b_i ≤ 10^6), coordinates of robbers. Each of the next m lines contains two integers c_i, d_i (0 ≤ c_i, d_i ≤ 10^6), coordinates of searchlights. Output Print one integer: the minimum number of moves you need to perform to reach a safe configuration. Examples Input 1 1 0 0 2 3 Output 3 Input 2 3 1 6 6 1 10 1 1 10 7 7 Output 4 Input 1 2 0 0 0 0 0 0 Output 1 Input 7 3 0 8 3 8 2 7 0 10 5 5 7 0 3 5 6 6 3 11 11 5 Output 6 Note In the first test, you can move each robber to the right three times. After that there will be one robber in the coordinates (3, 0). The configuration of the robbers is safe, because the only searchlight can't see the robber, because it is in the coordinates (2, 3) and 3 > 2. In the second test, you can move each robber to the right two times and two times up. After that robbers will be in the coordinates (3, 8), (8, 3). It's easy the see that the configuration of the robbers is safe. It can be proved that you can't reach a safe configuration using no more than 3 moves. Tags: binary search, brute force, data structures, dp, implementation, sortings, two pointers Correct Solution: ``` # region fastio # from https://codeforces.com/contest/1333/submission/75948789 import sys, io, os BUFSIZE = 8192 class FastIO(io.IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = io.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(io.IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #endregion from heapq import heapify, heappop, heappush N, M = map(int, input().split()) AB = [list(map(int, input().split())) for _ in range(N)] CD_ = [list(map(int, input().split())) for _ in range(M)] #CD_.sort() L = [0 for _ in range(10**6 + 1)] maxs = [0] * N for i, (a, b) in enumerate(AB): for c, d in CD_: dx = c - a dy = d - b + 1 if dx < 0 or dy < 0: continue #L[dx].append(dy) L[dx] = max(L[dx], dy) #print(L[:11]) #exit() max_dy = 0 ans = 1<<60 for dx, dy in zip(range(10**6, -1, -1), L[::-1]): if max_dy < dy: max_dy = dy if max_dy + dx < ans: ans = max_dy + dx print(ans) exit() ```
103,873
Provide tags and a correct Python 3 solution for this coding contest problem. There are n robbers at coordinates (a_1, b_1), (a_2, b_2), ..., (a_n, b_n) and m searchlight at coordinates (c_1, d_1), (c_2, d_2), ..., (c_m, d_m). In one move you can move each robber to the right (increase a_i of each robber by one) or move each robber up (increase b_i of each robber by one). Note that you should either increase all a_i or all b_i, you can't increase a_i for some points and b_i for some other points. Searchlight j can see a robber i if a_i ≤ c_j and b_i ≤ d_j. A configuration of robbers is safe if no searchlight can see a robber (i.e. if there is no pair i,j such that searchlight j can see a robber i). What is the minimum number of moves you need to perform to reach a safe configuration? Input The first line of input contains two integers n and m (1 ≤ n, m ≤ 2000): the number of robbers and the number of searchlight. Each of the next n lines contains two integers a_i, b_i (0 ≤ a_i, b_i ≤ 10^6), coordinates of robbers. Each of the next m lines contains two integers c_i, d_i (0 ≤ c_i, d_i ≤ 10^6), coordinates of searchlights. Output Print one integer: the minimum number of moves you need to perform to reach a safe configuration. Examples Input 1 1 0 0 2 3 Output 3 Input 2 3 1 6 6 1 10 1 1 10 7 7 Output 4 Input 1 2 0 0 0 0 0 0 Output 1 Input 7 3 0 8 3 8 2 7 0 10 5 5 7 0 3 5 6 6 3 11 11 5 Output 6 Note In the first test, you can move each robber to the right three times. After that there will be one robber in the coordinates (3, 0). The configuration of the robbers is safe, because the only searchlight can't see the robber, because it is in the coordinates (2, 3) and 3 > 2. In the second test, you can move each robber to the right two times and two times up. After that robbers will be in the coordinates (3, 8), (8, 3). It's easy the see that the configuration of the robbers is safe. It can be proved that you can't reach a safe configuration using no more than 3 moves. Tags: binary search, brute force, data structures, dp, implementation, sortings, two pointers Correct Solution: ``` from sys import stdin, stdout def search_lights(n, m, ab, cd): y_a = [0] * (10**6 + 1) for i in range(n): for j in range(m): if ab[i][0] > cd[j][0] or ab[i][1] > cd[j][1]: continue x = cd[j][0] - ab[i][0] y = cd[j][1] - ab[i][1] + 1 y_a[x] = max(y_a[x], y) r = 10 ** 9 mx = 0 for i in range(10**6, -1, -1): mx = max(mx, y_a[i]) r = min(r, mx + i) return r n, m = map(int, stdin.readline().split()) ab = [] cd = [] for _ in range(n): ab.append(list(map(int, stdin.readline().split()))) for _ in range(m): cd.append(list(map(int, stdin.readline().split()))) res = search_lights(n, m, ab, cd) stdout.write(str(res) + '\n') ```
103,874
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n robbers at coordinates (a_1, b_1), (a_2, b_2), ..., (a_n, b_n) and m searchlight at coordinates (c_1, d_1), (c_2, d_2), ..., (c_m, d_m). In one move you can move each robber to the right (increase a_i of each robber by one) or move each robber up (increase b_i of each robber by one). Note that you should either increase all a_i or all b_i, you can't increase a_i for some points and b_i for some other points. Searchlight j can see a robber i if a_i ≤ c_j and b_i ≤ d_j. A configuration of robbers is safe if no searchlight can see a robber (i.e. if there is no pair i,j such that searchlight j can see a robber i). What is the minimum number of moves you need to perform to reach a safe configuration? Input The first line of input contains two integers n and m (1 ≤ n, m ≤ 2000): the number of robbers and the number of searchlight. Each of the next n lines contains two integers a_i, b_i (0 ≤ a_i, b_i ≤ 10^6), coordinates of robbers. Each of the next m lines contains two integers c_i, d_i (0 ≤ c_i, d_i ≤ 10^6), coordinates of searchlights. Output Print one integer: the minimum number of moves you need to perform to reach a safe configuration. Examples Input 1 1 0 0 2 3 Output 3 Input 2 3 1 6 6 1 10 1 1 10 7 7 Output 4 Input 1 2 0 0 0 0 0 0 Output 1 Input 7 3 0 8 3 8 2 7 0 10 5 5 7 0 3 5 6 6 3 11 11 5 Output 6 Note In the first test, you can move each robber to the right three times. After that there will be one robber in the coordinates (3, 0). The configuration of the robbers is safe, because the only searchlight can't see the robber, because it is in the coordinates (2, 3) and 3 > 2. In the second test, you can move each robber to the right two times and two times up. After that robbers will be in the coordinates (3, 8), (8, 3). It's easy the see that the configuration of the robbers is safe. It can be proved that you can't reach a safe configuration using no more than 3 moves. Submitted Solution: ``` N, M = map(int, input().split()) X = [] for _ in range(N): a, b = map(int, input().split()) X.append((a, b)) Y = [] for _ in range(M): a, b = map(int, input().split()) Y.append((a, b)) R = [0]*(10**6+1) for i in range(N): a, b = X[i] for j in range(M): x, y = Y[j] if x-a<0:continue k = x-a R[k] = max(R[k], max(y-b+1, 0)) #print(R) r = 10**18 mx = 0 for i in range(10**6,-1,-1): mx = max(mx, R[i]) r = min(r, i+mx) print(r) ``` Yes
103,875
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n robbers at coordinates (a_1, b_1), (a_2, b_2), ..., (a_n, b_n) and m searchlight at coordinates (c_1, d_1), (c_2, d_2), ..., (c_m, d_m). In one move you can move each robber to the right (increase a_i of each robber by one) or move each robber up (increase b_i of each robber by one). Note that you should either increase all a_i or all b_i, you can't increase a_i for some points and b_i for some other points. Searchlight j can see a robber i if a_i ≤ c_j and b_i ≤ d_j. A configuration of robbers is safe if no searchlight can see a robber (i.e. if there is no pair i,j such that searchlight j can see a robber i). What is the minimum number of moves you need to perform to reach a safe configuration? Input The first line of input contains two integers n and m (1 ≤ n, m ≤ 2000): the number of robbers and the number of searchlight. Each of the next n lines contains two integers a_i, b_i (0 ≤ a_i, b_i ≤ 10^6), coordinates of robbers. Each of the next m lines contains two integers c_i, d_i (0 ≤ c_i, d_i ≤ 10^6), coordinates of searchlights. Output Print one integer: the minimum number of moves you need to perform to reach a safe configuration. Examples Input 1 1 0 0 2 3 Output 3 Input 2 3 1 6 6 1 10 1 1 10 7 7 Output 4 Input 1 2 0 0 0 0 0 0 Output 1 Input 7 3 0 8 3 8 2 7 0 10 5 5 7 0 3 5 6 6 3 11 11 5 Output 6 Note In the first test, you can move each robber to the right three times. After that there will be one robber in the coordinates (3, 0). The configuration of the robbers is safe, because the only searchlight can't see the robber, because it is in the coordinates (2, 3) and 3 > 2. In the second test, you can move each robber to the right two times and two times up. After that robbers will be in the coordinates (3, 8), (8, 3). It's easy the see that the configuration of the robbers is safe. It can be proved that you can't reach a safe configuration using no more than 3 moves. Submitted Solution: ``` import sys import heapq, functools, collections import math, random from collections import Counter, defaultdict # available on Google, not available on Codeforces # import numpy as np # import scipy def solve(arr, brr): # fix inputs here console("----- solving ------") arr = sorted(arr, key=lambda x:x[1]) arr = sorted(arr, key=lambda x:x[0]) brr = sorted(brr, key=lambda x:x[1])[::-1] brr = sorted(brr, key=lambda x:x[0]) console(arr) console(brr) arr2 = [arr[0]] miny = arr[0][1] for x,y in arr[1:]: if y >= miny: continue arr2.append([x,y]) miny = min(miny, y) brr2 = [brr[-1]] maxy = brr[-1][1] for x,y in brr[::-1][1:]: if y <= maxy: continue brr2.append([x,y]) maxy = max(maxy, y) brr2 = brr2[::-1] brr2 = [[-1, brr2[0][1]+1]] + brr2 + [[brr2[-1][0]+1, -1]] del arr, brr limits = {} for robx, roby in arr2: cur = [] for (x1,y1),(x2,y2) in zip(brr2, brr2[1:]): if x2 < robx: continue if y1 < roby: continue dx = max(0, x1+1 - robx) dy = max(0, y2+1 - roby) cur.append([dx,dy]) console("cur", cur) for (dx1,dy1),(dx2,dy2) in zip(cur,cur[1:]): console(dx2,dy1) if dx2 in limits: limits[dx2] = max(limits[dx2], dy1) else: limits[dx2] = dy1 # limits.extend(cur) if cur: dx2, dy1 = cur[0] if dx2 in limits: limits[dx2] = max(limits[dx2], dy1) else: limits[dx2] = dy1 dx2, dy1 = cur[-1] if dx2 in limits: limits[dx2] = max(limits[dx2], dy1) else: limits[dx2] = dy1 if not limits: return 0 del arr2, brr2 limits = sorted(limits.items()) console("limits", limits) limits = sorted(limits, key=lambda x:x[1])[::-1] limits = sorted(limits, key=lambda x:x[0]) brr = limits brr2 = [limits[-1]] maxy = brr[-1][1] for x,y in brr[::-1][1:]: if y <= maxy: continue brr2.append((x,y)) maxy = max(maxy, y) brr2 = brr2[::-1] console("limits", brr2) console("result", brr2) limits = brr2 minres = min(limits[0][1], limits[-1][0]) for (k1,v1),(k2,v2) in zip(limits,limits[1:]): minres = min(minres, k1+v2) return minres def console(*args): # the judge will not read these print statement # print('\033[36m', *args, '\033[0m', file=sys.stderr) return # fast read all # sys.stdin.readlines() for case_num in [1]: # read line as a string # strr = input() # read line as an integer # k = int(input()) # read one line and parse each word as a string # lst = input().split() # read one line and parse each word as an integer a,b = list(map(int,input().split())) # read matrix and parse as integers (after reading read nrows) # lst = list(map(int,input().split())) # nrows = lst[0] # index containing information, please change arr = [] for _ in range(a): arr.append(list(map(int,input().split()))) brr = [] for _ in range(b): brr.append(list(map(int,input().split()))) res = solve(arr, brr) # please change # Google - case number required # print("Case #{}: {}".format(case_num+1, res)) # Codeforces - no case number required print(res) ``` Yes
103,876
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n robbers at coordinates (a_1, b_1), (a_2, b_2), ..., (a_n, b_n) and m searchlight at coordinates (c_1, d_1), (c_2, d_2), ..., (c_m, d_m). In one move you can move each robber to the right (increase a_i of each robber by one) or move each robber up (increase b_i of each robber by one). Note that you should either increase all a_i or all b_i, you can't increase a_i for some points and b_i for some other points. Searchlight j can see a robber i if a_i ≤ c_j and b_i ≤ d_j. A configuration of robbers is safe if no searchlight can see a robber (i.e. if there is no pair i,j such that searchlight j can see a robber i). What is the minimum number of moves you need to perform to reach a safe configuration? Input The first line of input contains two integers n and m (1 ≤ n, m ≤ 2000): the number of robbers and the number of searchlight. Each of the next n lines contains two integers a_i, b_i (0 ≤ a_i, b_i ≤ 10^6), coordinates of robbers. Each of the next m lines contains two integers c_i, d_i (0 ≤ c_i, d_i ≤ 10^6), coordinates of searchlights. Output Print one integer: the minimum number of moves you need to perform to reach a safe configuration. Examples Input 1 1 0 0 2 3 Output 3 Input 2 3 1 6 6 1 10 1 1 10 7 7 Output 4 Input 1 2 0 0 0 0 0 0 Output 1 Input 7 3 0 8 3 8 2 7 0 10 5 5 7 0 3 5 6 6 3 11 11 5 Output 6 Note In the first test, you can move each robber to the right three times. After that there will be one robber in the coordinates (3, 0). The configuration of the robbers is safe, because the only searchlight can't see the robber, because it is in the coordinates (2, 3) and 3 > 2. In the second test, you can move each robber to the right two times and two times up. After that robbers will be in the coordinates (3, 8), (8, 3). It's easy the see that the configuration of the robbers is safe. It can be proved that you can't reach a safe configuration using no more than 3 moves. Submitted Solution: ``` import sys from itertools import accumulate def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c for j in range(b)] for i in range(a)] def list3d(a, b, c, d): return [[[d for k in range(c)] for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e for l in range(d)] for k in range(c)] for j in range(b)] for i in range(a)] def ceil(x, y=1): return int(-(-x // y)) def INT(): return int(input()) def MAP(): return map(int, input().split()) def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)] def Yes(): print('Yes') def No(): print('No') def YES(): print('YES') def NO(): print('NO') INF = 10**18 MOD = 10**9 + 7 EPS = 10**-10 N, M = MAP() AB = [] for i in range(N): a, b = MAP() AB.append((a, b)) CD = [] for i in range(M): c, d = MAP() CD.append((c, d)) C, D = zip(*CD) L = max(C) acc = [0] * (L+2) for a, b in AB: for c, d in CD: if c-a >= 0: acc[c-a] = max(acc[c-a], d-b+1) acc = list(accumulate(acc[::-1], max))[::-1] ans = INF for x in range(L+2): y = acc[x] ans = min(ans, x+y) print(ans) ``` Yes
103,877
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n robbers at coordinates (a_1, b_1), (a_2, b_2), ..., (a_n, b_n) and m searchlight at coordinates (c_1, d_1), (c_2, d_2), ..., (c_m, d_m). In one move you can move each robber to the right (increase a_i of each robber by one) or move each robber up (increase b_i of each robber by one). Note that you should either increase all a_i or all b_i, you can't increase a_i for some points and b_i for some other points. Searchlight j can see a robber i if a_i ≤ c_j and b_i ≤ d_j. A configuration of robbers is safe if no searchlight can see a robber (i.e. if there is no pair i,j such that searchlight j can see a robber i). What is the minimum number of moves you need to perform to reach a safe configuration? Input The first line of input contains two integers n and m (1 ≤ n, m ≤ 2000): the number of robbers and the number of searchlight. Each of the next n lines contains two integers a_i, b_i (0 ≤ a_i, b_i ≤ 10^6), coordinates of robbers. Each of the next m lines contains two integers c_i, d_i (0 ≤ c_i, d_i ≤ 10^6), coordinates of searchlights. Output Print one integer: the minimum number of moves you need to perform to reach a safe configuration. Examples Input 1 1 0 0 2 3 Output 3 Input 2 3 1 6 6 1 10 1 1 10 7 7 Output 4 Input 1 2 0 0 0 0 0 0 Output 1 Input 7 3 0 8 3 8 2 7 0 10 5 5 7 0 3 5 6 6 3 11 11 5 Output 6 Note In the first test, you can move each robber to the right three times. After that there will be one robber in the coordinates (3, 0). The configuration of the robbers is safe, because the only searchlight can't see the robber, because it is in the coordinates (2, 3) and 3 > 2. In the second test, you can move each robber to the right two times and two times up. After that robbers will be in the coordinates (3, 8), (8, 3). It's easy the see that the configuration of the robbers is safe. It can be proved that you can't reach a safe configuration using no more than 3 moves. Submitted Solution: ``` import os from sys import stdin, stdout class Input: def __init__(self): self.lines = stdin.readlines() self.idx = 0 def line(self): try: return self.lines[self.idx].strip() finally: self.idx += 1 def array(self, sep = ' ', cast = int): return list(map(cast, self.line().split(sep = sep))) def known_tests(self): num_of_cases, = self.array() for case in range(num_of_cases): yield self def unknown_tests(self): while self.idx < len(self.lines): yield self def problem_solver(): ''' D. Searchlights ''' def solver(inpt): n, m = inpt.array() robs = [inpt.array() for i in range(n)] lights = [inpt.array() for i in range(m)] N = 1000006 d = [0 for i in range(N)] for r in robs: for l in lights: if r[0] <= l[0]: d[l[0] - r[0]] = max(d[l[0] - r[0]], l[1] - r[1] + 1) ans = N << 1 dmax = 0 for i in range(N): dx = (N - 1) - i dmax = max(dmax, d[dx]) ans = min(ans, dx + dmax) print(ans) '''Returns solver''' return solver try: solver = problem_solver() for tc in Input().unknown_tests(): solver(tc) except Exception as e: import traceback traceback.print_exc(file=stdout) ``` Yes
103,878
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n robbers at coordinates (a_1, b_1), (a_2, b_2), ..., (a_n, b_n) and m searchlight at coordinates (c_1, d_1), (c_2, d_2), ..., (c_m, d_m). In one move you can move each robber to the right (increase a_i of each robber by one) or move each robber up (increase b_i of each robber by one). Note that you should either increase all a_i or all b_i, you can't increase a_i for some points and b_i for some other points. Searchlight j can see a robber i if a_i ≤ c_j and b_i ≤ d_j. A configuration of robbers is safe if no searchlight can see a robber (i.e. if there is no pair i,j such that searchlight j can see a robber i). What is the minimum number of moves you need to perform to reach a safe configuration? Input The first line of input contains two integers n and m (1 ≤ n, m ≤ 2000): the number of robbers and the number of searchlight. Each of the next n lines contains two integers a_i, b_i (0 ≤ a_i, b_i ≤ 10^6), coordinates of robbers. Each of the next m lines contains two integers c_i, d_i (0 ≤ c_i, d_i ≤ 10^6), coordinates of searchlights. Output Print one integer: the minimum number of moves you need to perform to reach a safe configuration. Examples Input 1 1 0 0 2 3 Output 3 Input 2 3 1 6 6 1 10 1 1 10 7 7 Output 4 Input 1 2 0 0 0 0 0 0 Output 1 Input 7 3 0 8 3 8 2 7 0 10 5 5 7 0 3 5 6 6 3 11 11 5 Output 6 Note In the first test, you can move each robber to the right three times. After that there will be one robber in the coordinates (3, 0). The configuration of the robbers is safe, because the only searchlight can't see the robber, because it is in the coordinates (2, 3) and 3 > 2. In the second test, you can move each robber to the right two times and two times up. After that robbers will be in the coordinates (3, 8), (8, 3). It's easy the see that the configuration of the robbers is safe. It can be proved that you can't reach a safe configuration using no more than 3 moves. Submitted Solution: ``` temparr = input() temparr = temparr.split() n = int(temparr[0]) k = int(temparr[1]) robber = [] lp = [] for i in range(n): temparr = input() temparr = temparr.split() x = int(temparr[0]) y = int(temparr[1]) robber.append([x, y]) robber = sorted(robber) for i in range(k): temparr = input() temparr = temparr.split() x = int(temparr[0]) y = int(temparr[1]) lp.append([x, y]) lp = sorted(lp) x = 0 y = 0 ans = 0 # print(robber) # print(lp) for rob in robber: xx = rob[0] + x yy = rob[1] + y # print(str(x) + " " + str(y)) for lampost in lp: nx = lampost[0] ny = lampost[1] if xx > nx or yy > ny: continue elif xx == nx: xx += 1 x += 1 ans += 1 continue elif yy == ny: yy += 1 y += 1 ans += 1 continue elif (nx - xx) <= (ny - yy): incr = (nx - xx) + 1 xx += incr x += incr ans += incr continue elif (ny - yy) <= (nx - xx) : incr = (ny - yy) + 1 yy += incr y += incr ans += incr continue # print("xx " + str(xx) + " yy " + str(yy)) # print(ans) print(ans) ``` No
103,879
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n robbers at coordinates (a_1, b_1), (a_2, b_2), ..., (a_n, b_n) and m searchlight at coordinates (c_1, d_1), (c_2, d_2), ..., (c_m, d_m). In one move you can move each robber to the right (increase a_i of each robber by one) or move each robber up (increase b_i of each robber by one). Note that you should either increase all a_i or all b_i, you can't increase a_i for some points and b_i for some other points. Searchlight j can see a robber i if a_i ≤ c_j and b_i ≤ d_j. A configuration of robbers is safe if no searchlight can see a robber (i.e. if there is no pair i,j such that searchlight j can see a robber i). What is the minimum number of moves you need to perform to reach a safe configuration? Input The first line of input contains two integers n and m (1 ≤ n, m ≤ 2000): the number of robbers and the number of searchlight. Each of the next n lines contains two integers a_i, b_i (0 ≤ a_i, b_i ≤ 10^6), coordinates of robbers. Each of the next m lines contains two integers c_i, d_i (0 ≤ c_i, d_i ≤ 10^6), coordinates of searchlights. Output Print one integer: the minimum number of moves you need to perform to reach a safe configuration. Examples Input 1 1 0 0 2 3 Output 3 Input 2 3 1 6 6 1 10 1 1 10 7 7 Output 4 Input 1 2 0 0 0 0 0 0 Output 1 Input 7 3 0 8 3 8 2 7 0 10 5 5 7 0 3 5 6 6 3 11 11 5 Output 6 Note In the first test, you can move each robber to the right three times. After that there will be one robber in the coordinates (3, 0). The configuration of the robbers is safe, because the only searchlight can't see the robber, because it is in the coordinates (2, 3) and 3 > 2. In the second test, you can move each robber to the right two times and two times up. After that robbers will be in the coordinates (3, 8), (8, 3). It's easy the see that the configuration of the robbers is safe. It can be proved that you can't reach a safe configuration using no more than 3 moves. Submitted Solution: ``` import sys #from collections import deque #from functools import * #from fractions import Fraction as f #from copy import * #from bisect import * #from heapq import * #from heapq import * #from math import gcd,ceil,sqrt #from itertools import permutations as prm,product def eprint(*args): print(*args, file=sys.stderr) zz=1 #sys.setrecursionlimit(10**6) if zz: input=sys.stdin.readline else: sys.stdin=open('input.txt', 'r') sys.stdout=open('all.txt','w') di=[[-1,0],[1,0],[0,1],[0,-1]] def string(s): return "".join(s) def fori(n): return [fi() for i in range(n)] def inc(d,c,x=1): d[c]=d[c]+x if c in d else x def bo(i): return ord(i)-ord('A') def li(): return [int(xx) for xx in input().split()] def fli(): return [float(x) for x in input().split()] def comp(a,b): if(a>b): return 2 return 2 if a==b else 0 def gi(): return [xx for xx in input().split()] def cil(n,m): return n//m+int(n%m>0) def fi(): return int(input()) def pro(a): return reduce(lambda a,b:a*b,a) def swap(a,i,j): a[i],a[j]=a[j],a[i] def si(): return list(input().rstrip()) def mi(): return map(int,input().split()) def gh(): sys.stdout.flush() def isvalid(i,j): return 0<=i<n and 0<=j<m and a[i][j]!="." def bo(i): return ord(i)-ord('a') def graph(n,m): for i in range(m): x,y=mi() a[x].append(y) a[y].append(x) t=1 while t>0: t-=1 n,m=mi() a=[] b=[] for i in range(n): a.append(li()) for i in range(m): b.append(li()) dis=[[[0,0] for i in range(m+1)] for j in range(n+1)] for i in range(n): for j in range(m): for k in range(2): dis[i][j][k]=max(-1,b[j][k]-a[i][k]) mx=my=0 cc=[] for i in range(n): for j in range(m): if min(dis[i][j])!=-1: cc.append([dis[i][j][0]+1,dis[i][j][1]+1]) cc.sort() ans=10**18 #print(*cc) d=[] for i in range(len(cc)): d.append(cc[i][1]) suf=[0 for i in range(len(d)+1)] for i in range(len(d)-1,-1,-1) : suf[i]=max(suf[i+1],d[i]) for i in range(len(cc)): ans=min(ans,cc[i][0]+suf[i+1]) print(ans) ``` No
103,880
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n robbers at coordinates (a_1, b_1), (a_2, b_2), ..., (a_n, b_n) and m searchlight at coordinates (c_1, d_1), (c_2, d_2), ..., (c_m, d_m). In one move you can move each robber to the right (increase a_i of each robber by one) or move each robber up (increase b_i of each robber by one). Note that you should either increase all a_i or all b_i, you can't increase a_i for some points and b_i for some other points. Searchlight j can see a robber i if a_i ≤ c_j and b_i ≤ d_j. A configuration of robbers is safe if no searchlight can see a robber (i.e. if there is no pair i,j such that searchlight j can see a robber i). What is the minimum number of moves you need to perform to reach a safe configuration? Input The first line of input contains two integers n and m (1 ≤ n, m ≤ 2000): the number of robbers and the number of searchlight. Each of the next n lines contains two integers a_i, b_i (0 ≤ a_i, b_i ≤ 10^6), coordinates of robbers. Each of the next m lines contains two integers c_i, d_i (0 ≤ c_i, d_i ≤ 10^6), coordinates of searchlights. Output Print one integer: the minimum number of moves you need to perform to reach a safe configuration. Examples Input 1 1 0 0 2 3 Output 3 Input 2 3 1 6 6 1 10 1 1 10 7 7 Output 4 Input 1 2 0 0 0 0 0 0 Output 1 Input 7 3 0 8 3 8 2 7 0 10 5 5 7 0 3 5 6 6 3 11 11 5 Output 6 Note In the first test, you can move each robber to the right three times. After that there will be one robber in the coordinates (3, 0). The configuration of the robbers is safe, because the only searchlight can't see the robber, because it is in the coordinates (2, 3) and 3 > 2. In the second test, you can move each robber to the right two times and two times up. After that robbers will be in the coordinates (3, 8), (8, 3). It's easy the see that the configuration of the robbers is safe. It can be proved that you can't reach a safe configuration using no more than 3 moves. Submitted Solution: ``` n,m = map(int, input().split()) AB = [] for i in range(n): a,b = map(int ,input().split()) AB.append((a, b)) CD = [] for i in range(m): c, d = map(int, input().split()) CD.append((c, d)) from itertools import accumulate def is_ok(x): imos = [0]*(x+2) for a, b in AB: for c, d in CD: if c < a or d < b: continue l = x-(d-b) r = c-a if r < l: continue else: imos[max(0, l)] += 1 imos[min(x+1, r+1)] -= 1 imos = list(accumulate(imos)) for i in range(x+1): if imos[i] == 0: return True else: return False ng = 0 ok = 2*10**6+1 while ng+1 < ok: c = (ng+ok)//2 if is_ok(c): ok = c else: ng = c print(ok) ``` No
103,881
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n robbers at coordinates (a_1, b_1), (a_2, b_2), ..., (a_n, b_n) and m searchlight at coordinates (c_1, d_1), (c_2, d_2), ..., (c_m, d_m). In one move you can move each robber to the right (increase a_i of each robber by one) or move each robber up (increase b_i of each robber by one). Note that you should either increase all a_i or all b_i, you can't increase a_i for some points and b_i for some other points. Searchlight j can see a robber i if a_i ≤ c_j and b_i ≤ d_j. A configuration of robbers is safe if no searchlight can see a robber (i.e. if there is no pair i,j such that searchlight j can see a robber i). What is the minimum number of moves you need to perform to reach a safe configuration? Input The first line of input contains two integers n and m (1 ≤ n, m ≤ 2000): the number of robbers and the number of searchlight. Each of the next n lines contains two integers a_i, b_i (0 ≤ a_i, b_i ≤ 10^6), coordinates of robbers. Each of the next m lines contains two integers c_i, d_i (0 ≤ c_i, d_i ≤ 10^6), coordinates of searchlights. Output Print one integer: the minimum number of moves you need to perform to reach a safe configuration. Examples Input 1 1 0 0 2 3 Output 3 Input 2 3 1 6 6 1 10 1 1 10 7 7 Output 4 Input 1 2 0 0 0 0 0 0 Output 1 Input 7 3 0 8 3 8 2 7 0 10 5 5 7 0 3 5 6 6 3 11 11 5 Output 6 Note In the first test, you can move each robber to the right three times. After that there will be one robber in the coordinates (3, 0). The configuration of the robbers is safe, because the only searchlight can't see the robber, because it is in the coordinates (2, 3) and 3 > 2. In the second test, you can move each robber to the right two times and two times up. After that robbers will be in the coordinates (3, 8), (8, 3). It's easy the see that the configuration of the robbers is safe. It can be proved that you can't reach a safe configuration using no more than 3 moves. Submitted Solution: ``` # by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO, IOBase def main(): n,m = map(int,input().split()) rob = [tuple(map(int,input().split())) for _ in range(n)] light = [tuple(map(int,input().split())) for _ in range(m)] maxx,maxy = max(light)[0],max(light,key=lambda z:z[1])[1] lst = [0]*(maxx+1) lsty = [0]*(maxy+1) for i in light: lst[i[0]] = max(lst[i[0]],i[1]) lsty[i[1]] = max(lsty[i[1]],i[0]) a,ay = 0,0 for i in range(maxx,-1,-1): a = max(a,lst[i]) lst[i] = a for i in range(maxy,-1,-1): ay = max(ay,lsty[i]) lsty[i] = ay st,en = 0,maxx+1 an,any = 0,0 for i in rob: if i[0] <= maxx: an = max(an,lst[i[0]]-i[1]+1) if i[1] <= maxy: any = max(any,lsty[i[1]]-i[0]+1) ans = min(an,any) while st<= en: mid1 = st+(en-st)//3 mid2 = en-(en-st)//3 an1,an2 = 0,0 for i in rob: if mid1 + i[0] <= maxx: an1 = max(an1,lst[mid1+i[0]]-i[1]+1) if mid2 + i[0] <= maxx: an2 = max(an2,lst[mid2+i[0]]-i[1]+1) ans = min(ans,mid2+an2,mid1+an1) tot1,tot2 = mid1+an1,mid2+an2 if tot1 > tot2: st = mid1+1 elif tot1 < tot2: en = mid2-1 else: st = mid1+1 en = mid2-1 print(ans) #Fast IO Region BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") if __name__ == '__main__': main() ``` No
103,882
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is the easy version of the problem. The only difference is that in this version q=1. You can make hacks only if all versions of the problem are solved. Zookeeper has been teaching his q sheep how to write and how to add. The i-th sheep has to write exactly k non-negative integers with the sum n_i. Strangely, sheep have superstitions about digits and believe that the digits 3, 6, and 9 are lucky. To them, the fortune of a number depends on the decimal representation of the number; the fortune of a number is equal to the sum of fortunes of its digits, and the fortune of a digit depends on its value and position and can be described by the following table. For example, the number 319 has fortune F_{2} + 3F_{0}. <image> Each sheep wants to maximize the sum of fortune among all its k written integers. Can you help them? Input The first line contains a single integer k (1 ≤ k ≤ 999999): the number of numbers each sheep has to write. The next line contains six integers F_0, F_1, F_2, F_3, F_4, F_5 (1 ≤ F_i ≤ 10^9): the fortune assigned to each digit. The next line contains a single integer q (q = 1): the number of sheep. Each of the next q lines contains a single integer n_i (1 ≤ n_i ≤ 999999): the sum of numbers that i-th sheep has to write. In this version, there is only one line. Output Print q lines, where the i-th line contains the maximum sum of fortune of all numbers of the i-th sheep. In this version, you should print only one line. Examples Input 3 1 2 3 4 5 6 1 57 Output 11 Input 3 1 2 3 4 5 6 1 63 Output 8 Note In the first test case, 57 = 9 + 9 + 39. The three 9's contribute 1 ⋅ 3 and 3 at the tens position contributes 2 ⋅ 1. Hence the sum of fortune is 11. In the second test case, 63 = 35 + 19 + 9. The sum of fortune is 8. Submitted Solution: ``` tc = {} score_cache = {} best_cache = {} def score(num): fortunes = tc['f'] if num in score_cache: return score_cache[num] num_s = str(num) place = 0 s = 0 for n in num_s[::-1]: if n == '3': s += fortunes[place] elif n == '6': s += fortunes[place] * 2 elif n == '9': s += fortunes[place] * 3 place += 1 score_cache[num] = s return s # return best score for number, k digits long def best_score(number, k): key = "{} {}".format(number, k) if key in best_cache: return best_cache[key] if k == 1: return score(number) digits = [(d, score(d)) for d in range(number) if '3' in str(d) or '6' in str(d) or '9' in str(d)] digits.sort(key=lambda x: x[1], reverse=True) # print(number, k, digits) if not digits: best_cache[key] = 0 return 0 num, s = digits[0] rest = number - num best_cache[key] = s + best_score(rest, k - 1) return s + best_score(rest, k - 1) def solve(): return best_score(tc['sum'], tc['k']) if __name__ == "__main__": tc['k'], = [int(s) for s in input().split(" ")] tc['f'] = [int(s) for s in input().split(" ")] tc['s'], = [int(s) for s in input().split(" ")] tc['sum'], = [int(s) for s in input().split(" ")] print("{}".format(solve())) ``` No
103,883
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is the easy version of the problem. The only difference is that in this version q=1. You can make hacks only if all versions of the problem are solved. Zookeeper has been teaching his q sheep how to write and how to add. The i-th sheep has to write exactly k non-negative integers with the sum n_i. Strangely, sheep have superstitions about digits and believe that the digits 3, 6, and 9 are lucky. To them, the fortune of a number depends on the decimal representation of the number; the fortune of a number is equal to the sum of fortunes of its digits, and the fortune of a digit depends on its value and position and can be described by the following table. For example, the number 319 has fortune F_{2} + 3F_{0}. <image> Each sheep wants to maximize the sum of fortune among all its k written integers. Can you help them? Input The first line contains a single integer k (1 ≤ k ≤ 999999): the number of numbers each sheep has to write. The next line contains six integers F_0, F_1, F_2, F_3, F_4, F_5 (1 ≤ F_i ≤ 10^9): the fortune assigned to each digit. The next line contains a single integer q (q = 1): the number of sheep. Each of the next q lines contains a single integer n_i (1 ≤ n_i ≤ 999999): the sum of numbers that i-th sheep has to write. In this version, there is only one line. Output Print q lines, where the i-th line contains the maximum sum of fortune of all numbers of the i-th sheep. In this version, you should print only one line. Examples Input 3 1 2 3 4 5 6 1 57 Output 11 Input 3 1 2 3 4 5 6 1 63 Output 8 Note In the first test case, 57 = 9 + 9 + 39. The three 9's contribute 1 ⋅ 3 and 3 at the tens position contributes 2 ⋅ 1. Hence the sum of fortune is 11. In the second test case, 63 = 35 + 19 + 9. The sum of fortune is 8. Submitted Solution: ``` def solve(t): cache = {} def score(num, fortunes): nonlocal cache if num in cache: return cache[num] num_s = str(num) place = 0 s = 0 for n in num_s[::-1]: if n == '3': s += fortunes[place] elif n == '6': s += fortunes[place] * 2 elif n == '9': s += fortunes[place] * 3 place += 1 cache[num] = s return s digits = [i for i in range(1, int(tc['sum']//1.4), 1) if '3' in str(i) or '9' in str(i) or '6' in str(i)] digits.sort(key=lambda x: score(x, tc['f']), reverse=True) best_score = 0 for d1 in digits: for d2 in digits: if tc['sum'] > d1 + d2: d3 = tc['sum'] - (d1 + d2) if d1 + d2 + d3 == tc['sum']: s = score(d1, tc['f']) + score(d2, tc['f']) + score(d3, tc['f']) # return s # print(d1, d2, d3, s) if best_score < s: best_score = s if tc['sum'] / 3 > d1: return best_score return best_score if __name__ == "__main__": tc = {} tc['k'], = [int(s) for s in input().split(" ")] tc['f'] = [int(s) for s in input().split(" ")] tc['s'], = [int(s) for s in input().split(" ")] tc['sum'], = [int(s) for s in input().split(" ")] print("{}".format(solve(tc))) ``` No
103,884
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is the easy version of the problem. The only difference is that in this version q=1. You can make hacks only if all versions of the problem are solved. Zookeeper has been teaching his q sheep how to write and how to add. The i-th sheep has to write exactly k non-negative integers with the sum n_i. Strangely, sheep have superstitions about digits and believe that the digits 3, 6, and 9 are lucky. To them, the fortune of a number depends on the decimal representation of the number; the fortune of a number is equal to the sum of fortunes of its digits, and the fortune of a digit depends on its value and position and can be described by the following table. For example, the number 319 has fortune F_{2} + 3F_{0}. <image> Each sheep wants to maximize the sum of fortune among all its k written integers. Can you help them? Input The first line contains a single integer k (1 ≤ k ≤ 999999): the number of numbers each sheep has to write. The next line contains six integers F_0, F_1, F_2, F_3, F_4, F_5 (1 ≤ F_i ≤ 10^9): the fortune assigned to each digit. The next line contains a single integer q (q = 1): the number of sheep. Each of the next q lines contains a single integer n_i (1 ≤ n_i ≤ 999999): the sum of numbers that i-th sheep has to write. In this version, there is only one line. Output Print q lines, where the i-th line contains the maximum sum of fortune of all numbers of the i-th sheep. In this version, you should print only one line. Examples Input 3 1 2 3 4 5 6 1 57 Output 11 Input 3 1 2 3 4 5 6 1 63 Output 8 Note In the first test case, 57 = 9 + 9 + 39. The three 9's contribute 1 ⋅ 3 and 3 at the tens position contributes 2 ⋅ 1. Hence the sum of fortune is 11. In the second test case, 63 = 35 + 19 + 9. The sum of fortune is 8. Submitted Solution: ``` def solve(t): cache = {} def score(num, fortunes): nonlocal cache if num in cache: return cache[num] num_s = str(num) place = 0 s = 0 for n in num_s[::-1]: if n == '3': s += fortunes[place] elif n == '6': s += fortunes[place] * 2 elif n == '9': s += fortunes[place] * 3 place += 1 cache[num] = s return s digits = [i for i in range(1, tc['sum'], 1) if '3' in str(i) or '9' in str(i) or '6' in str(i)] digits.sort(key=lambda x: score(x, tc['f']), reverse=True) best_score = 0 for d1 in digits: for d2 in digits: if tc['sum'] > d1 + d2: d3 = tc['sum'] - (d1 + d2) if d1 + d2 + d3 == tc['sum']: s = score(d1, tc['f']) + score(d2, tc['f']) + score(d3, tc['f']) # return s # print(d1, d2, d3, s) if best_score < s: best_score = s if tc['sum'] / 4 > d1: return best_score return best_score if __name__ == "__main__": tc = {} tc['k'], = [int(s) for s in input().split(" ")] tc['f'] = [int(s) for s in input().split(" ")] tc['s'], = [int(s) for s in input().split(" ")] tc['sum'], = [int(s) for s in input().split(" ")] print("{}".format(solve(tc))) ``` No
103,885
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is the easy version of the problem. The only difference is that in this version q=1. You can make hacks only if all versions of the problem are solved. Zookeeper has been teaching his q sheep how to write and how to add. The i-th sheep has to write exactly k non-negative integers with the sum n_i. Strangely, sheep have superstitions about digits and believe that the digits 3, 6, and 9 are lucky. To them, the fortune of a number depends on the decimal representation of the number; the fortune of a number is equal to the sum of fortunes of its digits, and the fortune of a digit depends on its value and position and can be described by the following table. For example, the number 319 has fortune F_{2} + 3F_{0}. <image> Each sheep wants to maximize the sum of fortune among all its k written integers. Can you help them? Input The first line contains a single integer k (1 ≤ k ≤ 999999): the number of numbers each sheep has to write. The next line contains six integers F_0, F_1, F_2, F_3, F_4, F_5 (1 ≤ F_i ≤ 10^9): the fortune assigned to each digit. The next line contains a single integer q (q = 1): the number of sheep. Each of the next q lines contains a single integer n_i (1 ≤ n_i ≤ 999999): the sum of numbers that i-th sheep has to write. In this version, there is only one line. Output Print q lines, where the i-th line contains the maximum sum of fortune of all numbers of the i-th sheep. In this version, you should print only one line. Examples Input 3 1 2 3 4 5 6 1 57 Output 11 Input 3 1 2 3 4 5 6 1 63 Output 8 Note In the first test case, 57 = 9 + 9 + 39. The three 9's contribute 1 ⋅ 3 and 3 at the tens position contributes 2 ⋅ 1. Hence the sum of fortune is 11. In the second test case, 63 = 35 + 19 + 9. The sum of fortune is 8. Submitted Solution: ``` def solve(t): def score(num, fortunes): num = str(num) place = 0 s = 0 for n in num[::-1]: if n == '3': s += fortunes[place] elif n == '6': s += fortunes[place] * 2 elif n == '9': s += fortunes[place] * 3 place += 1 return s digits = [i for i in range(1, tc['sum'], 1)] digits.sort(key=lambda x: score(x, tc['f']), reverse=True) sofar = [] for _ in range(3): for d in digits: if tc['sum'] - sum(sofar) - d - (3-len(sofar)-1) >= 0: sofar.append(d) if len(sofar) == 3 and sum(sofar) != tc['sum']: del sofar[-1] if len(sofar) != 3: sofar.append(tc['sum'] - sum(sofar)) return score(sofar[0], tc['f']) + score(sofar[1], tc['f']) + score(sofar[2], tc['f']) if __name__ == "__main__": tc = {} tc['k'], = [int(s) for s in input().split(" ")] tc['f'] = [int(s) for s in input().split(" ")] tc['s'], = [int(s) for s in input().split(" ")] tc['sum'], = [int(s) for s in input().split(" ")] print("{}".format(solve(tc))) ``` No
103,886
Provide tags and a correct Python 3 solution for this coding contest problem. You are asked to watch your nephew who likes to play with toy blocks in a strange way. He has n boxes and the i-th box has a_i blocks. His game consists of two steps: 1. he chooses an arbitrary box i; 2. he tries to move all blocks from the i-th box to other boxes. If he can make the same number of blocks in each of n - 1 other boxes then he will be happy, otherwise, will be sad. Note that your nephew can only move the blocks from the chosen box to the other boxes; he cannot move blocks from the other boxes. You don't want to make your nephew sad, so you decided to put several extra blocks into some boxes in such a way that no matter which box i he chooses he won't be sad. What is the minimum number of extra blocks you need to put? Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains the integer n (2 ≤ n ≤ 10^5) — the number of boxes. The second line of each test case contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9) — the number of blocks in each box. It's guaranteed that the sum of n over test cases doesn't exceed 10^5. Output For each test case, print a single integer — the minimum number of blocks you need to put. It can be proved that the answer always exists, i. e. the number of blocks is finite. Example Input 3 3 3 2 2 4 2 2 3 2 3 0 3 0 Output 1 0 3 Note In the first test case, you can, for example, put one extra block into the first box and make a = [4, 2, 2]. If your nephew chooses the box with 4 blocks, then we will move two blocks to the second box and two blocks to the third box. If he chooses the box with 2 blocks then he will move these two blocks to the other box with 2 blocks. In the second test case, you don't need to put any extra blocks, since no matter which box your nephew chooses, he can always make other boxes equal. In the third test case, you should put 3 extra blocks. For example, you can put 2 blocks in the first box and 1 block in the third box. You'll get array a = [2, 3, 1]. Tags: binary search, greedy, math, sortings Correct Solution: ``` for _ in range(int(input())): n = int(input()) l = list(map(int,input().split())) a = 0 s = sum(l) if s%(n-1)==0: m = max(l) if m>s//(n-1): print(a+(m-s//(n-1))*(n-1)) else: print(a) else: a+=(n-1)-s%(n-1) s+=a m = max(l) if m>s//(n-1): print(a+(m-s//(n-1))*(n-1)) else: print(a) ```
103,887
Provide tags and a correct Python 3 solution for this coding contest problem. You are asked to watch your nephew who likes to play with toy blocks in a strange way. He has n boxes and the i-th box has a_i blocks. His game consists of two steps: 1. he chooses an arbitrary box i; 2. he tries to move all blocks from the i-th box to other boxes. If he can make the same number of blocks in each of n - 1 other boxes then he will be happy, otherwise, will be sad. Note that your nephew can only move the blocks from the chosen box to the other boxes; he cannot move blocks from the other boxes. You don't want to make your nephew sad, so you decided to put several extra blocks into some boxes in such a way that no matter which box i he chooses he won't be sad. What is the minimum number of extra blocks you need to put? Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains the integer n (2 ≤ n ≤ 10^5) — the number of boxes. The second line of each test case contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9) — the number of blocks in each box. It's guaranteed that the sum of n over test cases doesn't exceed 10^5. Output For each test case, print a single integer — the minimum number of blocks you need to put. It can be proved that the answer always exists, i. e. the number of blocks is finite. Example Input 3 3 3 2 2 4 2 2 3 2 3 0 3 0 Output 1 0 3 Note In the first test case, you can, for example, put one extra block into the first box and make a = [4, 2, 2]. If your nephew chooses the box with 4 blocks, then we will move two blocks to the second box and two blocks to the third box. If he chooses the box with 2 blocks then he will move these two blocks to the other box with 2 blocks. In the second test case, you don't need to put any extra blocks, since no matter which box your nephew chooses, he can always make other boxes equal. In the third test case, you should put 3 extra blocks. For example, you can put 2 blocks in the first box and 1 block in the third box. You'll get array a = [2, 3, 1]. Tags: binary search, greedy, math, sortings Correct Solution: ``` #!/usr/bin/env python import os import sys from io import BytesIO, IOBase import math def main(): for _ in range(int(input())): n = int(input()) a = list(map(int,input().split())) print(max(max(a),math.ceil(float(sum(a))/(n-1)))*(n-1)-sum(a)) # 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() ```
103,888
Provide tags and a correct Python 3 solution for this coding contest problem. You are asked to watch your nephew who likes to play with toy blocks in a strange way. He has n boxes and the i-th box has a_i blocks. His game consists of two steps: 1. he chooses an arbitrary box i; 2. he tries to move all blocks from the i-th box to other boxes. If he can make the same number of blocks in each of n - 1 other boxes then he will be happy, otherwise, will be sad. Note that your nephew can only move the blocks from the chosen box to the other boxes; he cannot move blocks from the other boxes. You don't want to make your nephew sad, so you decided to put several extra blocks into some boxes in such a way that no matter which box i he chooses he won't be sad. What is the minimum number of extra blocks you need to put? Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains the integer n (2 ≤ n ≤ 10^5) — the number of boxes. The second line of each test case contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9) — the number of blocks in each box. It's guaranteed that the sum of n over test cases doesn't exceed 10^5. Output For each test case, print a single integer — the minimum number of blocks you need to put. It can be proved that the answer always exists, i. e. the number of blocks is finite. Example Input 3 3 3 2 2 4 2 2 3 2 3 0 3 0 Output 1 0 3 Note In the first test case, you can, for example, put one extra block into the first box and make a = [4, 2, 2]. If your nephew chooses the box with 4 blocks, then we will move two blocks to the second box and two blocks to the third box. If he chooses the box with 2 blocks then he will move these two blocks to the other box with 2 blocks. In the second test case, you don't need to put any extra blocks, since no matter which box your nephew chooses, he can always make other boxes equal. In the third test case, you should put 3 extra blocks. For example, you can put 2 blocks in the first box and 1 block in the third box. You'll get array a = [2, 3, 1]. Tags: binary search, greedy, math, sortings Correct Solution: ``` p=int(input()) for i in range(p): n=int(input()) minn=0 maxx=0 sm=0 k=list(map(int,input().split())) for i in range(n): if i==0: minn=k[i] maxx=k[i] else: if minn>k[i]: minn=k[i] if maxx<k[i]: maxx=k[i] sm+=k[i] r=maxx*(n-1)-sm+minn if minn>r: if n-1==1: print(0) else: if (minn-r)%(n-1)==0: print(0) else: otv=(n-1)-(minn-r)%(n-1) print(otv) else: print(r-minn) ```
103,889
Provide tags and a correct Python 3 solution for this coding contest problem. You are asked to watch your nephew who likes to play with toy blocks in a strange way. He has n boxes and the i-th box has a_i blocks. His game consists of two steps: 1. he chooses an arbitrary box i; 2. he tries to move all blocks from the i-th box to other boxes. If he can make the same number of blocks in each of n - 1 other boxes then he will be happy, otherwise, will be sad. Note that your nephew can only move the blocks from the chosen box to the other boxes; he cannot move blocks from the other boxes. You don't want to make your nephew sad, so you decided to put several extra blocks into some boxes in such a way that no matter which box i he chooses he won't be sad. What is the minimum number of extra blocks you need to put? Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains the integer n (2 ≤ n ≤ 10^5) — the number of boxes. The second line of each test case contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9) — the number of blocks in each box. It's guaranteed that the sum of n over test cases doesn't exceed 10^5. Output For each test case, print a single integer — the minimum number of blocks you need to put. It can be proved that the answer always exists, i. e. the number of blocks is finite. Example Input 3 3 3 2 2 4 2 2 3 2 3 0 3 0 Output 1 0 3 Note In the first test case, you can, for example, put one extra block into the first box and make a = [4, 2, 2]. If your nephew chooses the box with 4 blocks, then we will move two blocks to the second box and two blocks to the third box. If he chooses the box with 2 blocks then he will move these two blocks to the other box with 2 blocks. In the second test case, you don't need to put any extra blocks, since no matter which box your nephew chooses, he can always make other boxes equal. In the third test case, you should put 3 extra blocks. For example, you can put 2 blocks in the first box and 1 block in the third box. You'll get array a = [2, 3, 1]. Tags: binary search, greedy, math, sortings Correct Solution: ``` import math t = int(input()) while t: n = int(input()) a = list(map(int,input().split())) total = sum(a) k = max(math.ceil(total/(n-1)), max(a)) ans = (n-1)*k - total print(ans) t-=1 ```
103,890
Provide tags and a correct Python 3 solution for this coding contest problem. You are asked to watch your nephew who likes to play with toy blocks in a strange way. He has n boxes and the i-th box has a_i blocks. His game consists of two steps: 1. he chooses an arbitrary box i; 2. he tries to move all blocks from the i-th box to other boxes. If he can make the same number of blocks in each of n - 1 other boxes then he will be happy, otherwise, will be sad. Note that your nephew can only move the blocks from the chosen box to the other boxes; he cannot move blocks from the other boxes. You don't want to make your nephew sad, so you decided to put several extra blocks into some boxes in such a way that no matter which box i he chooses he won't be sad. What is the minimum number of extra blocks you need to put? Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains the integer n (2 ≤ n ≤ 10^5) — the number of boxes. The second line of each test case contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9) — the number of blocks in each box. It's guaranteed that the sum of n over test cases doesn't exceed 10^5. Output For each test case, print a single integer — the minimum number of blocks you need to put. It can be proved that the answer always exists, i. e. the number of blocks is finite. Example Input 3 3 3 2 2 4 2 2 3 2 3 0 3 0 Output 1 0 3 Note In the first test case, you can, for example, put one extra block into the first box and make a = [4, 2, 2]. If your nephew chooses the box with 4 blocks, then we will move two blocks to the second box and two blocks to the third box. If he chooses the box with 2 blocks then he will move these two blocks to the other box with 2 blocks. In the second test case, you don't need to put any extra blocks, since no matter which box your nephew chooses, he can always make other boxes equal. In the third test case, you should put 3 extra blocks. For example, you can put 2 blocks in the first box and 1 block in the third box. You'll get array a = [2, 3, 1]. Tags: binary search, greedy, math, sortings Correct Solution: ``` # cook your dish here import math t = int(input()) for i in range(t): n = int(input()) a = list(map(int,input().split())) s,m = sum(a),max(a) ans = max(m,math.ceil(s/(n-1)))*(n-1)-s print(ans) ```
103,891
Provide tags and a correct Python 3 solution for this coding contest problem. You are asked to watch your nephew who likes to play with toy blocks in a strange way. He has n boxes and the i-th box has a_i blocks. His game consists of two steps: 1. he chooses an arbitrary box i; 2. he tries to move all blocks from the i-th box to other boxes. If he can make the same number of blocks in each of n - 1 other boxes then he will be happy, otherwise, will be sad. Note that your nephew can only move the blocks from the chosen box to the other boxes; he cannot move blocks from the other boxes. You don't want to make your nephew sad, so you decided to put several extra blocks into some boxes in such a way that no matter which box i he chooses he won't be sad. What is the minimum number of extra blocks you need to put? Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains the integer n (2 ≤ n ≤ 10^5) — the number of boxes. The second line of each test case contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9) — the number of blocks in each box. It's guaranteed that the sum of n over test cases doesn't exceed 10^5. Output For each test case, print a single integer — the minimum number of blocks you need to put. It can be proved that the answer always exists, i. e. the number of blocks is finite. Example Input 3 3 3 2 2 4 2 2 3 2 3 0 3 0 Output 1 0 3 Note In the first test case, you can, for example, put one extra block into the first box and make a = [4, 2, 2]. If your nephew chooses the box with 4 blocks, then we will move two blocks to the second box and two blocks to the third box. If he chooses the box with 2 blocks then he will move these two blocks to the other box with 2 blocks. In the second test case, you don't need to put any extra blocks, since no matter which box your nephew chooses, he can always make other boxes equal. In the third test case, you should put 3 extra blocks. For example, you can put 2 blocks in the first box and 1 block in the third box. You'll get array a = [2, 3, 1]. Tags: binary search, greedy, math, sortings Correct Solution: ``` import sys import math from collections import Counter from collections import OrderedDict from collections import defaultdict from functools import reduce #from itertools import groupby sys.setrecursionlimit(10**6) def inputt(): return sys.stdin.readline().strip() def printt(n): sys.stdout.write(str(n)+'\n') def listt(): return [int(i) for i in inputt().split()] def gcd(a,b): return math.gcd(a,b) def lcm(a,b): return (a*b) // gcd(a,b) def factors(n): step = 2 if n%2 else 1 return set(reduce(list.__add__,([i, n//i] for i in range(1, int(math.sqrt(n))+1, step) if n % i == 0))) def comb(n,k): factn=math.factorial(n) factk=math.factorial(k) fact=math.factorial(n-k) ans=factn//(factk*fact) return ans def is_prime(n): if n <= 1: return False if n == 2: return True if n > 2 and n % 2 == 0: return False max_div = math.floor(math.sqrt(n)) for i in range(3, 1 + max_div, 2): if n % i == 0: return False return True def maxpower(n,x): B_max = int(math.log(n, x)) + 1 #tells upto what power of x n is less than it like 1024->5^4 return B_max t=int(inputt()) #t=1 for _ in range(t): n=int(inputt()) l=listt() maxi=max(l) s=sum(l) #k=max(maxi,math.ceil(s//(n-1))) #ans=(k*(n-1))-s #print(abs(ans)) print(max(maxi,math.ceil(s/(n-1)))*(n-1)-s) ```
103,892
Provide tags and a correct Python 3 solution for this coding contest problem. You are asked to watch your nephew who likes to play with toy blocks in a strange way. He has n boxes and the i-th box has a_i blocks. His game consists of two steps: 1. he chooses an arbitrary box i; 2. he tries to move all blocks from the i-th box to other boxes. If he can make the same number of blocks in each of n - 1 other boxes then he will be happy, otherwise, will be sad. Note that your nephew can only move the blocks from the chosen box to the other boxes; he cannot move blocks from the other boxes. You don't want to make your nephew sad, so you decided to put several extra blocks into some boxes in such a way that no matter which box i he chooses he won't be sad. What is the minimum number of extra blocks you need to put? Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains the integer n (2 ≤ n ≤ 10^5) — the number of boxes. The second line of each test case contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9) — the number of blocks in each box. It's guaranteed that the sum of n over test cases doesn't exceed 10^5. Output For each test case, print a single integer — the minimum number of blocks you need to put. It can be proved that the answer always exists, i. e. the number of blocks is finite. Example Input 3 3 3 2 2 4 2 2 3 2 3 0 3 0 Output 1 0 3 Note In the first test case, you can, for example, put one extra block into the first box and make a = [4, 2, 2]. If your nephew chooses the box with 4 blocks, then we will move two blocks to the second box and two blocks to the third box. If he chooses the box with 2 blocks then he will move these two blocks to the other box with 2 blocks. In the second test case, you don't need to put any extra blocks, since no matter which box your nephew chooses, he can always make other boxes equal. In the third test case, you should put 3 extra blocks. For example, you can put 2 blocks in the first box and 1 block in the third box. You'll get array a = [2, 3, 1]. Tags: binary search, greedy, math, sortings Correct Solution: ``` t = int(input()) for _ in range(t): n = int(input()) a = list(map(int,input().split())) x = max(a)*(n-1) s = sum(a) q = s//(n-1) r = s%(n-1) if r>0: q+=1 print(max(max(a),q)*(n-1)-s) ```
103,893
Provide tags and a correct Python 3 solution for this coding contest problem. You are asked to watch your nephew who likes to play with toy blocks in a strange way. He has n boxes and the i-th box has a_i blocks. His game consists of two steps: 1. he chooses an arbitrary box i; 2. he tries to move all blocks from the i-th box to other boxes. If he can make the same number of blocks in each of n - 1 other boxes then he will be happy, otherwise, will be sad. Note that your nephew can only move the blocks from the chosen box to the other boxes; he cannot move blocks from the other boxes. You don't want to make your nephew sad, so you decided to put several extra blocks into some boxes in such a way that no matter which box i he chooses he won't be sad. What is the minimum number of extra blocks you need to put? Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains the integer n (2 ≤ n ≤ 10^5) — the number of boxes. The second line of each test case contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9) — the number of blocks in each box. It's guaranteed that the sum of n over test cases doesn't exceed 10^5. Output For each test case, print a single integer — the minimum number of blocks you need to put. It can be proved that the answer always exists, i. e. the number of blocks is finite. Example Input 3 3 3 2 2 4 2 2 3 2 3 0 3 0 Output 1 0 3 Note In the first test case, you can, for example, put one extra block into the first box and make a = [4, 2, 2]. If your nephew chooses the box with 4 blocks, then we will move two blocks to the second box and two blocks to the third box. If he chooses the box with 2 blocks then he will move these two blocks to the other box with 2 blocks. In the second test case, you don't need to put any extra blocks, since no matter which box your nephew chooses, he can always make other boxes equal. In the third test case, you should put 3 extra blocks. For example, you can put 2 blocks in the first box and 1 block in the third box. You'll get array a = [2, 3, 1]. Tags: binary search, greedy, math, sortings Correct Solution: ``` import sys input = sys.stdin.readline from collections import * t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) M = (n-1)*max(a) S = sum(a) if S<=M: #print('a') print(M-S) else: tot = M+(S-M+(n-2))//(n-1)*(n-1) print(tot-S) ```
103,894
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are asked to watch your nephew who likes to play with toy blocks in a strange way. He has n boxes and the i-th box has a_i blocks. His game consists of two steps: 1. he chooses an arbitrary box i; 2. he tries to move all blocks from the i-th box to other boxes. If he can make the same number of blocks in each of n - 1 other boxes then he will be happy, otherwise, will be sad. Note that your nephew can only move the blocks from the chosen box to the other boxes; he cannot move blocks from the other boxes. You don't want to make your nephew sad, so you decided to put several extra blocks into some boxes in such a way that no matter which box i he chooses he won't be sad. What is the minimum number of extra blocks you need to put? Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains the integer n (2 ≤ n ≤ 10^5) — the number of boxes. The second line of each test case contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9) — the number of blocks in each box. It's guaranteed that the sum of n over test cases doesn't exceed 10^5. Output For each test case, print a single integer — the minimum number of blocks you need to put. It can be proved that the answer always exists, i. e. the number of blocks is finite. Example Input 3 3 3 2 2 4 2 2 3 2 3 0 3 0 Output 1 0 3 Note In the first test case, you can, for example, put one extra block into the first box and make a = [4, 2, 2]. If your nephew chooses the box with 4 blocks, then we will move two blocks to the second box and two blocks to the third box. If he chooses the box with 2 blocks then he will move these two blocks to the other box with 2 blocks. In the second test case, you don't need to put any extra blocks, since no matter which box your nephew chooses, he can always make other boxes equal. In the third test case, you should put 3 extra blocks. For example, you can put 2 blocks in the first box and 1 block in the third box. You'll get array a = [2, 3, 1]. Submitted Solution: ``` for _ in range(int(input())): n = int(input()) A = list(map(int, input().split())) A.sort(reverse=True) ans = 0 maxv = A[0] for i in range(1, n - 1): ans += maxv - A[i] ans = max(0, ans - A[-1]) r = (ans + sum(A)) % (n - 1) if not r: print(ans) else: ans += n - 1 - r print(ans) ``` Yes
103,895
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are asked to watch your nephew who likes to play with toy blocks in a strange way. He has n boxes and the i-th box has a_i blocks. His game consists of two steps: 1. he chooses an arbitrary box i; 2. he tries to move all blocks from the i-th box to other boxes. If he can make the same number of blocks in each of n - 1 other boxes then he will be happy, otherwise, will be sad. Note that your nephew can only move the blocks from the chosen box to the other boxes; he cannot move blocks from the other boxes. You don't want to make your nephew sad, so you decided to put several extra blocks into some boxes in such a way that no matter which box i he chooses he won't be sad. What is the minimum number of extra blocks you need to put? Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains the integer n (2 ≤ n ≤ 10^5) — the number of boxes. The second line of each test case contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9) — the number of blocks in each box. It's guaranteed that the sum of n over test cases doesn't exceed 10^5. Output For each test case, print a single integer — the minimum number of blocks you need to put. It can be proved that the answer always exists, i. e. the number of blocks is finite. Example Input 3 3 3 2 2 4 2 2 3 2 3 0 3 0 Output 1 0 3 Note In the first test case, you can, for example, put one extra block into the first box and make a = [4, 2, 2]. If your nephew chooses the box with 4 blocks, then we will move two blocks to the second box and two blocks to the third box. If he chooses the box with 2 blocks then he will move these two blocks to the other box with 2 blocks. In the second test case, you don't need to put any extra blocks, since no matter which box your nephew chooses, he can always make other boxes equal. In the third test case, you should put 3 extra blocks. For example, you can put 2 blocks in the first box and 1 block in the third box. You'll get array a = [2, 3, 1]. Submitted Solution: ``` import math from sys import stdin,stdout mp=lambda:map(int,stdin.readline().split()) li=lambda:list(map(int,stdin.readline().split())) for _ in range(int(input())): n=int(input()) c=li() mx1=max(c) sm=sum(c) mx2=(sm-1)//(n-1) + 1 mx=max(mx1,mx2) print((n-1)*mx-sm) ``` Yes
103,896
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are asked to watch your nephew who likes to play with toy blocks in a strange way. He has n boxes and the i-th box has a_i blocks. His game consists of two steps: 1. he chooses an arbitrary box i; 2. he tries to move all blocks from the i-th box to other boxes. If he can make the same number of blocks in each of n - 1 other boxes then he will be happy, otherwise, will be sad. Note that your nephew can only move the blocks from the chosen box to the other boxes; he cannot move blocks from the other boxes. You don't want to make your nephew sad, so you decided to put several extra blocks into some boxes in such a way that no matter which box i he chooses he won't be sad. What is the minimum number of extra blocks you need to put? Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains the integer n (2 ≤ n ≤ 10^5) — the number of boxes. The second line of each test case contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9) — the number of blocks in each box. It's guaranteed that the sum of n over test cases doesn't exceed 10^5. Output For each test case, print a single integer — the minimum number of blocks you need to put. It can be proved that the answer always exists, i. e. the number of blocks is finite. Example Input 3 3 3 2 2 4 2 2 3 2 3 0 3 0 Output 1 0 3 Note In the first test case, you can, for example, put one extra block into the first box and make a = [4, 2, 2]. If your nephew chooses the box with 4 blocks, then we will move two blocks to the second box and two blocks to the third box. If he chooses the box with 2 blocks then he will move these two blocks to the other box with 2 blocks. In the second test case, you don't need to put any extra blocks, since no matter which box your nephew chooses, he can always make other boxes equal. In the third test case, you should put 3 extra blocks. For example, you can put 2 blocks in the first box and 1 block in the third box. You'll get array a = [2, 3, 1]. Submitted Solution: ``` t = int(input()) for i in range(t): n = int(input()) nums = list(map(int, input().split())) s = sum(nums) ma = max(nums) lim, r = divmod(s, n-1) if r: lim += 1 print(max(lim, ma)*(n-1)-s) ``` Yes
103,897
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are asked to watch your nephew who likes to play with toy blocks in a strange way. He has n boxes and the i-th box has a_i blocks. His game consists of two steps: 1. he chooses an arbitrary box i; 2. he tries to move all blocks from the i-th box to other boxes. If he can make the same number of blocks in each of n - 1 other boxes then he will be happy, otherwise, will be sad. Note that your nephew can only move the blocks from the chosen box to the other boxes; he cannot move blocks from the other boxes. You don't want to make your nephew sad, so you decided to put several extra blocks into some boxes in such a way that no matter which box i he chooses he won't be sad. What is the minimum number of extra blocks you need to put? Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains the integer n (2 ≤ n ≤ 10^5) — the number of boxes. The second line of each test case contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9) — the number of blocks in each box. It's guaranteed that the sum of n over test cases doesn't exceed 10^5. Output For each test case, print a single integer — the minimum number of blocks you need to put. It can be proved that the answer always exists, i. e. the number of blocks is finite. Example Input 3 3 3 2 2 4 2 2 3 2 3 0 3 0 Output 1 0 3 Note In the first test case, you can, for example, put one extra block into the first box and make a = [4, 2, 2]. If your nephew chooses the box with 4 blocks, then we will move two blocks to the second box and two blocks to the third box. If he chooses the box with 2 blocks then he will move these two blocks to the other box with 2 blocks. In the second test case, you don't need to put any extra blocks, since no matter which box your nephew chooses, he can always make other boxes equal. In the third test case, you should put 3 extra blocks. For example, you can put 2 blocks in the first box and 1 block in the third box. You'll get array a = [2, 3, 1]. Submitted Solution: ``` # -*- coding: utf-8 -*- """ Created on Sun Nov 22 16:15:39 2020 @author: 章斯岚 """ for i in range(int(input())): n=int(input()) a=list(map(int,input().split())) c=max(a) b=sum(a) if c*(n-1)>=b: print(c*(n-1)-b) else: print((b%(n-1)>0)*(n-1-b%(n-1))) ``` Yes
103,898
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are asked to watch your nephew who likes to play with toy blocks in a strange way. He has n boxes and the i-th box has a_i blocks. His game consists of two steps: 1. he chooses an arbitrary box i; 2. he tries to move all blocks from the i-th box to other boxes. If he can make the same number of blocks in each of n - 1 other boxes then he will be happy, otherwise, will be sad. Note that your nephew can only move the blocks from the chosen box to the other boxes; he cannot move blocks from the other boxes. You don't want to make your nephew sad, so you decided to put several extra blocks into some boxes in such a way that no matter which box i he chooses he won't be sad. What is the minimum number of extra blocks you need to put? Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains the integer n (2 ≤ n ≤ 10^5) — the number of boxes. The second line of each test case contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9) — the number of blocks in each box. It's guaranteed that the sum of n over test cases doesn't exceed 10^5. Output For each test case, print a single integer — the minimum number of blocks you need to put. It can be proved that the answer always exists, i. e. the number of blocks is finite. Example Input 3 3 3 2 2 4 2 2 3 2 3 0 3 0 Output 1 0 3 Note In the first test case, you can, for example, put one extra block into the first box and make a = [4, 2, 2]. If your nephew chooses the box with 4 blocks, then we will move two blocks to the second box and two blocks to the third box. If he chooses the box with 2 blocks then he will move these two blocks to the other box with 2 blocks. In the second test case, you don't need to put any extra blocks, since no matter which box your nephew chooses, he can always make other boxes equal. In the third test case, you should put 3 extra blocks. For example, you can put 2 blocks in the first box and 1 block in the third box. You'll get array a = [2, 3, 1]. Submitted Solution: ``` """ usefull snippets: - map(int, input().split()) - map(int, sys.stdin.readline().split())) - int(input()) - int(sys.stdin.readline().strip()) - sys.stdout.write() - sys.stdout.write(" ".join(map(str, c) # writes c - collection of ints """ # import collections import sys import math from bisect import bisect_left from collections import defaultdict # recursion increase # sys.setrecursionlimit(10000) # number with big precision # from decimal import getcontext, Decimal # getcontext().prec = 34 # longest common prefix def get_lcp(s, suffix_array): s = s + "$" n = len(s) lcp = [0] * (n) pos = [0] * (n) for i in range(n - 1): pos[suffix_array[i]] = i k = 0 for i in range(n - 1): if k > 0: k -= 1 if pos[i] == n - 1: lcp[n - 1] = -1 k = 0 continue else: j = suffix_array[pos[i] + 1] while max([i + k, j + k]) < n and s[i + k] == s[j + k]: k += 1 lcp[pos[i]] = k return lcp def get_suffix_array(word): suffix_array = [("", len(word))] for position in range(len(word)): sliced = word[len(word) - position - 1 :] suffix_array.append((sliced, len(word) - position - 1)) suffix_array.sort(key=lambda x: x[0]) return [item[1] for item in suffix_array] def get_ints(): return map(int, sys.stdin.readline().strip().split()) def bin_search(collection, element): i = bisect_left(collection, element) if i != len(collection) and collection[i] == element: return i else: return -1 def main(): t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, sys.stdin.readline().split())) if n == 2: print(0) continue aim = max(a) m = min(a) s = sum(a) ans = aim * (n - 2) - (s - aim - m) - m if ans < 0: if aim <= (n - 2): ans = 1 + (n - 2) * n - s else: ans = s % (n - 1) print(ans) if __name__ == "__main__": main() ``` No
103,899