message
stringlengths
2
433k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
113
108k
cluster
float64
12
12
__index_level_0__
int64
226
217k
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,m = map(int,input().split()) t_deq = deque(list(map(int,input().split()))) t_quer = [[int(input()),x] for x in range(m)] t_quer = sorted(t_quer, key=lambda x: x[0]) c=0 co = 0 a = max(t_deq) l_t_deq = len(t_deq)-1 valid = False p_licz = 1 for x in range(m): licz = t_quer[x][0] if valid == True: co = (licz-p_licz)%l_t_deq if co == 0: co-=1 t_quer[x].append([t_deq[0],t_deq[co]]) continue while True: if t_deq[0] == a: valid = True c = t_deq.popleft() t_deq.append(t_deq.popleft()) t_deq.appendleft(c) co = (licz - p_licz) % l_t_deq if co == 0: co -= 1 t_quer[x].append([t_deq[0],t_deq[co]]) break if t_deq[0] < t_deq[1]: if licz==p_licz: t_quer[x].append([t_deq[0], t_deq[1]]) t_deq.append(t_deq.popleft()) p_licz+=1 break t_deq.append(t_deq.popleft()) else: if licz==p_licz: t_quer[x].append([t_deq[0], t_deq[1]]) c = t_deq.popleft() t_deq.append(t_deq.popleft()) t_deq.appendleft(c) p_licz+=1 break c=t_deq.popleft() t_deq.append(t_deq.popleft()) t_deq.appendleft(c) p_licz += 1 t_quer = sorted(t_quer, key=lambda x: x[1]) for x in t_quer: print(x[2][0], x[2][1]) ```
instruction
0
107,910
12
215,820
No
output
1
107,910
12
215,821
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,q=map(int,input().split()) a=list(map(int,input().split())) m=[] for i in range(q): ta=int(input()) m.append(ta) i,j=0,0 iarr=[] jarr=[] maxele=max(a) maxindex=0 for _ in range(2*n): if(a[j]>a[i]): i=j j=j+1 if(j>=n): j=0 if(j==i): j=j+1 if(j>=n): j=0 if(a[j]==maxele): maxindex=_+1 iarr.append(i) jarr.append(j) for i in range(len(m)): if(m[i]>n): print(a[iarr[maxindex]],a[jarr[maxindex+(m[i]-maxindex)%(n-1)-1]]) else: print(a[iarr[m[i]-1]],a[jarr[m[i]-1]]) ```
instruction
0
107,911
12
215,822
No
output
1
107,911
12
215,823
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 X = list(map(int, input().split())) Numbers = deque(map(int, input().split())) if X[1] == 0: exit() MyDict = {} for _ in range(X[1]): MyDict[int(input())] = 1 Max, i = max(Numbers), 0 while Numbers[0] != Max: First, Second = Numbers.popleft(), Numbers.popleft() if MyDict.get(i + 1) == 1: MyDict[i + 1] = [First, Second] Numbers.appendleft(max(First, Second)) Numbers.append(min(First, Second)) i += 1 for key in MyDict: if MyDict[key] != 1: print(*MyDict[key]) else: print(Max, Numbers[((key - i) % (X[0] - 1))]) # Hope the best for Ravens member ```
instruction
0
107,912
12
215,824
No
output
1
107,912
12
215,825
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: ``` def count(audrey,imba,banget): return(1+(imba-audrey-1)%(banget-1)) n,q=map(int,input().split()) L=list(map(int,input().split())) indexmax=L.index(max(L)) P=[] for i in range(indexmax): P.append((L[0],L[1])) if L[0]<L[1]: L.append(L.pop(0)) else: L.append(L.pop(1)) Y=tuple(L[1:]) for p in range(q): m=int(input()) if m<=indexmax: print((P[m-1][0]),P[m-1][1]) else: print(L[0],Y[count(indexmax,m,n)]) ```
instruction
0
107,913
12
215,826
No
output
1
107,913
12
215,827
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sorted array a_1, a_2, ..., a_n (for each index i > 1 condition a_i β‰₯ a_{i-1} holds) and an integer k. You are asked to divide this array into k non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let max(i) be equal to the maximum in the i-th subarray, and min(i) be equal to the minimum in the i-th subarray. The cost of division is equal to βˆ‘_{i=1}^{k} (max(i) - min(i)). For example, if a = [2, 4, 5, 5, 8, 11, 19] and we divide it into 3 subarrays in the following way: [2, 4], [5, 5], [8, 11, 19], then the cost of division is equal to (4 - 2) + (5 - 5) + (19 - 8) = 13. Calculate the minimum cost you can obtain by dividing the array a into k non-empty consecutive subarrays. Input The first line contains two integers n and k (1 ≀ k ≀ n ≀ 3 β‹… 10^5). The second line contains n integers a_1, a_2, ..., a_n ( 1 ≀ a_i ≀ 10^9, a_i β‰₯ a_{i-1}). Output Print the minimum cost you can obtain by dividing the array a into k nonempty consecutive subarrays. Examples Input 6 3 4 8 15 16 23 42 Output 12 Input 4 4 1 3 3 7 Output 0 Input 8 1 1 1 2 3 5 8 13 21 Output 20 Note In the first test we can divide array a in the following way: [4, 8, 15, 16], [23], [42].
instruction
0
107,914
12
215,828
Tags: greedy, sortings Correct Solution: ``` import sys,io,os input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n,k = [int(i) for i in input().split()] a = [int(i) for i in input().split()] suff = [0]*n suff[-1] = a[-1] for i in range (n-2,-1,-1): suff[i] = suff[i+1]+a[i] ans = suff[0] suff = suff[1:] suff.sort(reverse = 1) ans += sum(suff[:k-1]) print(ans) ```
output
1
107,914
12
215,829
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sorted array a_1, a_2, ..., a_n (for each index i > 1 condition a_i β‰₯ a_{i-1} holds) and an integer k. You are asked to divide this array into k non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let max(i) be equal to the maximum in the i-th subarray, and min(i) be equal to the minimum in the i-th subarray. The cost of division is equal to βˆ‘_{i=1}^{k} (max(i) - min(i)). For example, if a = [2, 4, 5, 5, 8, 11, 19] and we divide it into 3 subarrays in the following way: [2, 4], [5, 5], [8, 11, 19], then the cost of division is equal to (4 - 2) + (5 - 5) + (19 - 8) = 13. Calculate the minimum cost you can obtain by dividing the array a into k non-empty consecutive subarrays. Input The first line contains two integers n and k (1 ≀ k ≀ n ≀ 3 β‹… 10^5). The second line contains n integers a_1, a_2, ..., a_n ( 1 ≀ a_i ≀ 10^9, a_i β‰₯ a_{i-1}). Output Print the minimum cost you can obtain by dividing the array a into k nonempty consecutive subarrays. Examples Input 6 3 4 8 15 16 23 42 Output 12 Input 4 4 1 3 3 7 Output 0 Input 8 1 1 1 2 3 5 8 13 21 Output 20 Note In the first test we can divide array a in the following way: [4, 8, 15, 16], [23], [42].
instruction
0
107,915
12
215,830
Tags: greedy, sortings Correct Solution: ``` from bisect import bisect_right as br def f(k,a): d=[] for i in range(0,len(a)-1): d.append(a[i+1]-a[i]) ans=a[-1]-a[0] d=sorted(d,reverse=True) for i in range(k-1): ans-=d[i] return ans a,b=map(int,input().strip().split()) lst=list(map(int,input().strip().split())) print(f(b,lst)) ```
output
1
107,915
12
215,831
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sorted array a_1, a_2, ..., a_n (for each index i > 1 condition a_i β‰₯ a_{i-1} holds) and an integer k. You are asked to divide this array into k non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let max(i) be equal to the maximum in the i-th subarray, and min(i) be equal to the minimum in the i-th subarray. The cost of division is equal to βˆ‘_{i=1}^{k} (max(i) - min(i)). For example, if a = [2, 4, 5, 5, 8, 11, 19] and we divide it into 3 subarrays in the following way: [2, 4], [5, 5], [8, 11, 19], then the cost of division is equal to (4 - 2) + (5 - 5) + (19 - 8) = 13. Calculate the minimum cost you can obtain by dividing the array a into k non-empty consecutive subarrays. Input The first line contains two integers n and k (1 ≀ k ≀ n ≀ 3 β‹… 10^5). The second line contains n integers a_1, a_2, ..., a_n ( 1 ≀ a_i ≀ 10^9, a_i β‰₯ a_{i-1}). Output Print the minimum cost you can obtain by dividing the array a into k nonempty consecutive subarrays. Examples Input 6 3 4 8 15 16 23 42 Output 12 Input 4 4 1 3 3 7 Output 0 Input 8 1 1 1 2 3 5 8 13 21 Output 20 Note In the first test we can divide array a in the following way: [4, 8, 15, 16], [23], [42].
instruction
0
107,916
12
215,832
Tags: greedy, sortings Correct Solution: ``` n, k = map(int, input().split()) a = list(map(int, input().split())) for i in range(n - 1): a[i] = a[i + 1] - a[i] b = sorted(a[:-1], reverse=True) print(sum(b[k - 1:])) ```
output
1
107,916
12
215,833
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sorted array a_1, a_2, ..., a_n (for each index i > 1 condition a_i β‰₯ a_{i-1} holds) and an integer k. You are asked to divide this array into k non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let max(i) be equal to the maximum in the i-th subarray, and min(i) be equal to the minimum in the i-th subarray. The cost of division is equal to βˆ‘_{i=1}^{k} (max(i) - min(i)). For example, if a = [2, 4, 5, 5, 8, 11, 19] and we divide it into 3 subarrays in the following way: [2, 4], [5, 5], [8, 11, 19], then the cost of division is equal to (4 - 2) + (5 - 5) + (19 - 8) = 13. Calculate the minimum cost you can obtain by dividing the array a into k non-empty consecutive subarrays. Input The first line contains two integers n and k (1 ≀ k ≀ n ≀ 3 β‹… 10^5). The second line contains n integers a_1, a_2, ..., a_n ( 1 ≀ a_i ≀ 10^9, a_i β‰₯ a_{i-1}). Output Print the minimum cost you can obtain by dividing the array a into k nonempty consecutive subarrays. Examples Input 6 3 4 8 15 16 23 42 Output 12 Input 4 4 1 3 3 7 Output 0 Input 8 1 1 1 2 3 5 8 13 21 Output 20 Note In the first test we can divide array a in the following way: [4, 8, 15, 16], [23], [42].
instruction
0
107,917
12
215,834
Tags: greedy, sortings Correct Solution: ``` import io, os #input = io.StringIO(os.read(0, os.fstat(0).st_size).decode()).readline n, k = map(int, input().split()) a = list(map(int, input().split())) summ = 0 v = [] for i in range(n - 1, -1, -1): summ += a[i] if i > 0: v.append(summ) ans = summ v.sort(reverse = True) for i in range(k - 1): ans += v[i] print(ans) ```
output
1
107,917
12
215,835
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sorted array a_1, a_2, ..., a_n (for each index i > 1 condition a_i β‰₯ a_{i-1} holds) and an integer k. You are asked to divide this array into k non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let max(i) be equal to the maximum in the i-th subarray, and min(i) be equal to the minimum in the i-th subarray. The cost of division is equal to βˆ‘_{i=1}^{k} (max(i) - min(i)). For example, if a = [2, 4, 5, 5, 8, 11, 19] and we divide it into 3 subarrays in the following way: [2, 4], [5, 5], [8, 11, 19], then the cost of division is equal to (4 - 2) + (5 - 5) + (19 - 8) = 13. Calculate the minimum cost you can obtain by dividing the array a into k non-empty consecutive subarrays. Input The first line contains two integers n and k (1 ≀ k ≀ n ≀ 3 β‹… 10^5). The second line contains n integers a_1, a_2, ..., a_n ( 1 ≀ a_i ≀ 10^9, a_i β‰₯ a_{i-1}). Output Print the minimum cost you can obtain by dividing the array a into k nonempty consecutive subarrays. Examples Input 6 3 4 8 15 16 23 42 Output 12 Input 4 4 1 3 3 7 Output 0 Input 8 1 1 1 2 3 5 8 13 21 Output 20 Note In the first test we can divide array a in the following way: [4, 8, 15, 16], [23], [42].
instruction
0
107,918
12
215,836
Tags: greedy, sortings Correct Solution: ``` n,k=map(int,input().split()) a=list(map(int,input().split())) l=sorted([a[i]-a[i-1] for i in range(1,n)],reverse=True) ans=a[-1]-a[0] for i in range(k-1): ans-=l[i] print(ans) ```
output
1
107,918
12
215,837
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sorted array a_1, a_2, ..., a_n (for each index i > 1 condition a_i β‰₯ a_{i-1} holds) and an integer k. You are asked to divide this array into k non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let max(i) be equal to the maximum in the i-th subarray, and min(i) be equal to the minimum in the i-th subarray. The cost of division is equal to βˆ‘_{i=1}^{k} (max(i) - min(i)). For example, if a = [2, 4, 5, 5, 8, 11, 19] and we divide it into 3 subarrays in the following way: [2, 4], [5, 5], [8, 11, 19], then the cost of division is equal to (4 - 2) + (5 - 5) + (19 - 8) = 13. Calculate the minimum cost you can obtain by dividing the array a into k non-empty consecutive subarrays. Input The first line contains two integers n and k (1 ≀ k ≀ n ≀ 3 β‹… 10^5). The second line contains n integers a_1, a_2, ..., a_n ( 1 ≀ a_i ≀ 10^9, a_i β‰₯ a_{i-1}). Output Print the minimum cost you can obtain by dividing the array a into k nonempty consecutive subarrays. Examples Input 6 3 4 8 15 16 23 42 Output 12 Input 4 4 1 3 3 7 Output 0 Input 8 1 1 1 2 3 5 8 13 21 Output 20 Note In the first test we can divide array a in the following way: [4, 8, 15, 16], [23], [42].
instruction
0
107,919
12
215,838
Tags: greedy, sortings Correct Solution: ``` n,k=map(int,input().split()) a=list(map(int,input().split())) ans=a[n-1]-a[0] l=[] for i in range(1,n): l.append(a[i-1]-a[i]) l.sort() ans+=sum(l[:k-1]) print(ans) ```
output
1
107,919
12
215,839
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sorted array a_1, a_2, ..., a_n (for each index i > 1 condition a_i β‰₯ a_{i-1} holds) and an integer k. You are asked to divide this array into k non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let max(i) be equal to the maximum in the i-th subarray, and min(i) be equal to the minimum in the i-th subarray. The cost of division is equal to βˆ‘_{i=1}^{k} (max(i) - min(i)). For example, if a = [2, 4, 5, 5, 8, 11, 19] and we divide it into 3 subarrays in the following way: [2, 4], [5, 5], [8, 11, 19], then the cost of division is equal to (4 - 2) + (5 - 5) + (19 - 8) = 13. Calculate the minimum cost you can obtain by dividing the array a into k non-empty consecutive subarrays. Input The first line contains two integers n and k (1 ≀ k ≀ n ≀ 3 β‹… 10^5). The second line contains n integers a_1, a_2, ..., a_n ( 1 ≀ a_i ≀ 10^9, a_i β‰₯ a_{i-1}). Output Print the minimum cost you can obtain by dividing the array a into k nonempty consecutive subarrays. Examples Input 6 3 4 8 15 16 23 42 Output 12 Input 4 4 1 3 3 7 Output 0 Input 8 1 1 1 2 3 5 8 13 21 Output 20 Note In the first test we can divide array a in the following way: [4, 8, 15, 16], [23], [42].
instruction
0
107,920
12
215,840
Tags: greedy, sortings Correct Solution: ``` n,k=map(int,input().split()) a=[int(x) for x in input().split()] if n==k: print(0) else: b=[0]*(n-1) for i in range (0,n-1): b[i]=a[i+1]-a[i] b=sorted(b) s=0 for j in range (0,n-k): s=s+b[j] print(s) ```
output
1
107,920
12
215,841
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sorted array a_1, a_2, ..., a_n (for each index i > 1 condition a_i β‰₯ a_{i-1} holds) and an integer k. You are asked to divide this array into k non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let max(i) be equal to the maximum in the i-th subarray, and min(i) be equal to the minimum in the i-th subarray. The cost of division is equal to βˆ‘_{i=1}^{k} (max(i) - min(i)). For example, if a = [2, 4, 5, 5, 8, 11, 19] and we divide it into 3 subarrays in the following way: [2, 4], [5, 5], [8, 11, 19], then the cost of division is equal to (4 - 2) + (5 - 5) + (19 - 8) = 13. Calculate the minimum cost you can obtain by dividing the array a into k non-empty consecutive subarrays. Input The first line contains two integers n and k (1 ≀ k ≀ n ≀ 3 β‹… 10^5). The second line contains n integers a_1, a_2, ..., a_n ( 1 ≀ a_i ≀ 10^9, a_i β‰₯ a_{i-1}). Output Print the minimum cost you can obtain by dividing the array a into k nonempty consecutive subarrays. Examples Input 6 3 4 8 15 16 23 42 Output 12 Input 4 4 1 3 3 7 Output 0 Input 8 1 1 1 2 3 5 8 13 21 Output 20 Note In the first test we can divide array a in the following way: [4, 8, 15, 16], [23], [42].
instruction
0
107,921
12
215,842
Tags: greedy, sortings Correct Solution: ``` n,k = map(int,input().split(" ")) a= list(map(int, input().split(" "))) diff = [] for i in range(n-1): diff.append(a[i+1]-a[i]) diff = sorted(diff) res = 0 for i in range(n-k): res += diff[i] print(res) ```
output
1
107,921
12
215,843
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sorted array a_1, a_2, ..., a_n (for each index i > 1 condition a_i β‰₯ a_{i-1} holds) and an integer k. You are asked to divide this array into k non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let max(i) be equal to the maximum in the i-th subarray, and min(i) be equal to the minimum in the i-th subarray. The cost of division is equal to βˆ‘_{i=1}^{k} (max(i) - min(i)). For example, if a = [2, 4, 5, 5, 8, 11, 19] and we divide it into 3 subarrays in the following way: [2, 4], [5, 5], [8, 11, 19], then the cost of division is equal to (4 - 2) + (5 - 5) + (19 - 8) = 13. Calculate the minimum cost you can obtain by dividing the array a into k non-empty consecutive subarrays. Input The first line contains two integers n and k (1 ≀ k ≀ n ≀ 3 β‹… 10^5). The second line contains n integers a_1, a_2, ..., a_n ( 1 ≀ a_i ≀ 10^9, a_i β‰₯ a_{i-1}). Output Print the minimum cost you can obtain by dividing the array a into k nonempty consecutive subarrays. Examples Input 6 3 4 8 15 16 23 42 Output 12 Input 4 4 1 3 3 7 Output 0 Input 8 1 1 1 2 3 5 8 13 21 Output 20 Note In the first test we can divide array a in the following way: [4, 8, 15, 16], [23], [42]. Submitted Solution: ``` n, k = map(int, input().split()) a = list(map(int, input().split())) if n==k: print(0) elif k == 1: print(a[n-1]-a[0]) else: x = [] for i in range(1, n): y = a[i]-a[i-1] x.append(y) x.sort() ans = sum(x[:n-k]) print(ans) ```
instruction
0
107,922
12
215,844
Yes
output
1
107,922
12
215,845
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sorted array a_1, a_2, ..., a_n (for each index i > 1 condition a_i β‰₯ a_{i-1} holds) and an integer k. You are asked to divide this array into k non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let max(i) be equal to the maximum in the i-th subarray, and min(i) be equal to the minimum in the i-th subarray. The cost of division is equal to βˆ‘_{i=1}^{k} (max(i) - min(i)). For example, if a = [2, 4, 5, 5, 8, 11, 19] and we divide it into 3 subarrays in the following way: [2, 4], [5, 5], [8, 11, 19], then the cost of division is equal to (4 - 2) + (5 - 5) + (19 - 8) = 13. Calculate the minimum cost you can obtain by dividing the array a into k non-empty consecutive subarrays. Input The first line contains two integers n and k (1 ≀ k ≀ n ≀ 3 β‹… 10^5). The second line contains n integers a_1, a_2, ..., a_n ( 1 ≀ a_i ≀ 10^9, a_i β‰₯ a_{i-1}). Output Print the minimum cost you can obtain by dividing the array a into k nonempty consecutive subarrays. Examples Input 6 3 4 8 15 16 23 42 Output 12 Input 4 4 1 3 3 7 Output 0 Input 8 1 1 1 2 3 5 8 13 21 Output 20 Note In the first test we can divide array a in the following way: [4, 8, 15, 16], [23], [42]. Submitted Solution: ``` n, k=map(int, input().split()) a=list(map(int, input().split())) if n==k: p=0 elif k==1: p=a[n-1]-a[0] else: for i in range(n-1): a[i]=a[i+1]-a[i] del a[n-1] a.sort() n-=k p=0 for i in range(n): p+=a[i] print(p) ```
instruction
0
107,923
12
215,846
Yes
output
1
107,923
12
215,847
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sorted array a_1, a_2, ..., a_n (for each index i > 1 condition a_i β‰₯ a_{i-1} holds) and an integer k. You are asked to divide this array into k non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let max(i) be equal to the maximum in the i-th subarray, and min(i) be equal to the minimum in the i-th subarray. The cost of division is equal to βˆ‘_{i=1}^{k} (max(i) - min(i)). For example, if a = [2, 4, 5, 5, 8, 11, 19] and we divide it into 3 subarrays in the following way: [2, 4], [5, 5], [8, 11, 19], then the cost of division is equal to (4 - 2) + (5 - 5) + (19 - 8) = 13. Calculate the minimum cost you can obtain by dividing the array a into k non-empty consecutive subarrays. Input The first line contains two integers n and k (1 ≀ k ≀ n ≀ 3 β‹… 10^5). The second line contains n integers a_1, a_2, ..., a_n ( 1 ≀ a_i ≀ 10^9, a_i β‰₯ a_{i-1}). Output Print the minimum cost you can obtain by dividing the array a into k nonempty consecutive subarrays. Examples Input 6 3 4 8 15 16 23 42 Output 12 Input 4 4 1 3 3 7 Output 0 Input 8 1 1 1 2 3 5 8 13 21 Output 20 Note In the first test we can divide array a in the following way: [4, 8, 15, 16], [23], [42]. Submitted Solution: ``` n,k=map(int, input().split()) a=list(map(int, input().split())) if k==1: print(a[-1]-a[0]) exit() if k==n: print("0") exit() f=0 b=[] for i in range(n-1): if a[i]==a[i+1]: continue b.append(a[i]) b.append(a[-1]) nn=len(b) if k>=nn: print('0') exit() c=[] for i in range(1,n): c.append([a[i]-a[i-1],i]) c.sort(reverse=True) ans=0 d=[] for i in range(k-1): d.append(c[i][1]) d.sort() d.append(n) m=a[0] for i in range(len(d)): ans+=(a[d[i]-1]-m) if i==len(d)-1: break m=a[d[i]] print(ans) ```
instruction
0
107,924
12
215,848
Yes
output
1
107,924
12
215,849
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sorted array a_1, a_2, ..., a_n (for each index i > 1 condition a_i β‰₯ a_{i-1} holds) and an integer k. You are asked to divide this array into k non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let max(i) be equal to the maximum in the i-th subarray, and min(i) be equal to the minimum in the i-th subarray. The cost of division is equal to βˆ‘_{i=1}^{k} (max(i) - min(i)). For example, if a = [2, 4, 5, 5, 8, 11, 19] and we divide it into 3 subarrays in the following way: [2, 4], [5, 5], [8, 11, 19], then the cost of division is equal to (4 - 2) + (5 - 5) + (19 - 8) = 13. Calculate the minimum cost you can obtain by dividing the array a into k non-empty consecutive subarrays. Input The first line contains two integers n and k (1 ≀ k ≀ n ≀ 3 β‹… 10^5). The second line contains n integers a_1, a_2, ..., a_n ( 1 ≀ a_i ≀ 10^9, a_i β‰₯ a_{i-1}). Output Print the minimum cost you can obtain by dividing the array a into k nonempty consecutive subarrays. Examples Input 6 3 4 8 15 16 23 42 Output 12 Input 4 4 1 3 3 7 Output 0 Input 8 1 1 1 2 3 5 8 13 21 Output 20 Note In the first test we can divide array a in the following way: [4, 8, 15, 16], [23], [42]. Submitted Solution: ``` I = lambda: int(input()) IL = lambda: list(map(int, input().split())) IF = lambda: list(map(float, input().split())) n, k = IL() A = IL() B = sorted([a1-a0 for a0, a1 in zip(A[:-1], A[1:])]) print(sum(B[:n-k])) ```
instruction
0
107,925
12
215,850
Yes
output
1
107,925
12
215,851
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sorted array a_1, a_2, ..., a_n (for each index i > 1 condition a_i β‰₯ a_{i-1} holds) and an integer k. You are asked to divide this array into k non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let max(i) be equal to the maximum in the i-th subarray, and min(i) be equal to the minimum in the i-th subarray. The cost of division is equal to βˆ‘_{i=1}^{k} (max(i) - min(i)). For example, if a = [2, 4, 5, 5, 8, 11, 19] and we divide it into 3 subarrays in the following way: [2, 4], [5, 5], [8, 11, 19], then the cost of division is equal to (4 - 2) + (5 - 5) + (19 - 8) = 13. Calculate the minimum cost you can obtain by dividing the array a into k non-empty consecutive subarrays. Input The first line contains two integers n and k (1 ≀ k ≀ n ≀ 3 β‹… 10^5). The second line contains n integers a_1, a_2, ..., a_n ( 1 ≀ a_i ≀ 10^9, a_i β‰₯ a_{i-1}). Output Print the minimum cost you can obtain by dividing the array a into k nonempty consecutive subarrays. Examples Input 6 3 4 8 15 16 23 42 Output 12 Input 4 4 1 3 3 7 Output 0 Input 8 1 1 1 2 3 5 8 13 21 Output 20 Note In the first test we can divide array a in the following way: [4, 8, 15, 16], [23], [42]. Submitted Solution: ``` def fastio(): import sys from io import StringIO from atexit import register global input sys.stdin = StringIO(sys.stdin.read()) input = lambda : sys.stdin.readline().rstrip('\r\n') sys.stdout = StringIO() register(lambda : sys.__stdout__.write(sys.stdout.getvalue())) fastio() MOD = 10**9 + 7 I = lambda:list(map(int,input().split())) def fastio(): import sys from io import StringIO from atexit import register global input sys.stdin = StringIO(sys.stdin.read()) input = lambda : sys.stdin.readline().rstrip('\r\n') sys.stdout = StringIO() register(lambda : sys.__stdout__.write(sys.stdout.getvalue())) fastio() MOD = 10**9 + 7 I = lambda:list(map(int,input().split())) n, k = I() a = I() z = [a[0]] for i in a[1:]: if i != z[-1]: z.append(i) n = len(z) m = n - k a = z ans = MOD z = [] if k >= n: print(0) exit() for i in range(n-1): z.append(a[i+1]-a[i]) z.sort(reverse = True) print(a[-1] - a[0] - sum(z[:k-1])) ```
instruction
0
107,926
12
215,852
No
output
1
107,926
12
215,853
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sorted array a_1, a_2, ..., a_n (for each index i > 1 condition a_i β‰₯ a_{i-1} holds) and an integer k. You are asked to divide this array into k non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let max(i) be equal to the maximum in the i-th subarray, and min(i) be equal to the minimum in the i-th subarray. The cost of division is equal to βˆ‘_{i=1}^{k} (max(i) - min(i)). For example, if a = [2, 4, 5, 5, 8, 11, 19] and we divide it into 3 subarrays in the following way: [2, 4], [5, 5], [8, 11, 19], then the cost of division is equal to (4 - 2) + (5 - 5) + (19 - 8) = 13. Calculate the minimum cost you can obtain by dividing the array a into k non-empty consecutive subarrays. Input The first line contains two integers n and k (1 ≀ k ≀ n ≀ 3 β‹… 10^5). The second line contains n integers a_1, a_2, ..., a_n ( 1 ≀ a_i ≀ 10^9, a_i β‰₯ a_{i-1}). Output Print the minimum cost you can obtain by dividing the array a into k nonempty consecutive subarrays. Examples Input 6 3 4 8 15 16 23 42 Output 12 Input 4 4 1 3 3 7 Output 0 Input 8 1 1 1 2 3 5 8 13 21 Output 20 Note In the first test we can divide array a in the following way: [4, 8, 15, 16], [23], [42]. Submitted Solution: ``` n, k = map(int, input().split()) a = list(map(int, input().split())) if(k==1): print(max(a)-min(a)) x = len(set(a)) if x<=k or x==1: print(0) else: u = sorted(list(set(a))) print(max(u[:-k]) - min(u[:-k])) ```
instruction
0
107,927
12
215,854
No
output
1
107,927
12
215,855
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sorted array a_1, a_2, ..., a_n (for each index i > 1 condition a_i β‰₯ a_{i-1} holds) and an integer k. You are asked to divide this array into k non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let max(i) be equal to the maximum in the i-th subarray, and min(i) be equal to the minimum in the i-th subarray. The cost of division is equal to βˆ‘_{i=1}^{k} (max(i) - min(i)). For example, if a = [2, 4, 5, 5, 8, 11, 19] and we divide it into 3 subarrays in the following way: [2, 4], [5, 5], [8, 11, 19], then the cost of division is equal to (4 - 2) + (5 - 5) + (19 - 8) = 13. Calculate the minimum cost you can obtain by dividing the array a into k non-empty consecutive subarrays. Input The first line contains two integers n and k (1 ≀ k ≀ n ≀ 3 β‹… 10^5). The second line contains n integers a_1, a_2, ..., a_n ( 1 ≀ a_i ≀ 10^9, a_i β‰₯ a_{i-1}). Output Print the minimum cost you can obtain by dividing the array a into k nonempty consecutive subarrays. Examples Input 6 3 4 8 15 16 23 42 Output 12 Input 4 4 1 3 3 7 Output 0 Input 8 1 1 1 2 3 5 8 13 21 Output 20 Note In the first test we can divide array a in the following way: [4, 8, 15, 16], [23], [42]. Submitted Solution: ``` def func(n,k,arr): if(k == 1): return arr[-1] - arr[0] arr2 = [] for i in range(n-1): arr2.append((i,arr[i+1] - arr[i])) arr2.sort(key = lambda x:(-x[1])) # print(arr2) mark = [0 for i in range(n)] for i in range(k-1): mark[arr2[i][0]] = 1 ans = 0 start = 0 for i in range(n): if(mark[i] == 1): ans += arr[i] - arr[start] start = i+1 return ans a = [int(i) for i in input().split()] n = a[0] k = a[1] arr = [int(i) for i in input().split()] print(func(n,k,arr)) ```
instruction
0
107,928
12
215,856
No
output
1
107,928
12
215,857
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sorted array a_1, a_2, ..., a_n (for each index i > 1 condition a_i β‰₯ a_{i-1} holds) and an integer k. You are asked to divide this array into k non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let max(i) be equal to the maximum in the i-th subarray, and min(i) be equal to the minimum in the i-th subarray. The cost of division is equal to βˆ‘_{i=1}^{k} (max(i) - min(i)). For example, if a = [2, 4, 5, 5, 8, 11, 19] and we divide it into 3 subarrays in the following way: [2, 4], [5, 5], [8, 11, 19], then the cost of division is equal to (4 - 2) + (5 - 5) + (19 - 8) = 13. Calculate the minimum cost you can obtain by dividing the array a into k non-empty consecutive subarrays. Input The first line contains two integers n and k (1 ≀ k ≀ n ≀ 3 β‹… 10^5). The second line contains n integers a_1, a_2, ..., a_n ( 1 ≀ a_i ≀ 10^9, a_i β‰₯ a_{i-1}). Output Print the minimum cost you can obtain by dividing the array a into k nonempty consecutive subarrays. Examples Input 6 3 4 8 15 16 23 42 Output 12 Input 4 4 1 3 3 7 Output 0 Input 8 1 1 1 2 3 5 8 13 21 Output 20 Note In the first test we can divide array a in the following way: [4, 8, 15, 16], [23], [42]. Submitted Solution: ``` # cook your dish here n,k=map(int,input().split(" ")) y=list(map(int,input().split())) c=[] if n==k: print(0) else: x=n-k j=x while j<n: c.append(y[j]-y[j-x]) j+=1 print(min(c)) ```
instruction
0
107,929
12
215,858
No
output
1
107,929
12
215,859
Provide tags and a correct Python 3 solution for this coding contest problem. Yeah, we failed to make up a New Year legend for this problem. A permutation of length n is an array of n integers such that every integer from 1 to n appears in it exactly once. An element y of permutation p is reachable from element x if x = y, or p_x = y, or p_{p_x} = y, and so on. The decomposition of a permutation p is defined as follows: firstly, we have a permutation p, all elements of which are not marked, and an empty list l. Then we do the following: while there is at least one not marked element in p, we find the leftmost such element, list all elements that are reachable from it in the order they appear in p, mark all of these elements, then cyclically shift the list of those elements so that the maximum appears at the first position, and add this list as an element of l. After all elements are marked, l is the result of this decomposition. For example, if we want to build a decomposition of p = [5, 4, 2, 3, 1, 7, 8, 6], we do the following: 1. initially p = [5, 4, 2, 3, 1, 7, 8, 6] (bold elements are marked), l = []; 2. the leftmost unmarked element is 5; 5 and 1 are reachable from it, so the list we want to shift is [5, 1]; there is no need to shift it, since maximum is already the first element; 3. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1]]; 4. the leftmost unmarked element is 4, the list of reachable elements is [4, 2, 3]; the maximum is already the first element, so there's no need to shift it; 5. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1], [4, 2, 3]]; 6. the leftmost unmarked element is 7, the list of reachable elements is [7, 8, 6]; we have to shift it, so it becomes [8, 6, 7]; 7. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1], [4, 2, 3], [8, 6, 7]]; 8. all elements are marked, so [[5, 1], [4, 2, 3], [8, 6, 7]] is the result. The New Year transformation of a permutation is defined as follows: we build the decomposition of this permutation; then we sort all lists in decomposition in ascending order of the first elements (we don't swap the elements in these lists, only the lists themselves); then we concatenate the lists into one list which becomes a new permutation. For example, the New Year transformation of p = [5, 4, 2, 3, 1, 7, 8, 6] is built as follows: 1. the decomposition is [[5, 1], [4, 2, 3], [8, 6, 7]]; 2. after sorting the decomposition, it becomes [[4, 2, 3], [5, 1], [8, 6, 7]]; 3. [4, 2, 3, 5, 1, 8, 6, 7] is the result of the transformation. We call a permutation good if the result of its transformation is the same as the permutation itself. For example, [4, 3, 1, 2, 8, 5, 6, 7] is a good permutation; and [5, 4, 2, 3, 1, 7, 8, 6] is bad, since the result of transformation is [4, 2, 3, 5, 1, 8, 6, 7]. Your task is the following: given n and k, find the k-th (lexicographically) good permutation of length n. Input The first line contains one integer t (1 ≀ t ≀ 1000) β€” the number of test cases. Then the test cases follow. Each test case is represented by one line containing two integers n and k (1 ≀ n ≀ 50, 1 ≀ k ≀ 10^{18}). Output For each test case, print the answer to it as follows: if the number of good permutations of length n is less than k, print one integer -1; otherwise, print the k-th good permutation on n elements (in lexicographical order). Example Input 5 3 3 5 15 4 13 6 8 4 2 Output 2 1 3 3 1 2 5 4 -1 1 2 6 3 4 5 1 2 4 3
instruction
0
107,956
12
215,912
Tags: combinatorics, dp Correct Solution: ``` import math # init maxn = 55 g = [1] for i in range(maxn): g.append(math.factorial(i)) f = [0] * maxn f[0] = 1 for i in range(1, maxn): for j in range(i): f[i] += f[j] * g[i - j - 1] def kth(n, k): if n == 1: return [1] ret = [-1] * n ret[0] = n - 1 p1 = [i for i in range(n)] p2 = [i for i in range(n)] vis = [False] * n p1[0] = n - 1 p2[n - 1] = 0 vis[n - 1] = True for i in range(1, n - 1): j = 0 now = math.factorial(n - i - 2) while True: while vis[j] or (i < n - 1 and j == p2[i]): j += 1 if k > now: k -= now j += 1 else: p1[p2[i]] = p1[j] p2[p1[j]] = p2[i] ret[i] = j vis[j] = True break ret[-1] = p2[-1] return [x + 1 for x in ret] def solve(n, k): if n == 0: return [] i = 1 while g[i - 1] * f[n - i] < k: k -= g[i - 1] * f[n - i] i += 1 rem = solve(n - i, (k - 1) % f[n - i] + 1) rem = [x + i for x in rem] k = (k - 1) // f[n - i] + 1 return kth(i, k) + rem def SOLVE(): n, k = map(int, input().split()) if k > f[n]: print(-1) return ans = solve(n, k) for x in ans: print(x, end = " ") print() T = int(input()) while T > 0: T -= 1 SOLVE() # # ```
output
1
107,956
12
215,913
Provide tags and a correct Python 3 solution for this coding contest problem. Yeah, we failed to make up a New Year legend for this problem. A permutation of length n is an array of n integers such that every integer from 1 to n appears in it exactly once. An element y of permutation p is reachable from element x if x = y, or p_x = y, or p_{p_x} = y, and so on. The decomposition of a permutation p is defined as follows: firstly, we have a permutation p, all elements of which are not marked, and an empty list l. Then we do the following: while there is at least one not marked element in p, we find the leftmost such element, list all elements that are reachable from it in the order they appear in p, mark all of these elements, then cyclically shift the list of those elements so that the maximum appears at the first position, and add this list as an element of l. After all elements are marked, l is the result of this decomposition. For example, if we want to build a decomposition of p = [5, 4, 2, 3, 1, 7, 8, 6], we do the following: 1. initially p = [5, 4, 2, 3, 1, 7, 8, 6] (bold elements are marked), l = []; 2. the leftmost unmarked element is 5; 5 and 1 are reachable from it, so the list we want to shift is [5, 1]; there is no need to shift it, since maximum is already the first element; 3. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1]]; 4. the leftmost unmarked element is 4, the list of reachable elements is [4, 2, 3]; the maximum is already the first element, so there's no need to shift it; 5. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1], [4, 2, 3]]; 6. the leftmost unmarked element is 7, the list of reachable elements is [7, 8, 6]; we have to shift it, so it becomes [8, 6, 7]; 7. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1], [4, 2, 3], [8, 6, 7]]; 8. all elements are marked, so [[5, 1], [4, 2, 3], [8, 6, 7]] is the result. The New Year transformation of a permutation is defined as follows: we build the decomposition of this permutation; then we sort all lists in decomposition in ascending order of the first elements (we don't swap the elements in these lists, only the lists themselves); then we concatenate the lists into one list which becomes a new permutation. For example, the New Year transformation of p = [5, 4, 2, 3, 1, 7, 8, 6] is built as follows: 1. the decomposition is [[5, 1], [4, 2, 3], [8, 6, 7]]; 2. after sorting the decomposition, it becomes [[4, 2, 3], [5, 1], [8, 6, 7]]; 3. [4, 2, 3, 5, 1, 8, 6, 7] is the result of the transformation. We call a permutation good if the result of its transformation is the same as the permutation itself. For example, [4, 3, 1, 2, 8, 5, 6, 7] is a good permutation; and [5, 4, 2, 3, 1, 7, 8, 6] is bad, since the result of transformation is [4, 2, 3, 5, 1, 8, 6, 7]. Your task is the following: given n and k, find the k-th (lexicographically) good permutation of length n. Input The first line contains one integer t (1 ≀ t ≀ 1000) β€” the number of test cases. Then the test cases follow. Each test case is represented by one line containing two integers n and k (1 ≀ n ≀ 50, 1 ≀ k ≀ 10^{18}). Output For each test case, print the answer to it as follows: if the number of good permutations of length n is less than k, print one integer -1; otherwise, print the k-th good permutation on n elements (in lexicographical order). Example Input 5 3 3 5 15 4 13 6 8 4 2 Output 2 1 3 3 1 2 5 4 -1 1 2 6 3 4 5 1 2 4 3
instruction
0
107,957
12
215,914
Tags: combinatorics, dp Correct Solution: ``` import math # init maxn = 55 g = [1] for i in range(maxn): g.append(math.factorial(i)) f = [0] * maxn f[0] = 1 for i in range(1, maxn): for j in range(i): f[i] += f[j] * g[i - j - 1] def kth(n, k): if n == 1: return [1] ret = [-1] * n ret[0] = n - 1 p1 = [i for i in range(n)] p2 = [i for i in range(n)] vis = [False] * n p1[0] = n - 1 p2[n - 1] = 0 vis[n - 1] = True for i in range(1, n - 1): j = 0 now = math.factorial(n - i - 2) while True: while vis[j] or (i < n - 1 and j == p2[i]): j += 1 if k > now: k -= now j += 1 else: p1[p2[i]] = p1[j] p2[p1[j]] = p2[i] ret[i] = j vis[j] = True break ret[-1] = p2[-1] return [x + 1 for x in ret] def solve(n, k): if n == 0: return [] i = 1 while g[i - 1] * f[n - i] < k: k -= g[i - 1] * f[n - i] i += 1 rem = solve(n - i, (k - 1) % f[n - i] + 1) rem = [x + i for x in rem] k = (k - 1) // f[n - i] + 1 return kth(i, k) + rem def SOLVE(): n, k = map(int, input().split()) if k > f[n]: print(-1) return ans = solve(n, k) for x in ans: print(x, end = " ") print() T = int(input()) while T > 0: T -= 1 SOLVE() ```
output
1
107,957
12
215,915
Provide tags and a correct Python 3 solution for this coding contest problem. Yeah, we failed to make up a New Year legend for this problem. A permutation of length n is an array of n integers such that every integer from 1 to n appears in it exactly once. An element y of permutation p is reachable from element x if x = y, or p_x = y, or p_{p_x} = y, and so on. The decomposition of a permutation p is defined as follows: firstly, we have a permutation p, all elements of which are not marked, and an empty list l. Then we do the following: while there is at least one not marked element in p, we find the leftmost such element, list all elements that are reachable from it in the order they appear in p, mark all of these elements, then cyclically shift the list of those elements so that the maximum appears at the first position, and add this list as an element of l. After all elements are marked, l is the result of this decomposition. For example, if we want to build a decomposition of p = [5, 4, 2, 3, 1, 7, 8, 6], we do the following: 1. initially p = [5, 4, 2, 3, 1, 7, 8, 6] (bold elements are marked), l = []; 2. the leftmost unmarked element is 5; 5 and 1 are reachable from it, so the list we want to shift is [5, 1]; there is no need to shift it, since maximum is already the first element; 3. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1]]; 4. the leftmost unmarked element is 4, the list of reachable elements is [4, 2, 3]; the maximum is already the first element, so there's no need to shift it; 5. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1], [4, 2, 3]]; 6. the leftmost unmarked element is 7, the list of reachable elements is [7, 8, 6]; we have to shift it, so it becomes [8, 6, 7]; 7. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1], [4, 2, 3], [8, 6, 7]]; 8. all elements are marked, so [[5, 1], [4, 2, 3], [8, 6, 7]] is the result. The New Year transformation of a permutation is defined as follows: we build the decomposition of this permutation; then we sort all lists in decomposition in ascending order of the first elements (we don't swap the elements in these lists, only the lists themselves); then we concatenate the lists into one list which becomes a new permutation. For example, the New Year transformation of p = [5, 4, 2, 3, 1, 7, 8, 6] is built as follows: 1. the decomposition is [[5, 1], [4, 2, 3], [8, 6, 7]]; 2. after sorting the decomposition, it becomes [[4, 2, 3], [5, 1], [8, 6, 7]]; 3. [4, 2, 3, 5, 1, 8, 6, 7] is the result of the transformation. We call a permutation good if the result of its transformation is the same as the permutation itself. For example, [4, 3, 1, 2, 8, 5, 6, 7] is a good permutation; and [5, 4, 2, 3, 1, 7, 8, 6] is bad, since the result of transformation is [4, 2, 3, 5, 1, 8, 6, 7]. Your task is the following: given n and k, find the k-th (lexicographically) good permutation of length n. Input The first line contains one integer t (1 ≀ t ≀ 1000) β€” the number of test cases. Then the test cases follow. Each test case is represented by one line containing two integers n and k (1 ≀ n ≀ 50, 1 ≀ k ≀ 10^{18}). Output For each test case, print the answer to it as follows: if the number of good permutations of length n is less than k, print one integer -1; otherwise, print the k-th good permutation on n elements (in lexicographical order). Example Input 5 3 3 5 15 4 13 6 8 4 2 Output 2 1 3 3 1 2 5 4 -1 1 2 6 3 4 5 1 2 4 3
instruction
0
107,958
12
215,916
Tags: combinatorics, dp Correct Solution: ``` MAXN = 55 f = [0] * MAXN fac = [0] * MAXN fac[0] = 1 for i in range(1, 51): fac[i] = fac[i - 1] * i f[0] = 1; for i in range(1, 51): f[i] += f[i - 1] for j in range(2, i + 1): f[i] += fac[j - 2] * f[i - j] def my_fac(n): if n <= 0: return 1 return fac[n] def solve_first(n, k): ret = [0] * (n + 1) ret[1] = n for p in range(2, n + 1): for i in range(1, n + 1): if i in ret or i == p: continue ret[p] = i cur = p good = True for fuck in range(0, n - 1): cur = ret[cur] if cur == 0: good = True break if cur == p: good = False break if not good: ret[p] = 0 continue k1 = my_fac(n - p - 1) if k > k1: k -= k1 else: break ret[p] = 0 ret.pop(0) assert len(ret) == n return ret; def solve(n, k): if k == 1: ret = [] for i in range(1, n + 1): ret.append(i) return ret tot = 0 first = -1 for i in range(1, n + 1): if tot + my_fac(i - 2) * f[n - i] >= k: first = i break; tot += my_fac(i - 2) * f[n - i] k -= tot cnt1 = my_fac(first - 1) cnt2 = f[n - first] x = k // cnt2 + 1 y = k % cnt2 if y == 0: y = cnt2 x -= 1 ret = solve_first(first, x) for v in solve(n - first, y): ret.append(v + first) return ret T = int(input()) for t in range(0, T): s = input().split() n = int(s[0]) k = int(s[1]) if (k > f[n]): print("-1") else: ans = solve(n, k) for x in ans: print(x, end=" ") print("") ```
output
1
107,958
12
215,917
Provide tags and a correct Python 3 solution for this coding contest problem. Yeah, we failed to make up a New Year legend for this problem. A permutation of length n is an array of n integers such that every integer from 1 to n appears in it exactly once. An element y of permutation p is reachable from element x if x = y, or p_x = y, or p_{p_x} = y, and so on. The decomposition of a permutation p is defined as follows: firstly, we have a permutation p, all elements of which are not marked, and an empty list l. Then we do the following: while there is at least one not marked element in p, we find the leftmost such element, list all elements that are reachable from it in the order they appear in p, mark all of these elements, then cyclically shift the list of those elements so that the maximum appears at the first position, and add this list as an element of l. After all elements are marked, l is the result of this decomposition. For example, if we want to build a decomposition of p = [5, 4, 2, 3, 1, 7, 8, 6], we do the following: 1. initially p = [5, 4, 2, 3, 1, 7, 8, 6] (bold elements are marked), l = []; 2. the leftmost unmarked element is 5; 5 and 1 are reachable from it, so the list we want to shift is [5, 1]; there is no need to shift it, since maximum is already the first element; 3. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1]]; 4. the leftmost unmarked element is 4, the list of reachable elements is [4, 2, 3]; the maximum is already the first element, so there's no need to shift it; 5. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1], [4, 2, 3]]; 6. the leftmost unmarked element is 7, the list of reachable elements is [7, 8, 6]; we have to shift it, so it becomes [8, 6, 7]; 7. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1], [4, 2, 3], [8, 6, 7]]; 8. all elements are marked, so [[5, 1], [4, 2, 3], [8, 6, 7]] is the result. The New Year transformation of a permutation is defined as follows: we build the decomposition of this permutation; then we sort all lists in decomposition in ascending order of the first elements (we don't swap the elements in these lists, only the lists themselves); then we concatenate the lists into one list which becomes a new permutation. For example, the New Year transformation of p = [5, 4, 2, 3, 1, 7, 8, 6] is built as follows: 1. the decomposition is [[5, 1], [4, 2, 3], [8, 6, 7]]; 2. after sorting the decomposition, it becomes [[4, 2, 3], [5, 1], [8, 6, 7]]; 3. [4, 2, 3, 5, 1, 8, 6, 7] is the result of the transformation. We call a permutation good if the result of its transformation is the same as the permutation itself. For example, [4, 3, 1, 2, 8, 5, 6, 7] is a good permutation; and [5, 4, 2, 3, 1, 7, 8, 6] is bad, since the result of transformation is [4, 2, 3, 5, 1, 8, 6, 7]. Your task is the following: given n and k, find the k-th (lexicographically) good permutation of length n. Input The first line contains one integer t (1 ≀ t ≀ 1000) β€” the number of test cases. Then the test cases follow. Each test case is represented by one line containing two integers n and k (1 ≀ n ≀ 50, 1 ≀ k ≀ 10^{18}). Output For each test case, print the answer to it as follows: if the number of good permutations of length n is less than k, print one integer -1; otherwise, print the k-th good permutation on n elements (in lexicographical order). Example Input 5 3 3 5 15 4 13 6 8 4 2 Output 2 1 3 3 1 2 5 4 -1 1 2 6 3 4 5 1 2 4 3
instruction
0
107,959
12
215,918
Tags: combinatorics, dp Correct Solution: ``` #!/usr/bin/python3 from math import factorial as fact N = 55 c = [1] for i in range(N): c.append(fact(i)) dp = [0] * N dp[0] = 1 for i in range(1, N): for j in range(i): dp[i] += dp[j] * c[i - j - 1] def get_kth_cycle(n, k): if n == 1: return [1] ans = [-1] * n ans[0] = n - 1 fin = [i for i in range(n)] fin[0] = n - 1 init = [i for i in range(n)] init[n - 1] = 0 used = [False] * n used[n - 1] = True for i in range(1, n - 1): j = 0 cur = fact(n - i - 2) while True: while used[j] or (i < n - 1 and j == init[i]): j += 1 if k > cur: k -= cur j += 1 else: fin[init[i]] = fin[j] init[fin[j]] = init[i] ans[i] = j used[j] = True break ans[-1] = init[-1] return [x + 1 for x in ans] def f(n, k): if n == 0: assert k == 1 return [] cl = 1 while c[cl - 1] * dp[n - cl] < k: k -= c[cl - 1] * dp[n - cl] cl += 1 rest = f(n - cl, (k - 1) % dp[n - cl] + 1) rest = [x + cl for x in rest] k = (k - 1) // dp[n - cl] + 1 return get_kth_cycle(cl, k) + rest def solve(): n, k = map(int, input().split()) if k > dp[n]: print(-1) return print(*f(n, k)) def main(): t = int(input()) while t > 0: t -= 1 solve() main() ```
output
1
107,959
12
215,919
Provide tags and a correct Python 3 solution for this coding contest problem. Yeah, we failed to make up a New Year legend for this problem. A permutation of length n is an array of n integers such that every integer from 1 to n appears in it exactly once. An element y of permutation p is reachable from element x if x = y, or p_x = y, or p_{p_x} = y, and so on. The decomposition of a permutation p is defined as follows: firstly, we have a permutation p, all elements of which are not marked, and an empty list l. Then we do the following: while there is at least one not marked element in p, we find the leftmost such element, list all elements that are reachable from it in the order they appear in p, mark all of these elements, then cyclically shift the list of those elements so that the maximum appears at the first position, and add this list as an element of l. After all elements are marked, l is the result of this decomposition. For example, if we want to build a decomposition of p = [5, 4, 2, 3, 1, 7, 8, 6], we do the following: 1. initially p = [5, 4, 2, 3, 1, 7, 8, 6] (bold elements are marked), l = []; 2. the leftmost unmarked element is 5; 5 and 1 are reachable from it, so the list we want to shift is [5, 1]; there is no need to shift it, since maximum is already the first element; 3. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1]]; 4. the leftmost unmarked element is 4, the list of reachable elements is [4, 2, 3]; the maximum is already the first element, so there's no need to shift it; 5. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1], [4, 2, 3]]; 6. the leftmost unmarked element is 7, the list of reachable elements is [7, 8, 6]; we have to shift it, so it becomes [8, 6, 7]; 7. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1], [4, 2, 3], [8, 6, 7]]; 8. all elements are marked, so [[5, 1], [4, 2, 3], [8, 6, 7]] is the result. The New Year transformation of a permutation is defined as follows: we build the decomposition of this permutation; then we sort all lists in decomposition in ascending order of the first elements (we don't swap the elements in these lists, only the lists themselves); then we concatenate the lists into one list which becomes a new permutation. For example, the New Year transformation of p = [5, 4, 2, 3, 1, 7, 8, 6] is built as follows: 1. the decomposition is [[5, 1], [4, 2, 3], [8, 6, 7]]; 2. after sorting the decomposition, it becomes [[4, 2, 3], [5, 1], [8, 6, 7]]; 3. [4, 2, 3, 5, 1, 8, 6, 7] is the result of the transformation. We call a permutation good if the result of its transformation is the same as the permutation itself. For example, [4, 3, 1, 2, 8, 5, 6, 7] is a good permutation; and [5, 4, 2, 3, 1, 7, 8, 6] is bad, since the result of transformation is [4, 2, 3, 5, 1, 8, 6, 7]. Your task is the following: given n and k, find the k-th (lexicographically) good permutation of length n. Input The first line contains one integer t (1 ≀ t ≀ 1000) β€” the number of test cases. Then the test cases follow. Each test case is represented by one line containing two integers n and k (1 ≀ n ≀ 50, 1 ≀ k ≀ 10^{18}). Output For each test case, print the answer to it as follows: if the number of good permutations of length n is less than k, print one integer -1; otherwise, print the k-th good permutation on n elements (in lexicographical order). Example Input 5 3 3 5 15 4 13 6 8 4 2 Output 2 1 3 3 1 2 5 4 -1 1 2 6 3 4 5 1 2 4 3
instruction
0
107,960
12
215,920
Tags: combinatorics, dp Correct Solution: ``` from math import factorial as fact N = 55 c = [1] for i in range(N): c.append(fact(i)) dp = [0] * N dp[0] = 1 for i in range(1, N): for j in range(i): dp[i] += dp[j] * c[i - j - 1] def get_kth_cycle(n, k): if n == 1: return [1] ans = [-1] * n ans[0] = n - 1 fin = [i for i in range(n)] fin[0] = n - 1 init = [i for i in range(n)] init[n - 1] = 0 used = [False] * n used[n - 1] = True for i in range(1, n - 1): j = 0 cur = fact(n - i - 2) while True: while used[j] or (i < n - 1 and j == init[i]): j += 1 if k > cur: k -= cur j += 1 else: fin[init[i]] = fin[j] init[fin[j]] = init[i] ans[i] = j used[j] = True break ans[-1] = init[-1] return [x + 1 for x in ans] def f(n, k): if n == 0: assert k == 1 return [] cl = 1 while c[cl - 1] * dp[n - cl] < k: k -= c[cl - 1] * dp[n - cl] cl += 1 rest = f(n - cl, (k - 1) % dp[n - cl] + 1) rest = [x + cl for x in rest] k = (k - 1) // dp[n - cl] + 1 return get_kth_cycle(cl, k) + rest def solve(): n, k = map(int, input().split()) if k > dp[n]: print(-1) return print(*f(n, k)) def main(): t = int(input()) while t > 0: t -= 1 solve() main() ```
output
1
107,960
12
215,921
Provide tags and a correct Python 3 solution for this coding contest problem. Yeah, we failed to make up a New Year legend for this problem. A permutation of length n is an array of n integers such that every integer from 1 to n appears in it exactly once. An element y of permutation p is reachable from element x if x = y, or p_x = y, or p_{p_x} = y, and so on. The decomposition of a permutation p is defined as follows: firstly, we have a permutation p, all elements of which are not marked, and an empty list l. Then we do the following: while there is at least one not marked element in p, we find the leftmost such element, list all elements that are reachable from it in the order they appear in p, mark all of these elements, then cyclically shift the list of those elements so that the maximum appears at the first position, and add this list as an element of l. After all elements are marked, l is the result of this decomposition. For example, if we want to build a decomposition of p = [5, 4, 2, 3, 1, 7, 8, 6], we do the following: 1. initially p = [5, 4, 2, 3, 1, 7, 8, 6] (bold elements are marked), l = []; 2. the leftmost unmarked element is 5; 5 and 1 are reachable from it, so the list we want to shift is [5, 1]; there is no need to shift it, since maximum is already the first element; 3. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1]]; 4. the leftmost unmarked element is 4, the list of reachable elements is [4, 2, 3]; the maximum is already the first element, so there's no need to shift it; 5. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1], [4, 2, 3]]; 6. the leftmost unmarked element is 7, the list of reachable elements is [7, 8, 6]; we have to shift it, so it becomes [8, 6, 7]; 7. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1], [4, 2, 3], [8, 6, 7]]; 8. all elements are marked, so [[5, 1], [4, 2, 3], [8, 6, 7]] is the result. The New Year transformation of a permutation is defined as follows: we build the decomposition of this permutation; then we sort all lists in decomposition in ascending order of the first elements (we don't swap the elements in these lists, only the lists themselves); then we concatenate the lists into one list which becomes a new permutation. For example, the New Year transformation of p = [5, 4, 2, 3, 1, 7, 8, 6] is built as follows: 1. the decomposition is [[5, 1], [4, 2, 3], [8, 6, 7]]; 2. after sorting the decomposition, it becomes [[4, 2, 3], [5, 1], [8, 6, 7]]; 3. [4, 2, 3, 5, 1, 8, 6, 7] is the result of the transformation. We call a permutation good if the result of its transformation is the same as the permutation itself. For example, [4, 3, 1, 2, 8, 5, 6, 7] is a good permutation; and [5, 4, 2, 3, 1, 7, 8, 6] is bad, since the result of transformation is [4, 2, 3, 5, 1, 8, 6, 7]. Your task is the following: given n and k, find the k-th (lexicographically) good permutation of length n. Input The first line contains one integer t (1 ≀ t ≀ 1000) β€” the number of test cases. Then the test cases follow. Each test case is represented by one line containing two integers n and k (1 ≀ n ≀ 50, 1 ≀ k ≀ 10^{18}). Output For each test case, print the answer to it as follows: if the number of good permutations of length n is less than k, print one integer -1; otherwise, print the k-th good permutation on n elements (in lexicographical order). Example Input 5 3 3 5 15 4 13 6 8 4 2 Output 2 1 3 3 1 2 5 4 -1 1 2 6 3 4 5 1 2 4 3
instruction
0
107,961
12
215,922
Tags: combinatorics, dp Correct Solution: ``` from itertools import accumulate from math import * import os, sys import threading from io import BytesIO from bisect import bisect_left input = BytesIO(os.read(0, os.fstat(0).st_size)).readline from math import factorial as fact N = 55 c = [1] for i in range(N): c.append(fact(i)) dp = [0] * N dp[0] = 1 for i in range(1, N): for j in range(i): dp[i] += dp[j] * c[i - j - 1] def get_kth_cycle(n, k): if n == 1: return [1] ans = [-1] * n ans[0] = n - 1 fin = [i for i in range(n)] fin[0] = n - 1 init = [i for i in range(n)] init[n - 1] = 0 used = [False] * n used[n - 1] = True for i in range(1, n - 1): j = 0 cur = fact(n - i - 2) while True: while used[j] or (i < n - 1 and j == init[i]): j += 1 if k > cur: k -= cur j += 1 else: fin[init[i]] = fin[j] init[fin[j]] = init[i] ans[i] = j used[j] = True break ans[-1] = init[-1] return [x + 1 for x in ans] def f(n, k): if n == 0: assert k == 1 return [] cl = 1 while c[cl - 1] * dp[n - cl] < k: k -= c[cl - 1] * dp[n - cl] cl += 1 rest = f(n - cl, (k - 1) % dp[n - cl] + 1) rest = [x + cl for x in rest] k = (k - 1) // dp[n - cl] + 1 return get_kth_cycle(cl, k) + rest def solve(): n, k = map(int, input().split()) if k > dp[n]: print(-1) return print(*f(n, k)) t = int(input()) while t > 0: t -= 1 solve() ```
output
1
107,961
12
215,923
Provide tags and a correct Python 3 solution for this coding contest problem. Yeah, we failed to make up a New Year legend for this problem. A permutation of length n is an array of n integers such that every integer from 1 to n appears in it exactly once. An element y of permutation p is reachable from element x if x = y, or p_x = y, or p_{p_x} = y, and so on. The decomposition of a permutation p is defined as follows: firstly, we have a permutation p, all elements of which are not marked, and an empty list l. Then we do the following: while there is at least one not marked element in p, we find the leftmost such element, list all elements that are reachable from it in the order they appear in p, mark all of these elements, then cyclically shift the list of those elements so that the maximum appears at the first position, and add this list as an element of l. After all elements are marked, l is the result of this decomposition. For example, if we want to build a decomposition of p = [5, 4, 2, 3, 1, 7, 8, 6], we do the following: 1. initially p = [5, 4, 2, 3, 1, 7, 8, 6] (bold elements are marked), l = []; 2. the leftmost unmarked element is 5; 5 and 1 are reachable from it, so the list we want to shift is [5, 1]; there is no need to shift it, since maximum is already the first element; 3. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1]]; 4. the leftmost unmarked element is 4, the list of reachable elements is [4, 2, 3]; the maximum is already the first element, so there's no need to shift it; 5. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1], [4, 2, 3]]; 6. the leftmost unmarked element is 7, the list of reachable elements is [7, 8, 6]; we have to shift it, so it becomes [8, 6, 7]; 7. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1], [4, 2, 3], [8, 6, 7]]; 8. all elements are marked, so [[5, 1], [4, 2, 3], [8, 6, 7]] is the result. The New Year transformation of a permutation is defined as follows: we build the decomposition of this permutation; then we sort all lists in decomposition in ascending order of the first elements (we don't swap the elements in these lists, only the lists themselves); then we concatenate the lists into one list which becomes a new permutation. For example, the New Year transformation of p = [5, 4, 2, 3, 1, 7, 8, 6] is built as follows: 1. the decomposition is [[5, 1], [4, 2, 3], [8, 6, 7]]; 2. after sorting the decomposition, it becomes [[4, 2, 3], [5, 1], [8, 6, 7]]; 3. [4, 2, 3, 5, 1, 8, 6, 7] is the result of the transformation. We call a permutation good if the result of its transformation is the same as the permutation itself. For example, [4, 3, 1, 2, 8, 5, 6, 7] is a good permutation; and [5, 4, 2, 3, 1, 7, 8, 6] is bad, since the result of transformation is [4, 2, 3, 5, 1, 8, 6, 7]. Your task is the following: given n and k, find the k-th (lexicographically) good permutation of length n. Input The first line contains one integer t (1 ≀ t ≀ 1000) β€” the number of test cases. Then the test cases follow. Each test case is represented by one line containing two integers n and k (1 ≀ n ≀ 50, 1 ≀ k ≀ 10^{18}). Output For each test case, print the answer to it as follows: if the number of good permutations of length n is less than k, print one integer -1; otherwise, print the k-th good permutation on n elements (in lexicographical order). Example Input 5 3 3 5 15 4 13 6 8 4 2 Output 2 1 3 3 1 2 5 4 -1 1 2 6 3 4 5 1 2 4 3
instruction
0
107,962
12
215,924
Tags: combinatorics, dp Correct Solution: ``` from sys import stdin, stdout from math import factorial # Precompute N = 55 cyc = [1] * N for i in range(1, N): cyc[i] = factorial(i - 1) dp = [0] * N dp[0] = 1 for i in range(1, N): for j in range(i): dp[i] += dp[j] * cyc[i - j - 1] # Done Precompute def kth_cycle(n, k): if n == 1: return [1] res = [-1] * n res[0] = n - 1 used = [False] * n used[n - 1] = True fr = [i for i in range(n)] # from fr[n - 1] = 0 to = [i for i in range(n)] # to to[0] = n - 1 for i in range(1, n - 1): cur = factorial(n - i - 2) # number of cycles for j in range(n): if used[j] or j == fr[i]: # will create a loop j += 1 elif k > cur: k -= cur j += 1 else: to[fr[i]] = to[j] # next = to check for loops fr[to[j]] = fr[i] # to = to check for loops res[i] = j used[j] = True break res[n - 1] = fr[n - 1] return [x + 1 for x in res] def solve(n, k): if n == 0: assert k == 1 return [] cnt = 1 while cyc[cnt - 1] * dp[n - cnt] < k: k -= cyc[cnt - 1] * dp[n - cnt] cnt += 1 nxt = (k - 1) % dp[n - cnt] + 1 kth = (k - 1) // dp[n - cnt] + 1 other = solve(n - cnt, nxt) other = [x + cnt for x in other] return kth_cycle(cnt, kth) + other def solve_testcase(): n, k = [int(x) for x in stdin.readline().split()] if dp[n] < k: stdout.write("-1\n") return ans = solve(n, k) for i in ans: stdout.write(str(i) + " ") stdout.write("\n") def main(): t = int(stdin.readline()) for i in range(t): solve_testcase() main() ```
output
1
107,962
12
215,925
Provide tags and a correct Python 3 solution for this coding contest problem. Yeah, we failed to make up a New Year legend for this problem. A permutation of length n is an array of n integers such that every integer from 1 to n appears in it exactly once. An element y of permutation p is reachable from element x if x = y, or p_x = y, or p_{p_x} = y, and so on. The decomposition of a permutation p is defined as follows: firstly, we have a permutation p, all elements of which are not marked, and an empty list l. Then we do the following: while there is at least one not marked element in p, we find the leftmost such element, list all elements that are reachable from it in the order they appear in p, mark all of these elements, then cyclically shift the list of those elements so that the maximum appears at the first position, and add this list as an element of l. After all elements are marked, l is the result of this decomposition. For example, if we want to build a decomposition of p = [5, 4, 2, 3, 1, 7, 8, 6], we do the following: 1. initially p = [5, 4, 2, 3, 1, 7, 8, 6] (bold elements are marked), l = []; 2. the leftmost unmarked element is 5; 5 and 1 are reachable from it, so the list we want to shift is [5, 1]; there is no need to shift it, since maximum is already the first element; 3. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1]]; 4. the leftmost unmarked element is 4, the list of reachable elements is [4, 2, 3]; the maximum is already the first element, so there's no need to shift it; 5. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1], [4, 2, 3]]; 6. the leftmost unmarked element is 7, the list of reachable elements is [7, 8, 6]; we have to shift it, so it becomes [8, 6, 7]; 7. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1], [4, 2, 3], [8, 6, 7]]; 8. all elements are marked, so [[5, 1], [4, 2, 3], [8, 6, 7]] is the result. The New Year transformation of a permutation is defined as follows: we build the decomposition of this permutation; then we sort all lists in decomposition in ascending order of the first elements (we don't swap the elements in these lists, only the lists themselves); then we concatenate the lists into one list which becomes a new permutation. For example, the New Year transformation of p = [5, 4, 2, 3, 1, 7, 8, 6] is built as follows: 1. the decomposition is [[5, 1], [4, 2, 3], [8, 6, 7]]; 2. after sorting the decomposition, it becomes [[4, 2, 3], [5, 1], [8, 6, 7]]; 3. [4, 2, 3, 5, 1, 8, 6, 7] is the result of the transformation. We call a permutation good if the result of its transformation is the same as the permutation itself. For example, [4, 3, 1, 2, 8, 5, 6, 7] is a good permutation; and [5, 4, 2, 3, 1, 7, 8, 6] is bad, since the result of transformation is [4, 2, 3, 5, 1, 8, 6, 7]. Your task is the following: given n and k, find the k-th (lexicographically) good permutation of length n. Input The first line contains one integer t (1 ≀ t ≀ 1000) β€” the number of test cases. Then the test cases follow. Each test case is represented by one line containing two integers n and k (1 ≀ n ≀ 50, 1 ≀ k ≀ 10^{18}). Output For each test case, print the answer to it as follows: if the number of good permutations of length n is less than k, print one integer -1; otherwise, print the k-th good permutation on n elements (in lexicographical order). Example Input 5 3 3 5 15 4 13 6 8 4 2 Output 2 1 3 3 1 2 5 4 -1 1 2 6 3 4 5 1 2 4 3
instruction
0
107,963
12
215,926
Tags: combinatorics, dp Correct Solution: ``` # 1279E - New Year Permutations # Idea: # dp(i) --> # of good permutations of [i,n] # cycles(m) --> # of blocks of len m ( == (m-2)! as first element is fixed) # It is easy to test for impossibility ie. k > dp(1) # Another subproblem: how to compute jth smallest cycle # getGoodPerm(n,k) uses both getCycle(b, (k/dp[n-b])) and getGoodPerm(n-b, k%dp[n-b]) # TIME LIMIT EXCEEDED import math from decimal import * getcontext().prec = 50 # try to do in O(n) # simple implementation of the union find class DSU: def __init__(self, n): self.hash = {} for i in range(1, n+1): self.hash[i] = [i] def union(self, i, j): lst1 = self.hash[i] lst2 = self.hash[j] lst1.extend(lst2) for element in lst2: self.hash[element] = lst1 def same_set(self, i, j): return j in self.hash[i] def getKthPerm(lst, k, offset): if len(lst)-1 == offset: return True elif len(lst) <= offset: # incorrect params return False else: n = len(lst) - offset #print("n,k,offset == %d, %d, %d" % (n, k, offset)) index = (math.ceil(k/(math.factorial(n-1)))-1) + offset #print("index == %d" % index) if index >= len(lst): # to large k return False # move element at index up front if index > offset: temp = lst[index] lst.pop(index) lst.insert(offset, temp) while k-math.factorial(n-1) > 0: k -= math.factorial(n-1) return getKthPerm(lst, k, offset+1) def getKthCycle(n, k, fact): lst = [i-1 for i in range(n+1)] # num of ends that still dont have incoming link num_open = n dsu = DSU(n) dsu.union(1, n) lst[1] = n num_open -= 1 pos = 2 while pos < n: i = pos while i <= n: if dsu.same_set(pos, lst[i]): pass else: if k <= fact[num_open-2]: break else: k -= fact[num_open-2] i += 1 if i == n+1: # k is too large return None else: num_open -= 1 dsu.union(pos, lst[i]) # move the element at pos i to "pos" # while keeping the sorted-ness of lst temp = lst[i] j = i while j > pos: lst[j] = lst[j-1] j -= 1 lst[pos] = temp pos += 1 return lst[1:] # number of cycles with n elements def cycles(n, fact): if n <= 1: return 1 else: if n-2 in fact: return fact[n-2] else: return math.factorial(n-2) # number of good permutations of [i,n] def dp(i, n, table, fact): if i > n: return 0 elif i == n: return 1 else: if i in table: return table[i] else: val = 0 for j in range(i, n+1): val += dp(j+1, n, table, fact)*cycles(j-i+1, fact) table[i] = val return val def Max(i, table, fact): if i in table: return table[i] else: if i <= 1: table[i] = 1 return 1 else: val = 0 for j in range(1, i+1): val += Max(i-j, table, fact)*cycles(j, fact) table[i] = val return val def getKthGoodPermutation(n, k, Max, fact): if Max[n] < k: # k is too large return None if n == 1: if k == 1: return [1] else: return None block_len = 1 while k - cycles(block_len, fact)*Max[n-block_len] > 0: k -= cycles(block_len, fact)*Max[n-block_len] block_len += 1 k_block = math.ceil(Decimal(k)/Decimal(Max[n-block_len])) k_rem = k - (k_block - 1)*Max[n-block_len] new_lst = getKthCycle(block_len, k_block, fact) if n-block_len > 0: rem_lst = getKthGoodPermutation(n-block_len, k_rem, Max, fact) for i in range(len(rem_lst)): rem_lst[i] += block_len new_lst.extend(rem_lst) return new_lst def compute_fact(n, table): table[0] = 1 table[1] = 1 x = 2 while x <= n: table[x] = x*table[x-1] x += 1 return if __name__ == '__main__': T = int(input()) N, K = [], [] for _ in range(T): inp = input().rstrip().split(" ") n, k = int(inp[0]), int(inp[1]) N.append(n) K.append(k) # prepare tables max_n = max(N) + 5 fact = {} compute_fact(max_n, fact) dp_table = {} a = 1 while a <= max_n: Max(a, dp_table, fact) a += 1 j = 0 while j < len(N): lst = getKthGoodPermutation(N[j], K[j], dp_table, fact) if lst != None: for i in range(len(lst)): lst[i] = str(lst[i]) print(" ".join(lst)) else: print("-1") j += 1 ```
output
1
107,963
12
215,927
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Yeah, we failed to make up a New Year legend for this problem. A permutation of length n is an array of n integers such that every integer from 1 to n appears in it exactly once. An element y of permutation p is reachable from element x if x = y, or p_x = y, or p_{p_x} = y, and so on. The decomposition of a permutation p is defined as follows: firstly, we have a permutation p, all elements of which are not marked, and an empty list l. Then we do the following: while there is at least one not marked element in p, we find the leftmost such element, list all elements that are reachable from it in the order they appear in p, mark all of these elements, then cyclically shift the list of those elements so that the maximum appears at the first position, and add this list as an element of l. After all elements are marked, l is the result of this decomposition. For example, if we want to build a decomposition of p = [5, 4, 2, 3, 1, 7, 8, 6], we do the following: 1. initially p = [5, 4, 2, 3, 1, 7, 8, 6] (bold elements are marked), l = []; 2. the leftmost unmarked element is 5; 5 and 1 are reachable from it, so the list we want to shift is [5, 1]; there is no need to shift it, since maximum is already the first element; 3. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1]]; 4. the leftmost unmarked element is 4, the list of reachable elements is [4, 2, 3]; the maximum is already the first element, so there's no need to shift it; 5. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1], [4, 2, 3]]; 6. the leftmost unmarked element is 7, the list of reachable elements is [7, 8, 6]; we have to shift it, so it becomes [8, 6, 7]; 7. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1], [4, 2, 3], [8, 6, 7]]; 8. all elements are marked, so [[5, 1], [4, 2, 3], [8, 6, 7]] is the result. The New Year transformation of a permutation is defined as follows: we build the decomposition of this permutation; then we sort all lists in decomposition in ascending order of the first elements (we don't swap the elements in these lists, only the lists themselves); then we concatenate the lists into one list which becomes a new permutation. For example, the New Year transformation of p = [5, 4, 2, 3, 1, 7, 8, 6] is built as follows: 1. the decomposition is [[5, 1], [4, 2, 3], [8, 6, 7]]; 2. after sorting the decomposition, it becomes [[4, 2, 3], [5, 1], [8, 6, 7]]; 3. [4, 2, 3, 5, 1, 8, 6, 7] is the result of the transformation. We call a permutation good if the result of its transformation is the same as the permutation itself. For example, [4, 3, 1, 2, 8, 5, 6, 7] is a good permutation; and [5, 4, 2, 3, 1, 7, 8, 6] is bad, since the result of transformation is [4, 2, 3, 5, 1, 8, 6, 7]. Your task is the following: given n and k, find the k-th (lexicographically) good permutation of length n. Input The first line contains one integer t (1 ≀ t ≀ 1000) β€” the number of test cases. Then the test cases follow. Each test case is represented by one line containing two integers n and k (1 ≀ n ≀ 50, 1 ≀ k ≀ 10^{18}). Output For each test case, print the answer to it as follows: if the number of good permutations of length n is less than k, print one integer -1; otherwise, print the k-th good permutation on n elements (in lexicographical order). Example Input 5 3 3 5 15 4 13 6 8 4 2 Output 2 1 3 3 1 2 5 4 -1 1 2 6 3 4 5 1 2 4 3 Submitted Solution: ``` T = int(input()) f = [1] for i in range(60): f.append(f[-1] * (i + 1)) dp = [1] for i in range(1, 55): dp.append(0) for j in range(1, i + 1): dp[i] += f[max(0, j - 2)] * dp[i - j] def get(n, k): if n <= 0 or dp[n] < k: return [] have = 0 a = [] for i in range(1, n + 1): have += dp[n - i] * f[max(0, i - 2)] if have >= k: a.append(i) have -= dp[n - i] * f[max(0, i - 2)] break k0 = k - have if len(a) == 0: return [-1] left = list(range(1, a[0])) while len(left) > 0: for j in left: have += f[max(0, len(left) - 1)] * dp[n - a[0]] if have >= k0: have -= f[max(0, len(left) - 1)] * dp[n - a[0]] left = left[:left.index(j)] + left[left.index(j) + 1:] a.append(j) break b = get(n - len(a), k - have) for i in range(len(b)): b[i] += len(a) return a + b for _ in range(T): n, k = list(map(int, input().split())) if dp[n] < k: print(-1) else: print(*get(n, k)); ```
instruction
0
107,964
12
215,928
No
output
1
107,964
12
215,929
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Yeah, we failed to make up a New Year legend for this problem. A permutation of length n is an array of n integers such that every integer from 1 to n appears in it exactly once. An element y of permutation p is reachable from element x if x = y, or p_x = y, or p_{p_x} = y, and so on. The decomposition of a permutation p is defined as follows: firstly, we have a permutation p, all elements of which are not marked, and an empty list l. Then we do the following: while there is at least one not marked element in p, we find the leftmost such element, list all elements that are reachable from it in the order they appear in p, mark all of these elements, then cyclically shift the list of those elements so that the maximum appears at the first position, and add this list as an element of l. After all elements are marked, l is the result of this decomposition. For example, if we want to build a decomposition of p = [5, 4, 2, 3, 1, 7, 8, 6], we do the following: 1. initially p = [5, 4, 2, 3, 1, 7, 8, 6] (bold elements are marked), l = []; 2. the leftmost unmarked element is 5; 5 and 1 are reachable from it, so the list we want to shift is [5, 1]; there is no need to shift it, since maximum is already the first element; 3. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1]]; 4. the leftmost unmarked element is 4, the list of reachable elements is [4, 2, 3]; the maximum is already the first element, so there's no need to shift it; 5. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1], [4, 2, 3]]; 6. the leftmost unmarked element is 7, the list of reachable elements is [7, 8, 6]; we have to shift it, so it becomes [8, 6, 7]; 7. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1], [4, 2, 3], [8, 6, 7]]; 8. all elements are marked, so [[5, 1], [4, 2, 3], [8, 6, 7]] is the result. The New Year transformation of a permutation is defined as follows: we build the decomposition of this permutation; then we sort all lists in decomposition in ascending order of the first elements (we don't swap the elements in these lists, only the lists themselves); then we concatenate the lists into one list which becomes a new permutation. For example, the New Year transformation of p = [5, 4, 2, 3, 1, 7, 8, 6] is built as follows: 1. the decomposition is [[5, 1], [4, 2, 3], [8, 6, 7]]; 2. after sorting the decomposition, it becomes [[4, 2, 3], [5, 1], [8, 6, 7]]; 3. [4, 2, 3, 5, 1, 8, 6, 7] is the result of the transformation. We call a permutation good if the result of its transformation is the same as the permutation itself. For example, [4, 3, 1, 2, 8, 5, 6, 7] is a good permutation; and [5, 4, 2, 3, 1, 7, 8, 6] is bad, since the result of transformation is [4, 2, 3, 5, 1, 8, 6, 7]. Your task is the following: given n and k, find the k-th (lexicographically) good permutation of length n. Input The first line contains one integer t (1 ≀ t ≀ 1000) β€” the number of test cases. Then the test cases follow. Each test case is represented by one line containing two integers n and k (1 ≀ n ≀ 50, 1 ≀ k ≀ 10^{18}). Output For each test case, print the answer to it as follows: if the number of good permutations of length n is less than k, print one integer -1; otherwise, print the k-th good permutation on n elements (in lexicographical order). Example Input 5 3 3 5 15 4 13 6 8 4 2 Output 2 1 3 3 1 2 5 4 -1 1 2 6 3 4 5 1 2 4 3 Submitted Solution: ``` import math # init maxn = 55 g = [1] for i in range(maxn): g.append(math.factorial(i)) f = [0] * maxn f[0] = 1 for i in range(1, maxn): for j in range(i): f[i] += f[j] * g[i - j - 1] def kth(n, k): if n == 1: return [1] ret = [-1] * n ret[0] = n - 1 p1 = [i for i in range(n)] p2 = [i for i in range(n)] vis = [False] * n p1[0] = n - 1 p2[n - 1] = 0 vis[n - 1] = True for i in range(1, n - 1): j = 0 now = math.factorial(n - i - 2) while True: while vis[j] or (i < n - 1 and j == p2[i]): j += 1 if k > now: k -= now j += 1 else: p1[p2[i]] = p1[j] p2[p1[j]] = p2[i] ret[i] = j vis[j] = True break ret[-1] = p2[-1] return [x + 1 for x in ret] def solve(n, k): if n == 0: return [] i = 1 while g[i - 1] * f[n - i] < k: k -= g[i - 1] * f[n - i] i += 1 rem = solve(n - i, (k - 1) % f[n - i] + 1) rem = [x + i for x in rem] k = (k - 1) // f[n - i] + 1 return kth(i, k) + rem def SOLVE(): n, k = map(int, input().split()) if k > f[n]: print(-1) return ans = solve(n, k+1) for x in ans: print(x, end = " ") print() T = int(input()) while T > 0: T -= 1 SOLVE() ```
instruction
0
107,965
12
215,930
No
output
1
107,965
12
215,931
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Yeah, we failed to make up a New Year legend for this problem. A permutation of length n is an array of n integers such that every integer from 1 to n appears in it exactly once. An element y of permutation p is reachable from element x if x = y, or p_x = y, or p_{p_x} = y, and so on. The decomposition of a permutation p is defined as follows: firstly, we have a permutation p, all elements of which are not marked, and an empty list l. Then we do the following: while there is at least one not marked element in p, we find the leftmost such element, list all elements that are reachable from it in the order they appear in p, mark all of these elements, then cyclically shift the list of those elements so that the maximum appears at the first position, and add this list as an element of l. After all elements are marked, l is the result of this decomposition. For example, if we want to build a decomposition of p = [5, 4, 2, 3, 1, 7, 8, 6], we do the following: 1. initially p = [5, 4, 2, 3, 1, 7, 8, 6] (bold elements are marked), l = []; 2. the leftmost unmarked element is 5; 5 and 1 are reachable from it, so the list we want to shift is [5, 1]; there is no need to shift it, since maximum is already the first element; 3. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1]]; 4. the leftmost unmarked element is 4, the list of reachable elements is [4, 2, 3]; the maximum is already the first element, so there's no need to shift it; 5. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1], [4, 2, 3]]; 6. the leftmost unmarked element is 7, the list of reachable elements is [7, 8, 6]; we have to shift it, so it becomes [8, 6, 7]; 7. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1], [4, 2, 3], [8, 6, 7]]; 8. all elements are marked, so [[5, 1], [4, 2, 3], [8, 6, 7]] is the result. The New Year transformation of a permutation is defined as follows: we build the decomposition of this permutation; then we sort all lists in decomposition in ascending order of the first elements (we don't swap the elements in these lists, only the lists themselves); then we concatenate the lists into one list which becomes a new permutation. For example, the New Year transformation of p = [5, 4, 2, 3, 1, 7, 8, 6] is built as follows: 1. the decomposition is [[5, 1], [4, 2, 3], [8, 6, 7]]; 2. after sorting the decomposition, it becomes [[4, 2, 3], [5, 1], [8, 6, 7]]; 3. [4, 2, 3, 5, 1, 8, 6, 7] is the result of the transformation. We call a permutation good if the result of its transformation is the same as the permutation itself. For example, [4, 3, 1, 2, 8, 5, 6, 7] is a good permutation; and [5, 4, 2, 3, 1, 7, 8, 6] is bad, since the result of transformation is [4, 2, 3, 5, 1, 8, 6, 7]. Your task is the following: given n and k, find the k-th (lexicographically) good permutation of length n. Input The first line contains one integer t (1 ≀ t ≀ 1000) β€” the number of test cases. Then the test cases follow. Each test case is represented by one line containing two integers n and k (1 ≀ n ≀ 50, 1 ≀ k ≀ 10^{18}). Output For each test case, print the answer to it as follows: if the number of good permutations of length n is less than k, print one integer -1; otherwise, print the k-th good permutation on n elements (in lexicographical order). Example Input 5 3 3 5 15 4 13 6 8 4 2 Output 2 1 3 3 1 2 5 4 -1 1 2 6 3 4 5 1 2 4 3 Submitted Solution: ``` from sys import stdin, stdout from math import factorial # Precompute N = 55 cyc = [1] * N for i in range(1, N): cyc[i] = factorial(i - 1) dp = [0] * N dp[0] = 1 for i in range(1, N): for j in range(i): dp[i] += dp[j] * cyc[i - j - 1] # Done Precompute def kth_cycle(n, k): if n == 1: return [1] digits = [i for i in range(n)] res = [-1] * n res[0] = n - 1 digits.pop(n - 1) for i in range(1, n): cur = factorial(n - i - 1) j = 0 while True: if k > cur: k -= cur j += 1 else: res[i] = digits[j] digits.pop(j) break return [x + 1 for x in res] def solve(n, k): if n == 0: assert k == 1 return [] cnt = 1 while cyc[cnt - 1] * dp[n - cnt] < k: k -= cyc[cnt - 1] * dp[n - cnt] cnt += 1 nxt = (k - 1) % dp[n - cnt] + 1 kth = (k - 1) // dp[n - cnt] + 1 other = solve(n - cnt, nxt) other = [x + cnt for x in other] return kth_cycle(cnt, kth) + other def solve_testcase(): n, k = [int(x) for x in stdin.readline().split()] if dp[n] < k: stdout.write("-1\n") return ans = solve(n, k) for i in ans: stdout.write(str(i) + " ") stdout.write("\n") def main(): t = int(stdin.readline()) for i in range(t): solve_testcase() main() ```
instruction
0
107,966
12
215,932
No
output
1
107,966
12
215,933
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Yeah, we failed to make up a New Year legend for this problem. A permutation of length n is an array of n integers such that every integer from 1 to n appears in it exactly once. An element y of permutation p is reachable from element x if x = y, or p_x = y, or p_{p_x} = y, and so on. The decomposition of a permutation p is defined as follows: firstly, we have a permutation p, all elements of which are not marked, and an empty list l. Then we do the following: while there is at least one not marked element in p, we find the leftmost such element, list all elements that are reachable from it in the order they appear in p, mark all of these elements, then cyclically shift the list of those elements so that the maximum appears at the first position, and add this list as an element of l. After all elements are marked, l is the result of this decomposition. For example, if we want to build a decomposition of p = [5, 4, 2, 3, 1, 7, 8, 6], we do the following: 1. initially p = [5, 4, 2, 3, 1, 7, 8, 6] (bold elements are marked), l = []; 2. the leftmost unmarked element is 5; 5 and 1 are reachable from it, so the list we want to shift is [5, 1]; there is no need to shift it, since maximum is already the first element; 3. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1]]; 4. the leftmost unmarked element is 4, the list of reachable elements is [4, 2, 3]; the maximum is already the first element, so there's no need to shift it; 5. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1], [4, 2, 3]]; 6. the leftmost unmarked element is 7, the list of reachable elements is [7, 8, 6]; we have to shift it, so it becomes [8, 6, 7]; 7. p = [5, 4, 2, 3, 1, 7, 8, 6], l = [[5, 1], [4, 2, 3], [8, 6, 7]]; 8. all elements are marked, so [[5, 1], [4, 2, 3], [8, 6, 7]] is the result. The New Year transformation of a permutation is defined as follows: we build the decomposition of this permutation; then we sort all lists in decomposition in ascending order of the first elements (we don't swap the elements in these lists, only the lists themselves); then we concatenate the lists into one list which becomes a new permutation. For example, the New Year transformation of p = [5, 4, 2, 3, 1, 7, 8, 6] is built as follows: 1. the decomposition is [[5, 1], [4, 2, 3], [8, 6, 7]]; 2. after sorting the decomposition, it becomes [[4, 2, 3], [5, 1], [8, 6, 7]]; 3. [4, 2, 3, 5, 1, 8, 6, 7] is the result of the transformation. We call a permutation good if the result of its transformation is the same as the permutation itself. For example, [4, 3, 1, 2, 8, 5, 6, 7] is a good permutation; and [5, 4, 2, 3, 1, 7, 8, 6] is bad, since the result of transformation is [4, 2, 3, 5, 1, 8, 6, 7]. Your task is the following: given n and k, find the k-th (lexicographically) good permutation of length n. Input The first line contains one integer t (1 ≀ t ≀ 1000) β€” the number of test cases. Then the test cases follow. Each test case is represented by one line containing two integers n and k (1 ≀ n ≀ 50, 1 ≀ k ≀ 10^{18}). Output For each test case, print the answer to it as follows: if the number of good permutations of length n is less than k, print one integer -1; otherwise, print the k-th good permutation on n elements (in lexicographical order). Example Input 5 3 3 5 15 4 13 6 8 4 2 Output 2 1 3 3 1 2 5 4 -1 1 2 6 3 4 5 1 2 4 3 Submitted Solution: ``` import math dp = [0]*52 dp[0] = 1 fact = [math.factorial(i) for i in range(52)] for i in range(1, 52): for t in range(1, i+1): dp[i] += dp[i-t] * (1 if t < 2 else math.factorial(t-2)) def kthperm(n, k): # nonrecursive version S = [i+2 for i in range(n-1)] + [1] P = [] while S != []: f = math.factorial(len(S)-1) i = int(math.floor(k/f)) x = S[i] k = k%f P.append(x) S = S[:i] + S[i+1:] return P nbElem, posK = -1,-1 posK -= 1 tab = [-5]*52 def recherche(resteElem, resteRank): idxFirst = nbElem-resteElem if resteElem == 0: return taille = 1 origRank = resteRank while resteElem != taille and (1 if taille < 2 else fact[taille-2]) * dp[resteElem-taille] <= resteRank: resteRank -= (1 if taille < 2 else fact[taille-2]) * dp[resteElem-taille] taille += 1 suivRoule = dp[resteElem-taille] idxLast = idxFirst + taille - 1 rech = resteRank // suivRoule if taille <= 2: tab[idxFirst] = idxLast tab[idxLast] = idxFirst else: permIcare = kthperm(taille-2, rech) for i in range(taille-2): permIcare[i] += idxFirst tab[idxFirst] = idxLast tab[idxLast] = permIcare[0] for i in range(taille-3): tab[permIcare[i]] = permIcare[i+1] tab[permIcare[-1]] = idxFirst recherche(resteElem-taille, resteRank % suivRoule) tt = int(input()) for i in range(tt): nbElem, posK = map(int, input().split()) posK -= 1 if posK >= dp[nbElem]: print(-1) else: recherche(nbElem, posK) for i in range(nbElem): print(tab[i]+1,end=" ") print() ```
instruction
0
107,967
12
215,934
No
output
1
107,967
12
215,935
Provide tags and a correct Python 3 solution for this coding contest problem. You're given an array a of n integers, such that a_1 + a_2 + β‹…β‹…β‹… + a_n = 0. In one operation, you can choose two different indices i and j (1 ≀ i, j ≀ n), decrement a_i by one and increment a_j by one. If i < j this operation is free, otherwise it costs one coin. How many coins do you have to spend in order to make all elements equal to 0? Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 5000). Description of the test cases follows. The first line of each test case contains an integer n (1 ≀ n ≀ 10^5) β€” the number of elements. The next line contains n integers a_1, …, a_n (-10^9 ≀ a_i ≀ 10^9). It is given that βˆ‘_{i=1}^n a_i = 0. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print the minimum number of coins we have to spend in order to make all elements equal to 0. Example Input 7 4 -3 5 -3 1 2 1 -1 4 -3 2 -3 4 4 -1 1 1 -1 7 -5 7 -6 -4 17 -13 4 6 -1000000000 -1000000000 -1000000000 1000000000 1000000000 1000000000 1 0 Output 3 0 4 1 8 3000000000 0 Note Possible strategy for the first test case: * Do (i=2, j=3) three times (free), a = [-3, 2, 0, 1]. * Do (i=2, j=1) two times (pay two coins), a = [-1, 0, 0, 1]. * Do (i=4, j=1) one time (pay one coin), a = [0, 0, 0, 0].
instruction
0
108,020
12
216,040
Tags: constructive algorithms, implementation Correct Solution: ``` import sys import bisect as bi import math from collections import defaultdict as dd import heapq import itertools ##import operator input=sys.stdin.readline import random ##sys.setrecursionlimit(10**7) ##fo=open("output.txt","w") ##fi=open("input2.txt","w") mo=10**9+7 def cin(): return map(int,sin().split()) def ain(): return list(map(int,sin().split())) def sin(): return input() def inin(): return int(input()) def pref(a,n,f): pre=[0]*n if(f==0): ##from beginning pre[0]=a[0] for i in range(1,n): pre[i]=a[i]+pre[i-1] else: ##from end pre[-1]=a[-1] for i in range(n-2,-1,-1): pre[i]=pre[i+1]+a[i] return pre for _ in range(inin()): n=inin() l=ain() post=pref(l,n,1) ma=max(post) print(ma) ## n,k=cin() ## d=dd(int) ## x=ain() ## y=ain() ## for i in x: ## d[i]+=1 ## d=sorted(d.items(),key = lambda x:x[1],reverse=True) ## print(d) ##def msb(n):n|=n>>1;n|=n>>2;n|=n>>4;n|=n>>8;n|=n>>16;n|=n>>32;n|=n>>64;return n-(n>>1) #2 ki power ##def pref(a,n,f): ## pre=[0]*n ## if(f==0): ##from beginning ## pre[0]=a[0] ## for i in range(1,n): ## pre[i]=a[i]+pre[i-1] ## else: ##from end ## pre[-1]=a[-1] ## for i in range(n-2,-1,-1): ## pre[i]=pre[i+1]+a[i] ## return pre ##maxint=10**24 ##def kadane(a,size): ## max_so_far = -maxint - 1 ## max_ending_here = 0 ## ## for i in range(0, size): ## max_ending_here = max_ending_here + a[i] ## if (max_so_far < max_ending_here): ## max_so_far = max_ending_here ## ## if max_ending_here < 0: ## max_ending_here = 0 ## return max_so_far ##def power(x, y): ## if(y == 0):return 1 ## temp = power(x, int(y / 2))%mo ## if (y % 2 == 0):return (temp * temp)%mo ## else: ## if(y > 0):return (x * temp * temp)%mo ## else:return ((temp * temp)//x )%mo ```
output
1
108,020
12
216,041
Provide tags and a correct Python 3 solution for this coding contest problem. Kolya got an integer array a_1, a_2, ..., a_n. The array can contain both positive and negative integers, but Kolya doesn't like 0, so the array doesn't contain any zeros. Kolya doesn't like that the sum of some subsegments of his array can be 0. The subsegment is some consecutive segment of elements of the array. You have to help Kolya and change his array in such a way that it doesn't contain any subsegments with the sum 0. To reach this goal, you can insert any integers between any pair of adjacent elements of the array (integers can be really any: positive, negative, 0, any by absolute value, even such a huge that they can't be represented in most standard programming languages). Your task is to find the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0. Input The first line of the input contains one integer n (2 ≀ n ≀ 200 000) β€” the number of elements in Kolya's array. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^{9} ≀ a_i ≀ 10^{9}, a_i β‰  0) β€” the description of Kolya's array. Output Print the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0. Examples Input 4 1 -5 3 2 Output 1 Input 5 4 -2 3 -9 2 Output 0 Input 9 -1 1 -1 1 -1 1 1 -1 -1 Output 6 Input 8 16 -5 -11 -15 10 5 4 -4 Output 3 Note Consider the first example. There is only one subsegment with the sum 0. It starts in the second element and ends in the fourth element. It's enough to insert one element so the array doesn't contain any subsegments with the sum equal to zero. For example, it is possible to insert the integer 1 between second and third elements of the array. There are no subsegments having sum 0 in the second example so you don't need to do anything.
instruction
0
108,036
12
216,072
Tags: constructive algorithms, data structures, greedy, sortings Correct Solution: ``` from sys import stdin,stdout import math from bisect import bisect_left from collections import Counter,deque,defaultdict L=lambda:list(map(int, stdin.readline().strip().split())) M=lambda:map(int, stdin.readline().strip().split()) I=lambda:int(stdin.readline().strip()) S=lambda:stdin.readline().strip() C=lambda:stdin.readline().strip().split() def pr(a):return(" ".join(list(map(str,a)))) #_______________--------------------------______________# def solve(): n = I() a = L() ans, s = 0, 0 se = {0} for i in a: s += i if s in se: ans+=1 se ={0} s = i se |= {s} print(ans) for _ in range(1): solve() ```
output
1
108,036
12
216,073
Provide tags and a correct Python 3 solution for this coding contest problem. Kolya got an integer array a_1, a_2, ..., a_n. The array can contain both positive and negative integers, but Kolya doesn't like 0, so the array doesn't contain any zeros. Kolya doesn't like that the sum of some subsegments of his array can be 0. The subsegment is some consecutive segment of elements of the array. You have to help Kolya and change his array in such a way that it doesn't contain any subsegments with the sum 0. To reach this goal, you can insert any integers between any pair of adjacent elements of the array (integers can be really any: positive, negative, 0, any by absolute value, even such a huge that they can't be represented in most standard programming languages). Your task is to find the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0. Input The first line of the input contains one integer n (2 ≀ n ≀ 200 000) β€” the number of elements in Kolya's array. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^{9} ≀ a_i ≀ 10^{9}, a_i β‰  0) β€” the description of Kolya's array. Output Print the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0. Examples Input 4 1 -5 3 2 Output 1 Input 5 4 -2 3 -9 2 Output 0 Input 9 -1 1 -1 1 -1 1 1 -1 -1 Output 6 Input 8 16 -5 -11 -15 10 5 4 -4 Output 3 Note Consider the first example. There is only one subsegment with the sum 0. It starts in the second element and ends in the fourth element. It's enough to insert one element so the array doesn't contain any subsegments with the sum equal to zero. For example, it is possible to insert the integer 1 between second and third elements of the array. There are no subsegments having sum 0 in the second example so you don't need to do anything.
instruction
0
108,037
12
216,074
Tags: constructive algorithms, data structures, greedy, sortings Correct Solution: ``` def checker(lst, n): k, s, c = 0, set(), 0 for i in range(n): k += lst[i] if k == 0 or k in s: c += 1 s.clear() k = lst[i] s.add(k) return c n = int(input()) a = [int(i) for i in input().split()] print(checker(a,n)) ```
output
1
108,037
12
216,075
Provide tags and a correct Python 3 solution for this coding contest problem. Kolya got an integer array a_1, a_2, ..., a_n. The array can contain both positive and negative integers, but Kolya doesn't like 0, so the array doesn't contain any zeros. Kolya doesn't like that the sum of some subsegments of his array can be 0. The subsegment is some consecutive segment of elements of the array. You have to help Kolya and change his array in such a way that it doesn't contain any subsegments with the sum 0. To reach this goal, you can insert any integers between any pair of adjacent elements of the array (integers can be really any: positive, negative, 0, any by absolute value, even such a huge that they can't be represented in most standard programming languages). Your task is to find the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0. Input The first line of the input contains one integer n (2 ≀ n ≀ 200 000) β€” the number of elements in Kolya's array. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^{9} ≀ a_i ≀ 10^{9}, a_i β‰  0) β€” the description of Kolya's array. Output Print the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0. Examples Input 4 1 -5 3 2 Output 1 Input 5 4 -2 3 -9 2 Output 0 Input 9 -1 1 -1 1 -1 1 1 -1 -1 Output 6 Input 8 16 -5 -11 -15 10 5 4 -4 Output 3 Note Consider the first example. There is only one subsegment with the sum 0. It starts in the second element and ends in the fourth element. It's enough to insert one element so the array doesn't contain any subsegments with the sum equal to zero. For example, it is possible to insert the integer 1 between second and third elements of the array. There are no subsegments having sum 0 in the second example so you don't need to do anything.
instruction
0
108,038
12
216,076
Tags: constructive algorithms, data structures, greedy, sortings Correct Solution: ``` import collections n=int(input()) arr=list(map(int,input().split())) ans=0 sums=0 s=set() for val in arr: s.add(sums) sums+=val if sums in s: ans+=1 sums=val s=set() s.add(0) print(ans) ```
output
1
108,038
12
216,077
Provide tags and a correct Python 3 solution for this coding contest problem. Kolya got an integer array a_1, a_2, ..., a_n. The array can contain both positive and negative integers, but Kolya doesn't like 0, so the array doesn't contain any zeros. Kolya doesn't like that the sum of some subsegments of his array can be 0. The subsegment is some consecutive segment of elements of the array. You have to help Kolya and change his array in such a way that it doesn't contain any subsegments with the sum 0. To reach this goal, you can insert any integers between any pair of adjacent elements of the array (integers can be really any: positive, negative, 0, any by absolute value, even such a huge that they can't be represented in most standard programming languages). Your task is to find the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0. Input The first line of the input contains one integer n (2 ≀ n ≀ 200 000) β€” the number of elements in Kolya's array. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^{9} ≀ a_i ≀ 10^{9}, a_i β‰  0) β€” the description of Kolya's array. Output Print the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0. Examples Input 4 1 -5 3 2 Output 1 Input 5 4 -2 3 -9 2 Output 0 Input 9 -1 1 -1 1 -1 1 1 -1 -1 Output 6 Input 8 16 -5 -11 -15 10 5 4 -4 Output 3 Note Consider the first example. There is only one subsegment with the sum 0. It starts in the second element and ends in the fourth element. It's enough to insert one element so the array doesn't contain any subsegments with the sum equal to zero. For example, it is possible to insert the integer 1 between second and third elements of the array. There are no subsegments having sum 0 in the second example so you don't need to do anything.
instruction
0
108,039
12
216,078
Tags: constructive algorithms, data structures, greedy, sortings Correct Solution: ``` from collections import Counter import string import math import sys from fractions import Fraction def array_int(): return [int(i) for i in sys.stdin.readline().split()] def vary(arrber_of_variables): if arrber_of_variables==1: return int(sys.stdin.readline()) if arrber_of_variables>=2: return map(int,sys.stdin.readline().split()) def makedict(var): return dict(Counter(var)) # i am noob wanted to be better and trying hard for that def printDivisors(n): divisors=[] # Note that this loop runs till square root i = 1 while i <= math.sqrt(n): if (n % i == 0) : # If divisors are equal, print only one if (n//i == i) : divisors.append(i) else : # Otherwise print both divisors.extend((i,n//i)) i = i + 1 return divisors def countTotalBits(num): # convert number into it's binary and # remove first two characters 0b. binary = bin(num)[2:] return(len(binary)) def isPrime(n) : # Corner cases if (n <= 1) : return False if (n <= 3) : return True # This is checked so that we can skip # middle five numbers in below loop if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while(i * i <= n) : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True """ def dfs(node,val): global tree,visited visited[node]=1 ans[node]=val val^=1 for i in tree[node]: if visited[i]==-1: dfs(i,val) """ n=vary(1) num=array_int() sum=0 st=set() count=0 for i in range(n): sum+=num[i] if sum==0 or sum in st: count+=1 st.clear() st.add(num[i]) sum=num[i] else: st.add(sum) print(count) ```
output
1
108,039
12
216,079
Provide tags and a correct Python 3 solution for this coding contest problem. Kolya got an integer array a_1, a_2, ..., a_n. The array can contain both positive and negative integers, but Kolya doesn't like 0, so the array doesn't contain any zeros. Kolya doesn't like that the sum of some subsegments of his array can be 0. The subsegment is some consecutive segment of elements of the array. You have to help Kolya and change his array in such a way that it doesn't contain any subsegments with the sum 0. To reach this goal, you can insert any integers between any pair of adjacent elements of the array (integers can be really any: positive, negative, 0, any by absolute value, even such a huge that they can't be represented in most standard programming languages). Your task is to find the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0. Input The first line of the input contains one integer n (2 ≀ n ≀ 200 000) β€” the number of elements in Kolya's array. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^{9} ≀ a_i ≀ 10^{9}, a_i β‰  0) β€” the description of Kolya's array. Output Print the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0. Examples Input 4 1 -5 3 2 Output 1 Input 5 4 -2 3 -9 2 Output 0 Input 9 -1 1 -1 1 -1 1 1 -1 -1 Output 6 Input 8 16 -5 -11 -15 10 5 4 -4 Output 3 Note Consider the first example. There is only one subsegment with the sum 0. It starts in the second element and ends in the fourth element. It's enough to insert one element so the array doesn't contain any subsegments with the sum equal to zero. For example, it is possible to insert the integer 1 between second and third elements of the array. There are no subsegments having sum 0 in the second example so you don't need to do anything.
instruction
0
108,040
12
216,080
Tags: constructive algorithms, data structures, greedy, sortings Correct Solution: ``` n = int(input()) l = list(map(int,input().split())) num = {0} count,s = 0,0 for i in l: s += i if s in num: num = {0} count += 1 s = i num.add(s) print(count) ```
output
1
108,040
12
216,081
Provide tags and a correct Python 3 solution for this coding contest problem. Kolya got an integer array a_1, a_2, ..., a_n. The array can contain both positive and negative integers, but Kolya doesn't like 0, so the array doesn't contain any zeros. Kolya doesn't like that the sum of some subsegments of his array can be 0. The subsegment is some consecutive segment of elements of the array. You have to help Kolya and change his array in such a way that it doesn't contain any subsegments with the sum 0. To reach this goal, you can insert any integers between any pair of adjacent elements of the array (integers can be really any: positive, negative, 0, any by absolute value, even such a huge that they can't be represented in most standard programming languages). Your task is to find the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0. Input The first line of the input contains one integer n (2 ≀ n ≀ 200 000) β€” the number of elements in Kolya's array. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^{9} ≀ a_i ≀ 10^{9}, a_i β‰  0) β€” the description of Kolya's array. Output Print the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0. Examples Input 4 1 -5 3 2 Output 1 Input 5 4 -2 3 -9 2 Output 0 Input 9 -1 1 -1 1 -1 1 1 -1 -1 Output 6 Input 8 16 -5 -11 -15 10 5 4 -4 Output 3 Note Consider the first example. There is only one subsegment with the sum 0. It starts in the second element and ends in the fourth element. It's enough to insert one element so the array doesn't contain any subsegments with the sum equal to zero. For example, it is possible to insert the integer 1 between second and third elements of the array. There are no subsegments having sum 0 in the second example so you don't need to do anything.
instruction
0
108,041
12
216,082
Tags: constructive algorithms, data structures, greedy, sortings Correct Solution: ``` n = int(input()) a = list(map(int, input().split())) pre = ans = 0 visited = set([0]) for i in a: pre += i if pre in visited: ans += 1 visited.clear() visited.add(0) pre = i visited.add(pre) print(ans) ```
output
1
108,041
12
216,083
Provide tags and a correct Python 3 solution for this coding contest problem. Kolya got an integer array a_1, a_2, ..., a_n. The array can contain both positive and negative integers, but Kolya doesn't like 0, so the array doesn't contain any zeros. Kolya doesn't like that the sum of some subsegments of his array can be 0. The subsegment is some consecutive segment of elements of the array. You have to help Kolya and change his array in such a way that it doesn't contain any subsegments with the sum 0. To reach this goal, you can insert any integers between any pair of adjacent elements of the array (integers can be really any: positive, negative, 0, any by absolute value, even such a huge that they can't be represented in most standard programming languages). Your task is to find the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0. Input The first line of the input contains one integer n (2 ≀ n ≀ 200 000) β€” the number of elements in Kolya's array. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^{9} ≀ a_i ≀ 10^{9}, a_i β‰  0) β€” the description of Kolya's array. Output Print the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0. Examples Input 4 1 -5 3 2 Output 1 Input 5 4 -2 3 -9 2 Output 0 Input 9 -1 1 -1 1 -1 1 1 -1 -1 Output 6 Input 8 16 -5 -11 -15 10 5 4 -4 Output 3 Note Consider the first example. There is only one subsegment with the sum 0. It starts in the second element and ends in the fourth element. It's enough to insert one element so the array doesn't contain any subsegments with the sum equal to zero. For example, it is possible to insert the integer 1 between second and third elements of the array. There are no subsegments having sum 0 in the second example so you don't need to do anything.
instruction
0
108,042
12
216,084
Tags: constructive algorithms, data structures, greedy, sortings Correct Solution: ``` #! /usr/bin/python3 import os import sys from io import BytesIO, IOBase import math def main1(): for _ in range(int(input())): n, x = map(int, input().split()) if n <= 2: print(1) else: n -= 2 print(1 + math.ceil(n / x)) def main2(): for _ in range(int(input())): n, m = map(int, input().split()) flag = 0 for i in range(n): mat = [] for j in range(2): mat.append(list(map(int, input().split()))) if mat[0][1] == mat[1][0]: flag = 1 if m % 2 or flag == 0: print("NO") else: print("YES") def main3(): for _ in range(int(input())): n = int(input()) ans = float("inf") for i in range(1, math.floor(math.sqrt(n)) + 1): ans = min(ans, i - 1 + ((n -i) + i - 1) // i) print(ans) def main4(): n = int(input()) a = list(map(int, input().split())) ls = [0] * n ls[0] = a[0] for i in range(1, n): ls[i] = ls[i-1] + a[i] ans = 0 d = dict() d[0] = 0 d[ls[0]] = 0 prev_pos = 0 for i in range(1, n): if ls[i] in d: pos = d[ls[i]] + 1 if pos >= prev_pos: prev_pos = i ans += 1 d[ls[i]] = i print(ans) def main5(): n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) max_win = min(a[0], b[1]) + min(a[1], b[2]) + min(a[2], b[0]) min_win = max(0, a[0] - b[0] - b[2]) + max(0, a[1] - b[1] - b[0]) + max(0, a[2] - b[2] - b[1]) print(min_win, max_win) def main6(): pass # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": main4() ```
output
1
108,042
12
216,085
Provide tags and a correct Python 3 solution for this coding contest problem. Kolya got an integer array a_1, a_2, ..., a_n. The array can contain both positive and negative integers, but Kolya doesn't like 0, so the array doesn't contain any zeros. Kolya doesn't like that the sum of some subsegments of his array can be 0. The subsegment is some consecutive segment of elements of the array. You have to help Kolya and change his array in such a way that it doesn't contain any subsegments with the sum 0. To reach this goal, you can insert any integers between any pair of adjacent elements of the array (integers can be really any: positive, negative, 0, any by absolute value, even such a huge that they can't be represented in most standard programming languages). Your task is to find the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0. Input The first line of the input contains one integer n (2 ≀ n ≀ 200 000) β€” the number of elements in Kolya's array. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^{9} ≀ a_i ≀ 10^{9}, a_i β‰  0) β€” the description of Kolya's array. Output Print the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0. Examples Input 4 1 -5 3 2 Output 1 Input 5 4 -2 3 -9 2 Output 0 Input 9 -1 1 -1 1 -1 1 1 -1 -1 Output 6 Input 8 16 -5 -11 -15 10 5 4 -4 Output 3 Note Consider the first example. There is only one subsegment with the sum 0. It starts in the second element and ends in the fourth element. It's enough to insert one element so the array doesn't contain any subsegments with the sum equal to zero. For example, it is possible to insert the integer 1 between second and third elements of the array. There are no subsegments having sum 0 in the second example so you don't need to do anything.
instruction
0
108,043
12
216,086
Tags: constructive algorithms, data structures, greedy, sortings Correct Solution: ``` def main(): n = int(input()) a = list(map(int, input().split())) d = set([0]) presum = 0 ans = 0 for v in a: presum += v if presum in d: ans += 1 d.clear() d.add(v) d.add(0) presum = v else: d.add(presum) print(ans) main() ```
output
1
108,043
12
216,087
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Kolya got an integer array a_1, a_2, ..., a_n. The array can contain both positive and negative integers, but Kolya doesn't like 0, so the array doesn't contain any zeros. Kolya doesn't like that the sum of some subsegments of his array can be 0. The subsegment is some consecutive segment of elements of the array. You have to help Kolya and change his array in such a way that it doesn't contain any subsegments with the sum 0. To reach this goal, you can insert any integers between any pair of adjacent elements of the array (integers can be really any: positive, negative, 0, any by absolute value, even such a huge that they can't be represented in most standard programming languages). Your task is to find the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0. Input The first line of the input contains one integer n (2 ≀ n ≀ 200 000) β€” the number of elements in Kolya's array. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^{9} ≀ a_i ≀ 10^{9}, a_i β‰  0) β€” the description of Kolya's array. Output Print the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0. Examples Input 4 1 -5 3 2 Output 1 Input 5 4 -2 3 -9 2 Output 0 Input 9 -1 1 -1 1 -1 1 1 -1 -1 Output 6 Input 8 16 -5 -11 -15 10 5 4 -4 Output 3 Note Consider the first example. There is only one subsegment with the sum 0. It starts in the second element and ends in the fourth element. It's enough to insert one element so the array doesn't contain any subsegments with the sum equal to zero. For example, it is possible to insert the integer 1 between second and third elements of the array. There are no subsegments having sum 0 in the second example so you don't need to do anything. Submitted Solution: ``` #### IMPORTANT LIBRARY #### ############################ ### DO NOT USE import random --> 250ms to load the library ############################ ### In case of extra libraries: https://github.com/cheran-senthil/PyRival ###################### ####### IMPORT ####### ###################### from functools import cmp_to_key from collections import deque from heapq import heappush, heappop from math import log, ceil ###################### #### STANDARD I/O #### ###################### import sys import os from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) def print(*args, **kwargs): sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() def inp(): return sys.stdin.readline().rstrip("\r\n") # for fast input def ii(): return int(inp()) def li(lag = 0): l = list(map(int, inp().split())) if lag != 0: for i in range(len(l)): l[i] += lag return l def mi(lag = 0): matrix = list() for i in range(n): matrix.append(li(lag)) return matrix def sli(): #string list return list(map(str, inp().split())) def print_list(lista, space = " "): print(space.join(map(str, lista))) ###################### ##### UNION FIND ##### ###################### class UnionFind: def __init__(self, n): self.parent = list(range(n)) self.size = [1] * n self.num_sets = n def find(self, a): to_update = [] while a != self.parent[a]: to_update.append(a) a = self.parent[a] for b in to_update: self.parent[b] = a return self.parent[a] def merge(self, a, b): a = self.find(a) b = self.find(b) if a == b: return if self.size[a] < self.size[b]: a, b = b, a self.num_sets -= 1 self.parent[b] = a self.size[a] += self.size[b] def set_size(self, a): return self.size[self.find(a)] def __len__(self): return self.num_sets ###################### ### BISECT METHODS ### ###################### def bisect_left(a, x): """i tale che a[i] >= x e a[i-1] < x""" left = 0 right = len(a) while left < right: mid = (left+right)//2 if a[mid] < x: left = mid+1 else: right = mid return left def bisect_right(a, x): """i tale che a[i] > x e a[i-1] <= x""" left = 0 right = len(a) while left < right: mid = (left+right)//2 if a[mid] > x: right = mid else: left = mid+1 return left def bisect_elements(a, x): """elementi pari a x nell'Γ‘rray sortato""" return bisect_right(a, x) - bisect_left(a, x) ###################### #### CUSTOM SORT ##### ###################### def custom_sort(lista): def cmp(x,y): if x+y>y+x: return 1 else: return -1 return sorted(lista, key = cmp_to_key(cmp)) ###################### ### MOD OPERATION #### ###################### MOD = 10**9 + 7 maxN = 10**5 FACT = [0] * maxN def add(x, y): return (x+y) % MOD def multiply(x, y): return (x*y) % MOD def power(x, y): if y == 0: return 1 elif y % 2: return multiply(x, power(x, y-1)) else: a = power(x, y//2) return multiply(a, a) def inverse(x): return power(x, MOD-2) def divide(x, y): return multiply(x, inverse(y)) def allFactorials(): FACT[0] = 1 for i in range(1, maxN): FACT[i] = multiply(i, FACT[i-1]) def coeffBinom(n, k): if n < k: return 0 return divide(FACT[n], multiply(FACT[k], FACT[n-k])) ###################### #### GCD & PRIMES #### ###################### def primes(N): smallest_prime = [1] * (N+1) prime = [] smallest_prime[0] = 0 smallest_prime[1] = 0 for i in range(2, N+1): if smallest_prime[i] == 1: prime.append(i) smallest_prime[i] = i j = 0 while (j < len(prime) and i * prime[j] <= N): smallest_prime[i * prime[j]] = min(prime[j], smallest_prime[i]) j += 1 return prime, smallest_prime def gcd(a, b): s, t, r = 0, 1, b old_s, old_t, old_r = 1, 0, a while r != 0: quotient = old_r//r old_r, r = r, old_r - quotient*r old_s, s = s, old_s - quotient*s old_t, t = t, old_t - quotient*t return old_r, old_s, old_t #gcd, x, y for ax+by=gcd ###################### #### GRAPH ALGOS ##### ###################### # ZERO BASED GRAPH def create_graph(n, m, undirected = 1, unweighted = 1): graph = [[] for i in range(n)] if unweighted: for i in range(m): [x, y] = li(lag = -1) graph[x].append(y) if undirected: graph[y].append(x) else: for i in range(m): [x, y, w] = li(lag = -1) w += 1 graph[x].append([y,w]) if undirected: graph[y].append([x,w]) return graph def create_tree(n, unweighted = 1): children = [[] for i in range(n)] if unweighted: for i in range(n-1): [x, y] = li(lag = -1) children[x].append(y) children[y].append(x) else: for i in range(n-1): [x, y, w] = li(lag = -1) w += 1 children[x].append([y, w]) children[y].append([x, w]) return children def create_edges(m, unweighted = 0): edges = list() if unweighted: for i in range(m): edges.append(li(lag = -1)) else: for i in range(m): [x, y, w] = li(lag = -1) w += 1 edges.append([w,x,y]) return edges def dist(tree, n, A, B = -1): s = [[A, 0]] massimo, massimo_nodo = 0, 0 distanza = -1 v = [-1] * n while s: el, dis = s.pop() if dis > massimo: massimo = dis massimo_nodo = el if el == B: distanza = dis for child in tree[el]: if v[child] == -1: v[child] = 1 s.append([child, dis+1]) return massimo, massimo_nodo, distanza def diameter(tree): _, foglia, _ = dist(tree, n, 0) diam, _, _ = dist(tree, n, foglia) return diam def dfs(graph, n, A): v = [-1] * n s = [[A, 0]] v[A] = 0 while s: el, dis = s.pop() for child in graph[el]: if v[child] == -1: v[child] = dis + 1 s.append([child, dis + 1]) return v #visited: -1 if not visited, otherwise v[B] is the distance in terms of edges def bfs(graph, n, A): v = [-1] * n s = deque() s.append([A, 0]) v[A] = 0 while s: el, dis = s.popleft() for child in graph[el]: if v[child] == -1: v[child] = dis + 1 s.append([child, dis + 1]) return v #visited: -1 if not visited, otherwise v[B] is the distance in terms of edges def connected(graph, n): v = dfs(graph, n, 0) for el in v: if el == -1: return False return True # NON DIMENTICARTI DI PRENDERE GRAPH COME DIRETTO def topological(graph, n): indegree = [0] * n for el in range(n): for child in graph[el]: indegree[child] += 1 s = deque() for el in range(n): if indegree[el] == 0: s.append(el) order = [] while s: el = s.popleft() order.append(el) for child in graph[el]: indegree[child] -= 1 if indegree[child] == 0: s.append(child) if n == len(order): return False, order #False == no cycle else: return True, [] #True == there is a cycle and order is useless # ASSUMING CONNECTED def bipartite(graph, n): color = [-1] * n color[0] = 0 s = [0] while s: el = s.pop() for child in graph[el]: if color[child] == color[el]: return False if color[child] == -1: s.append(child) color[child] = 1 - color[el] return True # SHOULD BE DIRECTED AND WEIGHTED def dijkstra(graph, n, A): dist = [float('inf') for i in range(n)] prev = [-1 for i in range(n)] dist[A] = 0 pq = [] heappush(pq, [0, A]) while pq: [d_v, v] = heappop(pq) if (d_v != dist[v]): continue for to, w in graph[v]: if dist[v] + w < dist[to]: dist[to] = dist[v] + w prev[to] = v heappush(pq, [dist[to], to]) return dist, prev # SHOULD BE DIRECTED AND WEIGHTED def dijkstra_0_1(graph, n, A): dist = [float('inf') for i in range(n)] dist[A] = 0 p = deque() p.append(A) while p: v = p.popleft() for to, w in graph[v]: if dist[v] + w < dist[to]: dist[to] = dist[v] + w if w == 1: q.append(to) else: q.appendleft(to) return dist #SHOULD BE WEIGHTED (AND UNDIRECTED) def floyd_warshall(graph, n): dist = [[float('inf') for _ in range(n)] for _ in range(n)] for i in range(n): dist[i][i] = 0 for child, d in graph[i]: dist[i][child] = d dist[child][i] = d for k in range(n): for i in range(n): for j in range(j): dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) return dist #EDGES [w,x,y] def minimum_spanning_tree(edges, n): edges = sorted(edges) union_find = UnionFind(n) #implemented above used_edges = list() for w, x, y in edges: if union_find.find(x) != union_find.find(y): union_find.merge(x, y) used_edges.append([w,x,y]) return used_edges #FROM A GIVEN ROOT, RECOVER THE STRUCTURE def parents_children_root_unrooted_tree(tree, n, root = 0): q = deque() visited = [0] * n parent = [-1] * n children = [[] for i in range(n)] q.append(root) while q: all_done = 1 visited[q[0]] = 1 for child in tree[q[0]]: if not visited[child]: all_done = 0 q.appendleft(child) if all_done: for child in tree[q[0]]: if parent[child] == -1: parent[q[0]] = child children[child].append(q[0]) q.popleft() return parent, children # CALCULATING LONGEST PATH FOR ALL THE NODES def all_longest_path_passing_from_node(parent, children, n): q = deque() visited = [len(children[i]) for i in range(n)] downwards = [[0,0] for i in range(n)] upward = [1] * n longest_path = [1] * n for i in range(n): if not visited[i]: q.append(i) downwards[i] = [1,0] while q: node = q.popleft() if parent[node] != -1: visited[parent[node]] -= 1 if not visited[parent[node]]: q.append(parent[node]) else: root = node for child in children[node]: downwards[node] = sorted([downwards[node][0], downwards[node][1], downwards[child][0] + 1], reverse = True)[0:2] s = [node] while s: node = s.pop() if parent[node] != -1: if downwards[parent[node]][0] == downwards[node][0] + 1: upward[node] = 1 + max(upward[parent[node]], downwards[parent[node]][1]) else: upward[node] = 1 + max(upward[parent[node]], downwards[parent[node]][0]) longest_path[node] = downwards[node][0] + downwards[node][1] + upward[node] - min([downwards[node][0], downwards[node][1], upward[node]]) - 1 for child in children[node]: s.append(child) return longest_path def finding_ancestors(parent, queries, n): steps = int(ceil(log(n, 2))) ancestors = [[-1 for i in range(n)] for j in range(steps)] ancestors[0] = parent for i in range(1, steps): for node in range(n): if ancestors[i-1][node] != -1: ancestors[i][node] = ancestors[i-1][ancestors[i-1][node]] result = [] for node, k in queries: ans = node if k >= n: ans = -1 i = 0 while k > 0 and ans != -1: if k % 2: ans = ancestors[i][ans] k = k // 2 i += 1 result.append(ans) return result #Preprocessing in O(n log n). For each query O(log k) ### TBD SUCCESSOR GRAPH 7.5 ### TBD TREE QUERIES 10.2 da 2 a 4 ### TBD ADVANCED TREE 10.3 ### TBD GRAPHS AND MATRICES 11.3.3 e 11.4.3 e 11.5.3 (ON GAMES) ###################### ####### OTHERS ####### ###################### def prefix_sum(arr): r = [0] * (len(arr)+1) for i, el in enumerate(arr): r[i+1] = r[i] + el return r def nearest_from_the_left_smaller_elements(arr): n = len(arr) res = [-1] * n s = [] for i, el in enumerate(arr): while s and s[-1] >= el: s.pop() if s: res[i] = s[-1] s.append(el) return res def sliding_window_minimum(arr, k): res = [] q = deque() for i, el in enumerate(arr): while q and arr[q[-1]] >= el: q.pop() q.append(i) while q and q[0] <= i - k: q.popleft() if i >= k-1: res.append(arr[q[0]]) return res ### TBD COUNT ELEMENT SMALLER THAN SELF ###################### ## END OF LIBRARIES ## ###################### n = ii() a = li() i = 0 pre = 0 s = 0 d = set() d.add(0) while i < n: if pre + a[i] in d: s += 1 d = set() d.add(0) pre = 0 else: pre += a[i] d.add(pre) i += 1 print(s) ```
instruction
0
108,044
12
216,088
Yes
output
1
108,044
12
216,089
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Kolya got an integer array a_1, a_2, ..., a_n. The array can contain both positive and negative integers, but Kolya doesn't like 0, so the array doesn't contain any zeros. Kolya doesn't like that the sum of some subsegments of his array can be 0. The subsegment is some consecutive segment of elements of the array. You have to help Kolya and change his array in such a way that it doesn't contain any subsegments with the sum 0. To reach this goal, you can insert any integers between any pair of adjacent elements of the array (integers can be really any: positive, negative, 0, any by absolute value, even such a huge that they can't be represented in most standard programming languages). Your task is to find the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0. Input The first line of the input contains one integer n (2 ≀ n ≀ 200 000) β€” the number of elements in Kolya's array. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^{9} ≀ a_i ≀ 10^{9}, a_i β‰  0) β€” the description of Kolya's array. Output Print the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0. Examples Input 4 1 -5 3 2 Output 1 Input 5 4 -2 3 -9 2 Output 0 Input 9 -1 1 -1 1 -1 1 1 -1 -1 Output 6 Input 8 16 -5 -11 -15 10 5 4 -4 Output 3 Note Consider the first example. There is only one subsegment with the sum 0. It starts in the second element and ends in the fourth element. It's enough to insert one element so the array doesn't contain any subsegments with the sum equal to zero. For example, it is possible to insert the integer 1 between second and third elements of the array. There are no subsegments having sum 0 in the second example so you don't need to do anything. Submitted Solution: ``` if __name__ == '__main__': n = int( input() ) arr = list( map( int, input().split() ) ) Set = set([0]) prefix_sum = 0 count = 0 for i in range( n ) : prefix_sum += arr[i] if prefix_sum in Set : count += 1 # print(count) Set = set([0]) prefix_sum = arr[i] Set.add( prefix_sum ) print(count) ```
instruction
0
108,045
12
216,090
Yes
output
1
108,045
12
216,091
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Kolya got an integer array a_1, a_2, ..., a_n. The array can contain both positive and negative integers, but Kolya doesn't like 0, so the array doesn't contain any zeros. Kolya doesn't like that the sum of some subsegments of his array can be 0. The subsegment is some consecutive segment of elements of the array. You have to help Kolya and change his array in such a way that it doesn't contain any subsegments with the sum 0. To reach this goal, you can insert any integers between any pair of adjacent elements of the array (integers can be really any: positive, negative, 0, any by absolute value, even such a huge that they can't be represented in most standard programming languages). Your task is to find the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0. Input The first line of the input contains one integer n (2 ≀ n ≀ 200 000) β€” the number of elements in Kolya's array. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^{9} ≀ a_i ≀ 10^{9}, a_i β‰  0) β€” the description of Kolya's array. Output Print the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0. Examples Input 4 1 -5 3 2 Output 1 Input 5 4 -2 3 -9 2 Output 0 Input 9 -1 1 -1 1 -1 1 1 -1 -1 Output 6 Input 8 16 -5 -11 -15 10 5 4 -4 Output 3 Note Consider the first example. There is only one subsegment with the sum 0. It starts in the second element and ends in the fourth element. It's enough to insert one element so the array doesn't contain any subsegments with the sum equal to zero. For example, it is possible to insert the integer 1 between second and third elements of the array. There are no subsegments having sum 0 in the second example so you don't need to do anything. Submitted Solution: ``` n = int(input()) arr = list(map(int, input().strip().split())) d = {} d[0] = -1 ans = s = curr = 0 for i in range(len(arr)): s += arr[i] if s in d and curr <= d[s] + 1: ans += 1 curr = i d[s] = i print(ans) ```
instruction
0
108,046
12
216,092
Yes
output
1
108,046
12
216,093
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Kolya got an integer array a_1, a_2, ..., a_n. The array can contain both positive and negative integers, but Kolya doesn't like 0, so the array doesn't contain any zeros. Kolya doesn't like that the sum of some subsegments of his array can be 0. The subsegment is some consecutive segment of elements of the array. You have to help Kolya and change his array in such a way that it doesn't contain any subsegments with the sum 0. To reach this goal, you can insert any integers between any pair of adjacent elements of the array (integers can be really any: positive, negative, 0, any by absolute value, even such a huge that they can't be represented in most standard programming languages). Your task is to find the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0. Input The first line of the input contains one integer n (2 ≀ n ≀ 200 000) β€” the number of elements in Kolya's array. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^{9} ≀ a_i ≀ 10^{9}, a_i β‰  0) β€” the description of Kolya's array. Output Print the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0. Examples Input 4 1 -5 3 2 Output 1 Input 5 4 -2 3 -9 2 Output 0 Input 9 -1 1 -1 1 -1 1 1 -1 -1 Output 6 Input 8 16 -5 -11 -15 10 5 4 -4 Output 3 Note Consider the first example. There is only one subsegment with the sum 0. It starts in the second element and ends in the fourth element. It's enough to insert one element so the array doesn't contain any subsegments with the sum equal to zero. For example, it is possible to insert the integer 1 between second and third elements of the array. There are no subsegments having sum 0 in the second example so you don't need to do anything. Submitted Solution: ``` from sys import stdin,stdout input=stdin.readline n=int(input()) arr=list(map(int, input().split())) c=0 su=0 dic={} i=0 fixed=-1 dic[0]=-1 for d in arr: su+=d if su==0: if dic[su] >= fixed - 1: # print(i) c += 1 fixed = i dic[su] = i elif su in dic: # print("yes",i,c,su,dic[su],fixed) if dic[su]>=fixed-1: # print(i) c+=1 fixed=i dic[su]=i # print("no", i, c, su, dic[su], fixed) if su not in dic: dic[su]=i i+=1 print(c) # print(str(dic)) ```
instruction
0
108,047
12
216,094
Yes
output
1
108,047
12
216,095
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Kolya got an integer array a_1, a_2, ..., a_n. The array can contain both positive and negative integers, but Kolya doesn't like 0, so the array doesn't contain any zeros. Kolya doesn't like that the sum of some subsegments of his array can be 0. The subsegment is some consecutive segment of elements of the array. You have to help Kolya and change his array in such a way that it doesn't contain any subsegments with the sum 0. To reach this goal, you can insert any integers between any pair of adjacent elements of the array (integers can be really any: positive, negative, 0, any by absolute value, even such a huge that they can't be represented in most standard programming languages). Your task is to find the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0. Input The first line of the input contains one integer n (2 ≀ n ≀ 200 000) β€” the number of elements in Kolya's array. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^{9} ≀ a_i ≀ 10^{9}, a_i β‰  0) β€” the description of Kolya's array. Output Print the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0. Examples Input 4 1 -5 3 2 Output 1 Input 5 4 -2 3 -9 2 Output 0 Input 9 -1 1 -1 1 -1 1 1 -1 -1 Output 6 Input 8 16 -5 -11 -15 10 5 4 -4 Output 3 Note Consider the first example. There is only one subsegment with the sum 0. It starts in the second element and ends in the fourth element. It's enough to insert one element so the array doesn't contain any subsegments with the sum equal to zero. For example, it is possible to insert the integer 1 between second and third elements of the array. There are no subsegments having sum 0 in the second example so you don't need to do anything. Submitted Solution: ``` def main(): length = int(input()) array = list(map(int, input().split(' '))) print(findSubSeg(length, array)) def findSubSeg(length, array): if length == 1: return 0 zeroNum = 0 step = 1 headLoc = 0 flag = False newArray = [] while not flag and step < length: headLoc = 0 tailLoc = -1 for i in range(length-step): if i <= tailLoc: continue if sum(array[i:i+step+1]) == 0: bestLoc = findBestLoc(array, length, i, i+step) newArray.append(array[headLoc:bestLoc]) tailLoc = bestLoc - 1 headLoc = tailLoc + 1 zeroNum += 1 flag = True step += 1 if not flag: return 0 newArray.append(array[headLoc:]) for elem in newArray: zeroNum += findSubSeg(len(elem), elem) return zeroNum def findBestLoc(array, length, headLoc, tailLoc): bestLoc = tailLoc for i in range(tailLoc - headLoc, 0, -1): verify = 0 step = 0 while headLoc + i + step < length: verify += array[headLoc+i+step] if verify == 0: break step += 1 if verify != 0: bestLoc = headLoc + i return bestLoc if __name__ == '__main__': main() ```
instruction
0
108,048
12
216,096
No
output
1
108,048
12
216,097
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Kolya got an integer array a_1, a_2, ..., a_n. The array can contain both positive and negative integers, but Kolya doesn't like 0, so the array doesn't contain any zeros. Kolya doesn't like that the sum of some subsegments of his array can be 0. The subsegment is some consecutive segment of elements of the array. You have to help Kolya and change his array in such a way that it doesn't contain any subsegments with the sum 0. To reach this goal, you can insert any integers between any pair of adjacent elements of the array (integers can be really any: positive, negative, 0, any by absolute value, even such a huge that they can't be represented in most standard programming languages). Your task is to find the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0. Input The first line of the input contains one integer n (2 ≀ n ≀ 200 000) β€” the number of elements in Kolya's array. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^{9} ≀ a_i ≀ 10^{9}, a_i β‰  0) β€” the description of Kolya's array. Output Print the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0. Examples Input 4 1 -5 3 2 Output 1 Input 5 4 -2 3 -9 2 Output 0 Input 9 -1 1 -1 1 -1 1 1 -1 -1 Output 6 Input 8 16 -5 -11 -15 10 5 4 -4 Output 3 Note Consider the first example. There is only one subsegment with the sum 0. It starts in the second element and ends in the fourth element. It's enough to insert one element so the array doesn't contain any subsegments with the sum equal to zero. For example, it is possible to insert the integer 1 between second and third elements of the array. There are no subsegments having sum 0 in the second example so you don't need to do anything. Submitted Solution: ``` from collections import * from functools import * import math import sys # sys.stdin = open("Desktop//ip.txt",'r') # sys.stdout = open("Desktop//op.txt",'w') inp = sys.stdin.readline out = sys.stdout.write def mi(): return map(int,inp().split()) def li(): return list(mi()) def ii(): return int(inp()) def main(): n=ii() a=li() currsum = 0 dic = defaultdict(int) ans = 0 for i in a: currsum += i if currsum in dic: ans += dic[currsum] currsum = i dic[currsum]+=1 print(ans) main() ```
instruction
0
108,049
12
216,098
No
output
1
108,049
12
216,099
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Kolya got an integer array a_1, a_2, ..., a_n. The array can contain both positive and negative integers, but Kolya doesn't like 0, so the array doesn't contain any zeros. Kolya doesn't like that the sum of some subsegments of his array can be 0. The subsegment is some consecutive segment of elements of the array. You have to help Kolya and change his array in such a way that it doesn't contain any subsegments with the sum 0. To reach this goal, you can insert any integers between any pair of adjacent elements of the array (integers can be really any: positive, negative, 0, any by absolute value, even such a huge that they can't be represented in most standard programming languages). Your task is to find the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0. Input The first line of the input contains one integer n (2 ≀ n ≀ 200 000) β€” the number of elements in Kolya's array. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^{9} ≀ a_i ≀ 10^{9}, a_i β‰  0) β€” the description of Kolya's array. Output Print the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0. Examples Input 4 1 -5 3 2 Output 1 Input 5 4 -2 3 -9 2 Output 0 Input 9 -1 1 -1 1 -1 1 1 -1 -1 Output 6 Input 8 16 -5 -11 -15 10 5 4 -4 Output 3 Note Consider the first example. There is only one subsegment with the sum 0. It starts in the second element and ends in the fourth element. It's enough to insert one element so the array doesn't contain any subsegments with the sum equal to zero. For example, it is possible to insert the integer 1 between second and third elements of the array. There are no subsegments having sum 0 in the second example so you don't need to do anything. Submitted Solution: ``` n = int(input()) arr = list(map(lambda x: int(x), input().split(' '))) count = {0: 1} ans = 0 ssum = 0 for x in arr: ssum += x if ssum in count: ans += count[ssum] count = {0: 1} ssum = x else: count[ssum] = 1 print(ans) ```
instruction
0
108,050
12
216,100
No
output
1
108,050
12
216,101
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Kolya got an integer array a_1, a_2, ..., a_n. The array can contain both positive and negative integers, but Kolya doesn't like 0, so the array doesn't contain any zeros. Kolya doesn't like that the sum of some subsegments of his array can be 0. The subsegment is some consecutive segment of elements of the array. You have to help Kolya and change his array in such a way that it doesn't contain any subsegments with the sum 0. To reach this goal, you can insert any integers between any pair of adjacent elements of the array (integers can be really any: positive, negative, 0, any by absolute value, even such a huge that they can't be represented in most standard programming languages). Your task is to find the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0. Input The first line of the input contains one integer n (2 ≀ n ≀ 200 000) β€” the number of elements in Kolya's array. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^{9} ≀ a_i ≀ 10^{9}, a_i β‰  0) β€” the description of Kolya's array. Output Print the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum 0. Examples Input 4 1 -5 3 2 Output 1 Input 5 4 -2 3 -9 2 Output 0 Input 9 -1 1 -1 1 -1 1 1 -1 -1 Output 6 Input 8 16 -5 -11 -15 10 5 4 -4 Output 3 Note Consider the first example. There is only one subsegment with the sum 0. It starts in the second element and ends in the fourth element. It's enough to insert one element so the array doesn't contain any subsegments with the sum equal to zero. For example, it is possible to insert the integer 1 between second and third elements of the array. There are no subsegments having sum 0 in the second example so you don't need to do anything. Submitted Solution: ``` t = int(input()) arr = list(map(int, input().split())) to_add = 0 last_plus = 0 last_minus = 0 start_plus = 0 end_plus = 0 start_minus = 0 end_minus = 0 total = 0 total_index = 0 last_updated = "" intervals = [] for i, number in enumerate(arr): if number > 0: if last_updated == "-": last_plus = 0 start_plus = i last_plus += abs(number) total += number last_updated = "+" elif number < 0: if last_updated == "+": last_minus = 0 start_minus = i last_minus += abs(number) total += number last_updated = "-" if last_plus == last_minus: intervals.append((min(start_minus, start_plus), i)) total = number total_index = i elif total == 0: intervals.append((total_index, i)) total_index = i + 1 x = set() for item in intervals: x.add(item[0]) print(len(x)) ```
instruction
0
108,051
12
216,102
No
output
1
108,051
12
216,103
Provide tags and a correct Python 3 solution for this coding contest problem. You have a sequence a with n elements 1, 2, 3, ..., k - 1, k, k - 1, k - 2, ..., k - (n - k) (k ≀ n < 2k). Let's call as inversion in a a pair of indices i < j such that a[i] > a[j]. Suppose, you have some permutation p of size k and you build a sequence b of size n in the following manner: b[i] = p[a[i]]. Your goal is to find such permutation p that the total number of inversions in b doesn't exceed the total number of inversions in a, and b is lexicographically maximum. Small reminder: the sequence of k integers is called a permutation if it contains all integers from 1 to k exactly once. Another small reminder: a sequence s is lexicographically smaller than another sequence t, if either s is a prefix of t, or for the first i such that s_i β‰  t_i, s_i < t_i holds (in the first position that these sequences are different, s has smaller number than t). Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The first and only line of each test case contains two integers n and k (k ≀ n < 2k; 1 ≀ k ≀ 10^5) β€” the length of the sequence a and its maximum. It's guaranteed that the total sum of k over test cases doesn't exceed 10^5. Output For each test case, print k integers β€” the permutation p which maximizes b lexicographically without increasing the total number of inversions. It can be proven that p exists and is unique. Example Input 4 1 1 2 2 3 2 4 3 Output 1 1 2 2 1 1 3 2 Note In the first test case, the sequence a = [1], there is only one permutation p = [1]. In the second test case, the sequence a = [1, 2]. There is no inversion in a, so there is only one permutation p = [1, 2] which doesn't increase the number of inversions. In the third test case, a = [1, 2, 1] and has 1 inversion. If we use p = [2, 1], then b = [p[a[1]], p[a[2]], p[a[3]]] = [2, 1, 2] and also has 1 inversion. In the fourth test case, a = [1, 2, 3, 2], and since p = [1, 3, 2] then b = [1, 3, 2, 3]. Both a and b have 1 inversion and b is the lexicographically maximum.
instruction
0
108,068
12
216,136
Tags: constructive algorithms, math Correct Solution: ``` for i in range(int(input())): n,k=map(int,input().split()) g=[] for j in range(2*k-n): g.append(j+1) if (n-k)==0: print(' '.join(map(str,g))) else: h=[] for j in range(k-1-n+k): h.append(j+1) for j in range(k-(k-1-n+k)): h.append(k-j) print(' '.join(map(str,h))) ```
output
1
108,068
12
216,137