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. Recently, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with n elements. The i-th element is a_i (i = 1, 2, …, n). He gradually takes the first two leftmost elements from the deque (let's call them A and B, respectively), and then does the following: if A > B, he writes A to the beginning and writes B to the end of the deque, otherwise, he writes to the beginning B, and A writes to the end of the deque. We call this sequence of actions an operation. For example, if deque was [2, 3, 4, 5, 1], on the operation he will write B=3 to the beginning and A=2 to the end, so he will get [3, 4, 5, 1, 2]. The teacher of the course, seeing Valeriy, who was passionate about his work, approached him and gave him q queries. Each query consists of the singular number m_j (j = 1, 2, …, q). It is required for each query to answer which two elements he will pull out on the m_j-th operation. Note that the queries are independent and for each query the numbers A and B should be printed in the order in which they will be pulled out of the deque. Deque is a data structure representing a list of elements where insertion of new elements or deletion of existing elements can be made from both sides. Input The first line contains two integers n and q (2 ≤ n ≤ 10^5, 0 ≤ q ≤ 3 ⋅ 10^5) — the number of elements in the deque and the number of queries. The second line contains n integers a_1, a_2, ..., a_n, where a_i (0 ≤ a_i ≤ 10^9) — the deque element in i-th position. The next q lines contain one number each, meaning m_j (1 ≤ m_j ≤ 10^{18}). Output For each teacher's query, output two numbers A and B — the numbers that Valeriy pulls out of the deque for the m_j-th operation. Examples Input 5 3 1 2 3 4 5 1 2 10 Output 1 2 2 3 5 2 Input 2 0 0 0 Output Note Consider all 10 steps for the first test in detail: 1. [1, 2, 3, 4, 5] — on the first operation, A and B are 1 and 2, respectively. So, 2 we write to the beginning of the deque, and 1 — to the end. We get the following status of the deque: [2, 3, 4, 5, 1]. 2. [2, 3, 4, 5, 1] ⇒ A = 2, B = 3. 3. [3, 4, 5, 1, 2] 4. [4, 5, 1, 2, 3] 5. [5, 1, 2, 3, 4] 6. [5, 2, 3, 4, 1] 7. [5, 3, 4, 1, 2] 8. [5, 4, 1, 2, 3] 9. [5, 1, 2, 3, 4] 10. [5, 2, 3, 4, 1] ⇒ A = 5, B = 2. Submitted Solution: ``` # !/usr/bin/env python3 # encoding: UTF-8 # Modified: <22/Jun/2019 12:28:28 AM> # ✪ H4WK3yE乡 # Mohd. Farhan Tahir # Indian Institute Of Information Technology (IIIT), Gwalior import sys import os from io import IOBase, BytesIO def main(): from collections import deque n, tc = get_ints() arr = get_array() mx = max(arr) q = deque() for i in range(n): q.append(arr[i]) query = 1 dp = [0] * 10**6 while q[0] != mx: f = q.popleft() s = q.popleft() if (f > s): q.appendleft(f) q.append(s) else: q.appendleft(s) q.append(f) dp[query] = (f, s) query += 1 curr = 0 c2 = query while curr != n - 1: #print(q, c2) f = q.popleft() s = q.popleft() q.appendleft(f) q.append(s) dp[c2] = (f, s) curr += 1 c2 += 1 curr = 0 cycle = c2 - query while curr != n - 1: #print(q, c2) f = q.popleft() s = q.popleft() q.appendleft(f) q.append(s) dp[c2] = (f, s) curr += 1 c2 += 1 # print(dp[:10]) #print(cycle, query, c2) # print(dp[:10]) # print(c2) for _ in range(tc): j = int(input()) if j < c2: print(*dp[j]) else: j %= cycle j += cycle #print(j, "j") print(*dp[j]) # print(dp) def get_array(): return list(map(int, sys.stdin.readline().split())) def get_ints(): return map(int, sys.stdin.readline().split()) def input(): return sys.stdin.readline().strip() if __name__ == "__main__": main() ``` Yes
3,400
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with n elements. The i-th element is a_i (i = 1, 2, …, n). He gradually takes the first two leftmost elements from the deque (let's call them A and B, respectively), and then does the following: if A > B, he writes A to the beginning and writes B to the end of the deque, otherwise, he writes to the beginning B, and A writes to the end of the deque. We call this sequence of actions an operation. For example, if deque was [2, 3, 4, 5, 1], on the operation he will write B=3 to the beginning and A=2 to the end, so he will get [3, 4, 5, 1, 2]. The teacher of the course, seeing Valeriy, who was passionate about his work, approached him and gave him q queries. Each query consists of the singular number m_j (j = 1, 2, …, q). It is required for each query to answer which two elements he will pull out on the m_j-th operation. Note that the queries are independent and for each query the numbers A and B should be printed in the order in which they will be pulled out of the deque. Deque is a data structure representing a list of elements where insertion of new elements or deletion of existing elements can be made from both sides. Input The first line contains two integers n and q (2 ≤ n ≤ 10^5, 0 ≤ q ≤ 3 ⋅ 10^5) — the number of elements in the deque and the number of queries. The second line contains n integers a_1, a_2, ..., a_n, where a_i (0 ≤ a_i ≤ 10^9) — the deque element in i-th position. The next q lines contain one number each, meaning m_j (1 ≤ m_j ≤ 10^{18}). Output For each teacher's query, output two numbers A and B — the numbers that Valeriy pulls out of the deque for the m_j-th operation. Examples Input 5 3 1 2 3 4 5 1 2 10 Output 1 2 2 3 5 2 Input 2 0 0 0 Output Note Consider all 10 steps for the first test in detail: 1. [1, 2, 3, 4, 5] — on the first operation, A and B are 1 and 2, respectively. So, 2 we write to the beginning of the deque, and 1 — to the end. We get the following status of the deque: [2, 3, 4, 5, 1]. 2. [2, 3, 4, 5, 1] ⇒ A = 2, B = 3. 3. [3, 4, 5, 1, 2] 4. [4, 5, 1, 2, 3] 5. [5, 1, 2, 3, 4] 6. [5, 2, 3, 4, 1] 7. [5, 3, 4, 1, 2] 8. [5, 4, 1, 2, 3] 9. [5, 1, 2, 3, 4] 10. [5, 2, 3, 4, 1] ⇒ A = 5, B = 2. Submitted Solution: ``` from collections import deque n,q=list(map(int,input().split())) a=list(map(int,input().rstrip().split())) a=deque(a) c=[] maxi=max(a) k=a[0] j=0 while(a[0]!=maxi): j+=1 k=a.popleft() h=a.popleft() if k>h: a.appendleft(k) a.append(h) else: a.appendleft(h) a.append(k) c.append((k,h)) for i in range(q): h=int(input())-1 if h<j: print(*c[h]) else: print(maxi,a[(h-j)%(n-1) + 1]) ``` Yes
3,401
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with n elements. The i-th element is a_i (i = 1, 2, …, n). He gradually takes the first two leftmost elements from the deque (let's call them A and B, respectively), and then does the following: if A > B, he writes A to the beginning and writes B to the end of the deque, otherwise, he writes to the beginning B, and A writes to the end of the deque. We call this sequence of actions an operation. For example, if deque was [2, 3, 4, 5, 1], on the operation he will write B=3 to the beginning and A=2 to the end, so he will get [3, 4, 5, 1, 2]. The teacher of the course, seeing Valeriy, who was passionate about his work, approached him and gave him q queries. Each query consists of the singular number m_j (j = 1, 2, …, q). It is required for each query to answer which two elements he will pull out on the m_j-th operation. Note that the queries are independent and for each query the numbers A and B should be printed in the order in which they will be pulled out of the deque. Deque is a data structure representing a list of elements where insertion of new elements or deletion of existing elements can be made from both sides. Input The first line contains two integers n and q (2 ≤ n ≤ 10^5, 0 ≤ q ≤ 3 ⋅ 10^5) — the number of elements in the deque and the number of queries. The second line contains n integers a_1, a_2, ..., a_n, where a_i (0 ≤ a_i ≤ 10^9) — the deque element in i-th position. The next q lines contain one number each, meaning m_j (1 ≤ m_j ≤ 10^{18}). Output For each teacher's query, output two numbers A and B — the numbers that Valeriy pulls out of the deque for the m_j-th operation. Examples Input 5 3 1 2 3 4 5 1 2 10 Output 1 2 2 3 5 2 Input 2 0 0 0 Output Note Consider all 10 steps for the first test in detail: 1. [1, 2, 3, 4, 5] — on the first operation, A and B are 1 and 2, respectively. So, 2 we write to the beginning of the deque, and 1 — to the end. We get the following status of the deque: [2, 3, 4, 5, 1]. 2. [2, 3, 4, 5, 1] ⇒ A = 2, B = 3. 3. [3, 4, 5, 1, 2] 4. [4, 5, 1, 2, 3] 5. [5, 1, 2, 3, 4] 6. [5, 2, 3, 4, 1] 7. [5, 3, 4, 1, 2] 8. [5, 4, 1, 2, 3] 9. [5, 1, 2, 3, 4] 10. [5, 2, 3, 4, 1] ⇒ A = 5, B = 2. Submitted Solution: ``` # @author import sys class CValeriyAndDeque: def solve(self): from collections import deque n, q = [int(item) for item in input().split()] a = [int(item) for item in input().split()] mi = a.index(max(a)) b = deque(a) ans = [(-1, -1)] * mi for i in range(mi): u, v = b.popleft(), b.popleft() ans[i] = (u, v) if u < v: u, v = v, u b.appendleft(u) b.append(v) b = list(b) # print(b) for _ in range(q): m = int(input()) m -= 1 if m >= mi: m -= mi print(b[0], b[1 + m % (n - 1)]) else: print(*ans[m]) solver = CValeriyAndDeque() input = sys.stdin.readline solver.solve() ``` Yes
3,402
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with n elements. The i-th element is a_i (i = 1, 2, …, n). He gradually takes the first two leftmost elements from the deque (let's call them A and B, respectively), and then does the following: if A > B, he writes A to the beginning and writes B to the end of the deque, otherwise, he writes to the beginning B, and A writes to the end of the deque. We call this sequence of actions an operation. For example, if deque was [2, 3, 4, 5, 1], on the operation he will write B=3 to the beginning and A=2 to the end, so he will get [3, 4, 5, 1, 2]. The teacher of the course, seeing Valeriy, who was passionate about his work, approached him and gave him q queries. Each query consists of the singular number m_j (j = 1, 2, …, q). It is required for each query to answer which two elements he will pull out on the m_j-th operation. Note that the queries are independent and for each query the numbers A and B should be printed in the order in which they will be pulled out of the deque. Deque is a data structure representing a list of elements where insertion of new elements or deletion of existing elements can be made from both sides. Input The first line contains two integers n and q (2 ≤ n ≤ 10^5, 0 ≤ q ≤ 3 ⋅ 10^5) — the number of elements in the deque and the number of queries. The second line contains n integers a_1, a_2, ..., a_n, where a_i (0 ≤ a_i ≤ 10^9) — the deque element in i-th position. The next q lines contain one number each, meaning m_j (1 ≤ m_j ≤ 10^{18}). Output For each teacher's query, output two numbers A and B — the numbers that Valeriy pulls out of the deque for the m_j-th operation. Examples Input 5 3 1 2 3 4 5 1 2 10 Output 1 2 2 3 5 2 Input 2 0 0 0 Output Note Consider all 10 steps for the first test in detail: 1. [1, 2, 3, 4, 5] — on the first operation, A and B are 1 and 2, respectively. So, 2 we write to the beginning of the deque, and 1 — to the end. We get the following status of the deque: [2, 3, 4, 5, 1]. 2. [2, 3, 4, 5, 1] ⇒ A = 2, B = 3. 3. [3, 4, 5, 1, 2] 4. [4, 5, 1, 2, 3] 5. [5, 1, 2, 3, 4] 6. [5, 2, 3, 4, 1] 7. [5, 3, 4, 1, 2] 8. [5, 4, 1, 2, 3] 9. [5, 1, 2, 3, 4] 10. [5, 2, 3, 4, 1] ⇒ A = 5, B = 2. Submitted Solution: ``` from collections import deque n, qs = tuple(map(int, input().split())) d = deque(list(map(int, input().split()))) m = max(d) if qs == 0: exit() q = [] for i in range(qs): v = int(input()) q.append([v, i, 'a', 'b']) # print(q) q.sort() # print(q) # print(q[0][0]) i = 0 curv = q[i][0] j = 1 while(d[0] != m): a = d[0] b = d[1] if a > b: d.popleft() d.popleft() d.append(b) d.appendleft(a) else: d.popleft() d.append(a) if curv == j: # print(curv) q[i][2] = a q[i][3] = b i += 1 while i < qs and (q[i][0] == curv): q[i][2] = a q[i][3] = b i += 1 if i == qs: break curv = q[i][0] # print(curv) j += 1 # print(j-1, d) while(i<qs): curv = q[i][0] q[i][2] = m q[i][3] = d[1 + (curv - j)%(n-1)] i += 1 q.sort(key=lambda x: x[1]) for f in range(qs): print(str(q[f][2]) + ' ' +str(q[f][3])) ``` Yes
3,403
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with n elements. The i-th element is a_i (i = 1, 2, …, n). He gradually takes the first two leftmost elements from the deque (let's call them A and B, respectively), and then does the following: if A > B, he writes A to the beginning and writes B to the end of the deque, otherwise, he writes to the beginning B, and A writes to the end of the deque. We call this sequence of actions an operation. For example, if deque was [2, 3, 4, 5, 1], on the operation he will write B=3 to the beginning and A=2 to the end, so he will get [3, 4, 5, 1, 2]. The teacher of the course, seeing Valeriy, who was passionate about his work, approached him and gave him q queries. Each query consists of the singular number m_j (j = 1, 2, …, q). It is required for each query to answer which two elements he will pull out on the m_j-th operation. Note that the queries are independent and for each query the numbers A and B should be printed in the order in which they will be pulled out of the deque. Deque is a data structure representing a list of elements where insertion of new elements or deletion of existing elements can be made from both sides. Input The first line contains two integers n and q (2 ≤ n ≤ 10^5, 0 ≤ q ≤ 3 ⋅ 10^5) — the number of elements in the deque and the number of queries. The second line contains n integers a_1, a_2, ..., a_n, where a_i (0 ≤ a_i ≤ 10^9) — the deque element in i-th position. The next q lines contain one number each, meaning m_j (1 ≤ m_j ≤ 10^{18}). Output For each teacher's query, output two numbers A and B — the numbers that Valeriy pulls out of the deque for the m_j-th operation. Examples Input 5 3 1 2 3 4 5 1 2 10 Output 1 2 2 3 5 2 Input 2 0 0 0 Output Note Consider all 10 steps for the first test in detail: 1. [1, 2, 3, 4, 5] — on the first operation, A and B are 1 and 2, respectively. So, 2 we write to the beginning of the deque, and 1 — to the end. We get the following status of the deque: [2, 3, 4, 5, 1]. 2. [2, 3, 4, 5, 1] ⇒ A = 2, B = 3. 3. [3, 4, 5, 1, 2] 4. [4, 5, 1, 2, 3] 5. [5, 1, 2, 3, 4] 6. [5, 2, 3, 4, 1] 7. [5, 3, 4, 1, 2] 8. [5, 4, 1, 2, 3] 9. [5, 1, 2, 3, 4] 10. [5, 2, 3, 4, 1] ⇒ A = 5, B = 2. Submitted Solution: ``` n,x = map(int, input().split()) m = list(map(int, input().split())) ind = 0 for i in range(n): if(m[ind]<m[i]): ind = i z = m[ind] r = m[0] ans = [] l = [] for i in range(ind): ans.append([r,m[i+1]]) l.append(r) r = m[i+1] for i in range(ind+1, n): l.append(m[i]) #l.reverse() for i in range(x): q = int(input()) if(q<=ind): print(ans[q-1][0], ans[q-1][1]) elif(q>=n): print(z, l[(q-ind-1)%(n-1)]) else: print(z, m[q]) ``` No
3,404
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with n elements. The i-th element is a_i (i = 1, 2, …, n). He gradually takes the first two leftmost elements from the deque (let's call them A and B, respectively), and then does the following: if A > B, he writes A to the beginning and writes B to the end of the deque, otherwise, he writes to the beginning B, and A writes to the end of the deque. We call this sequence of actions an operation. For example, if deque was [2, 3, 4, 5, 1], on the operation he will write B=3 to the beginning and A=2 to the end, so he will get [3, 4, 5, 1, 2]. The teacher of the course, seeing Valeriy, who was passionate about his work, approached him and gave him q queries. Each query consists of the singular number m_j (j = 1, 2, …, q). It is required for each query to answer which two elements he will pull out on the m_j-th operation. Note that the queries are independent and for each query the numbers A and B should be printed in the order in which they will be pulled out of the deque. Deque is a data structure representing a list of elements where insertion of new elements or deletion of existing elements can be made from both sides. Input The first line contains two integers n and q (2 ≤ n ≤ 10^5, 0 ≤ q ≤ 3 ⋅ 10^5) — the number of elements in the deque and the number of queries. The second line contains n integers a_1, a_2, ..., a_n, where a_i (0 ≤ a_i ≤ 10^9) — the deque element in i-th position. The next q lines contain one number each, meaning m_j (1 ≤ m_j ≤ 10^{18}). Output For each teacher's query, output two numbers A and B — the numbers that Valeriy pulls out of the deque for the m_j-th operation. Examples Input 5 3 1 2 3 4 5 1 2 10 Output 1 2 2 3 5 2 Input 2 0 0 0 Output Note Consider all 10 steps for the first test in detail: 1. [1, 2, 3, 4, 5] — on the first operation, A and B are 1 and 2, respectively. So, 2 we write to the beginning of the deque, and 1 — to the end. We get the following status of the deque: [2, 3, 4, 5, 1]. 2. [2, 3, 4, 5, 1] ⇒ A = 2, B = 3. 3. [3, 4, 5, 1, 2] 4. [4, 5, 1, 2, 3] 5. [5, 1, 2, 3, 4] 6. [5, 2, 3, 4, 1] 7. [5, 3, 4, 1, 2] 8. [5, 4, 1, 2, 3] 9. [5, 1, 2, 3, 4] 10. [5, 2, 3, 4, 1] ⇒ A = 5, B = 2. Submitted Solution: ``` class Dek: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def addFront(self, item): self.items.append(item) def addRear(self, item): self.items.insert(0,item) def removeFront(self): return self.items.pop() def removeRear(self): return self.items.pop(0) def size(self): return len(self.items) def op(self): a = self.removeRear() b = self.removeRear() if a > b: self.addRear(a) self.addFront(b) else: self.addRear(b) self.addFront(a) return (a, b) dek = Dek() n, q = map(int, input().split()) arr = list(map(int, input().split())) for i in range(n): dek.addFront(arr[i]) qs = [] ans = [()]*q for i in range(q): qs.append(int(input())) i = 0 while dek.items[0] != max(dek.items): a, b = dek.op() if i + 1 in qs: for k in range(len(qs)): if qs[k] == i + 1: ans[k] = (a, b) i += 1 for j in qs: if j > i: j -= i num_el = j % (n - 1) if num_el == 0: num_el = n - 1 ans[qs.index(j + i)] = (dek.items[0], dek.items[num_el]) for an in ans: print(*an) ``` No
3,405
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with n elements. The i-th element is a_i (i = 1, 2, …, n). He gradually takes the first two leftmost elements from the deque (let's call them A and B, respectively), and then does the following: if A > B, he writes A to the beginning and writes B to the end of the deque, otherwise, he writes to the beginning B, and A writes to the end of the deque. We call this sequence of actions an operation. For example, if deque was [2, 3, 4, 5, 1], on the operation he will write B=3 to the beginning and A=2 to the end, so he will get [3, 4, 5, 1, 2]. The teacher of the course, seeing Valeriy, who was passionate about his work, approached him and gave him q queries. Each query consists of the singular number m_j (j = 1, 2, …, q). It is required for each query to answer which two elements he will pull out on the m_j-th operation. Note that the queries are independent and for each query the numbers A and B should be printed in the order in which they will be pulled out of the deque. Deque is a data structure representing a list of elements where insertion of new elements or deletion of existing elements can be made from both sides. Input The first line contains two integers n and q (2 ≤ n ≤ 10^5, 0 ≤ q ≤ 3 ⋅ 10^5) — the number of elements in the deque and the number of queries. The second line contains n integers a_1, a_2, ..., a_n, where a_i (0 ≤ a_i ≤ 10^9) — the deque element in i-th position. The next q lines contain one number each, meaning m_j (1 ≤ m_j ≤ 10^{18}). Output For each teacher's query, output two numbers A and B — the numbers that Valeriy pulls out of the deque for the m_j-th operation. Examples Input 5 3 1 2 3 4 5 1 2 10 Output 1 2 2 3 5 2 Input 2 0 0 0 Output Note Consider all 10 steps for the first test in detail: 1. [1, 2, 3, 4, 5] — on the first operation, A and B are 1 and 2, respectively. So, 2 we write to the beginning of the deque, and 1 — to the end. We get the following status of the deque: [2, 3, 4, 5, 1]. 2. [2, 3, 4, 5, 1] ⇒ A = 2, B = 3. 3. [3, 4, 5, 1, 2] 4. [4, 5, 1, 2, 3] 5. [5, 1, 2, 3, 4] 6. [5, 2, 3, 4, 1] 7. [5, 3, 4, 1, 2] 8. [5, 4, 1, 2, 3] 9. [5, 1, 2, 3, 4] 10. [5, 2, 3, 4, 1] ⇒ A = 5, B = 2. Submitted Solution: ``` import collections if __name__ == "__main__": n, q = list(map(int, input().split())) a = collections.deque(map(int, input().split())) maxn = max(a) res = list(range(n)) cnt = 1 while True: if a[0] == maxn: break res[cnt] = [a[0], a[1]] cnt += 1 A = a.popleft() B = a.popleft() if A > B: a.appendleft(A) a.append(B) else: a.appendleft(B) a.append(A) for i in range(q): m = int(input()) if m < cnt: print(res[m][0], res[m][1]) else: print(maxn, int((m - cnt) % (n - 1) + 1)) ``` No
3,406
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with n elements. The i-th element is a_i (i = 1, 2, …, n). He gradually takes the first two leftmost elements from the deque (let's call them A and B, respectively), and then does the following: if A > B, he writes A to the beginning and writes B to the end of the deque, otherwise, he writes to the beginning B, and A writes to the end of the deque. We call this sequence of actions an operation. For example, if deque was [2, 3, 4, 5, 1], on the operation he will write B=3 to the beginning and A=2 to the end, so he will get [3, 4, 5, 1, 2]. The teacher of the course, seeing Valeriy, who was passionate about his work, approached him and gave him q queries. Each query consists of the singular number m_j (j = 1, 2, …, q). It is required for each query to answer which two elements he will pull out on the m_j-th operation. Note that the queries are independent and for each query the numbers A and B should be printed in the order in which they will be pulled out of the deque. Deque is a data structure representing a list of elements where insertion of new elements or deletion of existing elements can be made from both sides. Input The first line contains two integers n and q (2 ≤ n ≤ 10^5, 0 ≤ q ≤ 3 ⋅ 10^5) — the number of elements in the deque and the number of queries. The second line contains n integers a_1, a_2, ..., a_n, where a_i (0 ≤ a_i ≤ 10^9) — the deque element in i-th position. The next q lines contain one number each, meaning m_j (1 ≤ m_j ≤ 10^{18}). Output For each teacher's query, output two numbers A and B — the numbers that Valeriy pulls out of the deque for the m_j-th operation. Examples Input 5 3 1 2 3 4 5 1 2 10 Output 1 2 2 3 5 2 Input 2 0 0 0 Output Note Consider all 10 steps for the first test in detail: 1. [1, 2, 3, 4, 5] — on the first operation, A and B are 1 and 2, respectively. So, 2 we write to the beginning of the deque, and 1 — to the end. We get the following status of the deque: [2, 3, 4, 5, 1]. 2. [2, 3, 4, 5, 1] ⇒ A = 2, B = 3. 3. [3, 4, 5, 1, 2] 4. [4, 5, 1, 2, 3] 5. [5, 1, 2, 3, 4] 6. [5, 2, 3, 4, 1] 7. [5, 3, 4, 1, 2] 8. [5, 4, 1, 2, 3] 9. [5, 1, 2, 3, 4] 10. [5, 2, 3, 4, 1] ⇒ A = 5, B = 2. Submitted Solution: ``` import sys from collections import deque input = sys.stdin.readline n, q = map(int, input().split()) a = list(map(int, input().split())) query = [int(input()) for i in range(q)] max_a = max(a) for i in range(n): if a[i] == max_a: max_ind = i break ans = [0]*(n+1) tmp_max = -1 for i in range(n-1): tmp_max = max(tmp_max, a[i]) ans[i] = [tmp_max, a[i+1]] if a[i+1] == max_a: break a = a[i+1:] + sorted(a[0:i+1]) for j in query: if j - 1 <= i: print(" ".join(map(str, ans[j-1]))) else: print(max_a, a[(j - 2 - i) % (n - 1)+1] ) ``` No
3,407
Provide tags and a correct Python 3 solution for this coding contest problem. One common way of digitalizing sound is to record sound intensity at particular time moments. For each time moment intensity is recorded as a non-negative integer. Thus we can represent a sound file as an array of n non-negative integers. If there are exactly K distinct values in the array, then we need k = ⌈ log_{2} K ⌉ bits to store each value. It then takes nk bits to store the whole file. To reduce the memory consumption we need to apply some compression. One common way is to reduce the number of possible intensity values. We choose two integers l ≤ r, and after that all intensity values are changed in the following way: if the intensity value is within the range [l;r], we don't change it. If it is less than l, we change it to l; if it is greater than r, we change it to r. You can see that we lose some low and some high intensities. Your task is to apply this compression in such a way that the file fits onto a disk of size I bytes, and the number of changed elements in the array is minimal possible. We remind you that 1 byte contains 8 bits. k = ⌈ log_{2} K ⌉ is the smallest integer such that K ≤ 2^{k}. In particular, if K = 1, then k = 0. Input The first line contains two integers n and I (1 ≤ n ≤ 4 ⋅ 10^{5}, 1 ≤ I ≤ 10^{8}) — the length of the array and the size of the disk in bytes, respectively. The next line contains n integers a_{i} (0 ≤ a_{i} ≤ 10^{9}) — the array denoting the sound file. Output Print a single integer — the minimal possible number of changed elements. Examples Input 6 1 2 1 2 3 4 3 Output 2 Input 6 2 2 1 2 3 4 3 Output 0 Input 6 1 1 1 2 2 3 3 Output 2 Note In the first example we can choose l=2, r=3. The array becomes 2 2 2 3 3 3, the number of distinct elements is K=2, and the sound file fits onto the disk. Only two values are changed. In the second example the disk is larger, so the initial file fits it and no changes are required. In the third example we have to change both 1s or both 3s. Tags: sortings, two pointers Correct Solution: ``` import math; n,I = map(int,input().split()); arr = list(map(int,input().split())); k = 8*I//n; K = 2**k; arr.sort(); nd = 1; le = arr[0]; b = [0]; for i in range(1,n): if(arr[i]!=le): le=arr[i]; b.append(i); nd+=1; b.append(n) #print(b); #print(nd); if(K>=nd): print(0); else: maxn = 0; for i in range(K,nd): maxn = max(maxn,(b[i]-b[i-K])); print(n-maxn) ```
3,408
Provide tags and a correct Python 3 solution for this coding contest problem. One common way of digitalizing sound is to record sound intensity at particular time moments. For each time moment intensity is recorded as a non-negative integer. Thus we can represent a sound file as an array of n non-negative integers. If there are exactly K distinct values in the array, then we need k = ⌈ log_{2} K ⌉ bits to store each value. It then takes nk bits to store the whole file. To reduce the memory consumption we need to apply some compression. One common way is to reduce the number of possible intensity values. We choose two integers l ≤ r, and after that all intensity values are changed in the following way: if the intensity value is within the range [l;r], we don't change it. If it is less than l, we change it to l; if it is greater than r, we change it to r. You can see that we lose some low and some high intensities. Your task is to apply this compression in such a way that the file fits onto a disk of size I bytes, and the number of changed elements in the array is minimal possible. We remind you that 1 byte contains 8 bits. k = ⌈ log_{2} K ⌉ is the smallest integer such that K ≤ 2^{k}. In particular, if K = 1, then k = 0. Input The first line contains two integers n and I (1 ≤ n ≤ 4 ⋅ 10^{5}, 1 ≤ I ≤ 10^{8}) — the length of the array and the size of the disk in bytes, respectively. The next line contains n integers a_{i} (0 ≤ a_{i} ≤ 10^{9}) — the array denoting the sound file. Output Print a single integer — the minimal possible number of changed elements. Examples Input 6 1 2 1 2 3 4 3 Output 2 Input 6 2 2 1 2 3 4 3 Output 0 Input 6 1 1 1 2 2 3 3 Output 2 Note In the first example we can choose l=2, r=3. The array becomes 2 2 2 3 3 3, the number of distinct elements is K=2, and the sound file fits onto the disk. Only two values are changed. In the second example the disk is larger, so the initial file fits it and no changes are required. In the third example we have to change both 1s or both 3s. Tags: sortings, two pointers Correct Solution: ``` n,l=[int(x) for x in input().split()] a=sorted([int(x) for x in input().split()]) num=len(set(a)) arr=2**((8*l)//n) a.append(10**100) b=[] counter=1 for i in range(1,n+1): if a[i]==a[i-1]: counter+=1 else: b.append(counter) counter=1 pref=[0] for item in b: pref.append(pref[-1]+item) c=max(num-arr,0) lena=len(pref) answer=10**100 for i in range(c+1): answer=min(answer,pref[i]+pref[lena-1]-pref[lena-c+i-1]) print(answer) ```
3,409
Provide tags and a correct Python 3 solution for this coding contest problem. One common way of digitalizing sound is to record sound intensity at particular time moments. For each time moment intensity is recorded as a non-negative integer. Thus we can represent a sound file as an array of n non-negative integers. If there are exactly K distinct values in the array, then we need k = ⌈ log_{2} K ⌉ bits to store each value. It then takes nk bits to store the whole file. To reduce the memory consumption we need to apply some compression. One common way is to reduce the number of possible intensity values. We choose two integers l ≤ r, and after that all intensity values are changed in the following way: if the intensity value is within the range [l;r], we don't change it. If it is less than l, we change it to l; if it is greater than r, we change it to r. You can see that we lose some low and some high intensities. Your task is to apply this compression in such a way that the file fits onto a disk of size I bytes, and the number of changed elements in the array is minimal possible. We remind you that 1 byte contains 8 bits. k = ⌈ log_{2} K ⌉ is the smallest integer such that K ≤ 2^{k}. In particular, if K = 1, then k = 0. Input The first line contains two integers n and I (1 ≤ n ≤ 4 ⋅ 10^{5}, 1 ≤ I ≤ 10^{8}) — the length of the array and the size of the disk in bytes, respectively. The next line contains n integers a_{i} (0 ≤ a_{i} ≤ 10^{9}) — the array denoting the sound file. Output Print a single integer — the minimal possible number of changed elements. Examples Input 6 1 2 1 2 3 4 3 Output 2 Input 6 2 2 1 2 3 4 3 Output 0 Input 6 1 1 1 2 2 3 3 Output 2 Note In the first example we can choose l=2, r=3. The array becomes 2 2 2 3 3 3, the number of distinct elements is K=2, and the sound file fits onto the disk. Only two values are changed. In the second example the disk is larger, so the initial file fits it and no changes are required. In the third example we have to change both 1s or both 3s. Tags: sortings, two pointers Correct Solution: ``` n, m = map(int, input().split()) a = sorted(map(int, input().split())) b = [0] a += [1 << 30] for i in range(n): if a[i] < a[i+1]: b += [i+1] print(n-max((y-x for x,y in zip(b,b[1<<8*m//n:])),default=n)) ```
3,410
Provide tags and a correct Python 3 solution for this coding contest problem. One common way of digitalizing sound is to record sound intensity at particular time moments. For each time moment intensity is recorded as a non-negative integer. Thus we can represent a sound file as an array of n non-negative integers. If there are exactly K distinct values in the array, then we need k = ⌈ log_{2} K ⌉ bits to store each value. It then takes nk bits to store the whole file. To reduce the memory consumption we need to apply some compression. One common way is to reduce the number of possible intensity values. We choose two integers l ≤ r, and after that all intensity values are changed in the following way: if the intensity value is within the range [l;r], we don't change it. If it is less than l, we change it to l; if it is greater than r, we change it to r. You can see that we lose some low and some high intensities. Your task is to apply this compression in such a way that the file fits onto a disk of size I bytes, and the number of changed elements in the array is minimal possible. We remind you that 1 byte contains 8 bits. k = ⌈ log_{2} K ⌉ is the smallest integer such that K ≤ 2^{k}. In particular, if K = 1, then k = 0. Input The first line contains two integers n and I (1 ≤ n ≤ 4 ⋅ 10^{5}, 1 ≤ I ≤ 10^{8}) — the length of the array and the size of the disk in bytes, respectively. The next line contains n integers a_{i} (0 ≤ a_{i} ≤ 10^{9}) — the array denoting the sound file. Output Print a single integer — the minimal possible number of changed elements. Examples Input 6 1 2 1 2 3 4 3 Output 2 Input 6 2 2 1 2 3 4 3 Output 0 Input 6 1 1 1 2 2 3 3 Output 2 Note In the first example we can choose l=2, r=3. The array becomes 2 2 2 3 3 3, the number of distinct elements is K=2, and the sound file fits onto the disk. Only two values are changed. In the second example the disk is larger, so the initial file fits it and no changes are required. In the third example we have to change both 1s or both 3s. Tags: sortings, two pointers Correct Solution: ``` from math import log2, ceil n, k = map(int, input().split()) k *= 8 a = sorted(list(map(int, input().split()))) q1, dif = 0, 1 ans = float('inf') for q in range(n): while n*ceil(log2(dif)) <= k and q1 < n: if q1 == n-1 or a[q1] != a[q1+1]: dif += 1 q1 += 1 ans = min(ans, q+n-q1) if q != n-1 and a[q] != a[q+1]: dif -= 1 print(ans) ```
3,411
Provide tags and a correct Python 3 solution for this coding contest problem. One common way of digitalizing sound is to record sound intensity at particular time moments. For each time moment intensity is recorded as a non-negative integer. Thus we can represent a sound file as an array of n non-negative integers. If there are exactly K distinct values in the array, then we need k = ⌈ log_{2} K ⌉ bits to store each value. It then takes nk bits to store the whole file. To reduce the memory consumption we need to apply some compression. One common way is to reduce the number of possible intensity values. We choose two integers l ≤ r, and after that all intensity values are changed in the following way: if the intensity value is within the range [l;r], we don't change it. If it is less than l, we change it to l; if it is greater than r, we change it to r. You can see that we lose some low and some high intensities. Your task is to apply this compression in such a way that the file fits onto a disk of size I bytes, and the number of changed elements in the array is minimal possible. We remind you that 1 byte contains 8 bits. k = ⌈ log_{2} K ⌉ is the smallest integer such that K ≤ 2^{k}. In particular, if K = 1, then k = 0. Input The first line contains two integers n and I (1 ≤ n ≤ 4 ⋅ 10^{5}, 1 ≤ I ≤ 10^{8}) — the length of the array and the size of the disk in bytes, respectively. The next line contains n integers a_{i} (0 ≤ a_{i} ≤ 10^{9}) — the array denoting the sound file. Output Print a single integer — the minimal possible number of changed elements. Examples Input 6 1 2 1 2 3 4 3 Output 2 Input 6 2 2 1 2 3 4 3 Output 0 Input 6 1 1 1 2 2 3 3 Output 2 Note In the first example we can choose l=2, r=3. The array becomes 2 2 2 3 3 3, the number of distinct elements is K=2, and the sound file fits onto the disk. Only two values are changed. In the second example the disk is larger, so the initial file fits it and no changes are required. In the third example we have to change both 1s or both 3s. Tags: sortings, two pointers Correct Solution: ``` n,I=map(int,input().split()) I*=8 I //= n arr=list(map(int,input().split())) arr.sort() smen = [0] typs = 1 for i in range(1,n): if arr[i] != arr[i-1]: typs+=1 smen.append(i) smen.append(n) deg = 1 lg = 0 while deg < typs: lg += 1 deg *= 2 if lg == 0 or I >= lg: print(0) else: degi = 2 ** I mon = typs - degi ans = 400001 for x in range(mon+1): now = smen[x] + n - smen[typs-mon+x] if now<ans: ans=now print(ans) ```
3,412
Provide tags and a correct Python 3 solution for this coding contest problem. One common way of digitalizing sound is to record sound intensity at particular time moments. For each time moment intensity is recorded as a non-negative integer. Thus we can represent a sound file as an array of n non-negative integers. If there are exactly K distinct values in the array, then we need k = ⌈ log_{2} K ⌉ bits to store each value. It then takes nk bits to store the whole file. To reduce the memory consumption we need to apply some compression. One common way is to reduce the number of possible intensity values. We choose two integers l ≤ r, and after that all intensity values are changed in the following way: if the intensity value is within the range [l;r], we don't change it. If it is less than l, we change it to l; if it is greater than r, we change it to r. You can see that we lose some low and some high intensities. Your task is to apply this compression in such a way that the file fits onto a disk of size I bytes, and the number of changed elements in the array is minimal possible. We remind you that 1 byte contains 8 bits. k = ⌈ log_{2} K ⌉ is the smallest integer such that K ≤ 2^{k}. In particular, if K = 1, then k = 0. Input The first line contains two integers n and I (1 ≤ n ≤ 4 ⋅ 10^{5}, 1 ≤ I ≤ 10^{8}) — the length of the array and the size of the disk in bytes, respectively. The next line contains n integers a_{i} (0 ≤ a_{i} ≤ 10^{9}) — the array denoting the sound file. Output Print a single integer — the minimal possible number of changed elements. Examples Input 6 1 2 1 2 3 4 3 Output 2 Input 6 2 2 1 2 3 4 3 Output 0 Input 6 1 1 1 2 2 3 3 Output 2 Note In the first example we can choose l=2, r=3. The array becomes 2 2 2 3 3 3, the number of distinct elements is K=2, and the sound file fits onto the disk. Only two values are changed. In the second example the disk is larger, so the initial file fits it and no changes are required. In the third example we have to change both 1s or both 3s. Tags: sortings, two pointers Correct Solution: ``` n,I=list(map(int, input().split())) l=list(map(int, input().split())) k=2**(I*8//n) dd={} for x in l: if x in dd: dd[x]+=1 else: dd[x]=1 # print(dd) l=[dd[x] for x in sorted(dd)] # print(l) n=len(l) if k>=n: print(0) else: ss=sum(l[:k]) mxm=ss for i in range(1,n-k+1): ss+=l[i+k-1]-l[i-1] if mxm<ss: mxm=ss print(sum(l)-mxm) ```
3,413
Provide tags and a correct Python 3 solution for this coding contest problem. One common way of digitalizing sound is to record sound intensity at particular time moments. For each time moment intensity is recorded as a non-negative integer. Thus we can represent a sound file as an array of n non-negative integers. If there are exactly K distinct values in the array, then we need k = ⌈ log_{2} K ⌉ bits to store each value. It then takes nk bits to store the whole file. To reduce the memory consumption we need to apply some compression. One common way is to reduce the number of possible intensity values. We choose two integers l ≤ r, and after that all intensity values are changed in the following way: if the intensity value is within the range [l;r], we don't change it. If it is less than l, we change it to l; if it is greater than r, we change it to r. You can see that we lose some low and some high intensities. Your task is to apply this compression in such a way that the file fits onto a disk of size I bytes, and the number of changed elements in the array is minimal possible. We remind you that 1 byte contains 8 bits. k = ⌈ log_{2} K ⌉ is the smallest integer such that K ≤ 2^{k}. In particular, if K = 1, then k = 0. Input The first line contains two integers n and I (1 ≤ n ≤ 4 ⋅ 10^{5}, 1 ≤ I ≤ 10^{8}) — the length of the array and the size of the disk in bytes, respectively. The next line contains n integers a_{i} (0 ≤ a_{i} ≤ 10^{9}) — the array denoting the sound file. Output Print a single integer — the minimal possible number of changed elements. Examples Input 6 1 2 1 2 3 4 3 Output 2 Input 6 2 2 1 2 3 4 3 Output 0 Input 6 1 1 1 2 2 3 3 Output 2 Note In the first example we can choose l=2, r=3. The array becomes 2 2 2 3 3 3, the number of distinct elements is K=2, and the sound file fits onto the disk. Only two values are changed. In the second example the disk is larger, so the initial file fits it and no changes are required. In the third example we have to change both 1s or both 3s. Tags: sortings, two pointers Correct Solution: ``` from sys import stdin input = stdin.readline from math import floor n, I = [int(i) for i in input().split()] a = [int(i) for i in input().split()] K = 2**(floor(8*I/n)) num_occ = dict() for i in range(n): num_occ[a[i]] = num_occ.get(a[i], 0) + 1 if K >= len(num_occ): print(0) else: sort_keys = sorted(num_occ.keys()) sum_K = [0]*(len(sort_keys)-K+1) acc_K = 0 for i in range(K): acc_K += num_occ[sort_keys[i]] sum_K[0] = acc_K for i in range(K, len(sort_keys)): acc_K += num_occ[sort_keys[i]]-num_occ[sort_keys[i-K]] sum_K[i-K+1] = acc_K print(n-max(sum_K)) ```
3,414
Provide tags and a correct Python 3 solution for this coding contest problem. One common way of digitalizing sound is to record sound intensity at particular time moments. For each time moment intensity is recorded as a non-negative integer. Thus we can represent a sound file as an array of n non-negative integers. If there are exactly K distinct values in the array, then we need k = ⌈ log_{2} K ⌉ bits to store each value. It then takes nk bits to store the whole file. To reduce the memory consumption we need to apply some compression. One common way is to reduce the number of possible intensity values. We choose two integers l ≤ r, and after that all intensity values are changed in the following way: if the intensity value is within the range [l;r], we don't change it. If it is less than l, we change it to l; if it is greater than r, we change it to r. You can see that we lose some low and some high intensities. Your task is to apply this compression in such a way that the file fits onto a disk of size I bytes, and the number of changed elements in the array is minimal possible. We remind you that 1 byte contains 8 bits. k = ⌈ log_{2} K ⌉ is the smallest integer such that K ≤ 2^{k}. In particular, if K = 1, then k = 0. Input The first line contains two integers n and I (1 ≤ n ≤ 4 ⋅ 10^{5}, 1 ≤ I ≤ 10^{8}) — the length of the array and the size of the disk in bytes, respectively. The next line contains n integers a_{i} (0 ≤ a_{i} ≤ 10^{9}) — the array denoting the sound file. Output Print a single integer — the minimal possible number of changed elements. Examples Input 6 1 2 1 2 3 4 3 Output 2 Input 6 2 2 1 2 3 4 3 Output 0 Input 6 1 1 1 2 2 3 3 Output 2 Note In the first example we can choose l=2, r=3. The array becomes 2 2 2 3 3 3, the number of distinct elements is K=2, and the sound file fits onto the disk. Only two values are changed. In the second example the disk is larger, so the initial file fits it and no changes are required. In the third example we have to change both 1s or both 3s. Tags: sortings, two pointers Correct Solution: ``` from itertools import accumulate # python template for atcoder1 import sys sys.setrecursionlimit(10**9) input = sys.stdin.readline N, K = map(int, input().split()) A = list(map(int, input().split())) A = sorted(A) L = [] prev = -1 for a in A: if a == prev: L[-1] += 1 else: L.append(1) prev = a max_types = int(2**((8*K)//N)) all_types = len(L) del_types = all_types-max_types if del_types <= 0: ans = 0 else: ans = float('inf') sum_L = N L_acc = [0]+list(accumulate(L)) for i in range(len(L)-max_types): s = L_acc[i+max_types]-L_acc[i] ans = min(ans, sum_L-s) print(ans) ```
3,415
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One common way of digitalizing sound is to record sound intensity at particular time moments. For each time moment intensity is recorded as a non-negative integer. Thus we can represent a sound file as an array of n non-negative integers. If there are exactly K distinct values in the array, then we need k = ⌈ log_{2} K ⌉ bits to store each value. It then takes nk bits to store the whole file. To reduce the memory consumption we need to apply some compression. One common way is to reduce the number of possible intensity values. We choose two integers l ≤ r, and after that all intensity values are changed in the following way: if the intensity value is within the range [l;r], we don't change it. If it is less than l, we change it to l; if it is greater than r, we change it to r. You can see that we lose some low and some high intensities. Your task is to apply this compression in such a way that the file fits onto a disk of size I bytes, and the number of changed elements in the array is minimal possible. We remind you that 1 byte contains 8 bits. k = ⌈ log_{2} K ⌉ is the smallest integer such that K ≤ 2^{k}. In particular, if K = 1, then k = 0. Input The first line contains two integers n and I (1 ≤ n ≤ 4 ⋅ 10^{5}, 1 ≤ I ≤ 10^{8}) — the length of the array and the size of the disk in bytes, respectively. The next line contains n integers a_{i} (0 ≤ a_{i} ≤ 10^{9}) — the array denoting the sound file. Output Print a single integer — the minimal possible number of changed elements. Examples Input 6 1 2 1 2 3 4 3 Output 2 Input 6 2 2 1 2 3 4 3 Output 0 Input 6 1 1 1 2 2 3 3 Output 2 Note In the first example we can choose l=2, r=3. The array becomes 2 2 2 3 3 3, the number of distinct elements is K=2, and the sound file fits onto the disk. Only two values are changed. In the second example the disk is larger, so the initial file fits it and no changes are required. In the third example we have to change both 1s or both 3s. Submitted Solution: ``` import sys import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline def main(): n, I = map(int, input().split()) A = list(map(int, input().split())) table = [0]*21 table[0] = 1 for i in range(1, 21): table[i] = table[i-1]*2 import bisect def is_ok(K): k = bisect.bisect_left(table, K) if n*k <= 8*I: return True else: return False ok = 1 ng = len(set(A))+1 while ok+1 <ng: c = (ok+ng)//2 if is_ok(c): ok = c else: ng = c K = ok #print(K) from collections import Counter C = Counter(A) if len(C) <= K: print(0) exit() C = list(C.items()) C.sort(key=lambda x: x[0]) #print(C) S = [] for k, v in C: S.append(v) #print(S) T = list(reversed(S)) from itertools import accumulate CS = [0]+S CT = [0]+T CS = list(accumulate(CS)) CT = list(accumulate(CT)) #print(CS) #print(CT) p = len(C)-K ans = 5*10**5 for x in range(0, p+1): y = p-x ans = min(ans, CS[x]+CT[y]) print(ans) if __name__ == '__main__': main() ``` Yes
3,416
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One common way of digitalizing sound is to record sound intensity at particular time moments. For each time moment intensity is recorded as a non-negative integer. Thus we can represent a sound file as an array of n non-negative integers. If there are exactly K distinct values in the array, then we need k = ⌈ log_{2} K ⌉ bits to store each value. It then takes nk bits to store the whole file. To reduce the memory consumption we need to apply some compression. One common way is to reduce the number of possible intensity values. We choose two integers l ≤ r, and after that all intensity values are changed in the following way: if the intensity value is within the range [l;r], we don't change it. If it is less than l, we change it to l; if it is greater than r, we change it to r. You can see that we lose some low and some high intensities. Your task is to apply this compression in such a way that the file fits onto a disk of size I bytes, and the number of changed elements in the array is minimal possible. We remind you that 1 byte contains 8 bits. k = ⌈ log_{2} K ⌉ is the smallest integer such that K ≤ 2^{k}. In particular, if K = 1, then k = 0. Input The first line contains two integers n and I (1 ≤ n ≤ 4 ⋅ 10^{5}, 1 ≤ I ≤ 10^{8}) — the length of the array and the size of the disk in bytes, respectively. The next line contains n integers a_{i} (0 ≤ a_{i} ≤ 10^{9}) — the array denoting the sound file. Output Print a single integer — the minimal possible number of changed elements. Examples Input 6 1 2 1 2 3 4 3 Output 2 Input 6 2 2 1 2 3 4 3 Output 0 Input 6 1 1 1 2 2 3 3 Output 2 Note In the first example we can choose l=2, r=3. The array becomes 2 2 2 3 3 3, the number of distinct elements is K=2, and the sound file fits onto the disk. Only two values are changed. In the second example the disk is larger, so the initial file fits it and no changes are required. In the third example we have to change both 1s or both 3s. Submitted Solution: ``` import sys import math # n=int(sys.stdin.readline()) n,y=list(map(int,sys.stdin.readline().strip().split())) a=list(map(int,sys.stdin.readline().strip().split())) a.sort() a.append(0) # print(a) y=y*8 arr=[] i=0 k=2**(y//n) # print(k) while(i<n): # x=[a[i],1,math.ceil(math.log(a[i],2))+1] # x=[a[i],1] x=1 # print(i) while(a[i]==a[i+1] and i<n): # x[1]+=1 x+=1 i+=1 # print(i) arr.append(x) i+=1 # print(a,arr) arr=[0]+arr # print(arr) for i in range(1,len(arr)): arr[i]=arr[i]+arr[i-1] # print(arr) op=n # print(k) if(len(arr)<k): print(0) exit(0) for i in range(1,len(arr)): # xxx=arr[i]-arr[min(i-1,i-k)] if(i<k): xxx=arr[i]-arr[i-1] else: xxx=arr[i]-arr[i-k] # print(xxx) op=min(op,n-xxx) print(op) ``` Yes
3,417
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One common way of digitalizing sound is to record sound intensity at particular time moments. For each time moment intensity is recorded as a non-negative integer. Thus we can represent a sound file as an array of n non-negative integers. If there are exactly K distinct values in the array, then we need k = ⌈ log_{2} K ⌉ bits to store each value. It then takes nk bits to store the whole file. To reduce the memory consumption we need to apply some compression. One common way is to reduce the number of possible intensity values. We choose two integers l ≤ r, and after that all intensity values are changed in the following way: if the intensity value is within the range [l;r], we don't change it. If it is less than l, we change it to l; if it is greater than r, we change it to r. You can see that we lose some low and some high intensities. Your task is to apply this compression in such a way that the file fits onto a disk of size I bytes, and the number of changed elements in the array is minimal possible. We remind you that 1 byte contains 8 bits. k = ⌈ log_{2} K ⌉ is the smallest integer such that K ≤ 2^{k}. In particular, if K = 1, then k = 0. Input The first line contains two integers n and I (1 ≤ n ≤ 4 ⋅ 10^{5}, 1 ≤ I ≤ 10^{8}) — the length of the array and the size of the disk in bytes, respectively. The next line contains n integers a_{i} (0 ≤ a_{i} ≤ 10^{9}) — the array denoting the sound file. Output Print a single integer — the minimal possible number of changed elements. Examples Input 6 1 2 1 2 3 4 3 Output 2 Input 6 2 2 1 2 3 4 3 Output 0 Input 6 1 1 1 2 2 3 3 Output 2 Note In the first example we can choose l=2, r=3. The array becomes 2 2 2 3 3 3, the number of distinct elements is K=2, and the sound file fits onto the disk. Only two values are changed. In the second example the disk is larger, so the initial file fits it and no changes are required. In the third example we have to change both 1s or both 3s. Submitted Solution: ``` R=lambda:map(int,input().split()) n,I=R() a=[-1]+sorted(R()) b=[i for i in range(n)if a[i]<a[i+1]] print(n-max(y-x for x,y in zip(b,b[1<<8*I//n:]+[n]))) ``` Yes
3,418
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One common way of digitalizing sound is to record sound intensity at particular time moments. For each time moment intensity is recorded as a non-negative integer. Thus we can represent a sound file as an array of n non-negative integers. If there are exactly K distinct values in the array, then we need k = ⌈ log_{2} K ⌉ bits to store each value. It then takes nk bits to store the whole file. To reduce the memory consumption we need to apply some compression. One common way is to reduce the number of possible intensity values. We choose two integers l ≤ r, and after that all intensity values are changed in the following way: if the intensity value is within the range [l;r], we don't change it. If it is less than l, we change it to l; if it is greater than r, we change it to r. You can see that we lose some low and some high intensities. Your task is to apply this compression in such a way that the file fits onto a disk of size I bytes, and the number of changed elements in the array is minimal possible. We remind you that 1 byte contains 8 bits. k = ⌈ log_{2} K ⌉ is the smallest integer such that K ≤ 2^{k}. In particular, if K = 1, then k = 0. Input The first line contains two integers n and I (1 ≤ n ≤ 4 ⋅ 10^{5}, 1 ≤ I ≤ 10^{8}) — the length of the array and the size of the disk in bytes, respectively. The next line contains n integers a_{i} (0 ≤ a_{i} ≤ 10^{9}) — the array denoting the sound file. Output Print a single integer — the minimal possible number of changed elements. Examples Input 6 1 2 1 2 3 4 3 Output 2 Input 6 2 2 1 2 3 4 3 Output 0 Input 6 1 1 1 2 2 3 3 Output 2 Note In the first example we can choose l=2, r=3. The array becomes 2 2 2 3 3 3, the number of distinct elements is K=2, and the sound file fits onto the disk. Only two values are changed. In the second example the disk is larger, so the initial file fits it and no changes are required. In the third example we have to change both 1s or both 3s. Submitted Solution: ``` import math n, I = map(int, input().split()) a = list(map(int,input().split())) a.sort() vals = 2**((I*8)//n) K = len(a) if K>vals: d = {} for i in a: d[i] = d.get(i, 0) + 1 d = list(d.items()) s = sum([val for key, val in d[:vals]]) maxs = s for i in range(vals, len(d)): s = s - d[i-vals][1] + d[i][1] maxs = max(maxs, s) print(n - maxs) else: print(0) ``` Yes
3,419
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One common way of digitalizing sound is to record sound intensity at particular time moments. For each time moment intensity is recorded as a non-negative integer. Thus we can represent a sound file as an array of n non-negative integers. If there are exactly K distinct values in the array, then we need k = ⌈ log_{2} K ⌉ bits to store each value. It then takes nk bits to store the whole file. To reduce the memory consumption we need to apply some compression. One common way is to reduce the number of possible intensity values. We choose two integers l ≤ r, and after that all intensity values are changed in the following way: if the intensity value is within the range [l;r], we don't change it. If it is less than l, we change it to l; if it is greater than r, we change it to r. You can see that we lose some low and some high intensities. Your task is to apply this compression in such a way that the file fits onto a disk of size I bytes, and the number of changed elements in the array is minimal possible. We remind you that 1 byte contains 8 bits. k = ⌈ log_{2} K ⌉ is the smallest integer such that K ≤ 2^{k}. In particular, if K = 1, then k = 0. Input The first line contains two integers n and I (1 ≤ n ≤ 4 ⋅ 10^{5}, 1 ≤ I ≤ 10^{8}) — the length of the array and the size of the disk in bytes, respectively. The next line contains n integers a_{i} (0 ≤ a_{i} ≤ 10^{9}) — the array denoting the sound file. Output Print a single integer — the minimal possible number of changed elements. Examples Input 6 1 2 1 2 3 4 3 Output 2 Input 6 2 2 1 2 3 4 3 Output 0 Input 6 1 1 1 2 2 3 3 Output 2 Note In the first example we can choose l=2, r=3. The array becomes 2 2 2 3 3 3, the number of distinct elements is K=2, and the sound file fits onto the disk. Only two values are changed. In the second example the disk is larger, so the initial file fits it and no changes are required. In the third example we have to change both 1s or both 3s. Submitted Solution: ``` import sys input = sys.stdin.readline from math import log from collections import deque n, i = map(int, input().split()) l = list(map(int, input().split())) quota = 8 * i / n k = 1 for i in range(100): if log(k * 2, 2) <= quota: k *= 2 else: break l = sorted(l) a = l[0] b = l[0] + k d = deque() d.append(a) i = 1 ans = 1 cnt = 1 while (i < n): #print(d, cnt, ans) x = l[i] if x >= b: while (d != deque() and d[0] <= l[i] - k): d.popleft() cnt -= 1 d.append(x) cnt += 1 else: d.append(x) cnt += 1 ans = max(cnt, ans) i += 1 print(n - ans) ``` No
3,420
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One common way of digitalizing sound is to record sound intensity at particular time moments. For each time moment intensity is recorded as a non-negative integer. Thus we can represent a sound file as an array of n non-negative integers. If there are exactly K distinct values in the array, then we need k = ⌈ log_{2} K ⌉ bits to store each value. It then takes nk bits to store the whole file. To reduce the memory consumption we need to apply some compression. One common way is to reduce the number of possible intensity values. We choose two integers l ≤ r, and after that all intensity values are changed in the following way: if the intensity value is within the range [l;r], we don't change it. If it is less than l, we change it to l; if it is greater than r, we change it to r. You can see that we lose some low and some high intensities. Your task is to apply this compression in such a way that the file fits onto a disk of size I bytes, and the number of changed elements in the array is minimal possible. We remind you that 1 byte contains 8 bits. k = ⌈ log_{2} K ⌉ is the smallest integer such that K ≤ 2^{k}. In particular, if K = 1, then k = 0. Input The first line contains two integers n and I (1 ≤ n ≤ 4 ⋅ 10^{5}, 1 ≤ I ≤ 10^{8}) — the length of the array and the size of the disk in bytes, respectively. The next line contains n integers a_{i} (0 ≤ a_{i} ≤ 10^{9}) — the array denoting the sound file. Output Print a single integer — the minimal possible number of changed elements. Examples Input 6 1 2 1 2 3 4 3 Output 2 Input 6 2 2 1 2 3 4 3 Output 0 Input 6 1 1 1 2 2 3 3 Output 2 Note In the first example we can choose l=2, r=3. The array becomes 2 2 2 3 3 3, the number of distinct elements is K=2, and the sound file fits onto the disk. Only two values are changed. In the second example the disk is larger, so the initial file fits it and no changes are required. In the third example we have to change both 1s or both 3s. Submitted Solution: ``` n,I=map(int,input().split()) print(n,I) a=list(map(int,input().split())) I*=8 k=I//n if k>=20: res=0 else: K=2**k print(K,I) cc={} for ai in a: cc[ai]=cc.get(ai,0)+1 pres=[] dd=sorted(cc) for i in dd: pres.append(cc[i]) for i in range(1,len(pres)): pres[i]+=pres[i-1] if K>=len(pres): res=0 else: mm=0 for i in range(K,len(pres)): if mm<pres[i]-pres[i-K]: mm=pres[i]-pres[i-K] res=n-mm print(res) ``` No
3,421
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One common way of digitalizing sound is to record sound intensity at particular time moments. For each time moment intensity is recorded as a non-negative integer. Thus we can represent a sound file as an array of n non-negative integers. If there are exactly K distinct values in the array, then we need k = ⌈ log_{2} K ⌉ bits to store each value. It then takes nk bits to store the whole file. To reduce the memory consumption we need to apply some compression. One common way is to reduce the number of possible intensity values. We choose two integers l ≤ r, and after that all intensity values are changed in the following way: if the intensity value is within the range [l;r], we don't change it. If it is less than l, we change it to l; if it is greater than r, we change it to r. You can see that we lose some low and some high intensities. Your task is to apply this compression in such a way that the file fits onto a disk of size I bytes, and the number of changed elements in the array is minimal possible. We remind you that 1 byte contains 8 bits. k = ⌈ log_{2} K ⌉ is the smallest integer such that K ≤ 2^{k}. In particular, if K = 1, then k = 0. Input The first line contains two integers n and I (1 ≤ n ≤ 4 ⋅ 10^{5}, 1 ≤ I ≤ 10^{8}) — the length of the array and the size of the disk in bytes, respectively. The next line contains n integers a_{i} (0 ≤ a_{i} ≤ 10^{9}) — the array denoting the sound file. Output Print a single integer — the minimal possible number of changed elements. Examples Input 6 1 2 1 2 3 4 3 Output 2 Input 6 2 2 1 2 3 4 3 Output 0 Input 6 1 1 1 2 2 3 3 Output 2 Note In the first example we can choose l=2, r=3. The array becomes 2 2 2 3 3 3, the number of distinct elements is K=2, and the sound file fits onto the disk. Only two values are changed. In the second example the disk is larger, so the initial file fits it and no changes are required. In the third example we have to change both 1s or both 3s. Submitted Solution: ``` n, l = map(int, input().split()) a = [*map(int, input().split())] a.sort() from math import log, ceil, exp t = ceil(log(len(set(a)))) * n if t <= l * 8: print('0') exit() r = 0 for i in range(n, -1, -1): if ceil(log(i)) * n <= l * 8: r = i break from collections import Counter c = Counter(a).most_common()[::-1] ans = 0 for i in c[:len(set(a)) - r]: ans += i[1] print(ans) ``` No
3,422
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One common way of digitalizing sound is to record sound intensity at particular time moments. For each time moment intensity is recorded as a non-negative integer. Thus we can represent a sound file as an array of n non-negative integers. If there are exactly K distinct values in the array, then we need k = ⌈ log_{2} K ⌉ bits to store each value. It then takes nk bits to store the whole file. To reduce the memory consumption we need to apply some compression. One common way is to reduce the number of possible intensity values. We choose two integers l ≤ r, and after that all intensity values are changed in the following way: if the intensity value is within the range [l;r], we don't change it. If it is less than l, we change it to l; if it is greater than r, we change it to r. You can see that we lose some low and some high intensities. Your task is to apply this compression in such a way that the file fits onto a disk of size I bytes, and the number of changed elements in the array is minimal possible. We remind you that 1 byte contains 8 bits. k = ⌈ log_{2} K ⌉ is the smallest integer such that K ≤ 2^{k}. In particular, if K = 1, then k = 0. Input The first line contains two integers n and I (1 ≤ n ≤ 4 ⋅ 10^{5}, 1 ≤ I ≤ 10^{8}) — the length of the array and the size of the disk in bytes, respectively. The next line contains n integers a_{i} (0 ≤ a_{i} ≤ 10^{9}) — the array denoting the sound file. Output Print a single integer — the minimal possible number of changed elements. Examples Input 6 1 2 1 2 3 4 3 Output 2 Input 6 2 2 1 2 3 4 3 Output 0 Input 6 1 1 1 2 2 3 3 Output 2 Note In the first example we can choose l=2, r=3. The array becomes 2 2 2 3 3 3, the number of distinct elements is K=2, and the sound file fits onto the disk. Only two values are changed. In the second example the disk is larger, so the initial file fits it and no changes are required. In the third example we have to change both 1s or both 3s. Submitted Solution: ``` #576_C import math l = [int(i) for i in input().split(" ")] n = l[0] bt = l[1] ln = sorted([int(i) for i in input().split(" ")]) K = 1 dists = [1] for i in range(1, len(ln)): if ln[i] != ln[i - 1]: K += 1 dists.append(1) else: dists[-1] += 1 rdists = dists[:] ldists = dists[::-1] minVal = math.floor(2 ** ((bt * 8) / n)) dels = 0 inds = 0 minVal = K - minVal while dels < minVal: if ldists[-1] < rdists[-1]: inds += ldists[-1] ldists.pop() else: inds += rdists[-1] rdists.pop() dels += 1 print(inds) ``` No
3,423
Provide tags and a correct Python 3 solution for this coding contest problem. Recently Vasya decided to improve his pistol shooting skills. Today his coach offered him the following exercise. He placed n cans in a row on a table. Cans are numbered from left to right from 1 to n. Vasya has to knock down each can exactly once to finish the exercise. He is allowed to choose the order in which he will knock the cans down. Vasya knows that the durability of the i-th can is a_i. It means that if Vasya has already knocked x cans down and is now about to start shooting the i-th one, he will need (a_i ⋅ x + 1) shots to knock it down. You can assume that if Vasya starts shooting the i-th can, he will be shooting it until he knocks it down. Your task is to choose such an order of shooting so that the number of shots required to knock each of the n given cans down exactly once is minimum possible. Input The first line of the input contains one integer n (2 ≤ n ≤ 1 000) — the number of cans. The second line of the input contains the sequence a_1, a_2, ..., a_n (1 ≤ a_i ≤ 1 000), where a_i is the durability of the i-th can. Output In the first line print the minimum number of shots required to knock each of the n given cans down exactly once. In the second line print the sequence consisting of n distinct integers from 1 to n — the order of indices of cans that minimizes the number of shots required. If there are several answers, you can print any of them. Examples Input 3 20 10 20 Output 43 1 3 2 Input 4 10 10 10 10 Output 64 2 1 4 3 Input 6 5 4 5 4 4 5 Output 69 6 1 3 5 2 4 Input 2 1 4 Output 3 2 1 Note In the first example Vasya can start shooting from the first can. He knocks it down with the first shot because he haven't knocked any other cans down before. After that he has to shoot the third can. To knock it down he shoots 20 ⋅ 1 + 1 = 21 times. After that only second can remains. To knock it down Vasya shoots 10 ⋅ 2 + 1 = 21 times. So the total number of shots is 1 + 21 + 21 = 43. In the second example the order of shooting does not matter because all cans have the same durability. Tags: greedy, implementation, sortings Correct Solution: ``` n = int(input()) l = list(map(int, input().split())) ind = {} i = 0 s = 0 for j in l: if j in ind.keys(): ind[j].append(str(i + 1)) else: ind[j] = [str(i + 1)] i += 1 l.sort(key = lambda x : -x) for x in range(len(l)): s += l[x] * x + 1 print(s) d = list(ind.items()) d.sort(key = lambda t : -t[0]) for i in d: print(' '.join(i[1]), end = ' ') ```
3,424
Provide tags and a correct Python 3 solution for this coding contest problem. Recently Vasya decided to improve his pistol shooting skills. Today his coach offered him the following exercise. He placed n cans in a row on a table. Cans are numbered from left to right from 1 to n. Vasya has to knock down each can exactly once to finish the exercise. He is allowed to choose the order in which he will knock the cans down. Vasya knows that the durability of the i-th can is a_i. It means that if Vasya has already knocked x cans down and is now about to start shooting the i-th one, he will need (a_i ⋅ x + 1) shots to knock it down. You can assume that if Vasya starts shooting the i-th can, he will be shooting it until he knocks it down. Your task is to choose such an order of shooting so that the number of shots required to knock each of the n given cans down exactly once is minimum possible. Input The first line of the input contains one integer n (2 ≤ n ≤ 1 000) — the number of cans. The second line of the input contains the sequence a_1, a_2, ..., a_n (1 ≤ a_i ≤ 1 000), where a_i is the durability of the i-th can. Output In the first line print the minimum number of shots required to knock each of the n given cans down exactly once. In the second line print the sequence consisting of n distinct integers from 1 to n — the order of indices of cans that minimizes the number of shots required. If there are several answers, you can print any of them. Examples Input 3 20 10 20 Output 43 1 3 2 Input 4 10 10 10 10 Output 64 2 1 4 3 Input 6 5 4 5 4 4 5 Output 69 6 1 3 5 2 4 Input 2 1 4 Output 3 2 1 Note In the first example Vasya can start shooting from the first can. He knocks it down with the first shot because he haven't knocked any other cans down before. After that he has to shoot the third can. To knock it down he shoots 20 ⋅ 1 + 1 = 21 times. After that only second can remains. To knock it down Vasya shoots 10 ⋅ 2 + 1 = 21 times. So the total number of shots is 1 + 21 + 21 = 43. In the second example the order of shooting does not matter because all cans have the same durability. Tags: greedy, implementation, sortings Correct Solution: ``` n = int(input()) a = [(int(el), i + 1) for i, el in enumerate(input().split())] a = sorted(a, reverse=True) shots = 0 for i, (el, _) in enumerate(a): shots += i * el + 1 print(shots) print(*(i for _, i in a)) ```
3,425
Provide tags and a correct Python 3 solution for this coding contest problem. Recently Vasya decided to improve his pistol shooting skills. Today his coach offered him the following exercise. He placed n cans in a row on a table. Cans are numbered from left to right from 1 to n. Vasya has to knock down each can exactly once to finish the exercise. He is allowed to choose the order in which he will knock the cans down. Vasya knows that the durability of the i-th can is a_i. It means that if Vasya has already knocked x cans down and is now about to start shooting the i-th one, he will need (a_i ⋅ x + 1) shots to knock it down. You can assume that if Vasya starts shooting the i-th can, he will be shooting it until he knocks it down. Your task is to choose such an order of shooting so that the number of shots required to knock each of the n given cans down exactly once is minimum possible. Input The first line of the input contains one integer n (2 ≤ n ≤ 1 000) — the number of cans. The second line of the input contains the sequence a_1, a_2, ..., a_n (1 ≤ a_i ≤ 1 000), where a_i is the durability of the i-th can. Output In the first line print the minimum number of shots required to knock each of the n given cans down exactly once. In the second line print the sequence consisting of n distinct integers from 1 to n — the order of indices of cans that minimizes the number of shots required. If there are several answers, you can print any of them. Examples Input 3 20 10 20 Output 43 1 3 2 Input 4 10 10 10 10 Output 64 2 1 4 3 Input 6 5 4 5 4 4 5 Output 69 6 1 3 5 2 4 Input 2 1 4 Output 3 2 1 Note In the first example Vasya can start shooting from the first can. He knocks it down with the first shot because he haven't knocked any other cans down before. After that he has to shoot the third can. To knock it down he shoots 20 ⋅ 1 + 1 = 21 times. After that only second can remains. To knock it down Vasya shoots 10 ⋅ 2 + 1 = 21 times. So the total number of shots is 1 + 21 + 21 = 43. In the second example the order of shooting does not matter because all cans have the same durability. Tags: greedy, implementation, sortings Correct Solution: ``` n = int(input()) a = list(map(int, input().split())) r = [] ans = 0 for i in range(n): pos = -1 for j in range(n): if (pos == -1 or a[j] > a[pos]): pos = j r.append(pos + 1) ans += i * a[pos] + 1 a[pos] = 0 print(ans) print(*r) ```
3,426
Provide tags and a correct Python 3 solution for this coding contest problem. Recently Vasya decided to improve his pistol shooting skills. Today his coach offered him the following exercise. He placed n cans in a row on a table. Cans are numbered from left to right from 1 to n. Vasya has to knock down each can exactly once to finish the exercise. He is allowed to choose the order in which he will knock the cans down. Vasya knows that the durability of the i-th can is a_i. It means that if Vasya has already knocked x cans down and is now about to start shooting the i-th one, he will need (a_i ⋅ x + 1) shots to knock it down. You can assume that if Vasya starts shooting the i-th can, he will be shooting it until he knocks it down. Your task is to choose such an order of shooting so that the number of shots required to knock each of the n given cans down exactly once is minimum possible. Input The first line of the input contains one integer n (2 ≤ n ≤ 1 000) — the number of cans. The second line of the input contains the sequence a_1, a_2, ..., a_n (1 ≤ a_i ≤ 1 000), where a_i is the durability of the i-th can. Output In the first line print the minimum number of shots required to knock each of the n given cans down exactly once. In the second line print the sequence consisting of n distinct integers from 1 to n — the order of indices of cans that minimizes the number of shots required. If there are several answers, you can print any of them. Examples Input 3 20 10 20 Output 43 1 3 2 Input 4 10 10 10 10 Output 64 2 1 4 3 Input 6 5 4 5 4 4 5 Output 69 6 1 3 5 2 4 Input 2 1 4 Output 3 2 1 Note In the first example Vasya can start shooting from the first can. He knocks it down with the first shot because he haven't knocked any other cans down before. After that he has to shoot the third can. To knock it down he shoots 20 ⋅ 1 + 1 = 21 times. After that only second can remains. To knock it down Vasya shoots 10 ⋅ 2 + 1 = 21 times. So the total number of shots is 1 + 21 + 21 = 43. In the second example the order of shooting does not matter because all cans have the same durability. Tags: greedy, implementation, sortings Correct Solution: ``` n=int(input()) x=list(map(int,input().split())) y=[] for i in range(n) : y.append([x[i],i+1]) y=sorted(y);s=0;temp=[] y=list(reversed(y)) for i in range(n) : s=s+(y[i][0]*i+1) temp.append(y[i][1]) print(s) for c in temp : print(c,end=' ') ```
3,427
Provide tags and a correct Python 3 solution for this coding contest problem. Recently Vasya decided to improve his pistol shooting skills. Today his coach offered him the following exercise. He placed n cans in a row on a table. Cans are numbered from left to right from 1 to n. Vasya has to knock down each can exactly once to finish the exercise. He is allowed to choose the order in which he will knock the cans down. Vasya knows that the durability of the i-th can is a_i. It means that if Vasya has already knocked x cans down and is now about to start shooting the i-th one, he will need (a_i ⋅ x + 1) shots to knock it down. You can assume that if Vasya starts shooting the i-th can, he will be shooting it until he knocks it down. Your task is to choose such an order of shooting so that the number of shots required to knock each of the n given cans down exactly once is minimum possible. Input The first line of the input contains one integer n (2 ≤ n ≤ 1 000) — the number of cans. The second line of the input contains the sequence a_1, a_2, ..., a_n (1 ≤ a_i ≤ 1 000), where a_i is the durability of the i-th can. Output In the first line print the minimum number of shots required to knock each of the n given cans down exactly once. In the second line print the sequence consisting of n distinct integers from 1 to n — the order of indices of cans that minimizes the number of shots required. If there are several answers, you can print any of them. Examples Input 3 20 10 20 Output 43 1 3 2 Input 4 10 10 10 10 Output 64 2 1 4 3 Input 6 5 4 5 4 4 5 Output 69 6 1 3 5 2 4 Input 2 1 4 Output 3 2 1 Note In the first example Vasya can start shooting from the first can. He knocks it down with the first shot because he haven't knocked any other cans down before. After that he has to shoot the third can. To knock it down he shoots 20 ⋅ 1 + 1 = 21 times. After that only second can remains. To knock it down Vasya shoots 10 ⋅ 2 + 1 = 21 times. So the total number of shots is 1 + 21 + 21 = 43. In the second example the order of shooting does not matter because all cans have the same durability. Tags: greedy, implementation, sortings Correct Solution: ``` n=int(input()) aa=list(map(int, input().split())) a=[ [0]*2 for i in range(n)] for i in range(n): a[i][0]=aa[i] a[i][1]=i+1 #for i in range(n): #for j in range(2): #print(a[i][j], end=' ') #print() a.sort(key= lambda x: x[0]) #for i in range(n): #for j in range(2): #print(a[i][j], end=' ') #print() k=0 x=0 for i in range(n-1, -1, -1): k+=a[i][0]*x+1 x+=1 print(k) for i in range(n-1, -1, -1): print(a[i][1], end=' ') ```
3,428
Provide tags and a correct Python 3 solution for this coding contest problem. Recently Vasya decided to improve his pistol shooting skills. Today his coach offered him the following exercise. He placed n cans in a row on a table. Cans are numbered from left to right from 1 to n. Vasya has to knock down each can exactly once to finish the exercise. He is allowed to choose the order in which he will knock the cans down. Vasya knows that the durability of the i-th can is a_i. It means that if Vasya has already knocked x cans down and is now about to start shooting the i-th one, he will need (a_i ⋅ x + 1) shots to knock it down. You can assume that if Vasya starts shooting the i-th can, he will be shooting it until he knocks it down. Your task is to choose such an order of shooting so that the number of shots required to knock each of the n given cans down exactly once is minimum possible. Input The first line of the input contains one integer n (2 ≤ n ≤ 1 000) — the number of cans. The second line of the input contains the sequence a_1, a_2, ..., a_n (1 ≤ a_i ≤ 1 000), where a_i is the durability of the i-th can. Output In the first line print the minimum number of shots required to knock each of the n given cans down exactly once. In the second line print the sequence consisting of n distinct integers from 1 to n — the order of indices of cans that minimizes the number of shots required. If there are several answers, you can print any of them. Examples Input 3 20 10 20 Output 43 1 3 2 Input 4 10 10 10 10 Output 64 2 1 4 3 Input 6 5 4 5 4 4 5 Output 69 6 1 3 5 2 4 Input 2 1 4 Output 3 2 1 Note In the first example Vasya can start shooting from the first can. He knocks it down with the first shot because he haven't knocked any other cans down before. After that he has to shoot the third can. To knock it down he shoots 20 ⋅ 1 + 1 = 21 times. After that only second can remains. To knock it down Vasya shoots 10 ⋅ 2 + 1 = 21 times. So the total number of shots is 1 + 21 + 21 = 43. In the second example the order of shooting does not matter because all cans have the same durability. Tags: greedy, implementation, sortings Correct Solution: ``` n = int(input()) h = list(map(int, input().split())) s = 0 c = [] i = 0 while i < n: c.append(h.index(max(h))+1) s += max(h)*i+1 h[h.index(max(h))] = -100 i+=1 print(s) i = 0 while i < len(c): print(c[i], end=' ') i+=1 ```
3,429
Provide tags and a correct Python 3 solution for this coding contest problem. Recently Vasya decided to improve his pistol shooting skills. Today his coach offered him the following exercise. He placed n cans in a row on a table. Cans are numbered from left to right from 1 to n. Vasya has to knock down each can exactly once to finish the exercise. He is allowed to choose the order in which he will knock the cans down. Vasya knows that the durability of the i-th can is a_i. It means that if Vasya has already knocked x cans down and is now about to start shooting the i-th one, he will need (a_i ⋅ x + 1) shots to knock it down. You can assume that if Vasya starts shooting the i-th can, he will be shooting it until he knocks it down. Your task is to choose such an order of shooting so that the number of shots required to knock each of the n given cans down exactly once is minimum possible. Input The first line of the input contains one integer n (2 ≤ n ≤ 1 000) — the number of cans. The second line of the input contains the sequence a_1, a_2, ..., a_n (1 ≤ a_i ≤ 1 000), where a_i is the durability of the i-th can. Output In the first line print the minimum number of shots required to knock each of the n given cans down exactly once. In the second line print the sequence consisting of n distinct integers from 1 to n — the order of indices of cans that minimizes the number of shots required. If there are several answers, you can print any of them. Examples Input 3 20 10 20 Output 43 1 3 2 Input 4 10 10 10 10 Output 64 2 1 4 3 Input 6 5 4 5 4 4 5 Output 69 6 1 3 5 2 4 Input 2 1 4 Output 3 2 1 Note In the first example Vasya can start shooting from the first can. He knocks it down with the first shot because he haven't knocked any other cans down before. After that he has to shoot the third can. To knock it down he shoots 20 ⋅ 1 + 1 = 21 times. After that only second can remains. To knock it down Vasya shoots 10 ⋅ 2 + 1 = 21 times. So the total number of shots is 1 + 21 + 21 = 43. In the second example the order of shooting does not matter because all cans have the same durability. Tags: greedy, implementation, sortings Correct Solution: ``` n = int(input()) s = map(int,input().split()) s = list(s) # max(s) - это дорогая операция (O(n)), точно так же, как и s.index(a) # Хотя для этой задачи это не принципиально, все же программу можно сильно ускорить # Сейчас её сложность равна O(n^2), а мы ускорим до O(n * log(n)) # Чтобы не искать каждый раз максимум, вначале отсортируем список # Так как нам нужно сортировать не только элементы, но и их индексы, построим промежуточный список: l = [(i, a) for i, a in enumerate(s)] # Отсортируем его. При этом исходные индексы отсортируются вместе с элементами # Сортировка работает за O(n * log(n)). Это самая сложная часть программы. l = sorted(l, reverse=True, key=lambda x: x[1]) banok_sbito = 0 otvet = 0 poryadok_banok = [] # Это простой проход по циклу. Сложность - O(n) for i, a in l: otvet += a * banok_sbito + 1 banok_sbito += 1 poryadok_banok.append(i + 1) print(otvet) print(' '.join(map(str, poryadok_banok))) ```
3,430
Provide tags and a correct Python 3 solution for this coding contest problem. Recently Vasya decided to improve his pistol shooting skills. Today his coach offered him the following exercise. He placed n cans in a row on a table. Cans are numbered from left to right from 1 to n. Vasya has to knock down each can exactly once to finish the exercise. He is allowed to choose the order in which he will knock the cans down. Vasya knows that the durability of the i-th can is a_i. It means that if Vasya has already knocked x cans down and is now about to start shooting the i-th one, he will need (a_i ⋅ x + 1) shots to knock it down. You can assume that if Vasya starts shooting the i-th can, he will be shooting it until he knocks it down. Your task is to choose such an order of shooting so that the number of shots required to knock each of the n given cans down exactly once is minimum possible. Input The first line of the input contains one integer n (2 ≤ n ≤ 1 000) — the number of cans. The second line of the input contains the sequence a_1, a_2, ..., a_n (1 ≤ a_i ≤ 1 000), where a_i is the durability of the i-th can. Output In the first line print the minimum number of shots required to knock each of the n given cans down exactly once. In the second line print the sequence consisting of n distinct integers from 1 to n — the order of indices of cans that minimizes the number of shots required. If there are several answers, you can print any of them. Examples Input 3 20 10 20 Output 43 1 3 2 Input 4 10 10 10 10 Output 64 2 1 4 3 Input 6 5 4 5 4 4 5 Output 69 6 1 3 5 2 4 Input 2 1 4 Output 3 2 1 Note In the first example Vasya can start shooting from the first can. He knocks it down with the first shot because he haven't knocked any other cans down before. After that he has to shoot the third can. To knock it down he shoots 20 ⋅ 1 + 1 = 21 times. After that only second can remains. To knock it down Vasya shoots 10 ⋅ 2 + 1 = 21 times. So the total number of shots is 1 + 21 + 21 = 43. In the second example the order of shooting does not matter because all cans have the same durability. Tags: greedy, implementation, sortings Correct Solution: ``` # -*- coding: utf-8 -*- """ Created on Wed Jul 29 07:49:14 2020 @author: Harshal """ n=int(input()) arr=list(map(int,input().split())) temp=[(c,i) for i,c in enumerate(arr)] temp.sort(reverse=True) score=0 order=[] for i,can in enumerate(temp): score+=can[0]*i+1 order.append(can[1]+1) print(score) print(*order) ```
3,431
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently Vasya decided to improve his pistol shooting skills. Today his coach offered him the following exercise. He placed n cans in a row on a table. Cans are numbered from left to right from 1 to n. Vasya has to knock down each can exactly once to finish the exercise. He is allowed to choose the order in which he will knock the cans down. Vasya knows that the durability of the i-th can is a_i. It means that if Vasya has already knocked x cans down and is now about to start shooting the i-th one, he will need (a_i ⋅ x + 1) shots to knock it down. You can assume that if Vasya starts shooting the i-th can, he will be shooting it until he knocks it down. Your task is to choose such an order of shooting so that the number of shots required to knock each of the n given cans down exactly once is minimum possible. Input The first line of the input contains one integer n (2 ≤ n ≤ 1 000) — the number of cans. The second line of the input contains the sequence a_1, a_2, ..., a_n (1 ≤ a_i ≤ 1 000), where a_i is the durability of the i-th can. Output In the first line print the minimum number of shots required to knock each of the n given cans down exactly once. In the second line print the sequence consisting of n distinct integers from 1 to n — the order of indices of cans that minimizes the number of shots required. If there are several answers, you can print any of them. Examples Input 3 20 10 20 Output 43 1 3 2 Input 4 10 10 10 10 Output 64 2 1 4 3 Input 6 5 4 5 4 4 5 Output 69 6 1 3 5 2 4 Input 2 1 4 Output 3 2 1 Note In the first example Vasya can start shooting from the first can. He knocks it down with the first shot because he haven't knocked any other cans down before. After that he has to shoot the third can. To knock it down he shoots 20 ⋅ 1 + 1 = 21 times. After that only second can remains. To knock it down Vasya shoots 10 ⋅ 2 + 1 = 21 times. So the total number of shots is 1 + 21 + 21 = 43. In the second example the order of shooting does not matter because all cans have the same durability. Submitted Solution: ``` n = int(input()) nums = list(map(int, input().strip().split())) sore = sorted(nums, reverse = True) alist = [] count = 0 for shin, i in enumerate(sore): ind = nums.index(i) count += (shin*nums[ind] + 1) nums[ind] = None alist.append(str(ind+1)) print(count) print(' '.join(alist)) ``` Yes
3,432
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently Vasya decided to improve his pistol shooting skills. Today his coach offered him the following exercise. He placed n cans in a row on a table. Cans are numbered from left to right from 1 to n. Vasya has to knock down each can exactly once to finish the exercise. He is allowed to choose the order in which he will knock the cans down. Vasya knows that the durability of the i-th can is a_i. It means that if Vasya has already knocked x cans down and is now about to start shooting the i-th one, he will need (a_i ⋅ x + 1) shots to knock it down. You can assume that if Vasya starts shooting the i-th can, he will be shooting it until he knocks it down. Your task is to choose such an order of shooting so that the number of shots required to knock each of the n given cans down exactly once is minimum possible. Input The first line of the input contains one integer n (2 ≤ n ≤ 1 000) — the number of cans. The second line of the input contains the sequence a_1, a_2, ..., a_n (1 ≤ a_i ≤ 1 000), where a_i is the durability of the i-th can. Output In the first line print the minimum number of shots required to knock each of the n given cans down exactly once. In the second line print the sequence consisting of n distinct integers from 1 to n — the order of indices of cans that minimizes the number of shots required. If there are several answers, you can print any of them. Examples Input 3 20 10 20 Output 43 1 3 2 Input 4 10 10 10 10 Output 64 2 1 4 3 Input 6 5 4 5 4 4 5 Output 69 6 1 3 5 2 4 Input 2 1 4 Output 3 2 1 Note In the first example Vasya can start shooting from the first can. He knocks it down with the first shot because he haven't knocked any other cans down before. After that he has to shoot the third can. To knock it down he shoots 20 ⋅ 1 + 1 = 21 times. After that only second can remains. To knock it down Vasya shoots 10 ⋅ 2 + 1 = 21 times. So the total number of shots is 1 + 21 + 21 = 43. In the second example the order of shooting does not matter because all cans have the same durability. Submitted Solution: ``` # your code goes here n = int(input()) arr = list(map(int,input().split())) data = [] for i in range(n): data.append([arr[i],i]) shots = 0 ans = 0 data.sort(key = lambda x:x[0],reverse = True) for i in range(n): ans += (shots*data[i][0] + 1) shots += 1 print(ans) for i in data: print(i[1]+1,end = ' ') ``` Yes
3,433
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently Vasya decided to improve his pistol shooting skills. Today his coach offered him the following exercise. He placed n cans in a row on a table. Cans are numbered from left to right from 1 to n. Vasya has to knock down each can exactly once to finish the exercise. He is allowed to choose the order in which he will knock the cans down. Vasya knows that the durability of the i-th can is a_i. It means that if Vasya has already knocked x cans down and is now about to start shooting the i-th one, he will need (a_i ⋅ x + 1) shots to knock it down. You can assume that if Vasya starts shooting the i-th can, he will be shooting it until he knocks it down. Your task is to choose such an order of shooting so that the number of shots required to knock each of the n given cans down exactly once is minimum possible. Input The first line of the input contains one integer n (2 ≤ n ≤ 1 000) — the number of cans. The second line of the input contains the sequence a_1, a_2, ..., a_n (1 ≤ a_i ≤ 1 000), where a_i is the durability of the i-th can. Output In the first line print the minimum number of shots required to knock each of the n given cans down exactly once. In the second line print the sequence consisting of n distinct integers from 1 to n — the order of indices of cans that minimizes the number of shots required. If there are several answers, you can print any of them. Examples Input 3 20 10 20 Output 43 1 3 2 Input 4 10 10 10 10 Output 64 2 1 4 3 Input 6 5 4 5 4 4 5 Output 69 6 1 3 5 2 4 Input 2 1 4 Output 3 2 1 Note In the first example Vasya can start shooting from the first can. He knocks it down with the first shot because he haven't knocked any other cans down before. After that he has to shoot the third can. To knock it down he shoots 20 ⋅ 1 + 1 = 21 times. After that only second can remains. To knock it down Vasya shoots 10 ⋅ 2 + 1 = 21 times. So the total number of shots is 1 + 21 + 21 = 43. In the second example the order of shooting does not matter because all cans have the same durability. Submitted Solution: ``` L = int(input()) c = list(map(int, input().split(' '))) Nc = [] for i, v in enumerate(c): Nc.append([v, i]) def d(v): return v[0] Nc.sort(key=d, reverse=True) counter = 0 x = 0 ans = '' for i in Nc: n= i[0] counter += n*x+1 ans += str(i[1]+1) + ' ' x +=1 print(counter) print(ans[:-1]) ``` Yes
3,434
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently Vasya decided to improve his pistol shooting skills. Today his coach offered him the following exercise. He placed n cans in a row on a table. Cans are numbered from left to right from 1 to n. Vasya has to knock down each can exactly once to finish the exercise. He is allowed to choose the order in which he will knock the cans down. Vasya knows that the durability of the i-th can is a_i. It means that if Vasya has already knocked x cans down and is now about to start shooting the i-th one, he will need (a_i ⋅ x + 1) shots to knock it down. You can assume that if Vasya starts shooting the i-th can, he will be shooting it until he knocks it down. Your task is to choose such an order of shooting so that the number of shots required to knock each of the n given cans down exactly once is minimum possible. Input The first line of the input contains one integer n (2 ≤ n ≤ 1 000) — the number of cans. The second line of the input contains the sequence a_1, a_2, ..., a_n (1 ≤ a_i ≤ 1 000), where a_i is the durability of the i-th can. Output In the first line print the minimum number of shots required to knock each of the n given cans down exactly once. In the second line print the sequence consisting of n distinct integers from 1 to n — the order of indices of cans that minimizes the number of shots required. If there are several answers, you can print any of them. Examples Input 3 20 10 20 Output 43 1 3 2 Input 4 10 10 10 10 Output 64 2 1 4 3 Input 6 5 4 5 4 4 5 Output 69 6 1 3 5 2 4 Input 2 1 4 Output 3 2 1 Note In the first example Vasya can start shooting from the first can. He knocks it down with the first shot because he haven't knocked any other cans down before. After that he has to shoot the third can. To knock it down he shoots 20 ⋅ 1 + 1 = 21 times. After that only second can remains. To knock it down Vasya shoots 10 ⋅ 2 + 1 = 21 times. So the total number of shots is 1 + 21 + 21 = 43. In the second example the order of shooting does not matter because all cans have the same durability. Submitted Solution: ``` def arr_enu(): return [[i + 1, int(x)] for i, x in enumerate(input().split())] def print_arr(arr): print(*arr, sep=' ') def get_col(arr, i): return [row[i] for row in arr] n, a, out = int(input()), arr_enu(), 1 a.sort(reverse=True, key=lambda x: x[1]) for i in range(1, n): out += a[i][1] * i + 1 print(out) print_arr(get_col(a,0)) ``` Yes
3,435
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently Vasya decided to improve his pistol shooting skills. Today his coach offered him the following exercise. He placed n cans in a row on a table. Cans are numbered from left to right from 1 to n. Vasya has to knock down each can exactly once to finish the exercise. He is allowed to choose the order in which he will knock the cans down. Vasya knows that the durability of the i-th can is a_i. It means that if Vasya has already knocked x cans down and is now about to start shooting the i-th one, he will need (a_i ⋅ x + 1) shots to knock it down. You can assume that if Vasya starts shooting the i-th can, he will be shooting it until he knocks it down. Your task is to choose such an order of shooting so that the number of shots required to knock each of the n given cans down exactly once is minimum possible. Input The first line of the input contains one integer n (2 ≤ n ≤ 1 000) — the number of cans. The second line of the input contains the sequence a_1, a_2, ..., a_n (1 ≤ a_i ≤ 1 000), where a_i is the durability of the i-th can. Output In the first line print the minimum number of shots required to knock each of the n given cans down exactly once. In the second line print the sequence consisting of n distinct integers from 1 to n — the order of indices of cans that minimizes the number of shots required. If there are several answers, you can print any of them. Examples Input 3 20 10 20 Output 43 1 3 2 Input 4 10 10 10 10 Output 64 2 1 4 3 Input 6 5 4 5 4 4 5 Output 69 6 1 3 5 2 4 Input 2 1 4 Output 3 2 1 Note In the first example Vasya can start shooting from the first can. He knocks it down with the first shot because he haven't knocked any other cans down before. After that he has to shoot the third can. To knock it down he shoots 20 ⋅ 1 + 1 = 21 times. After that only second can remains. To knock it down Vasya shoots 10 ⋅ 2 + 1 = 21 times. So the total number of shots is 1 + 21 + 21 = 43. In the second example the order of shooting does not matter because all cans have the same durability. Submitted Solution: ``` n = int(input()) a = [int(x) for x in input().split()] ans = 0 k = 0 d = dict() b = [] for i in range(n): b.append(a[i]) b.sort(reverse=True) for i in range(len(b)): ans += b[i] * k + 1 k += 1 if b[i] in d: d[b[i]].append(i) else: d[b[i]] = [i] print(ans) for i in range(n): print(d[a[i]][0] + 1, end=' ') if len(d[a[i]]) > 1: d[a[i]] = d[a[i]][1:] # def minn(): # mnn = 10000000 # for i in range(len(a)): # if mnn > a[i] and a[i] != 0: # mnn = a[i] # return mnn # # # n = int(input()) # a = [int(x) for x in input().split()] # if n == 2: # print(1, max(a) - min(a)) # exit() # mn = minn() # k = mn # for i in range(n): # if a[i] % mn != 0: # k = 1 # mx = max(a) # g = 0 # for i in range(n): # g += (mx - a[i]) // k # print(g, k) ``` No
3,436
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently Vasya decided to improve his pistol shooting skills. Today his coach offered him the following exercise. He placed n cans in a row on a table. Cans are numbered from left to right from 1 to n. Vasya has to knock down each can exactly once to finish the exercise. He is allowed to choose the order in which he will knock the cans down. Vasya knows that the durability of the i-th can is a_i. It means that if Vasya has already knocked x cans down and is now about to start shooting the i-th one, he will need (a_i ⋅ x + 1) shots to knock it down. You can assume that if Vasya starts shooting the i-th can, he will be shooting it until he knocks it down. Your task is to choose such an order of shooting so that the number of shots required to knock each of the n given cans down exactly once is minimum possible. Input The first line of the input contains one integer n (2 ≤ n ≤ 1 000) — the number of cans. The second line of the input contains the sequence a_1, a_2, ..., a_n (1 ≤ a_i ≤ 1 000), where a_i is the durability of the i-th can. Output In the first line print the minimum number of shots required to knock each of the n given cans down exactly once. In the second line print the sequence consisting of n distinct integers from 1 to n — the order of indices of cans that minimizes the number of shots required. If there are several answers, you can print any of them. Examples Input 3 20 10 20 Output 43 1 3 2 Input 4 10 10 10 10 Output 64 2 1 4 3 Input 6 5 4 5 4 4 5 Output 69 6 1 3 5 2 4 Input 2 1 4 Output 3 2 1 Note In the first example Vasya can start shooting from the first can. He knocks it down with the first shot because he haven't knocked any other cans down before. After that he has to shoot the third can. To knock it down he shoots 20 ⋅ 1 + 1 = 21 times. After that only second can remains. To knock it down Vasya shoots 10 ⋅ 2 + 1 = 21 times. So the total number of shots is 1 + 21 + 21 = 43. In the second example the order of shooting does not matter because all cans have the same durability. Submitted Solution: ``` n = int(input()) l = list(map(int,input().split())) a=[] for i in range(n): a.append([l[i],i+1]) a.sort(reverse=True) l=[] for i in range(n): l.append(a[i][1]) print(*l) ``` No
3,437
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently Vasya decided to improve his pistol shooting skills. Today his coach offered him the following exercise. He placed n cans in a row on a table. Cans are numbered from left to right from 1 to n. Vasya has to knock down each can exactly once to finish the exercise. He is allowed to choose the order in which he will knock the cans down. Vasya knows that the durability of the i-th can is a_i. It means that if Vasya has already knocked x cans down and is now about to start shooting the i-th one, he will need (a_i ⋅ x + 1) shots to knock it down. You can assume that if Vasya starts shooting the i-th can, he will be shooting it until he knocks it down. Your task is to choose such an order of shooting so that the number of shots required to knock each of the n given cans down exactly once is minimum possible. Input The first line of the input contains one integer n (2 ≤ n ≤ 1 000) — the number of cans. The second line of the input contains the sequence a_1, a_2, ..., a_n (1 ≤ a_i ≤ 1 000), where a_i is the durability of the i-th can. Output In the first line print the minimum number of shots required to knock each of the n given cans down exactly once. In the second line print the sequence consisting of n distinct integers from 1 to n — the order of indices of cans that minimizes the number of shots required. If there are several answers, you can print any of them. Examples Input 3 20 10 20 Output 43 1 3 2 Input 4 10 10 10 10 Output 64 2 1 4 3 Input 6 5 4 5 4 4 5 Output 69 6 1 3 5 2 4 Input 2 1 4 Output 3 2 1 Note In the first example Vasya can start shooting from the first can. He knocks it down with the first shot because he haven't knocked any other cans down before. After that he has to shoot the third can. To knock it down he shoots 20 ⋅ 1 + 1 = 21 times. After that only second can remains. To knock it down Vasya shoots 10 ⋅ 2 + 1 = 21 times. So the total number of shots is 1 + 21 + 21 = 43. In the second example the order of shooting does not matter because all cans have the same durability. Submitted Solution: ``` # cook your dish here n = int(input()) j = 0 a = [] for i in input().split(): t = [] t.append(int(i)) t.append(j) t.append(0) a.append(t) j += 1 a = sorted(a,key =lambda x: x[0]) # print(a) x = 0 to = 0 j = 1 for i in range(n-1,-1,-1): to += a[i][0]*x + 1 x += 1 a[i][2] = j j += 1 a = sorted(a,key = lambda x:x[1]) print(to) for i in range(n): print(a[i][2]) if i==n-1 else print(a[i][2],end=" ") ``` No
3,438
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently Vasya decided to improve his pistol shooting skills. Today his coach offered him the following exercise. He placed n cans in a row on a table. Cans are numbered from left to right from 1 to n. Vasya has to knock down each can exactly once to finish the exercise. He is allowed to choose the order in which he will knock the cans down. Vasya knows that the durability of the i-th can is a_i. It means that if Vasya has already knocked x cans down and is now about to start shooting the i-th one, he will need (a_i ⋅ x + 1) shots to knock it down. You can assume that if Vasya starts shooting the i-th can, he will be shooting it until he knocks it down. Your task is to choose such an order of shooting so that the number of shots required to knock each of the n given cans down exactly once is minimum possible. Input The first line of the input contains one integer n (2 ≤ n ≤ 1 000) — the number of cans. The second line of the input contains the sequence a_1, a_2, ..., a_n (1 ≤ a_i ≤ 1 000), where a_i is the durability of the i-th can. Output In the first line print the minimum number of shots required to knock each of the n given cans down exactly once. In the second line print the sequence consisting of n distinct integers from 1 to n — the order of indices of cans that minimizes the number of shots required. If there are several answers, you can print any of them. Examples Input 3 20 10 20 Output 43 1 3 2 Input 4 10 10 10 10 Output 64 2 1 4 3 Input 6 5 4 5 4 4 5 Output 69 6 1 3 5 2 4 Input 2 1 4 Output 3 2 1 Note In the first example Vasya can start shooting from the first can. He knocks it down with the first shot because he haven't knocked any other cans down before. After that he has to shoot the third can. To knock it down he shoots 20 ⋅ 1 + 1 = 21 times. After that only second can remains. To knock it down Vasya shoots 10 ⋅ 2 + 1 = 21 times. So the total number of shots is 1 + 21 + 21 = 43. In the second example the order of shooting does not matter because all cans have the same durability. Submitted Solution: ``` n = int(input()) datas = list(map(int,input().split())) answer = [0 for i in range(n)] dic = dict() for i,data in enumerate(datas): if dic.get(data)==None: dic[data]=[i] else: dic[data].append(i) items = list(dic.items()) items.sort(key = lambda x:x[0], reverse = True) count = 0 answer_num = 0 for item in items: for i in item[1]: answer[i] = count answer_num+= count*item[0]+1 count+=1 print(answer_num) print(*answer) ``` No
3,439
Provide tags and a correct Python 3 solution for this coding contest problem. There are n seats in the train's car and there is exactly one passenger occupying every seat. The seats are numbered from 1 to n from left to right. The trip is long, so each passenger will become hungry at some moment of time and will go to take boiled water for his noodles. The person at seat i (1 ≤ i ≤ n) will decide to go for boiled water at minute t_i. Tank with a boiled water is located to the left of the 1-st seat. In case too many passengers will go for boiled water simultaneously, they will form a queue, since there can be only one passenger using the tank at each particular moment of time. Each passenger uses the tank for exactly p minutes. We assume that the time it takes passengers to go from their seat to the tank is negligibly small. Nobody likes to stand in a queue. So when the passenger occupying the i-th seat wants to go for a boiled water, he will first take a look on all seats from 1 to i - 1. In case at least one of those seats is empty, he assumes that those people are standing in a queue right now, so he would be better seating for the time being. However, at the very first moment he observes that all seats with numbers smaller than i are busy, he will go to the tank. There is an unspoken rule, that in case at some moment several people can go to the tank, than only the leftmost of them (that is, seating on the seat with smallest number) will go to the tank, while all others will wait for the next moment. Your goal is to find for each passenger, when he will receive the boiled water for his noodles. Input The first line contains integers n and p (1 ≤ n ≤ 100 000, 1 ≤ p ≤ 10^9) — the number of people and the amount of time one person uses the tank. The second line contains n integers t_1, t_2, ..., t_n (0 ≤ t_i ≤ 10^9) — the moments when the corresponding passenger will go for the boiled water. Output Print n integers, where i-th of them is the time moment the passenger on i-th seat will receive his boiled water. Example Input 5 314 0 310 942 628 0 Output 314 628 1256 942 1570 Note Consider the example. At the 0-th minute there were two passengers willing to go for a water, passenger 1 and 5, so the first passenger has gone first, and returned at the 314-th minute. At this moment the passenger 2 was already willing to go for the water, so the passenger 2 has gone next, and so on. In the end, 5-th passenger was last to receive the boiled water. Tags: data structures, greedy, implementation Correct Solution: ``` import sys reader = (s.rstrip() for s in sys.stdin) input = reader.__next__ from heapq import heappop, heappush, heapify from collections import deque class SWAG_Stack(): def __init__(self, F): self.stack1 = deque() self.stack2 = deque() self.F = F self.len = 0 def push(self, x): if self.stack2: self.stack2.append((x, self.F(self.stack2[-1][1], x))) else: self.stack2.append((x, x)) self.len += 1 def pop(self): if not self.stack1: while self.stack2: x, _ = self.stack2.pop() if self.stack1: self.stack1.appendleft((x, self.F(x, self.stack1[0][1]))) else: self.stack1.appendleft((x, x)) x, _ = self.stack1.popleft() self.len -= 1 return x def sum_all(self): if self.stack1 and self.stack2: return self.F(self.stack1[0][1], self.stack2[-1][1]) elif self.stack1: return self.stack1[0][1] elif self.stack2: return self.stack2[-1][1] else: return float("inf") n,p = map(int, input().split()) t = list((j, i) for i,j in enumerate(map(int, input().split()))) heapify(t) stack = SWAG_Stack(min) heap = [] cur = 0 ans = [-1]*n hoge = 0 # 今追加できるやつで最も小さいものを追加 # ここでなにもなかったら? # 時間を変更する # 次の時間までに追加できるものを追加 # 清算 while hoge != n: if heap and stack.sum_all() > heap[0]: j = heappop(heap) stack.push(j) if stack.len==0 and t: cur = max(cur, t[0][0]) while t and t[0][0] <= cur+p: ti, i = heappop(t) if ti == cur+p: # 後回し heappush(heap, i) else: # いま追加できるか確認 if stack.sum_all() > i: stack.push(i) else: # 後回し heappush(heap, i) if stack.len: j = stack.pop() cur += p ans[j] = cur hoge += 1 print(*ans) ```
3,440
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n seats in the train's car and there is exactly one passenger occupying every seat. The seats are numbered from 1 to n from left to right. The trip is long, so each passenger will become hungry at some moment of time and will go to take boiled water for his noodles. The person at seat i (1 ≤ i ≤ n) will decide to go for boiled water at minute t_i. Tank with a boiled water is located to the left of the 1-st seat. In case too many passengers will go for boiled water simultaneously, they will form a queue, since there can be only one passenger using the tank at each particular moment of time. Each passenger uses the tank for exactly p minutes. We assume that the time it takes passengers to go from their seat to the tank is negligibly small. Nobody likes to stand in a queue. So when the passenger occupying the i-th seat wants to go for a boiled water, he will first take a look on all seats from 1 to i - 1. In case at least one of those seats is empty, he assumes that those people are standing in a queue right now, so he would be better seating for the time being. However, at the very first moment he observes that all seats with numbers smaller than i are busy, he will go to the tank. There is an unspoken rule, that in case at some moment several people can go to the tank, than only the leftmost of them (that is, seating on the seat with smallest number) will go to the tank, while all others will wait for the next moment. Your goal is to find for each passenger, when he will receive the boiled water for his noodles. Input The first line contains integers n and p (1 ≤ n ≤ 100 000, 1 ≤ p ≤ 10^9) — the number of people and the amount of time one person uses the tank. The second line contains n integers t_1, t_2, ..., t_n (0 ≤ t_i ≤ 10^9) — the moments when the corresponding passenger will go for the boiled water. Output Print n integers, where i-th of them is the time moment the passenger on i-th seat will receive his boiled water. Example Input 5 314 0 310 942 628 0 Output 314 628 1256 942 1570 Note Consider the example. At the 0-th minute there were two passengers willing to go for a water, passenger 1 and 5, so the first passenger has gone first, and returned at the 314-th minute. At this moment the passenger 2 was already willing to go for the water, so the passenger 2 has gone next, and so on. In the end, 5-th passenger was last to receive the boiled water. Submitted Solution: ``` n, p = [int(x) for x in input().split()] t = [int(x) for x in input().split()] data = [[t[i], i] for i in range(n)] data.sort(key = lambda x: x[0]) back = 0 ready = [] answer = [0 for i in range(n)] j = 0 while j < len(data):#пока есть кто-то while j < len(data) and data[j][0] <= back: ready.append(data[j][1]) j += 1 if ready: ind = min(ready) ready.remove(ind) back += p answer[ind] = back else: if j < len(data): ind = data[j][1] answer[ind] = data[j][0] + p back = answer[ind] j += 1 if ready: ready.sort() for i in range(len(ready)): answer[ready[i]] = back + (i + 1)*p for i in range(n): print(answer[i], end = ' ') ``` No
3,441
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n seats in the train's car and there is exactly one passenger occupying every seat. The seats are numbered from 1 to n from left to right. The trip is long, so each passenger will become hungry at some moment of time and will go to take boiled water for his noodles. The person at seat i (1 ≤ i ≤ n) will decide to go for boiled water at minute t_i. Tank with a boiled water is located to the left of the 1-st seat. In case too many passengers will go for boiled water simultaneously, they will form a queue, since there can be only one passenger using the tank at each particular moment of time. Each passenger uses the tank for exactly p minutes. We assume that the time it takes passengers to go from their seat to the tank is negligibly small. Nobody likes to stand in a queue. So when the passenger occupying the i-th seat wants to go for a boiled water, he will first take a look on all seats from 1 to i - 1. In case at least one of those seats is empty, he assumes that those people are standing in a queue right now, so he would be better seating for the time being. However, at the very first moment he observes that all seats with numbers smaller than i are busy, he will go to the tank. There is an unspoken rule, that in case at some moment several people can go to the tank, than only the leftmost of them (that is, seating on the seat with smallest number) will go to the tank, while all others will wait for the next moment. Your goal is to find for each passenger, when he will receive the boiled water for his noodles. Input The first line contains integers n and p (1 ≤ n ≤ 100 000, 1 ≤ p ≤ 10^9) — the number of people and the amount of time one person uses the tank. The second line contains n integers t_1, t_2, ..., t_n (0 ≤ t_i ≤ 10^9) — the moments when the corresponding passenger will go for the boiled water. Output Print n integers, where i-th of them is the time moment the passenger on i-th seat will receive his boiled water. Example Input 5 314 0 310 942 628 0 Output 314 628 1256 942 1570 Note Consider the example. At the 0-th minute there were two passengers willing to go for a water, passenger 1 and 5, so the first passenger has gone first, and returned at the 314-th minute. At this moment the passenger 2 was already willing to go for the water, so the passenger 2 has gone next, and so on. In the end, 5-th passenger was last to receive the boiled water. Submitted Solution: ``` mod=pow(10,9)+7 dp=[1,1] for i in range(100005): dp.append((dp[-1]+dp[-2])%mod) n,m=map(int,input().split()) print(2*(dp[n]+dp[m]-1)) ``` No
3,442
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n seats in the train's car and there is exactly one passenger occupying every seat. The seats are numbered from 1 to n from left to right. The trip is long, so each passenger will become hungry at some moment of time and will go to take boiled water for his noodles. The person at seat i (1 ≤ i ≤ n) will decide to go for boiled water at minute t_i. Tank with a boiled water is located to the left of the 1-st seat. In case too many passengers will go for boiled water simultaneously, they will form a queue, since there can be only one passenger using the tank at each particular moment of time. Each passenger uses the tank for exactly p minutes. We assume that the time it takes passengers to go from their seat to the tank is negligibly small. Nobody likes to stand in a queue. So when the passenger occupying the i-th seat wants to go for a boiled water, he will first take a look on all seats from 1 to i - 1. In case at least one of those seats is empty, he assumes that those people are standing in a queue right now, so he would be better seating for the time being. However, at the very first moment he observes that all seats with numbers smaller than i are busy, he will go to the tank. There is an unspoken rule, that in case at some moment several people can go to the tank, than only the leftmost of them (that is, seating on the seat with smallest number) will go to the tank, while all others will wait for the next moment. Your goal is to find for each passenger, when he will receive the boiled water for his noodles. Input The first line contains integers n and p (1 ≤ n ≤ 100 000, 1 ≤ p ≤ 10^9) — the number of people and the amount of time one person uses the tank. The second line contains n integers t_1, t_2, ..., t_n (0 ≤ t_i ≤ 10^9) — the moments when the corresponding passenger will go for the boiled water. Output Print n integers, where i-th of them is the time moment the passenger on i-th seat will receive his boiled water. Example Input 5 314 0 310 942 628 0 Output 314 628 1256 942 1570 Note Consider the example. At the 0-th minute there were two passengers willing to go for a water, passenger 1 and 5, so the first passenger has gone first, and returned at the 314-th minute. At this moment the passenger 2 was already willing to go for the water, so the passenger 2 has gone next, and so on. In the end, 5-th passenger was last to receive the boiled water. Submitted Solution: ``` n, p = [int(x) for x in input().split()] t = [int(x) for x in input().split()] v = [False] * n p0 = 0 t0 = min(t) t0i = t.index(min(t)) v[t0i] = True times = [0] * n while not all(v): p0 += p times[t0i] = p0 v[t0i] = True for i in range(n): if t[i] <= p0 and not v[i]: t0i = i break s = "" for time in times: s += str(time) + " " print(s.strip()) ``` No
3,443
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n seats in the train's car and there is exactly one passenger occupying every seat. The seats are numbered from 1 to n from left to right. The trip is long, so each passenger will become hungry at some moment of time and will go to take boiled water for his noodles. The person at seat i (1 ≤ i ≤ n) will decide to go for boiled water at minute t_i. Tank with a boiled water is located to the left of the 1-st seat. In case too many passengers will go for boiled water simultaneously, they will form a queue, since there can be only one passenger using the tank at each particular moment of time. Each passenger uses the tank for exactly p minutes. We assume that the time it takes passengers to go from their seat to the tank is negligibly small. Nobody likes to stand in a queue. So when the passenger occupying the i-th seat wants to go for a boiled water, he will first take a look on all seats from 1 to i - 1. In case at least one of those seats is empty, he assumes that those people are standing in a queue right now, so he would be better seating for the time being. However, at the very first moment he observes that all seats with numbers smaller than i are busy, he will go to the tank. There is an unspoken rule, that in case at some moment several people can go to the tank, than only the leftmost of them (that is, seating on the seat with smallest number) will go to the tank, while all others will wait for the next moment. Your goal is to find for each passenger, when he will receive the boiled water for his noodles. Input The first line contains integers n and p (1 ≤ n ≤ 100 000, 1 ≤ p ≤ 10^9) — the number of people and the amount of time one person uses the tank. The second line contains n integers t_1, t_2, ..., t_n (0 ≤ t_i ≤ 10^9) — the moments when the corresponding passenger will go for the boiled water. Output Print n integers, where i-th of them is the time moment the passenger on i-th seat will receive his boiled water. Example Input 5 314 0 310 942 628 0 Output 314 628 1256 942 1570 Note Consider the example. At the 0-th minute there were two passengers willing to go for a water, passenger 1 and 5, so the first passenger has gone first, and returned at the 314-th minute. At this moment the passenger 2 was already willing to go for the water, so the passenger 2 has gone next, and so on. In the end, 5-th passenger was last to receive the boiled water. Submitted Solution: ``` import heapq '''f = open('input.txt', 'r') n, p = map(int, f.readline().split()) l = list(map(int, f.readline().split())) f.close()''' n, p = map(int,input().split()) l = list(map(int,input().split())) out_time = 0 sol = [] for i in range(n): sol.append(0) for i in range(n): l[i] = (l[i],i) l.sort() order = [] heapq.heapify(order) while len(l): if out_time < l[0][0] and not len(order): out_time = l[0][0] + p sol[l[0][1]] = out_time l.pop(0) elif out_time < l[0][0] and len(order): idx = heapq.heappop(order) out_time += p sol[idx] = out_time elif out_time >= l[0][0]: while len(l) and l[0][0] <= out_time: heapq.heappush(order, l[0][1]) l.pop(0) idx = heapq.heappop(order) out_time += p sol[idx] = out_time while(len(order)): idx = heapq.heappop(order) out_time += p sol[idx] = out_time print(*sol) ``` No
3,444
Provide tags and a correct Python 3 solution for this coding contest problem. A team of three programmers is going to play a contest. The contest consists of n problems, numbered from 1 to n. Each problem is printed on a separate sheet of paper. The participants have decided to divide the problem statements into three parts: the first programmer took some prefix of the statements (some number of first paper sheets), the third contestant took some suffix of the statements (some number of last paper sheets), and the second contestant took all remaining problems. But something went wrong — the statements were printed in the wrong order, so the contestants have received the problems in some random order. The first contestant has received problems a_{1, 1}, a_{1, 2}, ..., a_{1, k_1}. The second one has received problems a_{2, 1}, a_{2, 2}, ..., a_{2, k_2}. The third one has received all remaining problems (a_{3, 1}, a_{3, 2}, ..., a_{3, k_3}). The contestants don't want to play the contest before they redistribute the statements. They want to redistribute them so that the first contestant receives some prefix of the problemset, the third contestant receives some suffix of the problemset, and the second contestant receives all the remaining problems. During one move, some contestant may give one of their problems to other contestant. What is the minimum number of moves required to redistribute the problems? It is possible that after redistribution some participant (or even two of them) will not have any problems. Input The first line contains three integers k_1, k_2 and k_3 (1 ≤ k_1, k_2, k_3 ≤ 2 ⋅ 10^5, k_1 + k_2 + k_3 ≤ 2 ⋅ 10^5) — the number of problems initially taken by the first, the second and the third participant, respectively. The second line contains k_1 integers a_{1, 1}, a_{1, 2}, ..., a_{1, k_1} — the problems initially taken by the first participant. The third line contains k_2 integers a_{2, 1}, a_{2, 2}, ..., a_{2, k_2} — the problems initially taken by the second participant. The fourth line contains k_3 integers a_{3, 1}, a_{3, 2}, ..., a_{3, k_3} — the problems initially taken by the third participant. It is guaranteed that no problem has been taken by two (or three) participants, and each integer a_{i, j} meets the condition 1 ≤ a_{i, j} ≤ n, where n = k_1 + k_2 + k_3. Output Print one integer — the minimum number of moves required to redistribute the problems so that the first participant gets the prefix of the problemset, the third participant gets the suffix of the problemset, and the second participant gets all of the remaining problems. Examples Input 2 1 2 3 1 4 2 5 Output 1 Input 3 2 1 3 2 1 5 4 6 Output 0 Input 2 1 3 5 6 4 1 2 3 Output 3 Input 1 5 1 6 5 1 2 4 7 3 Output 2 Note In the first example the third contestant should give the problem 2 to the first contestant, so the first contestant has 3 first problems, the third contestant has 1 last problem, and the second contestant has 1 remaining problem. In the second example the distribution of problems is already valid: the first contestant has 3 first problems, the third contestant has 1 last problem, and the second contestant has 2 remaining problems. The best course of action in the third example is to give all problems to the third contestant. The best course of action in the fourth example is to give all problems to the second contestant. Tags: data structures, dp, greedy Correct Solution: ``` x,y,z=map(int,input().split()) d=[[],[],[]] d[0]=list(map(int,input().split())) d[1]=list(map(int,input().split())) d[2]=list(map(int,input().split())) dicto=[dict(),dict(),dict()] dp=[[float("inf")]*(x+y+z+1) for i in range(3)] for i in range(3): for j in d[i]: dicto[i][j]=1 dp[0][0]=0 mini=9999999999999 for i in range(1,x+y+z+1): mini=999999999999 for j in range(3): for k in range(j+1): mini=min(mini,dp[k][i-1]) if i not in dicto[j]: dp[j][i]=mini+1 else: dp[j][i]=mini for i in range(3): mini=min(dp[0][x+y+z],dp[1][x+y+z],dp[2][x+y+z]) print(mini) ```
3,445
Provide tags and a correct Python 3 solution for this coding contest problem. A team of three programmers is going to play a contest. The contest consists of n problems, numbered from 1 to n. Each problem is printed on a separate sheet of paper. The participants have decided to divide the problem statements into three parts: the first programmer took some prefix of the statements (some number of first paper sheets), the third contestant took some suffix of the statements (some number of last paper sheets), and the second contestant took all remaining problems. But something went wrong — the statements were printed in the wrong order, so the contestants have received the problems in some random order. The first contestant has received problems a_{1, 1}, a_{1, 2}, ..., a_{1, k_1}. The second one has received problems a_{2, 1}, a_{2, 2}, ..., a_{2, k_2}. The third one has received all remaining problems (a_{3, 1}, a_{3, 2}, ..., a_{3, k_3}). The contestants don't want to play the contest before they redistribute the statements. They want to redistribute them so that the first contestant receives some prefix of the problemset, the third contestant receives some suffix of the problemset, and the second contestant receives all the remaining problems. During one move, some contestant may give one of their problems to other contestant. What is the minimum number of moves required to redistribute the problems? It is possible that after redistribution some participant (or even two of them) will not have any problems. Input The first line contains three integers k_1, k_2 and k_3 (1 ≤ k_1, k_2, k_3 ≤ 2 ⋅ 10^5, k_1 + k_2 + k_3 ≤ 2 ⋅ 10^5) — the number of problems initially taken by the first, the second and the third participant, respectively. The second line contains k_1 integers a_{1, 1}, a_{1, 2}, ..., a_{1, k_1} — the problems initially taken by the first participant. The third line contains k_2 integers a_{2, 1}, a_{2, 2}, ..., a_{2, k_2} — the problems initially taken by the second participant. The fourth line contains k_3 integers a_{3, 1}, a_{3, 2}, ..., a_{3, k_3} — the problems initially taken by the third participant. It is guaranteed that no problem has been taken by two (or three) participants, and each integer a_{i, j} meets the condition 1 ≤ a_{i, j} ≤ n, where n = k_1 + k_2 + k_3. Output Print one integer — the minimum number of moves required to redistribute the problems so that the first participant gets the prefix of the problemset, the third participant gets the suffix of the problemset, and the second participant gets all of the remaining problems. Examples Input 2 1 2 3 1 4 2 5 Output 1 Input 3 2 1 3 2 1 5 4 6 Output 0 Input 2 1 3 5 6 4 1 2 3 Output 3 Input 1 5 1 6 5 1 2 4 7 3 Output 2 Note In the first example the third contestant should give the problem 2 to the first contestant, so the first contestant has 3 first problems, the third contestant has 1 last problem, and the second contestant has 1 remaining problem. In the second example the distribution of problems is already valid: the first contestant has 3 first problems, the third contestant has 1 last problem, and the second contestant has 2 remaining problems. The best course of action in the third example is to give all problems to the third contestant. The best course of action in the fourth example is to give all problems to the second contestant. Tags: data structures, dp, greedy Correct Solution: ``` def main(): n1,n2,n3=readIntArr() n=n1+n2+n3 a=readIntArr() b=readIntArr() c=readIntArr() origPos=[-1 for _ in range(n+1)] for x in a: origPos[x]=1 for x in b: origPos[x]=2 for x in c: origPos[x]=3 dp=makeArr(inf,[n+1,4]) # dp[idx][number of participants]=min moves dp[0][1]=0 dp[0][2]=0 dp[0][3]=0 for i in range(1,n+1): for j in range(1,4): # put i in previous participant dp[i][j]=min(dp[i][j],dp[i][j-1]) # put i in current participant if origPos[i]!=j: extraMove=1 else: extraMove=0 dp[i][j]=min(dp[i][j],dp[i-1][j]+extraMove) ans=dp[n][3] print(ans) return import sys # input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok) input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS. def oneLineArrayPrint(arr): print(' '.join([str(x) for x in arr])) def multiLineArrayPrint(arr): print('\n'.join([str(x) for x in arr])) def multiLineArrayOfArraysPrint(arr): print('\n'.join([' '.join([str(x) for x in y]) for y in arr])) def readIntArr(): return [int(x) for x in input().split()] # def readFloatArr(): # return [float(x) for x in input().split()] def makeArr(defaultVal,dimensionArr): # eg. makeArr(0,[n,m]) dv=defaultVal;da=dimensionArr if len(da)==1:return [dv for _ in range(da[0])] else:return [makeArr(dv,da[1:]) for _ in range(da[0])] def queryInteractive(x,y): print('? {} {}'.format(x,y)) sys.stdout.flush() return int(input()) def answerInteractive(ans): print('! {}'.format(ans)) sys.stdout.flush() inf=float('inf') MOD=10**9+7 for _abc in range(1): main() ```
3,446
Provide tags and a correct Python 3 solution for this coding contest problem. A team of three programmers is going to play a contest. The contest consists of n problems, numbered from 1 to n. Each problem is printed on a separate sheet of paper. The participants have decided to divide the problem statements into three parts: the first programmer took some prefix of the statements (some number of first paper sheets), the third contestant took some suffix of the statements (some number of last paper sheets), and the second contestant took all remaining problems. But something went wrong — the statements were printed in the wrong order, so the contestants have received the problems in some random order. The first contestant has received problems a_{1, 1}, a_{1, 2}, ..., a_{1, k_1}. The second one has received problems a_{2, 1}, a_{2, 2}, ..., a_{2, k_2}. The third one has received all remaining problems (a_{3, 1}, a_{3, 2}, ..., a_{3, k_3}). The contestants don't want to play the contest before they redistribute the statements. They want to redistribute them so that the first contestant receives some prefix of the problemset, the third contestant receives some suffix of the problemset, and the second contestant receives all the remaining problems. During one move, some contestant may give one of their problems to other contestant. What is the minimum number of moves required to redistribute the problems? It is possible that after redistribution some participant (or even two of them) will not have any problems. Input The first line contains three integers k_1, k_2 and k_3 (1 ≤ k_1, k_2, k_3 ≤ 2 ⋅ 10^5, k_1 + k_2 + k_3 ≤ 2 ⋅ 10^5) — the number of problems initially taken by the first, the second and the third participant, respectively. The second line contains k_1 integers a_{1, 1}, a_{1, 2}, ..., a_{1, k_1} — the problems initially taken by the first participant. The third line contains k_2 integers a_{2, 1}, a_{2, 2}, ..., a_{2, k_2} — the problems initially taken by the second participant. The fourth line contains k_3 integers a_{3, 1}, a_{3, 2}, ..., a_{3, k_3} — the problems initially taken by the third participant. It is guaranteed that no problem has been taken by two (or three) participants, and each integer a_{i, j} meets the condition 1 ≤ a_{i, j} ≤ n, where n = k_1 + k_2 + k_3. Output Print one integer — the minimum number of moves required to redistribute the problems so that the first participant gets the prefix of the problemset, the third participant gets the suffix of the problemset, and the second participant gets all of the remaining problems. Examples Input 2 1 2 3 1 4 2 5 Output 1 Input 3 2 1 3 2 1 5 4 6 Output 0 Input 2 1 3 5 6 4 1 2 3 Output 3 Input 1 5 1 6 5 1 2 4 7 3 Output 2 Note In the first example the third contestant should give the problem 2 to the first contestant, so the first contestant has 3 first problems, the third contestant has 1 last problem, and the second contestant has 1 remaining problem. In the second example the distribution of problems is already valid: the first contestant has 3 first problems, the third contestant has 1 last problem, and the second contestant has 2 remaining problems. The best course of action in the third example is to give all problems to the third contestant. The best course of action in the fourth example is to give all problems to the second contestant. Tags: data structures, dp, greedy Correct Solution: ``` #!/usr/bin/env python3 import sys import bisect sys.setrecursionlimit(10**8) input = sys.stdin.readline INF = 10**9 anum, bnum, cnum = [int(item) for item in input().split()] k = anum + bnum + cnum a = [int(item) for item in input().split()] b = [int(item) for item in input().split()] c = [int(item) for item in input().split()] holder = [0] * k for item in a: holder[item-1] = 0 for item in b: holder[item-1] = 1 for item in c: holder[item-1] = 2 # seen ith, state(a hold, b hold, c hold) dp = [[INF] * (k + 1) for _ in range(3)] dp[0][0] = 0 dp[1][0] = 0 dp[2][0] = 0 for i in range(k): if holder[i] == 0: dp[0][i+1] = min(dp[0][i+1], dp[0][i]) dp[1][i+1] = min(dp[1][i+1], dp[1][i] + 1) dp[2][i+1] = min(dp[2][i+1], dp[2][i] + 1) dp[1][i+1] = min(dp[1][i+1], dp[0][i] + 1) dp[2][i+1] = min(dp[2][i+1], dp[1][i] + 1) dp[2][i+1] = min(dp[2][i+1], dp[0][i] + 1) elif holder[i] == 1: dp[0][i+1] = min(dp[0][i+1], dp[0][i] + 1) dp[1][i+1] = min(dp[1][i+1], dp[1][i]) dp[2][i+1] = min(dp[2][i+1], dp[2][i] + 1) dp[1][i+1] = min(dp[1][i+1], dp[0][i]) dp[2][i+1] = min(dp[2][i+1], dp[1][i] + 1) dp[2][i+1] = min(dp[2][i+1], dp[0][i] + 1) elif holder[i] == 2: dp[0][i+1] = min(dp[0][i+1], dp[0][i] + 1) dp[1][i+1] = min(dp[1][i+1], dp[1][i] + 1) dp[2][i+1] = min(dp[2][i+1], dp[2][i]) dp[1][i+1] = min(dp[1][i+1], dp[0][i] + 1) dp[2][i+1] = min(dp[2][i+1], dp[1][i]) dp[2][i+1] = min(dp[2][i+1], dp[0][i]) ans = INF for line in dp: ans = min(ans, line[-1]) print(ans) ```
3,447
Provide tags and a correct Python 3 solution for this coding contest problem. A team of three programmers is going to play a contest. The contest consists of n problems, numbered from 1 to n. Each problem is printed on a separate sheet of paper. The participants have decided to divide the problem statements into three parts: the first programmer took some prefix of the statements (some number of first paper sheets), the third contestant took some suffix of the statements (some number of last paper sheets), and the second contestant took all remaining problems. But something went wrong — the statements were printed in the wrong order, so the contestants have received the problems in some random order. The first contestant has received problems a_{1, 1}, a_{1, 2}, ..., a_{1, k_1}. The second one has received problems a_{2, 1}, a_{2, 2}, ..., a_{2, k_2}. The third one has received all remaining problems (a_{3, 1}, a_{3, 2}, ..., a_{3, k_3}). The contestants don't want to play the contest before they redistribute the statements. They want to redistribute them so that the first contestant receives some prefix of the problemset, the third contestant receives some suffix of the problemset, and the second contestant receives all the remaining problems. During one move, some contestant may give one of their problems to other contestant. What is the minimum number of moves required to redistribute the problems? It is possible that after redistribution some participant (or even two of them) will not have any problems. Input The first line contains three integers k_1, k_2 and k_3 (1 ≤ k_1, k_2, k_3 ≤ 2 ⋅ 10^5, k_1 + k_2 + k_3 ≤ 2 ⋅ 10^5) — the number of problems initially taken by the first, the second and the third participant, respectively. The second line contains k_1 integers a_{1, 1}, a_{1, 2}, ..., a_{1, k_1} — the problems initially taken by the first participant. The third line contains k_2 integers a_{2, 1}, a_{2, 2}, ..., a_{2, k_2} — the problems initially taken by the second participant. The fourth line contains k_3 integers a_{3, 1}, a_{3, 2}, ..., a_{3, k_3} — the problems initially taken by the third participant. It is guaranteed that no problem has been taken by two (or three) participants, and each integer a_{i, j} meets the condition 1 ≤ a_{i, j} ≤ n, where n = k_1 + k_2 + k_3. Output Print one integer — the minimum number of moves required to redistribute the problems so that the first participant gets the prefix of the problemset, the third participant gets the suffix of the problemset, and the second participant gets all of the remaining problems. Examples Input 2 1 2 3 1 4 2 5 Output 1 Input 3 2 1 3 2 1 5 4 6 Output 0 Input 2 1 3 5 6 4 1 2 3 Output 3 Input 1 5 1 6 5 1 2 4 7 3 Output 2 Note In the first example the third contestant should give the problem 2 to the first contestant, so the first contestant has 3 first problems, the third contestant has 1 last problem, and the second contestant has 1 remaining problem. In the second example the distribution of problems is already valid: the first contestant has 3 first problems, the third contestant has 1 last problem, and the second contestant has 2 remaining problems. The best course of action in the third example is to give all problems to the third contestant. The best course of action in the fourth example is to give all problems to the second contestant. Tags: data structures, dp, greedy Correct Solution: ``` import sys k1, k2, k3 = [int(i) for i in sys.stdin.readline().split()] k = [[], [], [], []] for j in range(1, 4): k[j] = [int(i) for i in sys.stdin.readline().split()] n = k1 + k2 + k3 k_4 = [] for f in [2, 3]: k_4.extend((jlk, f) for jlk in k[f]) k_4.sort(reverse=True) ndd = [0] * (k2 + k3 + 1) for j in range(1, k2 + k3 + 1): if k_4[j-1][1] == 3: ndd[j] = ndd[j-1] else: ndd[j] = ndd[j-1] + 1 fj = [] for j in range(k2+k3+1): fj.append(k3 - j + 2 * ndd[j]) # min of fj up to value i mnfj_i = [] mn = fj[0] for i in range(k2+k3+1): mn = min(mn, fj[i]) mnfj_i.append(mn) k3s = set(k[3]) cnt_lea3 = [0] * (n+1) for i in range(1, n+1): if i in k3s: cnt_lea3[i] = cnt_lea3[i-1] + 1 else: cnt_lea3[i] = cnt_lea3[i-1] k2s = set(k[2]) cnt_lea2 = [0] * (n+1) for i in range(1, n+1): if i in k2s: cnt_lea2[i] = cnt_lea2[i-1] + 1 else: cnt_lea2[i] = cnt_lea2[i-1] k1s = set(k[1]) cnt_lea1 = [0] * (n+1) for i in range(1, n+1): if i in k1s: cnt_lea1[i] = cnt_lea1[i-1] + 1 else: cnt_lea1[i] = cnt_lea1[i-1] # print(cnt_lea1) # print('fj', fj) # print('mnfj_i', mnfj_i) # print('ndd', ndd) ans = 5 * (k1 + k2 + k3) for alpha in range(n+1): ub = k2 + k3 - cnt_lea3[alpha] - cnt_lea2[alpha] # print(alpha, ub) ans = min(ans, mnfj_i[ub] - cnt_lea3[alpha] + k1 + alpha - 2 * cnt_lea1[alpha]) # print(alpha, ans, ':', k1 + alpha - 2 * cnt_lea1[alpha], mnfj_i[ub] - cnt_lea3[alpha] ) print(ans) ```
3,448
Provide tags and a correct Python 3 solution for this coding contest problem. A team of three programmers is going to play a contest. The contest consists of n problems, numbered from 1 to n. Each problem is printed on a separate sheet of paper. The participants have decided to divide the problem statements into three parts: the first programmer took some prefix of the statements (some number of first paper sheets), the third contestant took some suffix of the statements (some number of last paper sheets), and the second contestant took all remaining problems. But something went wrong — the statements were printed in the wrong order, so the contestants have received the problems in some random order. The first contestant has received problems a_{1, 1}, a_{1, 2}, ..., a_{1, k_1}. The second one has received problems a_{2, 1}, a_{2, 2}, ..., a_{2, k_2}. The third one has received all remaining problems (a_{3, 1}, a_{3, 2}, ..., a_{3, k_3}). The contestants don't want to play the contest before they redistribute the statements. They want to redistribute them so that the first contestant receives some prefix of the problemset, the third contestant receives some suffix of the problemset, and the second contestant receives all the remaining problems. During one move, some contestant may give one of their problems to other contestant. What is the minimum number of moves required to redistribute the problems? It is possible that after redistribution some participant (or even two of them) will not have any problems. Input The first line contains three integers k_1, k_2 and k_3 (1 ≤ k_1, k_2, k_3 ≤ 2 ⋅ 10^5, k_1 + k_2 + k_3 ≤ 2 ⋅ 10^5) — the number of problems initially taken by the first, the second and the third participant, respectively. The second line contains k_1 integers a_{1, 1}, a_{1, 2}, ..., a_{1, k_1} — the problems initially taken by the first participant. The third line contains k_2 integers a_{2, 1}, a_{2, 2}, ..., a_{2, k_2} — the problems initially taken by the second participant. The fourth line contains k_3 integers a_{3, 1}, a_{3, 2}, ..., a_{3, k_3} — the problems initially taken by the third participant. It is guaranteed that no problem has been taken by two (or three) participants, and each integer a_{i, j} meets the condition 1 ≤ a_{i, j} ≤ n, where n = k_1 + k_2 + k_3. Output Print one integer — the minimum number of moves required to redistribute the problems so that the first participant gets the prefix of the problemset, the third participant gets the suffix of the problemset, and the second participant gets all of the remaining problems. Examples Input 2 1 2 3 1 4 2 5 Output 1 Input 3 2 1 3 2 1 5 4 6 Output 0 Input 2 1 3 5 6 4 1 2 3 Output 3 Input 1 5 1 6 5 1 2 4 7 3 Output 2 Note In the first example the third contestant should give the problem 2 to the first contestant, so the first contestant has 3 first problems, the third contestant has 1 last problem, and the second contestant has 1 remaining problem. In the second example the distribution of problems is already valid: the first contestant has 3 first problems, the third contestant has 1 last problem, and the second contestant has 2 remaining problems. The best course of action in the third example is to give all problems to the third contestant. The best course of action in the fourth example is to give all problems to the second contestant. Tags: data structures, dp, greedy Correct Solution: ``` import sys input = sys.stdin.readline k1,k2,k3=map(int,input().split()) A1=list(map(int,input().split())) A2=list(map(int,input().split())) A3=list(map(int,input().split())) A=sorted(A1)+sorted(A2)+sorted(A3) import bisect N=k1+k2+k3 DP=[float("inf")]*N for a in A: pos=bisect.bisect_left(DP,a) DP[pos]=a ANS=0 for i in range(N): if DP[i]!=float("inf"): ANS=i print(N-(ANS+1)) ```
3,449
Provide tags and a correct Python 3 solution for this coding contest problem. A team of three programmers is going to play a contest. The contest consists of n problems, numbered from 1 to n. Each problem is printed on a separate sheet of paper. The participants have decided to divide the problem statements into three parts: the first programmer took some prefix of the statements (some number of first paper sheets), the third contestant took some suffix of the statements (some number of last paper sheets), and the second contestant took all remaining problems. But something went wrong — the statements were printed in the wrong order, so the contestants have received the problems in some random order. The first contestant has received problems a_{1, 1}, a_{1, 2}, ..., a_{1, k_1}. The second one has received problems a_{2, 1}, a_{2, 2}, ..., a_{2, k_2}. The third one has received all remaining problems (a_{3, 1}, a_{3, 2}, ..., a_{3, k_3}). The contestants don't want to play the contest before they redistribute the statements. They want to redistribute them so that the first contestant receives some prefix of the problemset, the third contestant receives some suffix of the problemset, and the second contestant receives all the remaining problems. During one move, some contestant may give one of their problems to other contestant. What is the minimum number of moves required to redistribute the problems? It is possible that after redistribution some participant (or even two of them) will not have any problems. Input The first line contains three integers k_1, k_2 and k_3 (1 ≤ k_1, k_2, k_3 ≤ 2 ⋅ 10^5, k_1 + k_2 + k_3 ≤ 2 ⋅ 10^5) — the number of problems initially taken by the first, the second and the third participant, respectively. The second line contains k_1 integers a_{1, 1}, a_{1, 2}, ..., a_{1, k_1} — the problems initially taken by the first participant. The third line contains k_2 integers a_{2, 1}, a_{2, 2}, ..., a_{2, k_2} — the problems initially taken by the second participant. The fourth line contains k_3 integers a_{3, 1}, a_{3, 2}, ..., a_{3, k_3} — the problems initially taken by the third participant. It is guaranteed that no problem has been taken by two (or three) participants, and each integer a_{i, j} meets the condition 1 ≤ a_{i, j} ≤ n, where n = k_1 + k_2 + k_3. Output Print one integer — the minimum number of moves required to redistribute the problems so that the first participant gets the prefix of the problemset, the third participant gets the suffix of the problemset, and the second participant gets all of the remaining problems. Examples Input 2 1 2 3 1 4 2 5 Output 1 Input 3 2 1 3 2 1 5 4 6 Output 0 Input 2 1 3 5 6 4 1 2 3 Output 3 Input 1 5 1 6 5 1 2 4 7 3 Output 2 Note In the first example the third contestant should give the problem 2 to the first contestant, so the first contestant has 3 first problems, the third contestant has 1 last problem, and the second contestant has 1 remaining problem. In the second example the distribution of problems is already valid: the first contestant has 3 first problems, the third contestant has 1 last problem, and the second contestant has 2 remaining problems. The best course of action in the third example is to give all problems to the third contestant. The best course of action in the fourth example is to give all problems to the second contestant. Tags: data structures, dp, greedy Correct Solution: ``` import sys input = sys.stdin.readline K1, K2, K3 = map(int, input().split()) N = K1+K2+K3 A1 = list(map(int, input().split())) A2 = list(map(int, input().split())) A3 = list(map(int, input().split())) A = [0] * N for i, A_ in enumerate([A1, A2, A3], 1): for a in A_: A[a-1] = i a_12to3 = K1+K2 ans = a_12to3 a_2to1 = 0 cnt_1 = 0 cnt_2 = 0 idx_12 = 0 for a in A: if a==3: a_12to3 += 1 else: a_12to3 -= 1 if a==1: cnt_1 += 1 if cnt_1 >= cnt_2: a_2to1 += cnt_2 cnt_1 = cnt_2 = 0 else: cnt_2 += 1 an = a_12to3 + a_2to1 + cnt_1 ans = min(ans, an) print(ans) ```
3,450
Provide tags and a correct Python 3 solution for this coding contest problem. A team of three programmers is going to play a contest. The contest consists of n problems, numbered from 1 to n. Each problem is printed on a separate sheet of paper. The participants have decided to divide the problem statements into three parts: the first programmer took some prefix of the statements (some number of first paper sheets), the third contestant took some suffix of the statements (some number of last paper sheets), and the second contestant took all remaining problems. But something went wrong — the statements were printed in the wrong order, so the contestants have received the problems in some random order. The first contestant has received problems a_{1, 1}, a_{1, 2}, ..., a_{1, k_1}. The second one has received problems a_{2, 1}, a_{2, 2}, ..., a_{2, k_2}. The third one has received all remaining problems (a_{3, 1}, a_{3, 2}, ..., a_{3, k_3}). The contestants don't want to play the contest before they redistribute the statements. They want to redistribute them so that the first contestant receives some prefix of the problemset, the third contestant receives some suffix of the problemset, and the second contestant receives all the remaining problems. During one move, some contestant may give one of their problems to other contestant. What is the minimum number of moves required to redistribute the problems? It is possible that after redistribution some participant (or even two of them) will not have any problems. Input The first line contains three integers k_1, k_2 and k_3 (1 ≤ k_1, k_2, k_3 ≤ 2 ⋅ 10^5, k_1 + k_2 + k_3 ≤ 2 ⋅ 10^5) — the number of problems initially taken by the first, the second and the third participant, respectively. The second line contains k_1 integers a_{1, 1}, a_{1, 2}, ..., a_{1, k_1} — the problems initially taken by the first participant. The third line contains k_2 integers a_{2, 1}, a_{2, 2}, ..., a_{2, k_2} — the problems initially taken by the second participant. The fourth line contains k_3 integers a_{3, 1}, a_{3, 2}, ..., a_{3, k_3} — the problems initially taken by the third participant. It is guaranteed that no problem has been taken by two (or three) participants, and each integer a_{i, j} meets the condition 1 ≤ a_{i, j} ≤ n, where n = k_1 + k_2 + k_3. Output Print one integer — the minimum number of moves required to redistribute the problems so that the first participant gets the prefix of the problemset, the third participant gets the suffix of the problemset, and the second participant gets all of the remaining problems. Examples Input 2 1 2 3 1 4 2 5 Output 1 Input 3 2 1 3 2 1 5 4 6 Output 0 Input 2 1 3 5 6 4 1 2 3 Output 3 Input 1 5 1 6 5 1 2 4 7 3 Output 2 Note In the first example the third contestant should give the problem 2 to the first contestant, so the first contestant has 3 first problems, the third contestant has 1 last problem, and the second contestant has 1 remaining problem. In the second example the distribution of problems is already valid: the first contestant has 3 first problems, the third contestant has 1 last problem, and the second contestant has 2 remaining problems. The best course of action in the third example is to give all problems to the third contestant. The best course of action in the fourth example is to give all problems to the second contestant. Tags: data structures, dp, greedy Correct Solution: ``` from sys import stdin,stdout inf=1000000000000007 def solve(): a1,b1,c1=[int(i) for i in stdin.readline().split()] k=a1+b1+c1; a=[0 for i in range(k+1)] for i in stdin.readline().split(): a[int(i)]=0 for i in stdin.readline().split(): a[int(i)]=1 for i in stdin.readline().split(): a[int(i)]=2 dp=[[inf for i in range(k+1)] for j in range(3)] dp[0][0],dp[1][0],dp[2][0]=0,0,0 for i in range(1,k+1): for j in range(3): if(a[i]==j): for l in range(0,j+1): dp[j][i]=min(dp[j][i],dp[l][i-1]) else: for l in range(0,j+1): dp[j][i]=min(dp[j][i],dp[l][i-1]+1) print(min(dp[0][k],dp[1][k],dp[2][k])) solve() ```
3,451
Provide tags and a correct Python 3 solution for this coding contest problem. A team of three programmers is going to play a contest. The contest consists of n problems, numbered from 1 to n. Each problem is printed on a separate sheet of paper. The participants have decided to divide the problem statements into three parts: the first programmer took some prefix of the statements (some number of first paper sheets), the third contestant took some suffix of the statements (some number of last paper sheets), and the second contestant took all remaining problems. But something went wrong — the statements were printed in the wrong order, so the contestants have received the problems in some random order. The first contestant has received problems a_{1, 1}, a_{1, 2}, ..., a_{1, k_1}. The second one has received problems a_{2, 1}, a_{2, 2}, ..., a_{2, k_2}. The third one has received all remaining problems (a_{3, 1}, a_{3, 2}, ..., a_{3, k_3}). The contestants don't want to play the contest before they redistribute the statements. They want to redistribute them so that the first contestant receives some prefix of the problemset, the third contestant receives some suffix of the problemset, and the second contestant receives all the remaining problems. During one move, some contestant may give one of their problems to other contestant. What is the minimum number of moves required to redistribute the problems? It is possible that after redistribution some participant (or even two of them) will not have any problems. Input The first line contains three integers k_1, k_2 and k_3 (1 ≤ k_1, k_2, k_3 ≤ 2 ⋅ 10^5, k_1 + k_2 + k_3 ≤ 2 ⋅ 10^5) — the number of problems initially taken by the first, the second and the third participant, respectively. The second line contains k_1 integers a_{1, 1}, a_{1, 2}, ..., a_{1, k_1} — the problems initially taken by the first participant. The third line contains k_2 integers a_{2, 1}, a_{2, 2}, ..., a_{2, k_2} — the problems initially taken by the second participant. The fourth line contains k_3 integers a_{3, 1}, a_{3, 2}, ..., a_{3, k_3} — the problems initially taken by the third participant. It is guaranteed that no problem has been taken by two (or three) participants, and each integer a_{i, j} meets the condition 1 ≤ a_{i, j} ≤ n, where n = k_1 + k_2 + k_3. Output Print one integer — the minimum number of moves required to redistribute the problems so that the first participant gets the prefix of the problemset, the third participant gets the suffix of the problemset, and the second participant gets all of the remaining problems. Examples Input 2 1 2 3 1 4 2 5 Output 1 Input 3 2 1 3 2 1 5 4 6 Output 0 Input 2 1 3 5 6 4 1 2 3 Output 3 Input 1 5 1 6 5 1 2 4 7 3 Output 2 Note In the first example the third contestant should give the problem 2 to the first contestant, so the first contestant has 3 first problems, the third contestant has 1 last problem, and the second contestant has 1 remaining problem. In the second example the distribution of problems is already valid: the first contestant has 3 first problems, the third contestant has 1 last problem, and the second contestant has 2 remaining problems. The best course of action in the third example is to give all problems to the third contestant. The best course of action in the fourth example is to give all problems to the second contestant. Tags: data structures, dp, greedy Correct Solution: ``` # inf = open('input.txt', 'r') # reader = (map(int, line.split()) for line in inf) # k1, k2, k3 = next(reader) # a = list(next(reader)) # b = list(next(reader)) # c = list(next(reader)) k1, k2, k3 = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) c = list(map(int, input().split())) def ceil(a, L, R, pivot): while L + 1 < R: m = (L + R) // 2 if (a[m] > pivot): R = m else: L = m return R def LIS(a, n): tails = [0 for _ in range(n + 1)] empty = 0 tails[0] = a[0] empty = 1 for i in range(1, n): if (a[i] < tails[0]): tails[0] = a[i] elif (a[i] >= tails[empty - 1]): tails[empty] = a[i] empty += 1 else: tails[ceil(tails, -1, empty - 1, a[i])] = a[i] return empty n = k1 + k2 + k3 abc = [None] * n for el in a: abc[el - 1] = 1 for el in b: abc[el - 1] = 2 for el in c: abc[el - 1] = 3 # print(abc) print(n - LIS(abc, n)) # inf.close() ```
3,452
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A team of three programmers is going to play a contest. The contest consists of n problems, numbered from 1 to n. Each problem is printed on a separate sheet of paper. The participants have decided to divide the problem statements into three parts: the first programmer took some prefix of the statements (some number of first paper sheets), the third contestant took some suffix of the statements (some number of last paper sheets), and the second contestant took all remaining problems. But something went wrong — the statements were printed in the wrong order, so the contestants have received the problems in some random order. The first contestant has received problems a_{1, 1}, a_{1, 2}, ..., a_{1, k_1}. The second one has received problems a_{2, 1}, a_{2, 2}, ..., a_{2, k_2}. The third one has received all remaining problems (a_{3, 1}, a_{3, 2}, ..., a_{3, k_3}). The contestants don't want to play the contest before they redistribute the statements. They want to redistribute them so that the first contestant receives some prefix of the problemset, the third contestant receives some suffix of the problemset, and the second contestant receives all the remaining problems. During one move, some contestant may give one of their problems to other contestant. What is the minimum number of moves required to redistribute the problems? It is possible that after redistribution some participant (or even two of them) will not have any problems. Input The first line contains three integers k_1, k_2 and k_3 (1 ≤ k_1, k_2, k_3 ≤ 2 ⋅ 10^5, k_1 + k_2 + k_3 ≤ 2 ⋅ 10^5) — the number of problems initially taken by the first, the second and the third participant, respectively. The second line contains k_1 integers a_{1, 1}, a_{1, 2}, ..., a_{1, k_1} — the problems initially taken by the first participant. The third line contains k_2 integers a_{2, 1}, a_{2, 2}, ..., a_{2, k_2} — the problems initially taken by the second participant. The fourth line contains k_3 integers a_{3, 1}, a_{3, 2}, ..., a_{3, k_3} — the problems initially taken by the third participant. It is guaranteed that no problem has been taken by two (or three) participants, and each integer a_{i, j} meets the condition 1 ≤ a_{i, j} ≤ n, where n = k_1 + k_2 + k_3. Output Print one integer — the minimum number of moves required to redistribute the problems so that the first participant gets the prefix of the problemset, the third participant gets the suffix of the problemset, and the second participant gets all of the remaining problems. Examples Input 2 1 2 3 1 4 2 5 Output 1 Input 3 2 1 3 2 1 5 4 6 Output 0 Input 2 1 3 5 6 4 1 2 3 Output 3 Input 1 5 1 6 5 1 2 4 7 3 Output 2 Note In the first example the third contestant should give the problem 2 to the first contestant, so the first contestant has 3 first problems, the third contestant has 1 last problem, and the second contestant has 1 remaining problem. In the second example the distribution of problems is already valid: the first contestant has 3 first problems, the third contestant has 1 last problem, and the second contestant has 2 remaining problems. The best course of action in the third example is to give all problems to the third contestant. The best course of action in the fourth example is to give all problems to the second contestant. Submitted Solution: ``` k1,k2,k3=map(int,input().split()) s=[set([int(o) for o in input().split()]) for i in range(3)] n=k1+k2+k3 dp=[[float('inf')]*3 for i in range(n+1)] dp[0][0]=0 for i in range(1,n+1): for j in range(3): for k in range(j,3): dp[i][k]=min(dp[i][k],dp[i-1][j]+(i not in s[k])) #for j in range(3): # for i in range(n+1): # print(dp[i][j],end=" ") # print() print(min(dp[n])) ``` Yes
3,453
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A team of three programmers is going to play a contest. The contest consists of n problems, numbered from 1 to n. Each problem is printed on a separate sheet of paper. The participants have decided to divide the problem statements into three parts: the first programmer took some prefix of the statements (some number of first paper sheets), the third contestant took some suffix of the statements (some number of last paper sheets), and the second contestant took all remaining problems. But something went wrong — the statements were printed in the wrong order, so the contestants have received the problems in some random order. The first contestant has received problems a_{1, 1}, a_{1, 2}, ..., a_{1, k_1}. The second one has received problems a_{2, 1}, a_{2, 2}, ..., a_{2, k_2}. The third one has received all remaining problems (a_{3, 1}, a_{3, 2}, ..., a_{3, k_3}). The contestants don't want to play the contest before they redistribute the statements. They want to redistribute them so that the first contestant receives some prefix of the problemset, the third contestant receives some suffix of the problemset, and the second contestant receives all the remaining problems. During one move, some contestant may give one of their problems to other contestant. What is the minimum number of moves required to redistribute the problems? It is possible that after redistribution some participant (or even two of them) will not have any problems. Input The first line contains three integers k_1, k_2 and k_3 (1 ≤ k_1, k_2, k_3 ≤ 2 ⋅ 10^5, k_1 + k_2 + k_3 ≤ 2 ⋅ 10^5) — the number of problems initially taken by the first, the second and the third participant, respectively. The second line contains k_1 integers a_{1, 1}, a_{1, 2}, ..., a_{1, k_1} — the problems initially taken by the first participant. The third line contains k_2 integers a_{2, 1}, a_{2, 2}, ..., a_{2, k_2} — the problems initially taken by the second participant. The fourth line contains k_3 integers a_{3, 1}, a_{3, 2}, ..., a_{3, k_3} — the problems initially taken by the third participant. It is guaranteed that no problem has been taken by two (or three) participants, and each integer a_{i, j} meets the condition 1 ≤ a_{i, j} ≤ n, where n = k_1 + k_2 + k_3. Output Print one integer — the minimum number of moves required to redistribute the problems so that the first participant gets the prefix of the problemset, the third participant gets the suffix of the problemset, and the second participant gets all of the remaining problems. Examples Input 2 1 2 3 1 4 2 5 Output 1 Input 3 2 1 3 2 1 5 4 6 Output 0 Input 2 1 3 5 6 4 1 2 3 Output 3 Input 1 5 1 6 5 1 2 4 7 3 Output 2 Note In the first example the third contestant should give the problem 2 to the first contestant, so the first contestant has 3 first problems, the third contestant has 1 last problem, and the second contestant has 1 remaining problem. In the second example the distribution of problems is already valid: the first contestant has 3 first problems, the third contestant has 1 last problem, and the second contestant has 2 remaining problems. The best course of action in the third example is to give all problems to the third contestant. The best course of action in the fourth example is to give all problems to the second contestant. Submitted Solution: ``` import os import sys from io import BytesIO, IOBase from types import GeneratorType from collections import defaultdict 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") k1,k2,k3=map(int,input().split()) c=[dict(),dict(),dict()] a=[[],[],[]] a[0]=list(map(int,input().split())) a[1]=list(map(int,input().split())) a[2]=list(map(int,input().split())) for i in range(3): for j in a[i]: c[i][j]=1 dp=[[float("inf") for j in range(3)] for i in range(k1+k2+k3+1)] dp[0]=[0,0,0] #we want to see for each number from 1 to k1+k2+k3 that to which person we shold give this. #dp[i][j] represents the state that what will be minimum number of operations if we have to assign numbers till i and ith number is given #to kth person. for i in range(1,k1+k2+k3+1): for j in range(3): for k in range(j,3): dp[i][k]=min(dp[i][k],dp[i-1][j]+(1 if i not in c[k] else 0)) print(min(dp[k1+k2+k3])) ``` Yes
3,454
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A team of three programmers is going to play a contest. The contest consists of n problems, numbered from 1 to n. Each problem is printed on a separate sheet of paper. The participants have decided to divide the problem statements into three parts: the first programmer took some prefix of the statements (some number of first paper sheets), the third contestant took some suffix of the statements (some number of last paper sheets), and the second contestant took all remaining problems. But something went wrong — the statements were printed in the wrong order, so the contestants have received the problems in some random order. The first contestant has received problems a_{1, 1}, a_{1, 2}, ..., a_{1, k_1}. The second one has received problems a_{2, 1}, a_{2, 2}, ..., a_{2, k_2}. The third one has received all remaining problems (a_{3, 1}, a_{3, 2}, ..., a_{3, k_3}). The contestants don't want to play the contest before they redistribute the statements. They want to redistribute them so that the first contestant receives some prefix of the problemset, the third contestant receives some suffix of the problemset, and the second contestant receives all the remaining problems. During one move, some contestant may give one of their problems to other contestant. What is the minimum number of moves required to redistribute the problems? It is possible that after redistribution some participant (or even two of them) will not have any problems. Input The first line contains three integers k_1, k_2 and k_3 (1 ≤ k_1, k_2, k_3 ≤ 2 ⋅ 10^5, k_1 + k_2 + k_3 ≤ 2 ⋅ 10^5) — the number of problems initially taken by the first, the second and the third participant, respectively. The second line contains k_1 integers a_{1, 1}, a_{1, 2}, ..., a_{1, k_1} — the problems initially taken by the first participant. The third line contains k_2 integers a_{2, 1}, a_{2, 2}, ..., a_{2, k_2} — the problems initially taken by the second participant. The fourth line contains k_3 integers a_{3, 1}, a_{3, 2}, ..., a_{3, k_3} — the problems initially taken by the third participant. It is guaranteed that no problem has been taken by two (or three) participants, and each integer a_{i, j} meets the condition 1 ≤ a_{i, j} ≤ n, where n = k_1 + k_2 + k_3. Output Print one integer — the minimum number of moves required to redistribute the problems so that the first participant gets the prefix of the problemset, the third participant gets the suffix of the problemset, and the second participant gets all of the remaining problems. Examples Input 2 1 2 3 1 4 2 5 Output 1 Input 3 2 1 3 2 1 5 4 6 Output 0 Input 2 1 3 5 6 4 1 2 3 Output 3 Input 1 5 1 6 5 1 2 4 7 3 Output 2 Note In the first example the third contestant should give the problem 2 to the first contestant, so the first contestant has 3 first problems, the third contestant has 1 last problem, and the second contestant has 1 remaining problem. In the second example the distribution of problems is already valid: the first contestant has 3 first problems, the third contestant has 1 last problem, and the second contestant has 2 remaining problems. The best course of action in the third example is to give all problems to the third contestant. The best course of action in the fourth example is to give all problems to the second contestant. Submitted Solution: ``` import sys import math import collections import heapq import decimal input=sys.stdin.readline k1,k2,k3=(int(i) for i in input().split()) n=k1+k2+k3 l=[0 for i in range(n)] for i in range(3): l1=[int(j) for j in input().split()] for j in l1: l[j-1]=i ans=0 m=0 for i in range(n): if(l[i]<=1): ans+=1 le=[0,0,0] ri=[0,0,0] for i in range(n): ri[l[i]]+=1 for i in range(n): le[l[i]]+=1 ri[l[i]]-=1 m=max(m,le[0]-le[1]) k=ri[0]+ri[1]+le[2]+le[0]-m ans=min(ans,k) print(ans) ``` Yes
3,455
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A team of three programmers is going to play a contest. The contest consists of n problems, numbered from 1 to n. Each problem is printed on a separate sheet of paper. The participants have decided to divide the problem statements into three parts: the first programmer took some prefix of the statements (some number of first paper sheets), the third contestant took some suffix of the statements (some number of last paper sheets), and the second contestant took all remaining problems. But something went wrong — the statements were printed in the wrong order, so the contestants have received the problems in some random order. The first contestant has received problems a_{1, 1}, a_{1, 2}, ..., a_{1, k_1}. The second one has received problems a_{2, 1}, a_{2, 2}, ..., a_{2, k_2}. The third one has received all remaining problems (a_{3, 1}, a_{3, 2}, ..., a_{3, k_3}). The contestants don't want to play the contest before they redistribute the statements. They want to redistribute them so that the first contestant receives some prefix of the problemset, the third contestant receives some suffix of the problemset, and the second contestant receives all the remaining problems. During one move, some contestant may give one of their problems to other contestant. What is the minimum number of moves required to redistribute the problems? It is possible that after redistribution some participant (or even two of them) will not have any problems. Input The first line contains three integers k_1, k_2 and k_3 (1 ≤ k_1, k_2, k_3 ≤ 2 ⋅ 10^5, k_1 + k_2 + k_3 ≤ 2 ⋅ 10^5) — the number of problems initially taken by the first, the second and the third participant, respectively. The second line contains k_1 integers a_{1, 1}, a_{1, 2}, ..., a_{1, k_1} — the problems initially taken by the first participant. The third line contains k_2 integers a_{2, 1}, a_{2, 2}, ..., a_{2, k_2} — the problems initially taken by the second participant. The fourth line contains k_3 integers a_{3, 1}, a_{3, 2}, ..., a_{3, k_3} — the problems initially taken by the third participant. It is guaranteed that no problem has been taken by two (or three) participants, and each integer a_{i, j} meets the condition 1 ≤ a_{i, j} ≤ n, where n = k_1 + k_2 + k_3. Output Print one integer — the minimum number of moves required to redistribute the problems so that the first participant gets the prefix of the problemset, the third participant gets the suffix of the problemset, and the second participant gets all of the remaining problems. Examples Input 2 1 2 3 1 4 2 5 Output 1 Input 3 2 1 3 2 1 5 4 6 Output 0 Input 2 1 3 5 6 4 1 2 3 Output 3 Input 1 5 1 6 5 1 2 4 7 3 Output 2 Note In the first example the third contestant should give the problem 2 to the first contestant, so the first contestant has 3 first problems, the third contestant has 1 last problem, and the second contestant has 1 remaining problem. In the second example the distribution of problems is already valid: the first contestant has 3 first problems, the third contestant has 1 last problem, and the second contestant has 2 remaining problems. The best course of action in the third example is to give all problems to the third contestant. The best course of action in the fourth example is to give all problems to the second contestant. Submitted Solution: ``` # ---------------------------iye ha aam zindegi--------------------------------------------- import math import random import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys import threading from collections import defaultdict threading.stack_size(10**8) mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase sys.setrecursionlimit(300000) BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # -------------------game starts now----------------------------------------------------import math class TreeNode: def __init__(self, k, v): self.key = k self.value = v self.left = None self.right = None self.parent = None self.height = 1 self.num_left = 1 self.num_total = 1 class AvlTree: def __init__(self): self._tree = None def add(self, k, v): if not self._tree: self._tree = TreeNode(k, v) return node = self._add(k, v) if node: self._rebalance(node) def _add(self, k, v): node = self._tree while node: if k < node.key: if node.left: node = node.left else: node.left = TreeNode(k, v) node.left.parent = node return node.left elif node.key < k: if node.right: node = node.right else: node.right = TreeNode(k, v) node.right.parent = node return node.right else: node.value = v return @staticmethod def get_height(x): return x.height if x else 0 @staticmethod def get_num_total(x): return x.num_total if x else 0 def _rebalance(self, node): n = node while n: lh = self.get_height(n.left) rh = self.get_height(n.right) n.height = max(lh, rh) + 1 balance_factor = lh - rh n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right) n.num_left = 1 + self.get_num_total(n.left) if balance_factor > 1: if self.get_height(n.left.left) < self.get_height(n.left.right): self._rotate_left(n.left) self._rotate_right(n) elif balance_factor < -1: if self.get_height(n.right.right) < self.get_height(n.right.left): self._rotate_right(n.right) self._rotate_left(n) else: n = n.parent def _remove_one(self, node): """ Side effect!!! Changes node. Node should have exactly one child """ replacement = node.left or node.right if node.parent: if AvlTree._is_left(node): node.parent.left = replacement else: node.parent.right = replacement replacement.parent = node.parent node.parent = None else: self._tree = replacement replacement.parent = None node.left = None node.right = None node.parent = None self._rebalance(replacement) def _remove_leaf(self, node): if node.parent: if AvlTree._is_left(node): node.parent.left = None else: node.parent.right = None self._rebalance(node.parent) else: self._tree = None node.parent = None node.left = None node.right = None def remove(self, k): node = self._get_node(k) if not node: return if AvlTree._is_leaf(node): self._remove_leaf(node) return if node.left and node.right: nxt = AvlTree._get_next(node) node.key = nxt.key node.value = nxt.value if self._is_leaf(nxt): self._remove_leaf(nxt) else: self._remove_one(nxt) self._rebalance(node) else: self._remove_one(node) def get(self, k): node = self._get_node(k) return node.value if node else -1 def _get_node(self, k): if not self._tree: return None node = self._tree while node: if k < node.key: node = node.left elif node.key < k: node = node.right else: return node return None def get_at(self, pos): x = pos + 1 node = self._tree while node: if x < node.num_left: node = node.left elif node.num_left < x: x -= node.num_left node = node.right else: return (node.key, node.value) raise IndexError("Out of ranges") @staticmethod def _is_left(node): return node.parent.left and node.parent.left == node @staticmethod def _is_leaf(node): return node.left is None and node.right is None def _rotate_right(self, node): if not node.parent: self._tree = node.left node.left.parent = None elif AvlTree._is_left(node): node.parent.left = node.left node.left.parent = node.parent else: node.parent.right = node.left node.left.parent = node.parent bk = node.left.right node.left.right = node node.parent = node.left node.left = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) def _rotate_left(self, node): if not node.parent: self._tree = node.right node.right.parent = None elif AvlTree._is_left(node): node.parent.left = node.right node.right.parent = node.parent else: node.parent.right = node.right node.right.parent = node.parent bk = node.right.left node.right.left = node node.parent = node.right node.right = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) @staticmethod def _get_next(node): if not node.right: return node.parent n = node.right while n.left: n = n.left return n # -----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default=2**51, func=lambda a, b: a & b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------game starts now----------------------------------------------------import math class SegmentTree: def __init__(self, data, default=0, func=lambda a, b: a + b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------------------iye ha chutiya zindegi------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD # --------------------------------------iye ha combinations ka zindegi--------------------------------- def powm(a, n, m): if a == 1 or n == 0: return 1 if n % 2 == 0: s = powm(a, n // 2, m) return s * s % m else: return a * powm(a, n - 1, m) % m # --------------------------------------iye ha power ka zindegi--------------------------------- def sort_list(list1, list2): zipped_pairs = zip(list2, list1) z = [x for _, x in sorted(zipped_pairs)] return z # --------------------------------------------------product---------------------------------------- def product(l): por = 1 for i in range(len(l)): por *= l[i] return por # --------------------------------------------------binary---------------------------------------- def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left) / 2) # Check if middle element is # less than or equal to key if (arr[mid] < key): count = mid + 1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # --------------------------------------------------binary---------------------------------------- def countdig(n): c = 0 while (n > 0): n //= 10 c += 1 return c def binary(x, length): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y def countGreater(arr, n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) if (arr[m] >= k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) # --------------------------------------------------binary------------------------------------ a,b,c=map(int,input().split()) s=set(map(int,input().split())) s1=set(map(int,input().split())) s2=set(map(int,input().split())) dp=[[0 for i in range(3)]for j in range(a+b+c+1)] for i in range(1,a+b+c+1): dp[i][0]=dp[i-1][0] dp[i][1]=min(dp[i-1][1],dp[i-1][0]) dp[i][2] = min(dp[i - 1][1], dp[i - 1][0],dp[i-1][2]) if i in s: dp[i][1]+=1 dp[i][2]+=1 elif i in s1: dp[i][0] += 1 dp[i][2] += 1 else: dp[i][1] += 1 dp[i][0] += 1 print(min (dp[-1])) #print(dp) ``` Yes
3,456
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A team of three programmers is going to play a contest. The contest consists of n problems, numbered from 1 to n. Each problem is printed on a separate sheet of paper. The participants have decided to divide the problem statements into three parts: the first programmer took some prefix of the statements (some number of first paper sheets), the third contestant took some suffix of the statements (some number of last paper sheets), and the second contestant took all remaining problems. But something went wrong — the statements were printed in the wrong order, so the contestants have received the problems in some random order. The first contestant has received problems a_{1, 1}, a_{1, 2}, ..., a_{1, k_1}. The second one has received problems a_{2, 1}, a_{2, 2}, ..., a_{2, k_2}. The third one has received all remaining problems (a_{3, 1}, a_{3, 2}, ..., a_{3, k_3}). The contestants don't want to play the contest before they redistribute the statements. They want to redistribute them so that the first contestant receives some prefix of the problemset, the third contestant receives some suffix of the problemset, and the second contestant receives all the remaining problems. During one move, some contestant may give one of their problems to other contestant. What is the minimum number of moves required to redistribute the problems? It is possible that after redistribution some participant (or even two of them) will not have any problems. Input The first line contains three integers k_1, k_2 and k_3 (1 ≤ k_1, k_2, k_3 ≤ 2 ⋅ 10^5, k_1 + k_2 + k_3 ≤ 2 ⋅ 10^5) — the number of problems initially taken by the first, the second and the third participant, respectively. The second line contains k_1 integers a_{1, 1}, a_{1, 2}, ..., a_{1, k_1} — the problems initially taken by the first participant. The third line contains k_2 integers a_{2, 1}, a_{2, 2}, ..., a_{2, k_2} — the problems initially taken by the second participant. The fourth line contains k_3 integers a_{3, 1}, a_{3, 2}, ..., a_{3, k_3} — the problems initially taken by the third participant. It is guaranteed that no problem has been taken by two (or three) participants, and each integer a_{i, j} meets the condition 1 ≤ a_{i, j} ≤ n, where n = k_1 + k_2 + k_3. Output Print one integer — the minimum number of moves required to redistribute the problems so that the first participant gets the prefix of the problemset, the third participant gets the suffix of the problemset, and the second participant gets all of the remaining problems. Examples Input 2 1 2 3 1 4 2 5 Output 1 Input 3 2 1 3 2 1 5 4 6 Output 0 Input 2 1 3 5 6 4 1 2 3 Output 3 Input 1 5 1 6 5 1 2 4 7 3 Output 2 Note In the first example the third contestant should give the problem 2 to the first contestant, so the first contestant has 3 first problems, the third contestant has 1 last problem, and the second contestant has 1 remaining problem. In the second example the distribution of problems is already valid: the first contestant has 3 first problems, the third contestant has 1 last problem, and the second contestant has 2 remaining problems. The best course of action in the third example is to give all problems to the third contestant. The best course of action in the fourth example is to give all problems to the second contestant. Submitted Solution: ``` x,y,z=map(int,input().split()) a=list(map(int,input().split())) b=list(map(int,input().split())) c=list(map(int,input().split())) n=x+y+z tag=[0 for i in range(n+1)] fill=[[0]*(n+2) for i in range(3)] refill=[[0]*(n+2) for i in range(3)] d=[a,b,c] k=[x,y,z] for i in range(3): for j in range(k[i]): tag[d[i][j]]=i for i in range(1,n+1): for j in range(3): if(tag[i]==j): fill[j][i]=fill[j][i-1] else: fill[j][i]=fill[j][i-1]+1 for i in range(n,0,-1): for j in range(3): if(tag[i]==j): refill[j][i]=refill[j][i+1] else: refill[j][i]=refill[j][i+1]+1 i,j=0,0 mini=99999999999 while(i<n+1): if(fill[1][i]!=fill[1][i+1]): mini=min(mini,min(fill[0][j],fill[1][j])+min(refill[1][i+1],refill[2][i+1])) j=i+1 i+=1 if(mini==99999999999): print(0) else: print(mini,x+y,y+z,z+x) ``` No
3,457
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A team of three programmers is going to play a contest. The contest consists of n problems, numbered from 1 to n. Each problem is printed on a separate sheet of paper. The participants have decided to divide the problem statements into three parts: the first programmer took some prefix of the statements (some number of first paper sheets), the third contestant took some suffix of the statements (some number of last paper sheets), and the second contestant took all remaining problems. But something went wrong — the statements were printed in the wrong order, so the contestants have received the problems in some random order. The first contestant has received problems a_{1, 1}, a_{1, 2}, ..., a_{1, k_1}. The second one has received problems a_{2, 1}, a_{2, 2}, ..., a_{2, k_2}. The third one has received all remaining problems (a_{3, 1}, a_{3, 2}, ..., a_{3, k_3}). The contestants don't want to play the contest before they redistribute the statements. They want to redistribute them so that the first contestant receives some prefix of the problemset, the third contestant receives some suffix of the problemset, and the second contestant receives all the remaining problems. During one move, some contestant may give one of their problems to other contestant. What is the minimum number of moves required to redistribute the problems? It is possible that after redistribution some participant (or even two of them) will not have any problems. Input The first line contains three integers k_1, k_2 and k_3 (1 ≤ k_1, k_2, k_3 ≤ 2 ⋅ 10^5, k_1 + k_2 + k_3 ≤ 2 ⋅ 10^5) — the number of problems initially taken by the first, the second and the third participant, respectively. The second line contains k_1 integers a_{1, 1}, a_{1, 2}, ..., a_{1, k_1} — the problems initially taken by the first participant. The third line contains k_2 integers a_{2, 1}, a_{2, 2}, ..., a_{2, k_2} — the problems initially taken by the second participant. The fourth line contains k_3 integers a_{3, 1}, a_{3, 2}, ..., a_{3, k_3} — the problems initially taken by the third participant. It is guaranteed that no problem has been taken by two (or three) participants, and each integer a_{i, j} meets the condition 1 ≤ a_{i, j} ≤ n, where n = k_1 + k_2 + k_3. Output Print one integer — the minimum number of moves required to redistribute the problems so that the first participant gets the prefix of the problemset, the third participant gets the suffix of the problemset, and the second participant gets all of the remaining problems. Examples Input 2 1 2 3 1 4 2 5 Output 1 Input 3 2 1 3 2 1 5 4 6 Output 0 Input 2 1 3 5 6 4 1 2 3 Output 3 Input 1 5 1 6 5 1 2 4 7 3 Output 2 Note In the first example the third contestant should give the problem 2 to the first contestant, so the first contestant has 3 first problems, the third contestant has 1 last problem, and the second contestant has 1 remaining problem. In the second example the distribution of problems is already valid: the first contestant has 3 first problems, the third contestant has 1 last problem, and the second contestant has 2 remaining problems. The best course of action in the third example is to give all problems to the third contestant. The best course of action in the fourth example is to give all problems to the second contestant. Submitted Solution: ``` x,y,z=map(int,input().split()) a=list(map(int,input().split())) b=list(map(int,input().split())) c=list(map(int,input().split())) n=x+y+z tag=[0 for i in range(n+1)] fill=[[0]*(n+2) for i in range(3)] refill=[[0]*(n+2) for i in range(3)] d=[a,b,c] k=[x,y,z] for i in range(3): for j in range(k[i]): tag[d[i][j]]=i for i in range(1,n+1): for j in range(3): if(tag[i]==j): fill[j][i]=fill[j][i-1] else: fill[j][i]=fill[j][i-1]+1 for i in range(n,0,-1): for j in range(3): if(tag[i]==j): refill[j][i]=refill[j][i+1] else: refill[j][i]=refill[j][i+1]+1 i,j=0,0 mini=99999999999 while(i<n+1): if(fill[1][i]!=fill[1][i+1]): mini=min(mini,min(fill[0][j],fill[1][j])+min(refill[1][i+1],refill[2][i+1])) j=i+1 i+=1 if(mini==99999999999): print(0) else: print(mini) ``` No
3,458
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A team of three programmers is going to play a contest. The contest consists of n problems, numbered from 1 to n. Each problem is printed on a separate sheet of paper. The participants have decided to divide the problem statements into three parts: the first programmer took some prefix of the statements (some number of first paper sheets), the third contestant took some suffix of the statements (some number of last paper sheets), and the second contestant took all remaining problems. But something went wrong — the statements were printed in the wrong order, so the contestants have received the problems in some random order. The first contestant has received problems a_{1, 1}, a_{1, 2}, ..., a_{1, k_1}. The second one has received problems a_{2, 1}, a_{2, 2}, ..., a_{2, k_2}. The third one has received all remaining problems (a_{3, 1}, a_{3, 2}, ..., a_{3, k_3}). The contestants don't want to play the contest before they redistribute the statements. They want to redistribute them so that the first contestant receives some prefix of the problemset, the third contestant receives some suffix of the problemset, and the second contestant receives all the remaining problems. During one move, some contestant may give one of their problems to other contestant. What is the minimum number of moves required to redistribute the problems? It is possible that after redistribution some participant (or even two of them) will not have any problems. Input The first line contains three integers k_1, k_2 and k_3 (1 ≤ k_1, k_2, k_3 ≤ 2 ⋅ 10^5, k_1 + k_2 + k_3 ≤ 2 ⋅ 10^5) — the number of problems initially taken by the first, the second and the third participant, respectively. The second line contains k_1 integers a_{1, 1}, a_{1, 2}, ..., a_{1, k_1} — the problems initially taken by the first participant. The third line contains k_2 integers a_{2, 1}, a_{2, 2}, ..., a_{2, k_2} — the problems initially taken by the second participant. The fourth line contains k_3 integers a_{3, 1}, a_{3, 2}, ..., a_{3, k_3} — the problems initially taken by the third participant. It is guaranteed that no problem has been taken by two (or three) participants, and each integer a_{i, j} meets the condition 1 ≤ a_{i, j} ≤ n, where n = k_1 + k_2 + k_3. Output Print one integer — the minimum number of moves required to redistribute the problems so that the first participant gets the prefix of the problemset, the third participant gets the suffix of the problemset, and the second participant gets all of the remaining problems. Examples Input 2 1 2 3 1 4 2 5 Output 1 Input 3 2 1 3 2 1 5 4 6 Output 0 Input 2 1 3 5 6 4 1 2 3 Output 3 Input 1 5 1 6 5 1 2 4 7 3 Output 2 Note In the first example the third contestant should give the problem 2 to the first contestant, so the first contestant has 3 first problems, the third contestant has 1 last problem, and the second contestant has 1 remaining problem. In the second example the distribution of problems is already valid: the first contestant has 3 first problems, the third contestant has 1 last problem, and the second contestant has 2 remaining problems. The best course of action in the third example is to give all problems to the third contestant. The best course of action in the fourth example is to give all problems to the second contestant. Submitted Solution: ``` import sys input = sys.stdin.readline k1,k2,k3=map(int,input().split()) A1=list(map(int,input().split())) A2=list(map(int,input().split())) A3=list(map(int,input().split())) A1.sort() A2.sort() A3.sort() S=k1+k2+k3 A1LIST=[0]*(S+1) for a1 in A1: A1LIST[a1]+=1 from itertools import accumulate S1LIST=list(accumulate(A1LIST)) A1USE=[-1]*(S+1) for i in range(S+1): A1USE[i]=(i-S1LIST[i])+(S1LIST[-1]-S1LIST[i]) MIN=min(A1USE) for i in range(S+1): if A1USE[i]==MIN: USE1=i ANS=A1USE[USE1] B2=[] B3=[] for a2 in A2: if a2>USE1: B2.append(a2) for a3 in A3: if a3>USE1: B3.append(a3) compression_dict={a: ind+1 for ind, a in enumerate(sorted(set(B2+B3)))} B2=[compression_dict[a] for a in B2] B3=[compression_dict[a] for a in B3] S=len(B2)+len(B3) B2LIST=[0]*(S+1) for b2 in B2: B2LIST[b2]+=1 S2LIST=list(accumulate(B2LIST)) B2USE=[-1]*(S+1) for i in range(S+1): B2USE[i]=(i-S2LIST[i])+(S2LIST[-1]-S2LIST[i]) MIN=min(B2USE) for i in range(S+1): if B2USE[i]==MIN: USE2=i ANS2=B2USE[USE2] print(ANS+ANS2) ``` No
3,459
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A team of three programmers is going to play a contest. The contest consists of n problems, numbered from 1 to n. Each problem is printed on a separate sheet of paper. The participants have decided to divide the problem statements into three parts: the first programmer took some prefix of the statements (some number of first paper sheets), the third contestant took some suffix of the statements (some number of last paper sheets), and the second contestant took all remaining problems. But something went wrong — the statements were printed in the wrong order, so the contestants have received the problems in some random order. The first contestant has received problems a_{1, 1}, a_{1, 2}, ..., a_{1, k_1}. The second one has received problems a_{2, 1}, a_{2, 2}, ..., a_{2, k_2}. The third one has received all remaining problems (a_{3, 1}, a_{3, 2}, ..., a_{3, k_3}). The contestants don't want to play the contest before they redistribute the statements. They want to redistribute them so that the first contestant receives some prefix of the problemset, the third contestant receives some suffix of the problemset, and the second contestant receives all the remaining problems. During one move, some contestant may give one of their problems to other contestant. What is the minimum number of moves required to redistribute the problems? It is possible that after redistribution some participant (or even two of them) will not have any problems. Input The first line contains three integers k_1, k_2 and k_3 (1 ≤ k_1, k_2, k_3 ≤ 2 ⋅ 10^5, k_1 + k_2 + k_3 ≤ 2 ⋅ 10^5) — the number of problems initially taken by the first, the second and the third participant, respectively. The second line contains k_1 integers a_{1, 1}, a_{1, 2}, ..., a_{1, k_1} — the problems initially taken by the first participant. The third line contains k_2 integers a_{2, 1}, a_{2, 2}, ..., a_{2, k_2} — the problems initially taken by the second participant. The fourth line contains k_3 integers a_{3, 1}, a_{3, 2}, ..., a_{3, k_3} — the problems initially taken by the third participant. It is guaranteed that no problem has been taken by two (or three) participants, and each integer a_{i, j} meets the condition 1 ≤ a_{i, j} ≤ n, where n = k_1 + k_2 + k_3. Output Print one integer — the minimum number of moves required to redistribute the problems so that the first participant gets the prefix of the problemset, the third participant gets the suffix of the problemset, and the second participant gets all of the remaining problems. Examples Input 2 1 2 3 1 4 2 5 Output 1 Input 3 2 1 3 2 1 5 4 6 Output 0 Input 2 1 3 5 6 4 1 2 3 Output 3 Input 1 5 1 6 5 1 2 4 7 3 Output 2 Note In the first example the third contestant should give the problem 2 to the first contestant, so the first contestant has 3 first problems, the third contestant has 1 last problem, and the second contestant has 1 remaining problem. In the second example the distribution of problems is already valid: the first contestant has 3 first problems, the third contestant has 1 last problem, and the second contestant has 2 remaining problems. The best course of action in the third example is to give all problems to the third contestant. The best course of action in the fourth example is to give all problems to the second contestant. Submitted Solution: ``` a = input() a = a.split() for i in range(3): a[i] = int(a[i]) total = sum(a) content = [] for i in range(3): b = input() b = b.split() content.append(b) for i in range(3): for j in range(len(content[i])): content[i][j] = int(content[i][j]) content[i].sort() #print (content) dp = [] if min(content[0]) > max(content[2]): print (total-len(content[1])) else: for i in range(total): for j in range(total): if i<j and (i+1) in content[0] and (j+1) in content[2]: #problem i given to first, j given to second changes = 0 for k in range(1, i+2): if k not in content[0]: changes += 1 for k in range(j+1, total): if k not in content[2]: changes += 1 for k in range(i+2, j+1): if k not in content[1]: changes += 1 dp.append([(i+1,j+1), changes]) min = 9999999999 for i in dp: if i[1] < min: min = i[1] print (min) ``` No
3,460
Provide tags and a correct Python 3 solution for this coding contest problem. You are an intergalactic surgeon and you have an alien patient. For the purposes of this problem, we can and we will model this patient's body using a 2 × (2k + 1) rectangular grid. The alien has 4k + 1 distinct organs, numbered 1 to 4k + 1. In healthy such aliens, the organs are arranged in a particular way. For example, here is how the organs of a healthy such alien would be positioned, when viewed from the top, for k = 4: <image> Here, the E represents empty space. In general, the first row contains organs 1 to 2k + 1 (in that order from left to right), and the second row contains organs 2k + 2 to 4k + 1 (in that order from left to right) and then empty space right after. Your patient's organs are complete, and inside their body, but they somehow got shuffled around! Your job, as an intergalactic surgeon, is to put everything back in its correct position. All organs of the alien must be in its body during the entire procedure. This means that at any point during the procedure, there is exactly one cell (in the grid) that is empty. In addition, you can only move organs around by doing one of the following things: * You can switch the positions of the empty space E with any organ to its immediate left or to its immediate right (if they exist). In reality, you do this by sliding the organ in question to the empty space; * You can switch the positions of the empty space E with any organ to its immediate top or its immediate bottom (if they exist) only if the empty space is on the leftmost column, rightmost column or in the centermost column. Again, you do this by sliding the organ in question to the empty space. Your job is to figure out a sequence of moves you must do during the surgical procedure in order to place back all 4k + 1 internal organs of your patient in the correct cells. If it is impossible to do so, you must say so. Input The first line of input contains a single integer t (1 ≤ t ≤ 4) denoting the number of test cases. The next lines contain descriptions of the test cases. Each test case consists of three lines. The first line contains a single integer k (1 ≤ k ≤ 15) which determines the size of the grid. Then two lines follow. Each of them contains 2k + 1 space-separated integers or the letter E. They describe the first and second rows of organs, respectively. It is guaranteed that all 4k + 1 organs are present and there is exactly one E. Output For each test case, first, print a single line containing either: * SURGERY COMPLETE if it is possible to place back all internal organs in the correct locations; * SURGERY FAILED if it is impossible. If it is impossible, then this is the only line of output for the test case. However, if it is possible, output a few more lines describing the sequence of moves to place the organs in the correct locations. The sequence of moves will be a (possibly empty) string of letters u, d, l or r, representing sliding the organ that's directly above, below, to the left or to the right of the empty space, respectively, into the empty space. Print the sequence of moves in the following line, as such a string. For convenience, you may use shortcuts to reduce the size of your output. You may use uppercase letters as shortcuts for sequences of moves. For example, you could choose T to represent the string lddrr. These shortcuts may also include other shortcuts on their own! For example, you could choose E to represent TruT, etc. You may use any number of uppercase letters (including none) as shortcuts. The only requirements are the following: * The total length of all strings in your output for a single case is at most 10^4; * There must be no cycles involving the shortcuts that are reachable from the main sequence; * The resulting sequence of moves is finite, after expanding all shortcuts. Note that the final sequence of moves (after expanding) may be much longer than 10^4; the only requirement is that it's finite. As an example, if T = lddrr, E = TruT and R = rrr, then TurTlER expands to: * TurTlER * lddrrurTlER * lddrrurlddrrlER * lddrrurlddrrlTruTR * lddrrurlddrrllddrrruTR * lddrrurlddrrllddrrrulddrrR * lddrrurlddrrllddrrrulddrrrrr To use shortcuts, print each one of them in a single line as the uppercase letter, then space, and then the string that this shortcut represents. They may be printed in any order. At the end of all of those, print a single line containing DONE. Note: You still need to print DONE even if you don't plan on using shortcuts. Your sequence does not need to be the shortest. Any valid sequence of moves (satisfying the requirements above) will be accepted. Example Input 2 3 1 2 3 5 6 E 7 8 9 10 4 11 12 13 11 34 45 6 22 16 43 38 44 5 4 41 14 7 29 28 19 9 18 42 8 17 33 1 E 15 40 36 31 24 10 2 21 11 32 23 30 27 35 25 13 12 39 37 26 20 3 Output SURGERY COMPLETE IR R SrS S rr I lldll DONE SURGERY FAILED Note There are three shortcuts defined in the first sample output: * R = SrS * S = rr * I = lldll The sequence of moves is IR and it expands to: * IR * lldllR * lldllSrS * lldllrrrS * lldllrrrrr Tags: combinatorics, constructive algorithms, math Correct Solution: ``` def flatten(grid): k = len(grid[0]) // 2 seek = list(range(2*k + 2)) + list(range(2*k + 2, 4*k + 2))[::-1] return [seek[v] for v in grid[0] + grid[1][::-1] if v] def solve(grid): grid = list(map(list, grid)) k = len(grid[0]) // 2 flat = flatten(grid) m = { 'L': 'l'*2*k + 'u' + 'r'*2*k + 'd', 'R': 'u' + 'l'*2*k + 'd' + 'r'*2*k, 'C': 'l'*k + 'u' + 'r'*k + 'd', 'D': 'CC' + 'R'*(2*k + 1) + 'CC' + 'R'*(2*k + 2), 'F': 'R'*(k - 1) + 'DD' + 'R'*(2*k + 1) + 'D' + 'L'*2*k + 'DD' + 'L'*k, 'G': 'FF', } [(i, j)] = [(i, j) for i in range(2) for j in range(2*k + 1) if grid[i][j] == 0] st = 'r'*(2*k - j) + 'd'*(1 - i) for v in range(2, 4*k + 2): ct = flat.index(v) if ct >= 2: st += 'L'*(ct - 2) + 'GR'*(ct - 2) + 'G' flat = flat[ct - 1: ct + 1] + flat[:ct - 1] + flat[ct + 1:] if ct >= 1: st += 'G' flat = flat[1:3] + flat[:1] + flat[3:] st += 'L' flat = flat[1:] + flat[:1] if flat[0] == 1: return st, m def main(): def get_line(): return [0 if x == 'E' else int(x) for x in input().split()] for cas in range(int(input())): k = int(input()) grid = [get_line() for i in range(2)] assert all(len(row) == 2*k + 1 for row in grid) res = solve(grid) if res is None: print('SURGERY FAILED') else: print('SURGERY COMPLETE') st, m = res print(st) for shortcut in m.items(): print(*shortcut) print('DONE') main() ```
3,461
Provide tags and a correct Python 3 solution for this coding contest problem. You are an intergalactic surgeon and you have an alien patient. For the purposes of this problem, we can and we will model this patient's body using a 2 × (2k + 1) rectangular grid. The alien has 4k + 1 distinct organs, numbered 1 to 4k + 1. In healthy such aliens, the organs are arranged in a particular way. For example, here is how the organs of a healthy such alien would be positioned, when viewed from the top, for k = 4: <image> Here, the E represents empty space. In general, the first row contains organs 1 to 2k + 1 (in that order from left to right), and the second row contains organs 2k + 2 to 4k + 1 (in that order from left to right) and then empty space right after. Your patient's organs are complete, and inside their body, but they somehow got shuffled around! Your job, as an intergalactic surgeon, is to put everything back in its correct position. All organs of the alien must be in its body during the entire procedure. This means that at any point during the procedure, there is exactly one cell (in the grid) that is empty. In addition, you can only move organs around by doing one of the following things: * You can switch the positions of the empty space E with any organ to its immediate left or to its immediate right (if they exist). In reality, you do this by sliding the organ in question to the empty space; * You can switch the positions of the empty space E with any organ to its immediate top or its immediate bottom (if they exist) only if the empty space is on the leftmost column, rightmost column or in the centermost column. Again, you do this by sliding the organ in question to the empty space. Your job is to figure out a sequence of moves you must do during the surgical procedure in order to place back all 4k + 1 internal organs of your patient in the correct cells. If it is impossible to do so, you must say so. Input The first line of input contains a single integer t (1 ≤ t ≤ 4) denoting the number of test cases. The next lines contain descriptions of the test cases. Each test case consists of three lines. The first line contains a single integer k (1 ≤ k ≤ 15) which determines the size of the grid. Then two lines follow. Each of them contains 2k + 1 space-separated integers or the letter E. They describe the first and second rows of organs, respectively. It is guaranteed that all 4k + 1 organs are present and there is exactly one E. Output For each test case, first, print a single line containing either: * SURGERY COMPLETE if it is possible to place back all internal organs in the correct locations; * SURGERY FAILED if it is impossible. If it is impossible, then this is the only line of output for the test case. However, if it is possible, output a few more lines describing the sequence of moves to place the organs in the correct locations. The sequence of moves will be a (possibly empty) string of letters u, d, l or r, representing sliding the organ that's directly above, below, to the left or to the right of the empty space, respectively, into the empty space. Print the sequence of moves in the following line, as such a string. For convenience, you may use shortcuts to reduce the size of your output. You may use uppercase letters as shortcuts for sequences of moves. For example, you could choose T to represent the string lddrr. These shortcuts may also include other shortcuts on their own! For example, you could choose E to represent TruT, etc. You may use any number of uppercase letters (including none) as shortcuts. The only requirements are the following: * The total length of all strings in your output for a single case is at most 10^4; * There must be no cycles involving the shortcuts that are reachable from the main sequence; * The resulting sequence of moves is finite, after expanding all shortcuts. Note that the final sequence of moves (after expanding) may be much longer than 10^4; the only requirement is that it's finite. As an example, if T = lddrr, E = TruT and R = rrr, then TurTlER expands to: * TurTlER * lddrrurTlER * lddrrurlddrrlER * lddrrurlddrrlTruTR * lddrrurlddrrllddrrruTR * lddrrurlddrrllddrrrulddrrR * lddrrurlddrrllddrrrulddrrrrr To use shortcuts, print each one of them in a single line as the uppercase letter, then space, and then the string that this shortcut represents. They may be printed in any order. At the end of all of those, print a single line containing DONE. Note: You still need to print DONE even if you don't plan on using shortcuts. Your sequence does not need to be the shortest. Any valid sequence of moves (satisfying the requirements above) will be accepted. Example Input 2 3 1 2 3 5 6 E 7 8 9 10 4 11 12 13 11 34 45 6 22 16 43 38 44 5 4 41 14 7 29 28 19 9 18 42 8 17 33 1 E 15 40 36 31 24 10 2 21 11 32 23 30 27 35 25 13 12 39 37 26 20 3 Output SURGERY COMPLETE IR R SrS S rr I lldll DONE SURGERY FAILED Note There are three shortcuts defined in the first sample output: * R = SrS * S = rr * I = lldll The sequence of moves is IR and it expands to: * IR * lldllR * lldllSrS * lldllrrrS * lldllrrrrr Tags: combinatorics, constructive algorithms, math Correct Solution: ``` def solve(k, grid): seek = *range(2*k + 2), *range(4*k + 1, 2*k + 1, -1) flat = [seek[v] for v in grid[0] + grid[1][::-1] if v] m = { 'L': 'l'*2*k + 'u' + 'r'*2*k + 'd', 'R': 'u' + 'l'*2*k + 'd' + 'r'*2*k, 'C': 'l'*k + 'u' + 'r'*k + 'd', 'D': 'CC' + 'R'*(2*k + 1) + 'CC' + 'R'*(2*k + 2), 'F': 'R'*(k - 1) + 'DD' + 'R'*(2*k + 1) + 'D' + 'L'*2*k + 'DD' + 'L'*k, 'G': 'FF', } [(i, j)] = [(i, j) for i in range(2) for j in range(2*k + 1) if grid[i][j] == 0] st = 'r'*(2*k - j) + 'd'*(1 - i) for v in range(2, 4*k + 2): ct = flat.index(v) if ct >= 2: st += 'L'*(ct - 2) + 'GR'*(ct - 2) + 'G' flat = flat[ct - 1: ct + 1] + flat[:ct - 1] + flat[ct + 1:] if ct >= 1: st += 'G' flat = flat[1:3] + flat[:1] + flat[3:] st += 'L' flat = flat[1:] + flat[:1] if flat[0] == 1: return st, m def main(): def get_line(): return [0 if x == 'E' else int(x) for x in input().split()] for cas in range(int(input())): res = solve(int(input()), [get_line() for i in range(2)]) if res is None: print('SURGERY FAILED') else: print('SURGERY COMPLETE') st, m = res print(st) for shortcut in m.items(): print(*shortcut) print('DONE') main() ```
3,462
Provide tags and a correct Python 3 solution for this coding contest problem. You are an intergalactic surgeon and you have an alien patient. For the purposes of this problem, we can and we will model this patient's body using a 2 × (2k + 1) rectangular grid. The alien has 4k + 1 distinct organs, numbered 1 to 4k + 1. In healthy such aliens, the organs are arranged in a particular way. For example, here is how the organs of a healthy such alien would be positioned, when viewed from the top, for k = 4: <image> Here, the E represents empty space. In general, the first row contains organs 1 to 2k + 1 (in that order from left to right), and the second row contains organs 2k + 2 to 4k + 1 (in that order from left to right) and then empty space right after. Your patient's organs are complete, and inside their body, but they somehow got shuffled around! Your job, as an intergalactic surgeon, is to put everything back in its correct position. All organs of the alien must be in its body during the entire procedure. This means that at any point during the procedure, there is exactly one cell (in the grid) that is empty. In addition, you can only move organs around by doing one of the following things: * You can switch the positions of the empty space E with any organ to its immediate left or to its immediate right (if they exist). In reality, you do this by sliding the organ in question to the empty space; * You can switch the positions of the empty space E with any organ to its immediate top or its immediate bottom (if they exist) only if the empty space is on the leftmost column, rightmost column or in the centermost column. Again, you do this by sliding the organ in question to the empty space. Your job is to figure out a sequence of moves you must do during the surgical procedure in order to place back all 4k + 1 internal organs of your patient in the correct cells. If it is impossible to do so, you must say so. Input The first line of input contains a single integer t (1 ≤ t ≤ 4) denoting the number of test cases. The next lines contain descriptions of the test cases. Each test case consists of three lines. The first line contains a single integer k (1 ≤ k ≤ 15) which determines the size of the grid. Then two lines follow. Each of them contains 2k + 1 space-separated integers or the letter E. They describe the first and second rows of organs, respectively. It is guaranteed that all 4k + 1 organs are present and there is exactly one E. Output For each test case, first, print a single line containing either: * SURGERY COMPLETE if it is possible to place back all internal organs in the correct locations; * SURGERY FAILED if it is impossible. If it is impossible, then this is the only line of output for the test case. However, if it is possible, output a few more lines describing the sequence of moves to place the organs in the correct locations. The sequence of moves will be a (possibly empty) string of letters u, d, l or r, representing sliding the organ that's directly above, below, to the left or to the right of the empty space, respectively, into the empty space. Print the sequence of moves in the following line, as such a string. For convenience, you may use shortcuts to reduce the size of your output. You may use uppercase letters as shortcuts for sequences of moves. For example, you could choose T to represent the string lddrr. These shortcuts may also include other shortcuts on their own! For example, you could choose E to represent TruT, etc. You may use any number of uppercase letters (including none) as shortcuts. The only requirements are the following: * The total length of all strings in your output for a single case is at most 10^4; * There must be no cycles involving the shortcuts that are reachable from the main sequence; * The resulting sequence of moves is finite, after expanding all shortcuts. Note that the final sequence of moves (after expanding) may be much longer than 10^4; the only requirement is that it's finite. As an example, if T = lddrr, E = TruT and R = rrr, then TurTlER expands to: * TurTlER * lddrrurTlER * lddrrurlddrrlER * lddrrurlddrrlTruTR * lddrrurlddrrllddrrruTR * lddrrurlddrrllddrrrulddrrR * lddrrurlddrrllddrrrulddrrrrr To use shortcuts, print each one of them in a single line as the uppercase letter, then space, and then the string that this shortcut represents. They may be printed in any order. At the end of all of those, print a single line containing DONE. Note: You still need to print DONE even if you don't plan on using shortcuts. Your sequence does not need to be the shortest. Any valid sequence of moves (satisfying the requirements above) will be accepted. Example Input 2 3 1 2 3 5 6 E 7 8 9 10 4 11 12 13 11 34 45 6 22 16 43 38 44 5 4 41 14 7 29 28 19 9 18 42 8 17 33 1 E 15 40 36 31 24 10 2 21 11 32 23 30 27 35 25 13 12 39 37 26 20 3 Output SURGERY COMPLETE IR R SrS S rr I lldll DONE SURGERY FAILED Note There are three shortcuts defined in the first sample output: * R = SrS * S = rr * I = lldll The sequence of moves is IR and it expands to: * IR * lldllR * lldllSrS * lldllrrrS * lldllrrrrr Tags: combinatorics, constructive algorithms, math Correct Solution: ``` def solve(kk,grid): sk = *range(kk * 2 + 2),*range(4 * kk + 1,2 * kk + 1,-1) flat = [sk[v] for v in grid[0] + grid[1][::-1] if v] dir = { 'L': 'l' * 2 * kk + 'u' + 'r' * 2 * kk + 'd', 'R': 'u' + 'l' * 2 * kk + 'd' + 'r' * 2 * kk, 'C': 'l' * kk + 'u' + 'r' * kk + 'd', 'D': 'CC' + 'R' * (2 * kk + 1) + 'CC' + 'R' * (2 * kk + 2), 'F': 'R' * (kk - 1) + 'DD' + 'R' * (2 * kk + 1) + 'D' + 'L' * 2 * kk + 'DD' + 'L' * kk, 'G': 'FF' } [(i,j)] = [(i,j) for i in range(2) for j in range(2 * kk + 1) if grid[i][j] == 0] st = 'r' * (2 * kk - j) + 'd' * (1 - i) for i in range(2,4 * kk + 2): tt = flat.index(i) if tt >= 2: st += 'L' * (tt - 2) + 'GR' * (tt - 2) + 'G' flat = flat[tt - 1 : tt + 1] + flat[:tt - 1] + flat[tt + 1:] if tt >= 1: st += 'G' flat = flat[1 : 3] + flat[:1] + flat[3:] st += 'L' flat = flat[1:] + flat[:1] if flat[0] == 1: return st,dir def getline(): return [0 if x == 'E' else int(x) for x in input().split()] for case in range(int(input())): ret = solve(int(input()),[getline() for i in range(2)]) if ret is None: print('SURGERY FAILED') else: print('SURGERY COMPLETE') st,vv = ret print(st) for shortcut in vv.items() : print(*shortcut) print('DONE') ```
3,463
Provide tags and a correct Python 3 solution for this coding contest problem. You are an intergalactic surgeon and you have an alien patient. For the purposes of this problem, we can and we will model this patient's body using a 2 × (2k + 1) rectangular grid. The alien has 4k + 1 distinct organs, numbered 1 to 4k + 1. In healthy such aliens, the organs are arranged in a particular way. For example, here is how the organs of a healthy such alien would be positioned, when viewed from the top, for k = 4: <image> Here, the E represents empty space. In general, the first row contains organs 1 to 2k + 1 (in that order from left to right), and the second row contains organs 2k + 2 to 4k + 1 (in that order from left to right) and then empty space right after. Your patient's organs are complete, and inside their body, but they somehow got shuffled around! Your job, as an intergalactic surgeon, is to put everything back in its correct position. All organs of the alien must be in its body during the entire procedure. This means that at any point during the procedure, there is exactly one cell (in the grid) that is empty. In addition, you can only move organs around by doing one of the following things: * You can switch the positions of the empty space E with any organ to its immediate left or to its immediate right (if they exist). In reality, you do this by sliding the organ in question to the empty space; * You can switch the positions of the empty space E with any organ to its immediate top or its immediate bottom (if they exist) only if the empty space is on the leftmost column, rightmost column or in the centermost column. Again, you do this by sliding the organ in question to the empty space. Your job is to figure out a sequence of moves you must do during the surgical procedure in order to place back all 4k + 1 internal organs of your patient in the correct cells. If it is impossible to do so, you must say so. Input The first line of input contains a single integer t (1 ≤ t ≤ 4) denoting the number of test cases. The next lines contain descriptions of the test cases. Each test case consists of three lines. The first line contains a single integer k (1 ≤ k ≤ 15) which determines the size of the grid. Then two lines follow. Each of them contains 2k + 1 space-separated integers or the letter E. They describe the first and second rows of organs, respectively. It is guaranteed that all 4k + 1 organs are present and there is exactly one E. Output For each test case, first, print a single line containing either: * SURGERY COMPLETE if it is possible to place back all internal organs in the correct locations; * SURGERY FAILED if it is impossible. If it is impossible, then this is the only line of output for the test case. However, if it is possible, output a few more lines describing the sequence of moves to place the organs in the correct locations. The sequence of moves will be a (possibly empty) string of letters u, d, l or r, representing sliding the organ that's directly above, below, to the left or to the right of the empty space, respectively, into the empty space. Print the sequence of moves in the following line, as such a string. For convenience, you may use shortcuts to reduce the size of your output. You may use uppercase letters as shortcuts for sequences of moves. For example, you could choose T to represent the string lddrr. These shortcuts may also include other shortcuts on their own! For example, you could choose E to represent TruT, etc. You may use any number of uppercase letters (including none) as shortcuts. The only requirements are the following: * The total length of all strings in your output for a single case is at most 10^4; * There must be no cycles involving the shortcuts that are reachable from the main sequence; * The resulting sequence of moves is finite, after expanding all shortcuts. Note that the final sequence of moves (after expanding) may be much longer than 10^4; the only requirement is that it's finite. As an example, if T = lddrr, E = TruT and R = rrr, then TurTlER expands to: * TurTlER * lddrrurTlER * lddrrurlddrrlER * lddrrurlddrrlTruTR * lddrrurlddrrllddrrruTR * lddrrurlddrrllddrrrulddrrR * lddrrurlddrrllddrrrulddrrrrr To use shortcuts, print each one of them in a single line as the uppercase letter, then space, and then the string that this shortcut represents. They may be printed in any order. At the end of all of those, print a single line containing DONE. Note: You still need to print DONE even if you don't plan on using shortcuts. Your sequence does not need to be the shortest. Any valid sequence of moves (satisfying the requirements above) will be accepted. Example Input 2 3 1 2 3 5 6 E 7 8 9 10 4 11 12 13 11 34 45 6 22 16 43 38 44 5 4 41 14 7 29 28 19 9 18 42 8 17 33 1 E 15 40 36 31 24 10 2 21 11 32 23 30 27 35 25 13 12 39 37 26 20 3 Output SURGERY COMPLETE IR R SrS S rr I lldll DONE SURGERY FAILED Note There are three shortcuts defined in the first sample output: * R = SrS * S = rr * I = lldll The sequence of moves is IR and it expands to: * IR * lldllR * lldllSrS * lldllrrrS * lldllrrrrr Tags: combinatorics, constructive algorithms, math Correct Solution: ``` import sys OP_CW1 = 'A' OP_CW4 = 'B' OP_CW16 = 'C' OP_CCW = 'E' OP_L = 'U' OP_INV_L = 'V' OP_R = 'W' OP_INV_R = 'X' OP_S = 'S' OP_MOVE_LL1 = 'O' OP_MOVE_LL4 = 'P' OP_MOVE_LL16 = 'Q' OP_MOVE_L_THROW = 'R' def GetK(board): return len(board) // 4 def Slot(board, slotval=-1): return board.index(slotval) def KS(board, slotval=-1): return GetK(board), Slot(board, slotval) def Width(K): return K * 2 + 1 def PrintPermumation(head, board, slotval=None): K = GetK(board) W = Width(K) if slotval is None: slotval = K slot = Slot(board, slotval) print(head, '===', file=sys.stderr) tostr = lambda x: 'EE' if x == slotval else '%2d' % x for row in [board[:W], board[W:]]: print(' '.join(tostr(x) for x in row), file=sys.stderr) def ApplyOps(board, seq, ops=None, slotval=-1): K, slot = KS(board, slotval) W = Width(K) for c in seq: if c == 'l': assert slot % W > 0, slot s1 = slot - 1 elif c == 'r': assert slot % W + 1 < W, slot s1 = slot + 1 elif c == 'd': assert slot % W in [0, K, K * 2], slot assert slot // W == 0 s1 = slot + W elif c == 'u': assert slot % W in [0, K, K * 2], slot assert slot // W == 1 s1 = slot - W else: s1 = None if s1 is not None: board[s1], board[slot] = board[slot], board[s1] else: P = ops[c] tmp = board[:] for i in range(len(board)): board[i] = tmp[P[i]] slot = Slot(board, slotval) def LoopedView(board): K, slot = KS(board) W = Width(slot) assert slot == K def translate(x): if x == -1: return x if x <= W: return x - 1 # W+1 -> 2W-2 return 3 * W - 1 - x r = [] for rng in [range(slot + 1, W), reversed(range(W, W * 2)), range(0, slot)]: for i in rng: r.append(translate(board[i])) return r def Mod(x, m): x %= m if x < 0: x += m return x def CanonicalizeView(view): i = view.index(0) view[:] = view[i:] + view[:i] def ToPermutation(K, ops, seq): board = list(range(K * 4 + 2)) ApplyOps(board, seq, ops, slotval=K) return board def InitOps(K, debug=False): W = Width(K) ops = {} ops_codes = {} def ToP(seq): return ToPermutation(K, ops, seq) def Assign(rep, seq): ops[rep] = ToP(seq) ops_codes[rep] = seq Assign(OP_CW1, 'l' * K + 'd' + 'r' * (K * 2) + 'u' + 'l' * K) if debug: PrintPermumation('CW1', ops[OP_CW1]) Assign(OP_CW4, OP_CW1 * 4) if debug: PrintPermumation('CW4', ops[OP_CW4]) Assign(OP_CW16, OP_CW4 * 4) Assign(OP_CCW, OP_CW1 * (W * 2 - 2)) if debug: PrintPermumation('CCW', ops[OP_CCW]) Assign(OP_L, 'l' * K + 'd' + 'r' * K + 'u') if debug: PrintPermumation('L', ops[OP_L]) Assign(OP_INV_L, OP_L * (K * 2)) if debug: PrintPermumation('INV_L', ops[OP_INV_L]) Assign(OP_R, 'r' * K + 'd' + 'l' * K + 'u') if debug: PrintPermumation('R', ops[OP_R]) Assign(OP_INV_R, OP_R * (K * 2)) if debug: PrintPermumation('INV_R', ops[OP_INV_R]) Assign(OP_S, OP_INV_R + OP_INV_L + OP_R + OP_L) if debug: PrintPermumation('S', ops[OP_S]) Assign(OP_MOVE_LL1, OP_CW1 + OP_S + OP_CW1) Assign(OP_MOVE_LL4, OP_MOVE_LL1 * 4) Assign(OP_MOVE_LL16, OP_MOVE_LL4 * 4) Assign(OP_MOVE_L_THROW, OP_S * 2 + OP_CW1) if debug: PrintPermumation('MOVE_LL', ops[OP_MOVE_LL1]) PrintPermumation('MOVE_L_THROW', ops[OP_MOVE_L_THROW]) return ops, ops_codes def Solve(board, debug=False): ans = [] K, slot = KS(board) W = Width(K) if slot % W < K: t = 'r' * (K - slot % W) else: t = 'l' * (slot % W - K) if slot // W == 1: t = t + 'u' ans.append(t) ApplyOps(board, t) slot = Slot(board) assert slot == K ops, ops_codes = InitOps(K) def ApplyMultipleOp(num, items): for k, op in reversed(items): while num >= k: num -= k ApplyOps(board, op, ops) ans.append(op) for k in range(1, W * 2 - 1): view = LoopedView(board) if debug: print('=' * 20, k, '\n', view, file=sys.stderr) num_cw = Mod(+(K * 2 - view.index(k)), len(view)) CanonicalizeView(view) num_move = view.index(k) - k if debug: print(num_cw, num_move, file=sys.stderr) ApplyMultipleOp(num_cw, [(1, OP_CW1), (4, OP_CW4), (16, OP_CW16)]) if debug: PrintPermumation('t', board, slotval=-1) ApplyMultipleOp(num_move // 2, [(1, OP_MOVE_LL1), (4, OP_MOVE_LL4), (16, OP_MOVE_LL16)]) if debug: PrintPermumation('tt', board, slotval=-1) if num_move % 2 > 0: if k == W * 2 - 2: return False ApplyOps(board, OP_MOVE_L_THROW, ops) ans.append(OP_MOVE_L_THROW) view = LoopedView(board) num_cw = Mod(K * 3 + 1 - view.index(0), len(view)) ApplyMultipleOp(num_cw, [(1, OP_CW1), (4, OP_CW4), (16, OP_CW16)]) if debug: PrintPermumation('ttt', board, slotval=-1) f = 'r' * K + 'd' ApplyOps(board, f) ans.append(f) if debug: PrintPermumation('ttt', board, slotval=-1) print('SURGERY COMPLETE') print(''.join(ans)) for k, v in ops_codes.items(): print(k, v) print('DONE') return True #ops = InitOps(11, debug=True) #import random #board = list(range(10 * 4 + 2)) #random.shuffle(board) #print(board) ##board = [4, 35, 3, 15, 38, 1, 31, 7, 42, 26, 19, 27, 5, 11, 2, 33, 40, 16, 20, 12, 18, 24, 28, 6, 36, 22, 9, 29, 30, 43, 21, 10, 17, 0, 13, 8, 45, 25, 37, 32, 44, 14, 39, 34, 23, 41] #if True: # board[board.index(0)] = -1 # a = Solve(board, debug=True) # print(a, file=sys.stderr) for _ in range(int(sys.stdin.readline())): sys.stdin.readline() tr = lambda s: -1 if s == 'E' else int(s) row1 = list(map(tr, sys.stdin.readline().split())) row2 = list(map(tr, sys.stdin.readline().split())) if not Solve(row1 + row2): print('SURGERY FAILED') ```
3,464
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are an intergalactic surgeon and you have an alien patient. For the purposes of this problem, we can and we will model this patient's body using a 2 × (2k + 1) rectangular grid. The alien has 4k + 1 distinct organs, numbered 1 to 4k + 1. In healthy such aliens, the organs are arranged in a particular way. For example, here is how the organs of a healthy such alien would be positioned, when viewed from the top, for k = 4: <image> Here, the E represents empty space. In general, the first row contains organs 1 to 2k + 1 (in that order from left to right), and the second row contains organs 2k + 2 to 4k + 1 (in that order from left to right) and then empty space right after. Your patient's organs are complete, and inside their body, but they somehow got shuffled around! Your job, as an intergalactic surgeon, is to put everything back in its correct position. All organs of the alien must be in its body during the entire procedure. This means that at any point during the procedure, there is exactly one cell (in the grid) that is empty. In addition, you can only move organs around by doing one of the following things: * You can switch the positions of the empty space E with any organ to its immediate left or to its immediate right (if they exist). In reality, you do this by sliding the organ in question to the empty space; * You can switch the positions of the empty space E with any organ to its immediate top or its immediate bottom (if they exist) only if the empty space is on the leftmost column, rightmost column or in the centermost column. Again, you do this by sliding the organ in question to the empty space. Your job is to figure out a sequence of moves you must do during the surgical procedure in order to place back all 4k + 1 internal organs of your patient in the correct cells. If it is impossible to do so, you must say so. Input The first line of input contains a single integer t (1 ≤ t ≤ 4) denoting the number of test cases. The next lines contain descriptions of the test cases. Each test case consists of three lines. The first line contains a single integer k (1 ≤ k ≤ 15) which determines the size of the grid. Then two lines follow. Each of them contains 2k + 1 space-separated integers or the letter E. They describe the first and second rows of organs, respectively. It is guaranteed that all 4k + 1 organs are present and there is exactly one E. Output For each test case, first, print a single line containing either: * SURGERY COMPLETE if it is possible to place back all internal organs in the correct locations; * SURGERY FAILED if it is impossible. If it is impossible, then this is the only line of output for the test case. However, if it is possible, output a few more lines describing the sequence of moves to place the organs in the correct locations. The sequence of moves will be a (possibly empty) string of letters u, d, l or r, representing sliding the organ that's directly above, below, to the left or to the right of the empty space, respectively, into the empty space. Print the sequence of moves in the following line, as such a string. For convenience, you may use shortcuts to reduce the size of your output. You may use uppercase letters as shortcuts for sequences of moves. For example, you could choose T to represent the string lddrr. These shortcuts may also include other shortcuts on their own! For example, you could choose E to represent TruT, etc. You may use any number of uppercase letters (including none) as shortcuts. The only requirements are the following: * The total length of all strings in your output for a single case is at most 10^4; * There must be no cycles involving the shortcuts that are reachable from the main sequence; * The resulting sequence of moves is finite, after expanding all shortcuts. Note that the final sequence of moves (after expanding) may be much longer than 10^4; the only requirement is that it's finite. As an example, if T = lddrr, E = TruT and R = rrr, then TurTlER expands to: * TurTlER * lddrrurTlER * lddrrurlddrrlER * lddrrurlddrrlTruTR * lddrrurlddrrllddrrruTR * lddrrurlddrrllddrrrulddrrR * lddrrurlddrrllddrrrulddrrrrr To use shortcuts, print each one of them in a single line as the uppercase letter, then space, and then the string that this shortcut represents. They may be printed in any order. At the end of all of those, print a single line containing DONE. Note: You still need to print DONE even if you don't plan on using shortcuts. Your sequence does not need to be the shortest. Any valid sequence of moves (satisfying the requirements above) will be accepted. Example Input 2 3 1 2 3 5 6 E 7 8 9 10 4 11 12 13 11 34 45 6 22 16 43 38 44 5 4 41 14 7 29 28 19 9 18 42 8 17 33 1 E 15 40 36 31 24 10 2 21 11 32 23 30 27 35 25 13 12 39 37 26 20 3 Output SURGERY COMPLETE IR R SrS S rr I lldll DONE SURGERY FAILED Note There are three shortcuts defined in the first sample output: * R = SrS * S = rr * I = lldll The sequence of moves is IR and it expands to: * IR * lldllR * lldllSrS * lldllrrrS * lldllrrrrr Submitted Solution: ``` import sys OP_CW1 = 'A' OP_CW4 = 'B' OP_CW16 = 'C' OP_CCW = 'E' OP_L = 'U' OP_INV_L = 'V' OP_R = 'W' OP_INV_R = 'X' OP_S = 'S' OP_MOVE_LL1 = 'O' OP_MOVE_LL4 = 'P' OP_MOVE_LL16 = 'Q' OP_MOVE_L_THROW = 'R' def GetK(board): return len(board) // 4 def Slot(board, slotval=-1): return board.index(slotval) def KS(board, slotval=-1): return GetK(board), Slot(board, slotval) def Width(K): return K * 2 + 1 def PrintPermumation(head, board, slotval=None): K = GetK(board) W = Width(K) if slotval is None: slotval = K slot = Slot(board, slotval) print(head, '===', file=sys.stderr) tostr = lambda x: 'EE' if x == slotval else '%2d' % x for row in [board[:W], board[W:]]: print(' '.join(tostr(x) for x in row), file=sys.stderr) def ApplyOps(board, seq, ops=None, slotval=-1): K, slot = KS(board, slotval) W = Width(K) for c in seq: if c == 'l': assert slot % W > 0, slot s1 = slot - 1 elif c == 'r': assert slot % W + 1 < W, slot s1 = slot + 1 elif c == 'd': assert slot % W in [0, K, K * 2], slot assert slot // W == 0 s1 = slot + W elif c == 'u': assert slot % W in [0, K, K * 2], slot assert slot // W == 1 s1 = slot - W else: s1 = None if s1 is not None: board[s1], board[slot] = board[slot], board[s1] else: P = ops[c] tmp = board[:] for i in range(len(board)): board[i] = tmp[P[i]] slot = Slot(board, slotval) def LoopedView(board): K, slot = KS(board) W = Width(slot) assert slot == K def translate(x): if x == -1: return x if x <= W: return x - 1 # W+1 -> 2W-2 return 3 * W - 1 - x r = [] for rng in [range(slot + 1, W), reversed(range(W, W * 2)), range(0, slot)]: for i in rng: r.append(translate(board[i])) return r def Mod(x, m): x %= m if x < 0: x += m return x def CanonicalizeView(view): i = view.index(0) view[:] = view[i:] + view[:i] def ToPermutation(K, ops, seq): board = list(range(K * 4 + 2)) ApplyOps(board, seq, ops, slotval=K) return board def InitOps(K, debug=False): W = Width(K) ops = {} ops_codes = {} def ToP(seq): return ToPermutation(K, ops, seq) def Assign(rep, seq): ops[rep] = ToP(seq) ops_codes[rep] = seq Assign(OP_CW1, 'l' * K + 'd' + 'r' * (K * 2) + 'u' + 'l' * K) if debug: PrintPermumation('CW1', ops[OP_CW1]) Assign(OP_CW4, OP_CW1 * 4) if debug: PrintPermumation('CW4', ops[OP_CW4]) Assign(OP_CW16, OP_CW4 * 4) Assign(OP_CCW, OP_CW1 * (W * 2 - 2)) if debug: PrintPermumation('CCW', ops[OP_CCW]) Assign(OP_L, 'l' * K + 'd' + 'r' * K + 'u') if debug: PrintPermumation('L', ops[OP_L]) Assign(OP_INV_L, OP_L * (K * 2)) if debug: PrintPermumation('INV_L', ops[OP_INV_L]) Assign(OP_R, 'r' * K + 'd' + 'l' * K + 'u') if debug: PrintPermumation('R', ops[OP_R]) Assign(OP_INV_R, OP_R * (K * 2)) if debug: PrintPermumation('INV_R', ops[OP_INV_R]) Assign(OP_S, OP_INV_R + OP_INV_L + OP_R + OP_L) if debug: PrintPermumation('S', ops[OP_S]) Assign(OP_MOVE_LL1, OP_CW1 + OP_S + OP_CW1) Assign(OP_MOVE_LL4, OP_MOVE_LL1 * 4) Assign(OP_MOVE_LL16, OP_MOVE_LL4 * 4) Assign(OP_MOVE_L_THROW, OP_S * 2 + OP_CW1) if debug: PrintPermumation('MOVE_LL', ops[OP_MOVE_LL1]) PrintPermumation('MOVE_L_THROW', ops[OP_MOVE_L_THROW]) return ops, ops_codes def Solve(board, debug=False): ans = [] K, slot = KS(board) W = Width(K) if slot % W < K: t = 'r' * (K - slot % W) else: t = 'l' * (slot % W - K) if slot // W == 1: t = t + 'u' ans.append(t) ApplyOps(board, t) slot = Slot(board) assert slot == K ops, ops_codes = InitOps(K) def ApplyMultipleOp(num, items): for k, op in reversed(items): while num >= k: num -= k ApplyOps(board, op, ops) ans.append(op) for k in range(1, W * 2 - 1): view = LoopedView(board) if debug: print('=' * 20, k, '\n', view, file=sys.stderr) num_cw = Mod(+(K * 2 - view.index(k)), len(view)) CanonicalizeView(view) num_move = view.index(k) - k if debug: print(num_cw, num_move, file=sys.stderr) ApplyMultipleOp(num_cw, [(1, OP_CW1), (4, OP_CW4), (16, OP_CW16)]) if debug: PrintPermumation('t', board, slotval=-1) ApplyMultipleOp(num_move // 2, [(1, OP_MOVE_LL1), (4, OP_MOVE_LL4), (16, OP_MOVE_LL16)]) if debug: PrintPermumation('tt', board, slotval=-1) if num_move % 2 > 0: if k == W * 2 - 2: return False ApplyOps(board, OP_MOVE_L_THROW, ops) ans.append(OP_MOVE_L_THROW) view = LoopedView(board) num_cw = Mod(K * 3 + 1 - view.index(0), len(view)) ApplyMultipleOp(num_cw, [(1, OP_CW1), (4, OP_CW4), (16, OP_CW16)]) if debug: PrintPermumation('ttt', board, slotval=-1) f = 'r' * K + 'd' ApplyOps(board, f) ans.append(f) if debug: PrintPermumation('ttt', board, slotval=-1) print('SURGERY COMPLETE') print(''.join(ans)) for k, v in ops_codes.items(): print(k, v) return True #ops = InitOps(11, debug=True) #import random #board = list(range(10 * 4 + 2)) #random.shuffle(board) #print(board) ##board = [4, 35, 3, 15, 38, 1, 31, 7, 42, 26, 19, 27, 5, 11, 2, 33, 40, 16, 20, 12, 18, 24, 28, 6, 36, 22, 9, 29, 30, 43, 21, 10, 17, 0, 13, 8, 45, 25, 37, 32, 44, 14, 39, 34, 23, 41] #if True: # board[board.index(0)] = -1 # a = Solve(board, debug=True) # print(a, file=sys.stderr) for _ in range(int(sys.stdin.readline())): sys.stdin.readline() tr = lambda s: -1 if s == 'E' else int(s) row1 = list(map(tr, sys.stdin.readline().split())) row2 = list(map(tr, sys.stdin.readline().split())) if not Solve(row1 + row2): print('SURGERY FAILED') ``` No
3,465
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are an intergalactic surgeon and you have an alien patient. For the purposes of this problem, we can and we will model this patient's body using a 2 × (2k + 1) rectangular grid. The alien has 4k + 1 distinct organs, numbered 1 to 4k + 1. In healthy such aliens, the organs are arranged in a particular way. For example, here is how the organs of a healthy such alien would be positioned, when viewed from the top, for k = 4: <image> Here, the E represents empty space. In general, the first row contains organs 1 to 2k + 1 (in that order from left to right), and the second row contains organs 2k + 2 to 4k + 1 (in that order from left to right) and then empty space right after. Your patient's organs are complete, and inside their body, but they somehow got shuffled around! Your job, as an intergalactic surgeon, is to put everything back in its correct position. All organs of the alien must be in its body during the entire procedure. This means that at any point during the procedure, there is exactly one cell (in the grid) that is empty. In addition, you can only move organs around by doing one of the following things: * You can switch the positions of the empty space E with any organ to its immediate left or to its immediate right (if they exist). In reality, you do this by sliding the organ in question to the empty space; * You can switch the positions of the empty space E with any organ to its immediate top or its immediate bottom (if they exist) only if the empty space is on the leftmost column, rightmost column or in the centermost column. Again, you do this by sliding the organ in question to the empty space. Your job is to figure out a sequence of moves you must do during the surgical procedure in order to place back all 4k + 1 internal organs of your patient in the correct cells. If it is impossible to do so, you must say so. Input The first line of input contains a single integer t (1 ≤ t ≤ 4) denoting the number of test cases. The next lines contain descriptions of the test cases. Each test case consists of three lines. The first line contains a single integer k (1 ≤ k ≤ 15) which determines the size of the grid. Then two lines follow. Each of them contains 2k + 1 space-separated integers or the letter E. They describe the first and second rows of organs, respectively. It is guaranteed that all 4k + 1 organs are present and there is exactly one E. Output For each test case, first, print a single line containing either: * SURGERY COMPLETE if it is possible to place back all internal organs in the correct locations; * SURGERY FAILED if it is impossible. If it is impossible, then this is the only line of output for the test case. However, if it is possible, output a few more lines describing the sequence of moves to place the organs in the correct locations. The sequence of moves will be a (possibly empty) string of letters u, d, l or r, representing sliding the organ that's directly above, below, to the left or to the right of the empty space, respectively, into the empty space. Print the sequence of moves in the following line, as such a string. For convenience, you may use shortcuts to reduce the size of your output. You may use uppercase letters as shortcuts for sequences of moves. For example, you could choose T to represent the string lddrr. These shortcuts may also include other shortcuts on their own! For example, you could choose E to represent TruT, etc. You may use any number of uppercase letters (including none) as shortcuts. The only requirements are the following: * The total length of all strings in your output for a single case is at most 10^4; * There must be no cycles involving the shortcuts that are reachable from the main sequence; * The resulting sequence of moves is finite, after expanding all shortcuts. Note that the final sequence of moves (after expanding) may be much longer than 10^4; the only requirement is that it's finite. As an example, if T = lddrr, E = TruT and R = rrr, then TurTlER expands to: * TurTlER * lddrrurTlER * lddrrurlddrrlER * lddrrurlddrrlTruTR * lddrrurlddrrllddrrruTR * lddrrurlddrrllddrrrulddrrR * lddrrurlddrrllddrrrulddrrrrr To use shortcuts, print each one of them in a single line as the uppercase letter, then space, and then the string that this shortcut represents. They may be printed in any order. At the end of all of those, print a single line containing DONE. Note: You still need to print DONE even if you don't plan on using shortcuts. Your sequence does not need to be the shortest. Any valid sequence of moves (satisfying the requirements above) will be accepted. Example Input 2 3 1 2 3 5 6 E 7 8 9 10 4 11 12 13 11 34 45 6 22 16 43 38 44 5 4 41 14 7 29 28 19 9 18 42 8 17 33 1 E 15 40 36 31 24 10 2 21 11 32 23 30 27 35 25 13 12 39 37 26 20 3 Output SURGERY COMPLETE IR R SrS S rr I lldll DONE SURGERY FAILED Note There are three shortcuts defined in the first sample output: * R = SrS * S = rr * I = lldll The sequence of moves is IR and it expands to: * IR * lldllR * lldllSrS * lldllrrrS * lldllrrrrr Submitted Solution: ``` def solve(kk,grid): sk = *range(kk * 2 + 2),*range(4 * kk + 1,2 * kk + 1,-1) flat = [sk[v] for v in grid[0] + grid[1][::-1] if v] dir = { 'L': 'l' * 2 * kk + 'u' + 'r' * 2 * kk + 'd', 'R': 'u' + 'l' * 2 * kk + 'd' + 'r' * 2 * kk, 'C': 'CC' + 'R' * (2 * kk + 1) + 'CC' + 'R' * (2 * kk + 2), 'F': 'R' * (kk - 1) + 'DD' + 'R' * (2 * kk + 1) + 'D' + 'L' * 2 * kk + 'DD' + 'L' * kk, 'G': 'FF' } [(i,j)] = [(i,j) for i in range(2) for j in range(2 * kk + 1) if grid[i][j] == 0] st = 'r' * (2 * kk - j) + 'd' * (1 - i) for i in range(2,4 * kk + 2): tt = flat.index(i) if tt >= 2: st += 'L' * (tt - 2) + 'GR' * (tt - 2) + 'G' flat = flat[tt - 1 : tt + 1] + flat[:tt - 1] + flat[tt + 1:] if tt >= 1: st += 'G' flat = flat[1 : 3] + flat[:1] + flat[3:] st += 'L' flat = flat[1:] + flat[:1] if flat[0] == 1: return st,dir def getline(): return [0 if x == 'E' else int(x) for x in input().split()] for case in range(int(input())): ret = solve(int(input()),[getline() for i in range(2)]) if ret is None: print('SURGERY FAILED') else: print('SURGERY COMPLETE') st,vv = ret print(st) for shortcut in vv.items() : print(*shortcut) print('DONE') ``` No
3,466
Provide tags and a correct Python 3 solution for this coding contest problem. There are n water tanks in a row, i-th of them contains a_i liters of water. The tanks are numbered from 1 to n from left to right. You can perform the following operation: choose some subsegment [l, r] (1≤ l ≤ r ≤ n), and redistribute water in tanks l, l+1, ..., r evenly. In other words, replace each of a_l, a_{l+1}, ..., a_r by \frac{a_l + a_{l+1} + ... + a_r}{r-l+1}. For example, if for volumes [1, 3, 6, 7] you choose l = 2, r = 3, new volumes of water will be [1, 4.5, 4.5, 7]. You can perform this operation any number of times. What is the lexicographically smallest sequence of volumes of water that you can achieve? As a reminder: A sequence a is lexicographically smaller than a sequence b of the same length if and only if the following holds: in the first (leftmost) position where a and b differ, the sequence a has a smaller element than the corresponding element in b. Input The first line contains an integer n (1 ≤ n ≤ 10^6) — the number of water tanks. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^6) — initial volumes of water in the water tanks, in liters. Because of large input, reading input as doubles is not recommended. Output Print the lexicographically smallest sequence you can get. In the i-th line print the final volume of water in the i-th tank. Your answer is considered correct if the absolute or relative error of each a_i does not exceed 10^{-9}. Formally, let your answer be a_1, a_2, ..., a_n, and the jury's answer be b_1, b_2, ..., b_n. Your answer is accepted if and only if \frac{|a_i - b_i|}{max{(1, |b_i|)}} ≤ 10^{-9} for each i. Examples Input 4 7 5 5 7 Output 5.666666667 5.666666667 5.666666667 7.000000000 Input 5 7 8 8 10 12 Output 7.000000000 8.000000000 8.000000000 10.000000000 12.000000000 Input 10 3 9 5 5 1 7 5 3 8 7 Output 3.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 7.500000000 7.500000000 Note In the first sample, you can get the sequence by applying the operation for subsegment [1, 3]. In the second sample, you can't get any lexicographically smaller sequence. Tags: data structures, geometry, greedy Correct Solution: ``` from collections import deque import sys input = sys.stdin.readline n = int(input()) a = list(map(int, input().split())) q_num = deque() q_len = deque() for i in range(n): num_0 = a[i] len_0 = 1 while True: if len(q_num) == 0: q_num.append(num_0) q_len.append(len_0) break num_1, len_1 = q_num[-1], q_len[-1] len_new = len_1 + len_0 num_new = (num_1 * len_1 + num_0 * len_0) / (len_new) if num_0 < num_new: q_num.pop() q_len.pop() num_0 = num_new len_0 = len_new else: q_num.append(num_0) q_len.append(len_0) break while q_len: num_0 = q_num.popleft() len_0 = q_len.popleft() print((str(num_0)+"\n")*len_0, end="") ```
3,467
Provide tags and a correct Python 3 solution for this coding contest problem. There are n water tanks in a row, i-th of them contains a_i liters of water. The tanks are numbered from 1 to n from left to right. You can perform the following operation: choose some subsegment [l, r] (1≤ l ≤ r ≤ n), and redistribute water in tanks l, l+1, ..., r evenly. In other words, replace each of a_l, a_{l+1}, ..., a_r by \frac{a_l + a_{l+1} + ... + a_r}{r-l+1}. For example, if for volumes [1, 3, 6, 7] you choose l = 2, r = 3, new volumes of water will be [1, 4.5, 4.5, 7]. You can perform this operation any number of times. What is the lexicographically smallest sequence of volumes of water that you can achieve? As a reminder: A sequence a is lexicographically smaller than a sequence b of the same length if and only if the following holds: in the first (leftmost) position where a and b differ, the sequence a has a smaller element than the corresponding element in b. Input The first line contains an integer n (1 ≤ n ≤ 10^6) — the number of water tanks. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^6) — initial volumes of water in the water tanks, in liters. Because of large input, reading input as doubles is not recommended. Output Print the lexicographically smallest sequence you can get. In the i-th line print the final volume of water in the i-th tank. Your answer is considered correct if the absolute or relative error of each a_i does not exceed 10^{-9}. Formally, let your answer be a_1, a_2, ..., a_n, and the jury's answer be b_1, b_2, ..., b_n. Your answer is accepted if and only if \frac{|a_i - b_i|}{max{(1, |b_i|)}} ≤ 10^{-9} for each i. Examples Input 4 7 5 5 7 Output 5.666666667 5.666666667 5.666666667 7.000000000 Input 5 7 8 8 10 12 Output 7.000000000 8.000000000 8.000000000 10.000000000 12.000000000 Input 10 3 9 5 5 1 7 5 3 8 7 Output 3.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 7.500000000 7.500000000 Note In the first sample, you can get the sequence by applying the operation for subsegment [1, 3]. In the second sample, you can't get any lexicographically smaller sequence. Tags: data structures, geometry, greedy Correct Solution: ``` #! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=tf-8 # """ """ from operator import itemgetter from collections import Counter from collections import deque import sys input = sys.stdin.readline def solve(a): b = [-1] c = [1] for aa in a: b.append(aa) c.append(1) while b[-2]*c[-1] >= b[-1]*c[-2]: a1 = b.pop() i1 = c.pop() b[-1] = a1+b[-1] c[-1] = i1+c[-1] for i, aa in enumerate(b[1:]): cc = c[i+1] d = aa/cc ss = (str(d)+"\n")*cc sys.stdout.write(ss) def main(): n= int(input()) a = list(map(int,input().split())) solve(a) if __name__ == "__main__": main() ```
3,468
Provide tags and a correct Python 3 solution for this coding contest problem. There are n water tanks in a row, i-th of them contains a_i liters of water. The tanks are numbered from 1 to n from left to right. You can perform the following operation: choose some subsegment [l, r] (1≤ l ≤ r ≤ n), and redistribute water in tanks l, l+1, ..., r evenly. In other words, replace each of a_l, a_{l+1}, ..., a_r by \frac{a_l + a_{l+1} + ... + a_r}{r-l+1}. For example, if for volumes [1, 3, 6, 7] you choose l = 2, r = 3, new volumes of water will be [1, 4.5, 4.5, 7]. You can perform this operation any number of times. What is the lexicographically smallest sequence of volumes of water that you can achieve? As a reminder: A sequence a is lexicographically smaller than a sequence b of the same length if and only if the following holds: in the first (leftmost) position where a and b differ, the sequence a has a smaller element than the corresponding element in b. Input The first line contains an integer n (1 ≤ n ≤ 10^6) — the number of water tanks. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^6) — initial volumes of water in the water tanks, in liters. Because of large input, reading input as doubles is not recommended. Output Print the lexicographically smallest sequence you can get. In the i-th line print the final volume of water in the i-th tank. Your answer is considered correct if the absolute or relative error of each a_i does not exceed 10^{-9}. Formally, let your answer be a_1, a_2, ..., a_n, and the jury's answer be b_1, b_2, ..., b_n. Your answer is accepted if and only if \frac{|a_i - b_i|}{max{(1, |b_i|)}} ≤ 10^{-9} for each i. Examples Input 4 7 5 5 7 Output 5.666666667 5.666666667 5.666666667 7.000000000 Input 5 7 8 8 10 12 Output 7.000000000 8.000000000 8.000000000 10.000000000 12.000000000 Input 10 3 9 5 5 1 7 5 3 8 7 Output 3.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 7.500000000 7.500000000 Note In the first sample, you can get the sequence by applying the operation for subsegment [1, 3]. In the second sample, you can't get any lexicographically smaller sequence. Tags: data structures, geometry, greedy Correct Solution: ``` # -*- coding: utf-8 -*- import sys def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e] * d for j 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') # sys.setrecursionlimit(10 ** 9) INF = 10 ** 18 MOD = 10 ** 9 + 7 N = INT() A = LIST() stack = [] for i, a in enumerate(A): stack.append((a, 1)) while len(stack) >= 2 and stack[-2][0] > stack[-1][0]: a1, cnt1 = stack.pop() a2, cnt2 = stack.pop() merged = (a1*cnt1+a2*cnt2) / (cnt1+cnt2) stack.append((merged, cnt1+cnt2)) for a, cnt in stack: print((str(a) + '\n') * cnt, end='') ```
3,469
Provide tags and a correct Python 3 solution for this coding contest problem. There are n water tanks in a row, i-th of them contains a_i liters of water. The tanks are numbered from 1 to n from left to right. You can perform the following operation: choose some subsegment [l, r] (1≤ l ≤ r ≤ n), and redistribute water in tanks l, l+1, ..., r evenly. In other words, replace each of a_l, a_{l+1}, ..., a_r by \frac{a_l + a_{l+1} + ... + a_r}{r-l+1}. For example, if for volumes [1, 3, 6, 7] you choose l = 2, r = 3, new volumes of water will be [1, 4.5, 4.5, 7]. You can perform this operation any number of times. What is the lexicographically smallest sequence of volumes of water that you can achieve? As a reminder: A sequence a is lexicographically smaller than a sequence b of the same length if and only if the following holds: in the first (leftmost) position where a and b differ, the sequence a has a smaller element than the corresponding element in b. Input The first line contains an integer n (1 ≤ n ≤ 10^6) — the number of water tanks. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^6) — initial volumes of water in the water tanks, in liters. Because of large input, reading input as doubles is not recommended. Output Print the lexicographically smallest sequence you can get. In the i-th line print the final volume of water in the i-th tank. Your answer is considered correct if the absolute or relative error of each a_i does not exceed 10^{-9}. Formally, let your answer be a_1, a_2, ..., a_n, and the jury's answer be b_1, b_2, ..., b_n. Your answer is accepted if and only if \frac{|a_i - b_i|}{max{(1, |b_i|)}} ≤ 10^{-9} for each i. Examples Input 4 7 5 5 7 Output 5.666666667 5.666666667 5.666666667 7.000000000 Input 5 7 8 8 10 12 Output 7.000000000 8.000000000 8.000000000 10.000000000 12.000000000 Input 10 3 9 5 5 1 7 5 3 8 7 Output 3.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 7.500000000 7.500000000 Note In the first sample, you can get the sequence by applying the operation for subsegment [1, 3]. In the second sample, you can't get any lexicographically smaller sequence. Tags: data structures, geometry, greedy Correct Solution: ``` from math import factorial from collections import Counter from heapq import heapify, heappop, heappush from sys import stdin def RL(): return map(int, stdin.readline().rstrip().split() ) def comb(n, m): return factorial(n)/(factorial(m)*factorial(n-m)) if n>=m else 0 def perm(n, m): return factorial(n)//(factorial(n-m)) if n>=m else 0 def mdis(x1, y1, x2, y2): return abs(x1-x2) + abs(y1-y2) mod = 1000000007 INF = float('inf') # ------------------------------ def main(): n = int(input()) arr = [int(i) for i in input().split()] sm = [0.0] for i in arr: sm.append(sm[-1]+i) # mean = lambda a, b: (sm[b]-sm[a])/(b-a) def mean(t): i, j = t return (sm[j] - sm[i]) / (j - i) stack = [] for i in range(n): # print(stack) stack.append((i, i+1)) while len(stack)>1 and mean(stack[-2])>=mean(stack[-1]): a, b = stack.pop() c, d = stack.pop() stack.append((c, b)) res = [0.0]*n for n, v in stack: m = mean((n, v)) for i in range(n, v): res[i] = m print(*res) # https://github.com/cheran-senthil/PyRival/blob/master/templates/template_py3.py import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": main() ```
3,470
Provide tags and a correct Python 3 solution for this coding contest problem. There are n water tanks in a row, i-th of them contains a_i liters of water. The tanks are numbered from 1 to n from left to right. You can perform the following operation: choose some subsegment [l, r] (1≤ l ≤ r ≤ n), and redistribute water in tanks l, l+1, ..., r evenly. In other words, replace each of a_l, a_{l+1}, ..., a_r by \frac{a_l + a_{l+1} + ... + a_r}{r-l+1}. For example, if for volumes [1, 3, 6, 7] you choose l = 2, r = 3, new volumes of water will be [1, 4.5, 4.5, 7]. You can perform this operation any number of times. What is the lexicographically smallest sequence of volumes of water that you can achieve? As a reminder: A sequence a is lexicographically smaller than a sequence b of the same length if and only if the following holds: in the first (leftmost) position where a and b differ, the sequence a has a smaller element than the corresponding element in b. Input The first line contains an integer n (1 ≤ n ≤ 10^6) — the number of water tanks. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^6) — initial volumes of water in the water tanks, in liters. Because of large input, reading input as doubles is not recommended. Output Print the lexicographically smallest sequence you can get. In the i-th line print the final volume of water in the i-th tank. Your answer is considered correct if the absolute or relative error of each a_i does not exceed 10^{-9}. Formally, let your answer be a_1, a_2, ..., a_n, and the jury's answer be b_1, b_2, ..., b_n. Your answer is accepted if and only if \frac{|a_i - b_i|}{max{(1, |b_i|)}} ≤ 10^{-9} for each i. Examples Input 4 7 5 5 7 Output 5.666666667 5.666666667 5.666666667 7.000000000 Input 5 7 8 8 10 12 Output 7.000000000 8.000000000 8.000000000 10.000000000 12.000000000 Input 10 3 9 5 5 1 7 5 3 8 7 Output 3.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 7.500000000 7.500000000 Note In the first sample, you can get the sequence by applying the operation for subsegment [1, 3]. In the second sample, you can't get any lexicographically smaller sequence. Tags: data structures, geometry, greedy Correct Solution: ``` import os,io import sys input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline def main(): n=int(input()) a=list(map(int,input().split())) d=n+1 b=[a[0]*d+1] for i in range(1,n): if b[-1]//d==a[i]: b[-1]+=1 else: b.append(a[i]*d+1) bx,bi=divmod(b[0],d) bx*=bi s=[bx*d+bi] for ii in range(1,len(b)): cx,ci=divmod(b[ii],d) cx*=ci s.append(cx*d+ci) bx,bi=divmod(s[-2],d) cx,ci=divmod(s[-1],d) while cx*bi<bx*ci: s.pop() s[-1]=(bx+cx)*d+bi+ci if len(s)==1: break bx,bi=divmod(s[-2],d) cx,ci=divmod(s[-1],d) ans=[] for ii in range(len(s)): sx,si=divmod(s[ii],d) ans+=[str(sx/si)]*si print(" ".join(ans)) if __name__ == "__main__": main() ```
3,471
Provide tags and a correct Python 3 solution for this coding contest problem. There are n water tanks in a row, i-th of them contains a_i liters of water. The tanks are numbered from 1 to n from left to right. You can perform the following operation: choose some subsegment [l, r] (1≤ l ≤ r ≤ n), and redistribute water in tanks l, l+1, ..., r evenly. In other words, replace each of a_l, a_{l+1}, ..., a_r by \frac{a_l + a_{l+1} + ... + a_r}{r-l+1}. For example, if for volumes [1, 3, 6, 7] you choose l = 2, r = 3, new volumes of water will be [1, 4.5, 4.5, 7]. You can perform this operation any number of times. What is the lexicographically smallest sequence of volumes of water that you can achieve? As a reminder: A sequence a is lexicographically smaller than a sequence b of the same length if and only if the following holds: in the first (leftmost) position where a and b differ, the sequence a has a smaller element than the corresponding element in b. Input The first line contains an integer n (1 ≤ n ≤ 10^6) — the number of water tanks. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^6) — initial volumes of water in the water tanks, in liters. Because of large input, reading input as doubles is not recommended. Output Print the lexicographically smallest sequence you can get. In the i-th line print the final volume of water in the i-th tank. Your answer is considered correct if the absolute or relative error of each a_i does not exceed 10^{-9}. Formally, let your answer be a_1, a_2, ..., a_n, and the jury's answer be b_1, b_2, ..., b_n. Your answer is accepted if and only if \frac{|a_i - b_i|}{max{(1, |b_i|)}} ≤ 10^{-9} for each i. Examples Input 4 7 5 5 7 Output 5.666666667 5.666666667 5.666666667 7.000000000 Input 5 7 8 8 10 12 Output 7.000000000 8.000000000 8.000000000 10.000000000 12.000000000 Input 10 3 9 5 5 1 7 5 3 8 7 Output 3.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 7.500000000 7.500000000 Note In the first sample, you can get the sequence by applying the operation for subsegment [1, 3]. In the second sample, you can't get any lexicographically smaller sequence. Tags: data structures, geometry, greedy Correct Solution: ``` def main(): from sys import stdin,stdout ans = [] stdin.readline() for ai in map(int, map(int, stdin.readline().split())): cnt=1 while ans and ai*ans[-1][0]<=ans[-1][1]*cnt: c, r = ans.pop() ai+=r cnt+=c ans.append((cnt, ai)) for i, res in ans: m = str(res/i) stdout.write((m+"\n")*i) main() ```
3,472
Provide tags and a correct Python 3 solution for this coding contest problem. There are n water tanks in a row, i-th of them contains a_i liters of water. The tanks are numbered from 1 to n from left to right. You can perform the following operation: choose some subsegment [l, r] (1≤ l ≤ r ≤ n), and redistribute water in tanks l, l+1, ..., r evenly. In other words, replace each of a_l, a_{l+1}, ..., a_r by \frac{a_l + a_{l+1} + ... + a_r}{r-l+1}. For example, if for volumes [1, 3, 6, 7] you choose l = 2, r = 3, new volumes of water will be [1, 4.5, 4.5, 7]. You can perform this operation any number of times. What is the lexicographically smallest sequence of volumes of water that you can achieve? As a reminder: A sequence a is lexicographically smaller than a sequence b of the same length if and only if the following holds: in the first (leftmost) position where a and b differ, the sequence a has a smaller element than the corresponding element in b. Input The first line contains an integer n (1 ≤ n ≤ 10^6) — the number of water tanks. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^6) — initial volumes of water in the water tanks, in liters. Because of large input, reading input as doubles is not recommended. Output Print the lexicographically smallest sequence you can get. In the i-th line print the final volume of water in the i-th tank. Your answer is considered correct if the absolute or relative error of each a_i does not exceed 10^{-9}. Formally, let your answer be a_1, a_2, ..., a_n, and the jury's answer be b_1, b_2, ..., b_n. Your answer is accepted if and only if \frac{|a_i - b_i|}{max{(1, |b_i|)}} ≤ 10^{-9} for each i. Examples Input 4 7 5 5 7 Output 5.666666667 5.666666667 5.666666667 7.000000000 Input 5 7 8 8 10 12 Output 7.000000000 8.000000000 8.000000000 10.000000000 12.000000000 Input 10 3 9 5 5 1 7 5 3 8 7 Output 3.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 7.500000000 7.500000000 Note In the first sample, you can get the sequence by applying the operation for subsegment [1, 3]. In the second sample, you can't get any lexicographically smaller sequence. Tags: data structures, geometry, greedy Correct Solution: ``` def main(): import sys from collections import deque input = sys.stdin.buffer.readline N = int(input()) A = list(map(int, input().split())) st = deque() st_append = st.append st_append((A[0], 1)) for a in A[1:]: L = 1 while st[-1][0] >= a: b, n = st.pop() a = (a*L+b*n) / (n+L) L += n if len(st) == 0: break st_append((a, L)) while st: b, n = st.popleft() print((str(b) + '\n') * n, end='') if __name__ == '__main__': main() ```
3,473
Provide tags and a correct Python 3 solution for this coding contest problem. There are n water tanks in a row, i-th of them contains a_i liters of water. The tanks are numbered from 1 to n from left to right. You can perform the following operation: choose some subsegment [l, r] (1≤ l ≤ r ≤ n), and redistribute water in tanks l, l+1, ..., r evenly. In other words, replace each of a_l, a_{l+1}, ..., a_r by \frac{a_l + a_{l+1} + ... + a_r}{r-l+1}. For example, if for volumes [1, 3, 6, 7] you choose l = 2, r = 3, new volumes of water will be [1, 4.5, 4.5, 7]. You can perform this operation any number of times. What is the lexicographically smallest sequence of volumes of water that you can achieve? As a reminder: A sequence a is lexicographically smaller than a sequence b of the same length if and only if the following holds: in the first (leftmost) position where a and b differ, the sequence a has a smaller element than the corresponding element in b. Input The first line contains an integer n (1 ≤ n ≤ 10^6) — the number of water tanks. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^6) — initial volumes of water in the water tanks, in liters. Because of large input, reading input as doubles is not recommended. Output Print the lexicographically smallest sequence you can get. In the i-th line print the final volume of water in the i-th tank. Your answer is considered correct if the absolute or relative error of each a_i does not exceed 10^{-9}. Formally, let your answer be a_1, a_2, ..., a_n, and the jury's answer be b_1, b_2, ..., b_n. Your answer is accepted if and only if \frac{|a_i - b_i|}{max{(1, |b_i|)}} ≤ 10^{-9} for each i. Examples Input 4 7 5 5 7 Output 5.666666667 5.666666667 5.666666667 7.000000000 Input 5 7 8 8 10 12 Output 7.000000000 8.000000000 8.000000000 10.000000000 12.000000000 Input 10 3 9 5 5 1 7 5 3 8 7 Output 3.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 7.500000000 7.500000000 Note In the first sample, you can get the sequence by applying the operation for subsegment [1, 3]. In the second sample, you can't get any lexicographically smaller sequence. Tags: data structures, geometry, greedy Correct Solution: ``` def main(): n,*a=map(int,open(0).read().split()) d=n+1 b=[a[0]*d+1] for i in range(1,n): if b[-1]//d==a[i]: b[-1]+=1 else: b.append(a[i]*d+1) bx,bi=divmod(b[0],d) bx*=bi s=[bx*d+bi] for ii in range(1,len(b)): cx,ci=divmod(b[ii],d) cx*=ci s.append(cx*d+ci) bx,bi=divmod(s[-2],d) cx,ci=divmod(s[-1],d) while cx*bi<bx*ci: s.pop() s[-1]=(bx+cx)*d+bi+ci if len(s)==1: break bx,bi=divmod(s[-2],d) cx,ci=divmod(s[-1],d) ans=[] for ii in range(len(s)): sx,si=divmod(s[ii],d) ans+=[str(sx/si)]*si print(" ".join(ans)) if __name__ == "__main__": main() ```
3,474
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n water tanks in a row, i-th of them contains a_i liters of water. The tanks are numbered from 1 to n from left to right. You can perform the following operation: choose some subsegment [l, r] (1≤ l ≤ r ≤ n), and redistribute water in tanks l, l+1, ..., r evenly. In other words, replace each of a_l, a_{l+1}, ..., a_r by \frac{a_l + a_{l+1} + ... + a_r}{r-l+1}. For example, if for volumes [1, 3, 6, 7] you choose l = 2, r = 3, new volumes of water will be [1, 4.5, 4.5, 7]. You can perform this operation any number of times. What is the lexicographically smallest sequence of volumes of water that you can achieve? As a reminder: A sequence a is lexicographically smaller than a sequence b of the same length if and only if the following holds: in the first (leftmost) position where a and b differ, the sequence a has a smaller element than the corresponding element in b. Input The first line contains an integer n (1 ≤ n ≤ 10^6) — the number of water tanks. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^6) — initial volumes of water in the water tanks, in liters. Because of large input, reading input as doubles is not recommended. Output Print the lexicographically smallest sequence you can get. In the i-th line print the final volume of water in the i-th tank. Your answer is considered correct if the absolute or relative error of each a_i does not exceed 10^{-9}. Formally, let your answer be a_1, a_2, ..., a_n, and the jury's answer be b_1, b_2, ..., b_n. Your answer is accepted if and only if \frac{|a_i - b_i|}{max{(1, |b_i|)}} ≤ 10^{-9} for each i. Examples Input 4 7 5 5 7 Output 5.666666667 5.666666667 5.666666667 7.000000000 Input 5 7 8 8 10 12 Output 7.000000000 8.000000000 8.000000000 10.000000000 12.000000000 Input 10 3 9 5 5 1 7 5 3 8 7 Output 3.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 7.500000000 7.500000000 Note In the first sample, you can get the sequence by applying the operation for subsegment [1, 3]. In the second sample, you can't get any lexicographically smaller sequence. Submitted Solution: ``` import sys input = sys.stdin.buffer.readline n = int(input()) a = list(map(int, input().split())) stk = [] for i in a: now_sum = i now_cnt = 1 while stk and now_sum * stk[-1][1] < stk[-1][0] * now_cnt: temp_sum, temp_cnt = stk.pop() now_sum += temp_sum now_cnt += temp_cnt stk.append((now_sum, now_cnt)) for i in stk: temp_ans = str(i[0]/i[1]) for j in range(i[1]): print(temp_ans) ``` Yes
3,475
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n water tanks in a row, i-th of them contains a_i liters of water. The tanks are numbered from 1 to n from left to right. You can perform the following operation: choose some subsegment [l, r] (1≤ l ≤ r ≤ n), and redistribute water in tanks l, l+1, ..., r evenly. In other words, replace each of a_l, a_{l+1}, ..., a_r by \frac{a_l + a_{l+1} + ... + a_r}{r-l+1}. For example, if for volumes [1, 3, 6, 7] you choose l = 2, r = 3, new volumes of water will be [1, 4.5, 4.5, 7]. You can perform this operation any number of times. What is the lexicographically smallest sequence of volumes of water that you can achieve? As a reminder: A sequence a is lexicographically smaller than a sequence b of the same length if and only if the following holds: in the first (leftmost) position where a and b differ, the sequence a has a smaller element than the corresponding element in b. Input The first line contains an integer n (1 ≤ n ≤ 10^6) — the number of water tanks. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^6) — initial volumes of water in the water tanks, in liters. Because of large input, reading input as doubles is not recommended. Output Print the lexicographically smallest sequence you can get. In the i-th line print the final volume of water in the i-th tank. Your answer is considered correct if the absolute or relative error of each a_i does not exceed 10^{-9}. Formally, let your answer be a_1, a_2, ..., a_n, and the jury's answer be b_1, b_2, ..., b_n. Your answer is accepted if and only if \frac{|a_i - b_i|}{max{(1, |b_i|)}} ≤ 10^{-9} for each i. Examples Input 4 7 5 5 7 Output 5.666666667 5.666666667 5.666666667 7.000000000 Input 5 7 8 8 10 12 Output 7.000000000 8.000000000 8.000000000 10.000000000 12.000000000 Input 10 3 9 5 5 1 7 5 3 8 7 Output 3.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 7.500000000 7.500000000 Note In the first sample, you can get the sequence by applying the operation for subsegment [1, 3]. In the second sample, you can't get any lexicographically smaller sequence. Submitted Solution: ``` from sys import stdin, gettrace, stdout if not gettrace(): def input(): return next(stdin)[:-1] def main(): n = int(input()) aa = [int(a) for a in input().split()] sum = [0] for a in aa: sum.append(sum[-1] + a) def mean(i,j): return (sum[j] - sum[i])/(j - i) stk = [] for i in range(n): stk.append((i, i+1)) while len(stk) > 1 and mean(*stk[-2]) >= mean(*stk[-1]): _, j = stk.pop() i, _ = stk.pop() stk.append((i, j)) for i,j in stk: v = str(mean(i,j))+'\n' for k in range(j-i): stdout.write(v) if __name__ == "__main__": main() ``` Yes
3,476
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n water tanks in a row, i-th of them contains a_i liters of water. The tanks are numbered from 1 to n from left to right. You can perform the following operation: choose some subsegment [l, r] (1≤ l ≤ r ≤ n), and redistribute water in tanks l, l+1, ..., r evenly. In other words, replace each of a_l, a_{l+1}, ..., a_r by \frac{a_l + a_{l+1} + ... + a_r}{r-l+1}. For example, if for volumes [1, 3, 6, 7] you choose l = 2, r = 3, new volumes of water will be [1, 4.5, 4.5, 7]. You can perform this operation any number of times. What is the lexicographically smallest sequence of volumes of water that you can achieve? As a reminder: A sequence a is lexicographically smaller than a sequence b of the same length if and only if the following holds: in the first (leftmost) position where a and b differ, the sequence a has a smaller element than the corresponding element in b. Input The first line contains an integer n (1 ≤ n ≤ 10^6) — the number of water tanks. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^6) — initial volumes of water in the water tanks, in liters. Because of large input, reading input as doubles is not recommended. Output Print the lexicographically smallest sequence you can get. In the i-th line print the final volume of water in the i-th tank. Your answer is considered correct if the absolute or relative error of each a_i does not exceed 10^{-9}. Formally, let your answer be a_1, a_2, ..., a_n, and the jury's answer be b_1, b_2, ..., b_n. Your answer is accepted if and only if \frac{|a_i - b_i|}{max{(1, |b_i|)}} ≤ 10^{-9} for each i. Examples Input 4 7 5 5 7 Output 5.666666667 5.666666667 5.666666667 7.000000000 Input 5 7 8 8 10 12 Output 7.000000000 8.000000000 8.000000000 10.000000000 12.000000000 Input 10 3 9 5 5 1 7 5 3 8 7 Output 3.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 7.500000000 7.500000000 Note In the first sample, you can get the sequence by applying the operation for subsegment [1, 3]. In the second sample, you can't get any lexicographically smaller sequence. Submitted Solution: ``` # -*- coding: utf-8 -*- import sys def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e] * d for j 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') # sys.setrecursionlimit(10 ** 9) INF = 10 ** 18 MOD = 10 ** 9 + 7 N = INT() A = LIST() stack = [(A[0], 1)] for i, a in enumerate(A[1:], 1): stack.append((a, 1)) while len(stack) >= 2 and stack[-2][0] > stack[-1][0]: a1, cnt1 = stack.pop() a2, cnt2 = stack.pop() merged = (a1*cnt1+a2*cnt2) / (cnt1+cnt2) stack.append((merged, cnt1+cnt2)) ans = [] for a, cnt in stack: sys.stdout.write((str(a) + '\n') * cnt) ``` Yes
3,477
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n water tanks in a row, i-th of them contains a_i liters of water. The tanks are numbered from 1 to n from left to right. You can perform the following operation: choose some subsegment [l, r] (1≤ l ≤ r ≤ n), and redistribute water in tanks l, l+1, ..., r evenly. In other words, replace each of a_l, a_{l+1}, ..., a_r by \frac{a_l + a_{l+1} + ... + a_r}{r-l+1}. For example, if for volumes [1, 3, 6, 7] you choose l = 2, r = 3, new volumes of water will be [1, 4.5, 4.5, 7]. You can perform this operation any number of times. What is the lexicographically smallest sequence of volumes of water that you can achieve? As a reminder: A sequence a is lexicographically smaller than a sequence b of the same length if and only if the following holds: in the first (leftmost) position where a and b differ, the sequence a has a smaller element than the corresponding element in b. Input The first line contains an integer n (1 ≤ n ≤ 10^6) — the number of water tanks. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^6) — initial volumes of water in the water tanks, in liters. Because of large input, reading input as doubles is not recommended. Output Print the lexicographically smallest sequence you can get. In the i-th line print the final volume of water in the i-th tank. Your answer is considered correct if the absolute or relative error of each a_i does not exceed 10^{-9}. Formally, let your answer be a_1, a_2, ..., a_n, and the jury's answer be b_1, b_2, ..., b_n. Your answer is accepted if and only if \frac{|a_i - b_i|}{max{(1, |b_i|)}} ≤ 10^{-9} for each i. Examples Input 4 7 5 5 7 Output 5.666666667 5.666666667 5.666666667 7.000000000 Input 5 7 8 8 10 12 Output 7.000000000 8.000000000 8.000000000 10.000000000 12.000000000 Input 10 3 9 5 5 1 7 5 3 8 7 Output 3.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 7.500000000 7.500000000 Note In the first sample, you can get the sequence by applying the operation for subsegment [1, 3]. In the second sample, you can't get any lexicographically smaller sequence. Submitted Solution: ``` import io import os from collections import Counter, defaultdict, deque def solve(N, A): # Bruteforce just to see if logic is right. Will TLE for i in range(N): best = (A[i], i, i + 1) for j in range(i + 1, N + 1): avg = sum(A[i:j]) / (j - i) best = min(best, (avg, i, j)) if best[0] < A[i]: avg, i, j = best A[i:j] = [avg] * (j - i) return "\n".join(map(str, A)) def solve(N, A): # Answer is always monotonically increasing (suppose not, then you can average the decrease to get something lexicographically smaller) # Track the monotonically increasing heights and number of consecutive columns with that that height # For each new value seen, merge with a block with same height maintaining monotonic property # Amortized linear. Total number of appends is N. Total number of pops is limited by appends. blocks = [(0, 0)] def combine(block1, block2): h1, w1 = block1 h2, w2 = block2 total = h1 * w1 + h2 * w2 w = w1 + w2 return (total / w, w) for x in A: block = (x, 1) while True: combinedBlock = combine(blocks[-1], block) if combinedBlock[0] <= blocks[-1][0]: blocks.pop() block = combinedBlock else: blocks.append(block) break # It seems like if you try to do map(str, ...) on a list of 10^6 floats it will TLE ans = [] for h, w in blocks: val = str(h) ans.extend([val] * w) return "\n".join(ans) 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) ``` Yes
3,478
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n water tanks in a row, i-th of them contains a_i liters of water. The tanks are numbered from 1 to n from left to right. You can perform the following operation: choose some subsegment [l, r] (1≤ l ≤ r ≤ n), and redistribute water in tanks l, l+1, ..., r evenly. In other words, replace each of a_l, a_{l+1}, ..., a_r by \frac{a_l + a_{l+1} + ... + a_r}{r-l+1}. For example, if for volumes [1, 3, 6, 7] you choose l = 2, r = 3, new volumes of water will be [1, 4.5, 4.5, 7]. You can perform this operation any number of times. What is the lexicographically smallest sequence of volumes of water that you can achieve? As a reminder: A sequence a is lexicographically smaller than a sequence b of the same length if and only if the following holds: in the first (leftmost) position where a and b differ, the sequence a has a smaller element than the corresponding element in b. Input The first line contains an integer n (1 ≤ n ≤ 10^6) — the number of water tanks. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^6) — initial volumes of water in the water tanks, in liters. Because of large input, reading input as doubles is not recommended. Output Print the lexicographically smallest sequence you can get. In the i-th line print the final volume of water in the i-th tank. Your answer is considered correct if the absolute or relative error of each a_i does not exceed 10^{-9}. Formally, let your answer be a_1, a_2, ..., a_n, and the jury's answer be b_1, b_2, ..., b_n. Your answer is accepted if and only if \frac{|a_i - b_i|}{max{(1, |b_i|)}} ≤ 10^{-9} for each i. Examples Input 4 7 5 5 7 Output 5.666666667 5.666666667 5.666666667 7.000000000 Input 5 7 8 8 10 12 Output 7.000000000 8.000000000 8.000000000 10.000000000 12.000000000 Input 10 3 9 5 5 1 7 5 3 8 7 Output 3.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 7.500000000 7.500000000 Note In the first sample, you can get the sequence by applying the operation for subsegment [1, 3]. In the second sample, you can't get any lexicographically smaller sequence. Submitted Solution: ``` from math import factorial from collections import Counter from heapq import heapify, heappop, heappush from sys import stdin def RL(): return map(int, stdin.readline().rstrip().split() ) def comb(n, m): return factorial(n)/(factorial(m)*factorial(n-m)) if n>=m else 0 def perm(n, m): return factorial(n)//(factorial(n-m)) if n>=m else 0 def mdis(x1, y1, x2, y2): return abs(x1-x2) + abs(y1-y2) mod = 1000000007 INF = float('inf') # ------------------------------ n = int(input()) arr = list(RL()) stack = [] for i in arr: if not stack: stack.append((1, i)) else: lstn, lstv = stack[-1] if (lstv*lstn+i)/(lstn+1)<=lstv: stack.pop() stack.append((lstn+1, (lstv*lstn+i)/(lstn+1))) else: stack.append((1, i)) for n, v in stack: for i in range(n): print(v) ``` No
3,479
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n water tanks in a row, i-th of them contains a_i liters of water. The tanks are numbered from 1 to n from left to right. You can perform the following operation: choose some subsegment [l, r] (1≤ l ≤ r ≤ n), and redistribute water in tanks l, l+1, ..., r evenly. In other words, replace each of a_l, a_{l+1}, ..., a_r by \frac{a_l + a_{l+1} + ... + a_r}{r-l+1}. For example, if for volumes [1, 3, 6, 7] you choose l = 2, r = 3, new volumes of water will be [1, 4.5, 4.5, 7]. You can perform this operation any number of times. What is the lexicographically smallest sequence of volumes of water that you can achieve? As a reminder: A sequence a is lexicographically smaller than a sequence b of the same length if and only if the following holds: in the first (leftmost) position where a and b differ, the sequence a has a smaller element than the corresponding element in b. Input The first line contains an integer n (1 ≤ n ≤ 10^6) — the number of water tanks. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^6) — initial volumes of water in the water tanks, in liters. Because of large input, reading input as doubles is not recommended. Output Print the lexicographically smallest sequence you can get. In the i-th line print the final volume of water in the i-th tank. Your answer is considered correct if the absolute or relative error of each a_i does not exceed 10^{-9}. Formally, let your answer be a_1, a_2, ..., a_n, and the jury's answer be b_1, b_2, ..., b_n. Your answer is accepted if and only if \frac{|a_i - b_i|}{max{(1, |b_i|)}} ≤ 10^{-9} for each i. Examples Input 4 7 5 5 7 Output 5.666666667 5.666666667 5.666666667 7.000000000 Input 5 7 8 8 10 12 Output 7.000000000 8.000000000 8.000000000 10.000000000 12.000000000 Input 10 3 9 5 5 1 7 5 3 8 7 Output 3.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 7.500000000 7.500000000 Note In the first sample, you can get the sequence by applying the operation for subsegment [1, 3]. In the second sample, you can't get any lexicographically smaller sequence. Submitted Solution: ``` from math import factorial from collections import Counter from heapq import heapify, heappop, heappush from sys import stdin def RL(): return map(int, stdin.readline().rstrip().split() ) def comb(n, m): return factorial(n)/(factorial(m)*factorial(n-m)) if n>=m else 0 def perm(n, m): return factorial(n)//(factorial(n-m)) if n>=m else 0 def mdis(x1, y1, x2, y2): return abs(x1-x2) + abs(y1-y2) mod = 1000000007 INF = float('inf') # ------------------------------ n = int(input()) arr = list(RL()) sm = [0] for i in arr: sm.append(sm[-1]+i) i = 1 while i<n: # print(arr, sm) mi, rag = INF, (-1, -1) for j in range(i+1, n+1): fir = arr[i-1] # print(sm[j] - sm[i-1]) avg = (sm[j] - sm[i-1])/(j-i+1) if avg<fir: # print(avg, rag) if avg<=mi: mi = avg rag = (i-1, j-1) if mi!=INF: for k in range(rag[0], rag[1] + 1): arr[k] = mi i = rag[1]+1 else: i+=1 for i in arr: print(i) ``` No
3,480
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n water tanks in a row, i-th of them contains a_i liters of water. The tanks are numbered from 1 to n from left to right. You can perform the following operation: choose some subsegment [l, r] (1≤ l ≤ r ≤ n), and redistribute water in tanks l, l+1, ..., r evenly. In other words, replace each of a_l, a_{l+1}, ..., a_r by \frac{a_l + a_{l+1} + ... + a_r}{r-l+1}. For example, if for volumes [1, 3, 6, 7] you choose l = 2, r = 3, new volumes of water will be [1, 4.5, 4.5, 7]. You can perform this operation any number of times. What is the lexicographically smallest sequence of volumes of water that you can achieve? As a reminder: A sequence a is lexicographically smaller than a sequence b of the same length if and only if the following holds: in the first (leftmost) position where a and b differ, the sequence a has a smaller element than the corresponding element in b. Input The first line contains an integer n (1 ≤ n ≤ 10^6) — the number of water tanks. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^6) — initial volumes of water in the water tanks, in liters. Because of large input, reading input as doubles is not recommended. Output Print the lexicographically smallest sequence you can get. In the i-th line print the final volume of water in the i-th tank. Your answer is considered correct if the absolute or relative error of each a_i does not exceed 10^{-9}. Formally, let your answer be a_1, a_2, ..., a_n, and the jury's answer be b_1, b_2, ..., b_n. Your answer is accepted if and only if \frac{|a_i - b_i|}{max{(1, |b_i|)}} ≤ 10^{-9} for each i. Examples Input 4 7 5 5 7 Output 5.666666667 5.666666667 5.666666667 7.000000000 Input 5 7 8 8 10 12 Output 7.000000000 8.000000000 8.000000000 10.000000000 12.000000000 Input 10 3 9 5 5 1 7 5 3 8 7 Output 3.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 7.500000000 7.500000000 Note In the first sample, you can get the sequence by applying the operation for subsegment [1, 3]. In the second sample, you can't get any lexicographically smaller sequence. Submitted Solution: ``` from sys import stdin, gettrace if not gettrace(): def input(): return next(stdin)[:-1] def main(): n = int(input()) aa = [int(a) for a in input().split()] sum = aa[0] count = 1 start = 0 for i,a in enumerate(aa[1:], 1): avr = sum / count if a > avr: aa[start:i] = [avr] * (i - start) start = i sum = a count = 1 else: count+=1 sum += a aa[start:n] = [sum/count] * (n - start) for a in aa: print(a) if __name__ == "__main__": main() ``` No
3,481
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n water tanks in a row, i-th of them contains a_i liters of water. The tanks are numbered from 1 to n from left to right. You can perform the following operation: choose some subsegment [l, r] (1≤ l ≤ r ≤ n), and redistribute water in tanks l, l+1, ..., r evenly. In other words, replace each of a_l, a_{l+1}, ..., a_r by \frac{a_l + a_{l+1} + ... + a_r}{r-l+1}. For example, if for volumes [1, 3, 6, 7] you choose l = 2, r = 3, new volumes of water will be [1, 4.5, 4.5, 7]. You can perform this operation any number of times. What is the lexicographically smallest sequence of volumes of water that you can achieve? As a reminder: A sequence a is lexicographically smaller than a sequence b of the same length if and only if the following holds: in the first (leftmost) position where a and b differ, the sequence a has a smaller element than the corresponding element in b. Input The first line contains an integer n (1 ≤ n ≤ 10^6) — the number of water tanks. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^6) — initial volumes of water in the water tanks, in liters. Because of large input, reading input as doubles is not recommended. Output Print the lexicographically smallest sequence you can get. In the i-th line print the final volume of water in the i-th tank. Your answer is considered correct if the absolute or relative error of each a_i does not exceed 10^{-9}. Formally, let your answer be a_1, a_2, ..., a_n, and the jury's answer be b_1, b_2, ..., b_n. Your answer is accepted if and only if \frac{|a_i - b_i|}{max{(1, |b_i|)}} ≤ 10^{-9} for each i. Examples Input 4 7 5 5 7 Output 5.666666667 5.666666667 5.666666667 7.000000000 Input 5 7 8 8 10 12 Output 7.000000000 8.000000000 8.000000000 10.000000000 12.000000000 Input 10 3 9 5 5 1 7 5 3 8 7 Output 3.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 7.500000000 7.500000000 Note In the first sample, you can get the sequence by applying the operation for subsegment [1, 3]. In the second sample, you can't get any lexicographically smaller sequence. Submitted Solution: ``` #! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=tf-8 # """ """ from operator import itemgetter from collections import Counter import sys input = sys.stdin.readline def solve(a): a.reverse() b = [-1] c = [1] while a: aa = a.pop() b.append(aa) c.append(1) while b[-2]*c[-1] >= b[-1]*c[-2]: a1 = b.pop() i1 = c.pop() a2 = b.pop() i2 = c.pop() b.append((a1+a2)) c.append((i1+i2)) for i, aa in enumerate(b): cc = c[i] d = aa/cc [print(d) for j in range(cc)] def main(): n= int(input()) a = list(map(int,input().split())) solve(a) if __name__ == "__main__": main() ``` No
3,482
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree consisting of n vertices. A tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a color assigned to it (a_v = 1 if the vertex v is white and 0 if the vertex v is black). You have to solve the following problem for each vertex v: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex v? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cnt_w white vertices and cnt_b black vertices, you have to maximize cnt_w - cnt_b. Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree. The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 1), where a_i is the color of the i-th vertex. Each of the next n-1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i). It is guaranteed that the given edges form a tree. Output Print n integers res_1, res_2, ..., res_n, where res_i is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex i. Examples Input 9 0 1 1 1 0 0 0 0 1 1 2 1 3 3 4 3 5 2 6 4 7 6 8 5 9 Output 2 2 2 2 2 1 1 0 2 Input 4 0 0 1 0 1 2 1 3 1 4 Output 0 -1 1 -1 Note The first example is shown below: <image> The black vertices have bold borders. In the second example, the best subtree for vertices 2, 3 and 4 are vertices 2, 3 and 4 correspondingly. And the best subtree for the vertex 1 is the subtree consisting of vertices 1 and 3. Tags: dfs and similar, dp, graphs, trees Correct Solution: ``` import sys sys.setrecursionlimit(10 ** 6) int1 = lambda x: int(x) - 1 p2D = lambda x: print(*x, sep="\n") def II(): return int(sys.stdin.readline()) def MI(): return map(int, sys.stdin.readline().split()) def MI1(): return map(int1, sys.stdin.readline().split()) def LI(): return list(map(int, sys.stdin.readline().split())) def LLI(rows_number): return [LI() for _ in range(rows_number)] def SI(): return sys.stdin.readline()[:-1] def main(): def dfs(): stack=[(0,-1,False)] while stack: u,pu,re=stack.pop() if re: dp1[u]+=aa[u]*2-1+sum(dp1[cu] for cu in to[u] if cu!=pu and dp1[cu]>0) else: stack.append((u,pu,True)) for cu in to[u]: if cu == pu: continue stack.append((cu,u,False)) def dfs2(): stack=[(0,-1)] while stack: u,pu=stack.pop() ans[u]=sum(dp1[cu] for cu in to[u] if cu!=pu and dp1[cu]>0)+aa[u]*2-1 if u and dp2[u]>0:ans[u]+=dp2[u] for cu in to[u]: if cu==pu:continue d=dp1[cu] if dp1[cu]>0 else 0 dp2[cu]=ans[u]-d stack.append((cu,u)) n=II() aa=LI() to=[[] for _ in range(n)] for _ in range(n-1): u,v=MI1() to[u].append(v) to[v].append(u) dp1=[0]*n dfs() #print(dp1) dp2=[0]*n ans=[0]*n dfs2() #print(dp2) print(*ans) main() ```
3,483
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree consisting of n vertices. A tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a color assigned to it (a_v = 1 if the vertex v is white and 0 if the vertex v is black). You have to solve the following problem for each vertex v: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex v? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cnt_w white vertices and cnt_b black vertices, you have to maximize cnt_w - cnt_b. Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree. The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 1), where a_i is the color of the i-th vertex. Each of the next n-1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i). It is guaranteed that the given edges form a tree. Output Print n integers res_1, res_2, ..., res_n, where res_i is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex i. Examples Input 9 0 1 1 1 0 0 0 0 1 1 2 1 3 3 4 3 5 2 6 4 7 6 8 5 9 Output 2 2 2 2 2 1 1 0 2 Input 4 0 0 1 0 1 2 1 3 1 4 Output 0 -1 1 -1 Note The first example is shown below: <image> The black vertices have bold borders. In the second example, the best subtree for vertices 2, 3 and 4 are vertices 2, 3 and 4 correspondingly. And the best subtree for the vertex 1 is the subtree consisting of vertices 1 and 3. Tags: dfs and similar, dp, graphs, trees Correct Solution: ``` import sys input = sys.stdin.readline getint = lambda: int(input()) getints = lambda: [int(a) for a in input().split()] if __name__ == "__main__": n = getint() colors = [(i*2-1) for i in getints()] tree = [[] for i in range(n)] for i in range(n-1): a, b = getints() tree[a-1].append(b-1) tree[b-1].append(a-1) parent = [-1] * n order = [0] for i in range(n): node = order[i] for child in tree[node]: if child == parent[node]: continue parent[child] = node order.append(child) # print(order) order.reverse() points = [0] * n for node in order: children = tree[node] point = colors[node] for child in children: if child == parent[node]: continue point += max(0, points[child]) points[node] = point # print(points) order.reverse() for node in order: children = tree[node] for child in children: if child == parent[node]: continue points[child] += max(0, points[node] - max(0, points[child])) print(' '.join([str(i) for i in points])) ```
3,484
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree consisting of n vertices. A tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a color assigned to it (a_v = 1 if the vertex v is white and 0 if the vertex v is black). You have to solve the following problem for each vertex v: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex v? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cnt_w white vertices and cnt_b black vertices, you have to maximize cnt_w - cnt_b. Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree. The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 1), where a_i is the color of the i-th vertex. Each of the next n-1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i). It is guaranteed that the given edges form a tree. Output Print n integers res_1, res_2, ..., res_n, where res_i is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex i. Examples Input 9 0 1 1 1 0 0 0 0 1 1 2 1 3 3 4 3 5 2 6 4 7 6 8 5 9 Output 2 2 2 2 2 1 1 0 2 Input 4 0 0 1 0 1 2 1 3 1 4 Output 0 -1 1 -1 Note The first example is shown below: <image> The black vertices have bold borders. In the second example, the best subtree for vertices 2, 3 and 4 are vertices 2, 3 and 4 correspondingly. And the best subtree for the vertex 1 is the subtree consisting of vertices 1 and 3. Tags: dfs and similar, dp, graphs, trees Correct Solution: ``` from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc def main(): n=int(input()) arr=[-1]+readIntArr() #to support 1-indexing for i in range(1,n+1): if arr[i]==0: arr[i]=-1 adj=[[] for _ in range(n+1)] for _ in range(n-1): u,v=readIntArr() adj[u].append(v) adj[v].append(u) ans=[None for _ in range(n+1)] memo=[None for _ in range(n+1)] #start by solving for root at 1 @bootstrap def initialSolve(node,parent): diff=arr[node] for child in adj[node]: if child!=parent: diff2=yield initialSolve(child,node) if diff2>0: diff+=diff2 memo[node]=diff yield diff initialSolve(1,0) ans[1]=memo[1] #re-root to every neighbouring node @bootstrap def rerootDFS(node): for child in adj[node]: if ans[child]==None: #not visited nodeVal=memo[node] childVal=memo[child] if childVal>0: memo[node]-=childVal if memo[node]>0: memo[child]+=memo[node] ans[child]=memo[child] yield rerootDFS(child) memo[node]=nodeVal memo[child]=childVal yield None rerootDFS(1) ans.pop(0) oneLineArrayPrint(ans) return #import sys #input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok) import sys input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS. def oneLineArrayPrint(arr): print(' '.join([str(x) for x in arr])) def multiLineArrayPrint(arr): print('\n'.join([str(x) for x in arr])) def multiLineArrayOfArraysPrint(arr): print('\n'.join([' '.join([str(x) for x in y]) for y in arr])) def readIntArr(): return [int(x) for x in input().split()] inf=float('inf') MOD=10**9+7 for _ in range(1): main() ```
3,485
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree consisting of n vertices. A tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a color assigned to it (a_v = 1 if the vertex v is white and 0 if the vertex v is black). You have to solve the following problem for each vertex v: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex v? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cnt_w white vertices and cnt_b black vertices, you have to maximize cnt_w - cnt_b. Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree. The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 1), where a_i is the color of the i-th vertex. Each of the next n-1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i). It is guaranteed that the given edges form a tree. Output Print n integers res_1, res_2, ..., res_n, where res_i is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex i. Examples Input 9 0 1 1 1 0 0 0 0 1 1 2 1 3 3 4 3 5 2 6 4 7 6 8 5 9 Output 2 2 2 2 2 1 1 0 2 Input 4 0 0 1 0 1 2 1 3 1 4 Output 0 -1 1 -1 Note The first example is shown below: <image> The black vertices have bold borders. In the second example, the best subtree for vertices 2, 3 and 4 are vertices 2, 3 and 4 correspondingly. And the best subtree for the vertex 1 is the subtree consisting of vertices 1 and 3. Tags: dfs and similar, dp, graphs, trees Correct Solution: ``` import os import sys from io import BytesIO, IOBase from types import GeneratorType from collections import defaultdict 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") sys.setrecursionlimit(2 * 10 ** 5) ans=0 def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc @bootstrap def dfs(now, lay, fa): SUM[now] = 0 NUM[now] = C[now] for to in A[now]: if to != fa: yield dfs(to, lay + 1, now) SUM[now] += SUM[to] SUM[now] += NUM[to] NUM[now] += NUM[to] yield @bootstrap def change(now, fa): global ans ans = max(ans, SUM[now]) for to in A[now]: if to != fa: SUM[now] -= SUM[to] SUM[now] -= NUM[to] NUM[now] -= NUM[to] NUM[to] += NUM[now] SUM[to] += SUM[now] SUM[to] += NUM[now] yield change(to, now) SUM[to] -= SUM[now] SUM[to] -= NUM[now] NUM[to] -= NUM[now] NUM[now] += NUM[to] SUM[now] += SUM[to] SUM[now] += NUM[to] yield n = int(input()) A = [[] for i in range(n + 1)] C = [0] + (list(map(int, input().split()))) NUM = [0] * (n + 1) SUM = [0] * (n + 1) for i in range(n - 1): x, y = map(int, input().split()) A[x].append(y) A[y].append(x) dfs(1, 0, 0) change(1, 0) print(ans) # print(NUM) # print(SUM) ```
3,486
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree consisting of n vertices. A tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a color assigned to it (a_v = 1 if the vertex v is white and 0 if the vertex v is black). You have to solve the following problem for each vertex v: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex v? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cnt_w white vertices and cnt_b black vertices, you have to maximize cnt_w - cnt_b. Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree. The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 1), where a_i is the color of the i-th vertex. Each of the next n-1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i). It is guaranteed that the given edges form a tree. Output Print n integers res_1, res_2, ..., res_n, where res_i is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex i. Examples Input 9 0 1 1 1 0 0 0 0 1 1 2 1 3 3 4 3 5 2 6 4 7 6 8 5 9 Output 2 2 2 2 2 1 1 0 2 Input 4 0 0 1 0 1 2 1 3 1 4 Output 0 -1 1 -1 Note The first example is shown below: <image> The black vertices have bold borders. In the second example, the best subtree for vertices 2, 3 and 4 are vertices 2, 3 and 4 correspondingly. And the best subtree for the vertex 1 is the subtree consisting of vertices 1 and 3. Tags: dfs and similar, dp, graphs, trees Correct Solution: ``` def main(): import sys input = sys.stdin.readline N = int(input()) A = list(map(int, input().split())) adj = [[] for _ in range(N+1)] for _ in range(N-1): a, b = map(int, input().split()) adj[a].append(b) adj[b].append(a) """ここから変更""" # op: 普通に根を固定した木DPで子の情報を親に集めるときの演算 def op(a, b): return a + max(0, b) # たん位元(op(x, ident) = x)(「たん」を漢字にするとCEになる(なぜ?)) ident_op = 0 # cum_merge: 累積opどうしをマージするときの演算 def cum_merge(a, b): return a + b # たん位元(cum_merge(x, ident) = x) ident_cum_merge = 0 """ここまで変更""" # root=1でまず普通に木DPをする # 並行して各頂点につき、子の値の累積opを左右から求めておく # その後根から順番に、親からの寄与を求めていく(from_par) def Rerooting(adj): N = len(adj) - 1 st = [1] seen = [0] * (N + 1) seen[1] = 1 par = [0] * (N + 1) child = [[] for _ in range(N + 1)] seq = [] while st: v = st.pop() seq.append(v) for u in adj[v]: if not seen[u]: seen[u] = 1 par[u] = v child[v].append(u) st.append(u) seq.reverse() dp = [ident_op] * (N+1) left = [ident_cum_merge] * (N + 1) right = [ident_cum_merge] * (N + 1) for v in seq: tmp = ident_cum_merge for u in child[v]: left[u] = tmp tmp = op(tmp, dp[u]) tmp = ident_cum_merge for u in reversed(child[v]): right[u] = tmp tmp = op(tmp, dp[u]) dp[v] = tmp if A[v-1]: dp[v] += 1 else: dp[v] -= 1 seq.reverse() from_par = [ident_op] * (N + 1) for v in seq: if v == 1: continue from_par[v] = op(cum_merge(left[v], right[v]), from_par[par[v]]) if A[par[v]-1]: from_par[v] += 1 else: from_par[v] -= 1 dp[v] = op(dp[v], from_par[v]) return dp dp = Rerooting(adj) print(*dp[1:]) if __name__ == '__main__': main() ```
3,487
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree consisting of n vertices. A tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a color assigned to it (a_v = 1 if the vertex v is white and 0 if the vertex v is black). You have to solve the following problem for each vertex v: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex v? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cnt_w white vertices and cnt_b black vertices, you have to maximize cnt_w - cnt_b. Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree. The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 1), where a_i is the color of the i-th vertex. Each of the next n-1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i). It is guaranteed that the given edges form a tree. Output Print n integers res_1, res_2, ..., res_n, where res_i is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex i. Examples Input 9 0 1 1 1 0 0 0 0 1 1 2 1 3 3 4 3 5 2 6 4 7 6 8 5 9 Output 2 2 2 2 2 1 1 0 2 Input 4 0 0 1 0 1 2 1 3 1 4 Output 0 -1 1 -1 Note The first example is shown below: <image> The black vertices have bold borders. In the second example, the best subtree for vertices 2, 3 and 4 are vertices 2, 3 and 4 correspondingly. And the best subtree for the vertex 1 is the subtree consisting of vertices 1 and 3. Tags: dfs and similar, dp, graphs, trees Correct Solution: ``` class Graph: def __init__(self, n_vertices, edges, directed=True): self.n_vertices = n_vertices self.edges = edges self.directed = directed @property def adj(self): try: return self._adj except AttributeError: adj = [[] for _ in range(self.n_vertices)] if self.directed: for u,v in self.edges: adj[u].append(v) else: for u,v in self.edges: adj[u].append(v) adj[v].append(u) self._adj = adj return adj class RootedTree(Graph): def __init__(self, n_vertices, edges, root_vertex=0): self.root = root_vertex super().__init__(n_vertices, edges, False) @property def parent(self): try: return self._parent except AttributeError: adj = self.adj parent = [None]*self.n_vertices parent[self.root] = -1 stack = [self.root] for _ in range(self.n_vertices): v = stack.pop() for u in adj[v]: if parent[u] is None: parent[u] = v stack.append(u) self._parent = parent return parent @property def children(self): try: return self._children except AttributeError: children = [None]*self.n_vertices for v,(l,p) in enumerate(zip(self.adj,self.parent)): children[v] = [u for u in l if u != p] self._children = children return children @property def dfs_order(self): try: return self._dfs_order except AttributeError: order = [None]*self.n_vertices children = self.children stack = [self.root] for i in range(self.n_vertices): v = stack.pop() order[i] = v for u in children[v]: stack.append(u) self._dfs_order = order return order from functools import reduce from itertools import accumulate,chain def rerooting(rooted_tree, merge, identity, finalize): N = rooted_tree.n_vertices parent = rooted_tree.parent children = rooted_tree.children order = rooted_tree.dfs_order # from leaf to parent dp_down = [None]*N for v in reversed(order): dp_down[v] = finalize(reduce(merge, (dp_down[c] for c in children[v]), identity), parent[v], v) # from parent to leaf dp_up = [None]*N dp_up[0] = identity for v in order: if len(children[v]) == 0: continue temp = (dp_up[v],)+tuple(dp_down[u] for u in children[v])+(identity,) left = accumulate(temp[:-2],merge) right = tuple(accumulate(reversed(temp[2:]),merge)) for u,l,r in zip(children[v],left,reversed(right)): dp_up[u] = finalize(merge(l,r), u, v) res = [None]*N for v,l in enumerate(children): res[v] = reduce(merge, (dp_down[u] for u in children[v]), identity) res[v] = finalize(merge(res[v], dp_up[v]), -1, v) return res,dp_up,dp_down import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline if __name__ == '__main__': n = int(readline()) color = tuple(map(int,readline().split())) temp = map(lambda x:int(x)-1, read().split()) edges = zip(temp,temp) min2 = lambda x,y: x if x < y else y t = RootedTree(n, edges) def merge(x,y): b1, w1, s1 = x b2, w2, s2 = y return b1+b2, w1+w2, s1+s2 def finalize(x,u,v): b, w, s = x if color[v]: w += 1 else: b += 1 s = min2(s, w-b) if u >= 0 else s return (b,w,s) e = sum(color)*2 - n res,_,_ = rerooting(t, merge, (0,0,0), finalize) print(*(e-s for _,_,s in res)) ```
3,488
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree consisting of n vertices. A tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a color assigned to it (a_v = 1 if the vertex v is white and 0 if the vertex v is black). You have to solve the following problem for each vertex v: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex v? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cnt_w white vertices and cnt_b black vertices, you have to maximize cnt_w - cnt_b. Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree. The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 1), where a_i is the color of the i-th vertex. Each of the next n-1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i). It is guaranteed that the given edges form a tree. Output Print n integers res_1, res_2, ..., res_n, where res_i is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex i. Examples Input 9 0 1 1 1 0 0 0 0 1 1 2 1 3 3 4 3 5 2 6 4 7 6 8 5 9 Output 2 2 2 2 2 1 1 0 2 Input 4 0 0 1 0 1 2 1 3 1 4 Output 0 -1 1 -1 Note The first example is shown below: <image> The black vertices have bold borders. In the second example, the best subtree for vertices 2, 3 and 4 are vertices 2, 3 and 4 correspondingly. And the best subtree for the vertex 1 is the subtree consisting of vertices 1 and 3. Tags: dfs and similar, dp, graphs, trees Correct Solution: ``` import sys from collections import deque input = sys.stdin.buffer.readline N = int(input()) A = list(map(int, input().split())) A = [-1] + A adj = [[] for _ in range(N+1)] for _ in range(N-1): a, b = map(int, input().split()) adj[a].append(b) adj[b].append(a) que = deque() que.append(1) seen = [-1] * (N+1) seen[1] = 0 par = [0] * (N+1) child = [[] for _ in range(N+1)] seq = [] while que: v = que.popleft() seq.append(v) for u in adj[v]: if seen[u] == -1: seen[u] = seen[v] + 1 par[u] = v child[v].append(u) que.append(u) seq.reverse() dp = [0] * (N+1) for v in seq: for u in child[v]: dp[v] += dp[u] if A[v]: dp[v] += 1 else: dp[v] -= 1 if dp[v] < 0: dp[v] = 0 seq.reverse() dp2 = [0] * (N+1) for v in seq: for u in child[v]: dp2[v] += dp[u] if v != 1: dp2[v] += max(0, dp2[par[v]] - dp[v]) if A[v]: dp2[v] += 1 else: dp2[v] -= 1 print(*[max(-1, ans) for ans in dp2[1:]]) ```
3,489
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree consisting of n vertices. A tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a color assigned to it (a_v = 1 if the vertex v is white and 0 if the vertex v is black). You have to solve the following problem for each vertex v: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex v? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cnt_w white vertices and cnt_b black vertices, you have to maximize cnt_w - cnt_b. Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree. The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 1), where a_i is the color of the i-th vertex. Each of the next n-1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i). It is guaranteed that the given edges form a tree. Output Print n integers res_1, res_2, ..., res_n, where res_i is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex i. Examples Input 9 0 1 1 1 0 0 0 0 1 1 2 1 3 3 4 3 5 2 6 4 7 6 8 5 9 Output 2 2 2 2 2 1 1 0 2 Input 4 0 0 1 0 1 2 1 3 1 4 Output 0 -1 1 -1 Note The first example is shown below: <image> The black vertices have bold borders. In the second example, the best subtree for vertices 2, 3 and 4 are vertices 2, 3 and 4 correspondingly. And the best subtree for the vertex 1 is the subtree consisting of vertices 1 and 3. Tags: dfs and similar, dp, graphs, trees Correct Solution: ``` import sys input = sys.stdin.readline N = int(input()) C = list(map(int, input().split())) T = [[] for _ in range(N)] edges = [] for _ in range(N-1): a, b = map(int, input().split()) a -= 1 b -= 1 edges.append([a, b]) T[a].append(b) T[b].append(a) root = [0]*N root[0] = -1 rank = [0]*N Q = [0] visited = {0} ra = 1 # BFS while Q: P = [] # next iteration for i in Q: for j in T[i]: if j in visited: continue rank[j] = ra # depth root[j] = i # parent visited.add(j) P.append(j) Q = P ra += 1 # set of [depth,node] rankk = [[rank[i], i] for i in range(N)] rankk.sort() # above code calc depth of each nodes from root(0) D = [0]*N # ans # start from farthest nodes(leave) for i in reversed(range(1, N)): k = rankk[i][1] # id if C[k] == 0: # node k is black D[k] -= 1 # minus 1 as itself blakc cnt else: D[k] += 1 # node k is white # if children value (D[k]) <0 , not use children ,just cut off children D[root[k]] += max(0, D[k]) if C[0] == 0: D[0] -= 1 else: D[0] += 1 # above code # calc max diff on each nodes when 0 is root and consider childrens of the node. # change root and calc value of each node from top(root 0) for i in range(1, N): k = rankk[i][1] D[k] = max(D[k], min(D[k], 0)+D[root[k]]) # compare two setting # 1. D[k]: ignore parent value # 2. min(D[k],0) + D[root[k]]: use parent print(*D) ```
3,490
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree consisting of n vertices. A tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a color assigned to it (a_v = 1 if the vertex v is white and 0 if the vertex v is black). You have to solve the following problem for each vertex v: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex v? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cnt_w white vertices and cnt_b black vertices, you have to maximize cnt_w - cnt_b. Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree. The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 1), where a_i is the color of the i-th vertex. Each of the next n-1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i). It is guaranteed that the given edges form a tree. Output Print n integers res_1, res_2, ..., res_n, where res_i is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex i. Examples Input 9 0 1 1 1 0 0 0 0 1 1 2 1 3 3 4 3 5 2 6 4 7 6 8 5 9 Output 2 2 2 2 2 1 1 0 2 Input 4 0 0 1 0 1 2 1 3 1 4 Output 0 -1 1 -1 Note The first example is shown below: <image> The black vertices have bold borders. In the second example, the best subtree for vertices 2, 3 and 4 are vertices 2, 3 and 4 correspondingly. And the best subtree for the vertex 1 is the subtree consisting of vertices 1 and 3. Submitted Solution: ``` import os import sys from io import BytesIO, IOBase from types import GeneratorType from collections import defaultdict 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") sys.setrecursionlimit(2*10**5) def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc @bootstrap def dfs(u,p): for j in adj[u]: if j!=p: yield dfs(j,u) f[u]+=(f[j]+res[j]) res[u]+=res[j] res[u]+=b[u-1] yield @bootstrap def dfs2(u,p,val): for j in adj[u]: if j!=p: yield dfs2(j,u,f[u]-(f[j]+res[j])+val+(s-res[u])) ans[u]=f[u]+val+(s-res[u]) yield n=int(input()) b=list(map(int,input().split())) s=sum(b) adj=[[] for i in range(n+1)] for j in range(n-1): u,v=map(int,input().split()) adj[u].append(v) adj[v].append(u) f=[0]*(n+1) res=[0]*(n+1) dfs(1,0) ans=[0]*(n+1) dfs2(1,0,0) print(max(ans[1:])) ``` Yes
3,491
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree consisting of n vertices. A tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a color assigned to it (a_v = 1 if the vertex v is white and 0 if the vertex v is black). You have to solve the following problem for each vertex v: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex v? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cnt_w white vertices and cnt_b black vertices, you have to maximize cnt_w - cnt_b. Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree. The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 1), where a_i is the color of the i-th vertex. Each of the next n-1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i). It is guaranteed that the given edges form a tree. Output Print n integers res_1, res_2, ..., res_n, where res_i is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex i. Examples Input 9 0 1 1 1 0 0 0 0 1 1 2 1 3 3 4 3 5 2 6 4 7 6 8 5 9 Output 2 2 2 2 2 1 1 0 2 Input 4 0 0 1 0 1 2 1 3 1 4 Output 0 -1 1 -1 Note The first example is shown below: <image> The black vertices have bold borders. In the second example, the best subtree for vertices 2, 3 and 4 are vertices 2, 3 and 4 correspondingly. And the best subtree for the vertex 1 is the subtree consisting of vertices 1 and 3. Submitted Solution: ``` import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # ------------------------------ from math import factorial from collections import Counter, defaultdict from heapq import heapify, heappop, heappush def RL(): return map(int, sys.stdin.readline().rstrip().split()) def RLL(): return list(map(int, sys.stdin.readline().rstrip().split())) def N(): return int(input()) def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0 def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0 def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2) def ctd(chr): return ord(chr)-ord("a") mod = 998244353 INF = float('inf') # ------------------------------ def main(): n = N() arr = [-1]+RLL() gp = [[] for _ in range(n+1)] for _ in range(n-1): f, t = RL() gp[f].append(t) gp[t].append(f) q = [1] vis = [0]*(n+1) vis[1] = 1 par = [0]*(n+1) chd = [[] for _ in range(n+1)] seq = [] for i in q: seq.append(i) for nex in gp[i]: if vis[nex]==1: continue par[nex] = i chd[i].append(nex) q.append(nex) vis[nex] = 1 dp = [0]*(n+1) for i in seq[::-1]: if arr[i]==1: dp[i]+=1 else: dp[i]-=1 for nex in chd[i]: dp[i]+=dp[nex] dp[i] = max(dp[i], 0) # print(dp) dp1 = [0]*(n+1) for i in seq: for nex in chd[i]: dp1[i]+=dp[nex] if i!=1: dp1[i] += max(dp1[par[i]]-dp[i], 0) if arr[i]==1: dp1[i]+=1 else: dp1[i]-=1 print(*[max(-1, i) for i in dp1[1:]]) if __name__ == "__main__": main() ``` Yes
3,492
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree consisting of n vertices. A tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a color assigned to it (a_v = 1 if the vertex v is white and 0 if the vertex v is black). You have to solve the following problem for each vertex v: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex v? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cnt_w white vertices and cnt_b black vertices, you have to maximize cnt_w - cnt_b. Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree. The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 1), where a_i is the color of the i-th vertex. Each of the next n-1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i). It is guaranteed that the given edges form a tree. Output Print n integers res_1, res_2, ..., res_n, where res_i is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex i. Examples Input 9 0 1 1 1 0 0 0 0 1 1 2 1 3 3 4 3 5 2 6 4 7 6 8 5 9 Output 2 2 2 2 2 1 1 0 2 Input 4 0 0 1 0 1 2 1 3 1 4 Output 0 -1 1 -1 Note The first example is shown below: <image> The black vertices have bold borders. In the second example, the best subtree for vertices 2, 3 and 4 are vertices 2, 3 and 4 correspondingly. And the best subtree for the vertex 1 is the subtree consisting of vertices 1 and 3. Submitted Solution: ``` import sys input=sys.stdin.readline import collections from collections import defaultdict def dfs(): q=collections.deque([(1,0)]) while q: v,par_val=q.pop() tmp={} for nxt_v in graph[v]: if nxt_v==par[v]: tmp[nxt_v]=par_val else: tmp[nxt_v]=ans[nxt_v] res=a[v-1] for nxt_v in tmp: if res+tmp[nxt_v]>res: res=res+tmp[nxt_v] dist2[v]=res for nxt_v in graph[v]: if nxt_v==par[v]: continue else: q.append((nxt_v,res-max(tmp[nxt_v],0))) n=int(input()) a=[int(i) for i in input().split() if i!='\n'] for i in range(len(a)): if a[i]==0: a[i]=-1 graph=defaultdict(list) for i in range(n-1): u,v=map(int,input().split()) graph[u].append(v) graph[v].append(u) ans=[0]*(n+1) OBSERVE = 0 CHECK = 1 stack = [(OBSERVE,1,0)] par={1:0} dist2=[0]*(n+1) while len(stack): state, vertex, parent = stack.pop() #print(stack) if state == OBSERVE: stack.append((CHECK, vertex, parent)) for child in graph[vertex]: if child != parent: stack.append((OBSERVE, child, vertex)) par[child]=vertex else: res=a[vertex-1] for child in graph[vertex]: if child==parent: continue elif child != parent: if (res+ans[child])>res: #print(vertex,child,res) res=res+ans[child] #print(res) ans[vertex]=res dfs() print(*dist2[1:]) ``` Yes
3,493
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree consisting of n vertices. A tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a color assigned to it (a_v = 1 if the vertex v is white and 0 if the vertex v is black). You have to solve the following problem for each vertex v: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex v? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cnt_w white vertices and cnt_b black vertices, you have to maximize cnt_w - cnt_b. Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree. The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 1), where a_i is the color of the i-th vertex. Each of the next n-1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i). It is guaranteed that the given edges form a tree. Output Print n integers res_1, res_2, ..., res_n, where res_i is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex i. Examples Input 9 0 1 1 1 0 0 0 0 1 1 2 1 3 3 4 3 5 2 6 4 7 6 8 5 9 Output 2 2 2 2 2 1 1 0 2 Input 4 0 0 1 0 1 2 1 3 1 4 Output 0 -1 1 -1 Note The first example is shown below: <image> The black vertices have bold borders. In the second example, the best subtree for vertices 2, 3 and 4 are vertices 2, 3 and 4 correspondingly. And the best subtree for the vertex 1 is the subtree consisting of vertices 1 and 3. Submitted Solution: ``` '''t=int(input()) while(t): t-=1 n,k=[int(x) for x in input().split()] s="" while(len(s)!=n): i=0 while(i<k): if len(s)==n: break s+=chr(97+i) i+=1 print(s)''' '''n=int(input()) arr=[int(x) for x in input().split()] arr=sorted(arr) ans=0 for i in range(0,n-1,2): ans+=abs(arr[i]-arr[i+1]) print(ans)''' from collections import defaultdict import sys,threading def work(): sys.setrecursionlimit(1 << 18) def fun(u,level,p): l[1]+=level*arr[u-1] summ[u]=arr[u-1] for i in graph[u]: if i!=p: fun(i,level+1,u) summ[u]+=summ[i] def fun2(u,p): for i in graph[u]: if i!=p: l[i]=l[u]+s-2*summ[i] fun2(i,u) n=int(input()) n1=n arr=[int(x) for x in input().split()] graph=defaultdict(list) while(n1-1): n1-=1 u,v=[int(x) for x in input().split()] graph[u].append(v) graph[v].append(u) s=0 for i in arr: s+=i summ=[0]*(n+1) l=[0]*(n+1) fun(1,0,0) fun2(1,0) print(max(l)) if __name__ == '__main__': sys.setrecursionlimit(200050) threading.stack_size(80000000) thread = threading.Thread(target=work) thread.start() ``` Yes
3,494
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree consisting of n vertices. A tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a color assigned to it (a_v = 1 if the vertex v is white and 0 if the vertex v is black). You have to solve the following problem for each vertex v: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex v? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cnt_w white vertices and cnt_b black vertices, you have to maximize cnt_w - cnt_b. Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree. The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 1), where a_i is the color of the i-th vertex. Each of the next n-1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i). It is guaranteed that the given edges form a tree. Output Print n integers res_1, res_2, ..., res_n, where res_i is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex i. Examples Input 9 0 1 1 1 0 0 0 0 1 1 2 1 3 3 4 3 5 2 6 4 7 6 8 5 9 Output 2 2 2 2 2 1 1 0 2 Input 4 0 0 1 0 1 2 1 3 1 4 Output 0 -1 1 -1 Note The first example is shown below: <image> The black vertices have bold borders. In the second example, the best subtree for vertices 2, 3 and 4 are vertices 2, 3 and 4 correspondingly. And the best subtree for the vertex 1 is the subtree consisting of vertices 1 and 3. Submitted Solution: ``` import math from bisect import bisect_left, bisect_right from sys import stdin, stdout, setrecursionlimit from collections import Counter import threading input = lambda: stdin.readline().strip() print = stdout.write def f(): n = int(input()) ls = list(map(int, input().split())) children = {} for i in range(1, n+1): children[i] = [] for i in range(n-1): a, b = map(int, input().split()) children[a].append(b) children[b].append(a) parent = [-1] ans = [-1] for i in range(1, n+1): parent.append(-1) ans.append(-1) visited = [False] for i in range(1, n+1): visited.append(False) def dfs(node): visited[node] = True ans[node] = 1 if ls[node-1] else -1 for i in children[node]: if not visited[i]: parent[i] = node tmp = dfs(i) if tmp>0: ans[node]+=tmp ans[node] = max(ans[node], 1 if ls[node-1] else -1) return ans[node] dfs(1) visited = [False] for i in range(1, n+1): visited.append(False) def dfs(node): visited[node] = True if node!=1: ans[node] = max(ans[node], ans[parent[node]] if ans[node]>=0 else ans[parent[node]]-1) for i in children[node]: if not visited[i]: dfs(i) dfs(1) for i in range(1, n+1): print(str(ans[i])+' ') print('\n') if __name__ == '__main__': setrecursionlimit(100000) threading.stack_size(1000000) thread = threading.Thread(target=f) thread.start() ``` No
3,495
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree consisting of n vertices. A tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a color assigned to it (a_v = 1 if the vertex v is white and 0 if the vertex v is black). You have to solve the following problem for each vertex v: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex v? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cnt_w white vertices and cnt_b black vertices, you have to maximize cnt_w - cnt_b. Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree. The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 1), where a_i is the color of the i-th vertex. Each of the next n-1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i). It is guaranteed that the given edges form a tree. Output Print n integers res_1, res_2, ..., res_n, where res_i is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex i. Examples Input 9 0 1 1 1 0 0 0 0 1 1 2 1 3 3 4 3 5 2 6 4 7 6 8 5 9 Output 2 2 2 2 2 1 1 0 2 Input 4 0 0 1 0 1 2 1 3 1 4 Output 0 -1 1 -1 Note The first example is shown below: <image> The black vertices have bold borders. In the second example, the best subtree for vertices 2, 3 and 4 are vertices 2, 3 and 4 correspondingly. And the best subtree for the vertex 1 is the subtree consisting of vertices 1 and 3. Submitted Solution: ``` import io import os from collections import Counter, defaultdict, deque from functools import lru_cache def solve(N, A, edges): print(N, A, edges) g = defaultdict(list) for u, v in edges: g[u].append(v) g[v].append(u) @lru_cache(maxsize=None) def getDiff(u, v): ans = 0 if A[v]: ans = 1 else: ans = -1 # Split graph on the edge uv, get maxdiff spanning out from v for w in g[v]: if w != u: maxDiff = getDiff(v, w) if maxDiff > 0: ans += maxDiff return max(0, ans) out = [] for u in range(N): ans = 0 if A[u]: ans = 1 else: ans = -1 for v in g[u]: maxDiff = getDiff(u, v) if maxDiff > 0: ans += maxDiff out.append(str(ans)) return " ".join(out) 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()] edges = [[int(x) - 1 for x in input().split()] for i in range(N - 1)] ans = solve(N, A, edges) print(ans) ``` No
3,496
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree consisting of n vertices. A tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a color assigned to it (a_v = 1 if the vertex v is white and 0 if the vertex v is black). You have to solve the following problem for each vertex v: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex v? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cnt_w white vertices and cnt_b black vertices, you have to maximize cnt_w - cnt_b. Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree. The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 1), where a_i is the color of the i-th vertex. Each of the next n-1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i). It is guaranteed that the given edges form a tree. Output Print n integers res_1, res_2, ..., res_n, where res_i is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex i. Examples Input 9 0 1 1 1 0 0 0 0 1 1 2 1 3 3 4 3 5 2 6 4 7 6 8 5 9 Output 2 2 2 2 2 1 1 0 2 Input 4 0 0 1 0 1 2 1 3 1 4 Output 0 -1 1 -1 Note The first example is shown below: <image> The black vertices have bold borders. In the second example, the best subtree for vertices 2, 3 and 4 are vertices 2, 3 and 4 correspondingly. And the best subtree for the vertex 1 is the subtree consisting of vertices 1 and 3. Submitted Solution: ``` import traceback try: # alpha = "abcdefghijklmnopqrstuvwxyz" n = int(input()) a = [0] a.extend(list(map(int, input().split()))) D = [[] for i in range(n+1)] for i in range(n-1): e1,e2 = (map(int, input().split())) D[e1].append(e2) D[e2].append(e1) # for i in range(1,n+1): # if i not in D: # D[i] = [] visited = [False for i in range(n+1)] cost = [a[i] for i in range(n+1)] val = 0 def dfs(s, depth): global visited global cost global val global a global D visited[s] = True val += depth*a[s] for i in D[s]: if not visited[i]: dfs(i, depth+1) cost[s]+=cost[i] dfs(1, 0) # ans = 1 max_cost = val # print(max_cost) visited = [False for i in range(n+1)] cost[0] = sum(a) def trav(s, some_val): global cost global visited global max_cost global D visited[s] = True # print(some_val, s) if some_val>max_cost: max_cost = some_val for i in D[s]: if not visited[i]: # print(i, some_val, cost[s], cost[i]) trav(i, some_val+(cost[0]-cost[i])-cost[i] ) trav(1, val) print(max_cost) except Exception as ex: traceback.print_tb(ex.__traceback__) print(ex) ``` No
3,497
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree consisting of n vertices. A tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a color assigned to it (a_v = 1 if the vertex v is white and 0 if the vertex v is black). You have to solve the following problem for each vertex v: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex v? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cnt_w white vertices and cnt_b black vertices, you have to maximize cnt_w - cnt_b. Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree. The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 1), where a_i is the color of the i-th vertex. Each of the next n-1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i). It is guaranteed that the given edges form a tree. Output Print n integers res_1, res_2, ..., res_n, where res_i is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex i. Examples Input 9 0 1 1 1 0 0 0 0 1 1 2 1 3 3 4 3 5 2 6 4 7 6 8 5 9 Output 2 2 2 2 2 1 1 0 2 Input 4 0 0 1 0 1 2 1 3 1 4 Output 0 -1 1 -1 Note The first example is shown below: <image> The black vertices have bold borders. In the second example, the best subtree for vertices 2, 3 and 4 are vertices 2, 3 and 4 correspondingly. And the best subtree for the vertex 1 is the subtree consisting of vertices 1 and 3. Submitted Solution: ``` from collections import defaultdict as dd import sys input=sys.stdin.readline def dfs(cur,prev,par,val,d): st=[(cur,prev)] bst=[] while st: cur,prev=st.pop() bst.append((cur,prev)) par[cur]=prev for i in d[cur]: if(i!=prev): st.append((i,cur)) while bst: cur,prev=bst.pop() for i in d[cur]: if(i!=prev): if(val[i]>0): val[cur]+=val[i] def dfs1(cur,prev,par,val,d): st=[(cur,prev)] while st: cur,prev=st.pop() if(val[cur]>=0): val[cur]=max(val[cur],val[par[cur]]) else: val[cur]=max(val[cur],val[par[cur]]+val[cur]) for i in d[cur]: if(i!=prev): st.append((i,cur)) n=int(input()) val=[0]+list(map(int,input().split())) for i in range(1,n+1): if(val[i]==0): val[i]=-1 d=dd(list) for i in range(n-1): u,v=map(int,input().split()) d[u].append(v) d[v].append(u) #val=[0]*n par=[0]*(n+1) dfs(1,-1,par,val,d) #print(val) dfs1(1,-1,par,val,d) for i in range(1,n+1): print(val[i],end=" ") ``` No
3,498
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected unweighted graph consisting of n vertices and m edges (which represents the map of Bertown) and the array of prices p of length m. It is guaranteed that there is a path between each pair of vertices (districts). Mike has planned a trip from the vertex (district) a to the vertex (district) b and then from the vertex (district) b to the vertex (district) c. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used p is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road. You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains five integers n, m, a, b and c (2 ≤ n ≤ 2 ⋅ 10^5, n-1 ≤ m ≤ min((n(n-1))/(2), 2 ⋅ 10^5), 1 ≤ a, b, c ≤ n) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains m integers p_1, p_2, ..., p_m (1 ≤ p_i ≤ 10^9), where p_i is the i-th price from the array. The following m lines of the test case denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the array of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of n (as well as the sum of m) does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5, ∑ m ≤ 2 ⋅ 10^5). Output For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally. Example Input 2 4 3 2 3 4 1 2 3 1 2 1 3 1 4 7 9 1 5 7 2 10 4 8 5 6 7 3 3 1 2 1 3 1 4 3 2 3 5 4 2 5 6 1 7 6 7 Output 7 12 Note One of the possible solution to the first test case of the example: <image> One of the possible solution to the second test case of the example: <image> Tags: brute force, graphs, greedy, shortest paths, sortings Correct Solution: ``` from collections import deque import sys from array import array # noqa: F401 import typing as Tp # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') def bfs(n, adj, start): cost = [-1] * n cost[start] = 0 dq = deque([start]) while dq: v = dq.popleft() for dest in adj[v]: if cost[dest] != -1: continue cost[dest] = cost[v] + 1 dq.append(dest) return cost def main(): t = int(input()) ans = [''] * t for ti in range(t): from itertools import accumulate n, m, a, b, c = map(int, input().split()) a, b, c = a - 1, b - 1, c - 1 p = (0, ) + tuple(accumulate(sorted(map(int, input().split())))) adj = [[] for _ in range(n)] for u, v in (map(int, input().split()) for _ in range(m)): adj[u - 1].append(v - 1) adj[v - 1].append(u - 1) a_to_x = bfs(n, adj, a) b_to_x = bfs(n, adj, b) c_to_x = bfs(n, adj, c) mincost = 10**18 for x in range(n): if a_to_x[x] + b_to_x[x] + c_to_x[x] > m: continue mincost = min( mincost, p[b_to_x[x]] + p[a_to_x[x] + b_to_x[x] + c_to_x[x]] ) ans[ti] = str(mincost) sys.stdout.buffer.write(('\n'.join(ans) + '\n').encode('utf-8')) if __name__ == '__main__': main() ```
3,499