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. You are given an array a_1, a_2, ... , a_n. Array is good if for each pair of indexes i < j the condition j - a_j ≠ i - a_i holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option). For example, if a = [1, 1, 3, 5], then shuffled arrays [1, 3, 5, 1], [3, 5, 1, 1] and [5, 3, 1, 1] are good, but shuffled arrays [3, 1, 5, 1], [1, 1, 3, 5] and [1, 1, 5, 3] aren't. It's guaranteed that it's always possible to shuffle an array to meet this condition. Input The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case contains one integer n (1 ≤ n ≤ 100) — the length of array a. The second line of each test case contains n integers a_1, a_2, ... , a_n (1 ≤ a_i ≤ 100). Output For each test case print the shuffled version of the array a which is good. Example Input 3 1 7 4 1 1 3 5 6 3 2 1 5 6 4 Output 7 1 5 1 3 2 4 6 1 3 5 Submitted Solution: ``` q = int(input()) for ii in range(q): n = int(input()) a = list(map(int, input().split())) a.sort(reverse=True) print (*a) # b = [] # for pos, j in enumerate(a): # b += (pos, j,) # b.sort(key=lambda x: x[0] - x[1]) ```
instruction
0
29,260
12
58,520
Yes
output
1
29,260
12
58,521
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a_1, a_2, ... , a_n. Array is good if for each pair of indexes i < j the condition j - a_j ≠ i - a_i holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option). For example, if a = [1, 1, 3, 5], then shuffled arrays [1, 3, 5, 1], [3, 5, 1, 1] and [5, 3, 1, 1] are good, but shuffled arrays [3, 1, 5, 1], [1, 1, 3, 5] and [1, 1, 5, 3] aren't. It's guaranteed that it's always possible to shuffle an array to meet this condition. Input The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case contains one integer n (1 ≤ n ≤ 100) — the length of array a. The second line of each test case contains n integers a_1, a_2, ... , a_n (1 ≤ a_i ≤ 100). Output For each test case print the shuffled version of the array a which is good. Example Input 3 1 7 4 1 1 3 5 6 3 2 1 5 6 4 Output 7 1 5 1 3 2 4 6 1 3 5 Submitted Solution: ``` t = int(input()) for k in range(t): n = int(input()) a = list(map(int, input().split())) a.sort(reverse=True) print(*a) ```
instruction
0
29,261
12
58,522
Yes
output
1
29,261
12
58,523
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a_1, a_2, ... , a_n. Array is good if for each pair of indexes i < j the condition j - a_j ≠ i - a_i holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option). For example, if a = [1, 1, 3, 5], then shuffled arrays [1, 3, 5, 1], [3, 5, 1, 1] and [5, 3, 1, 1] are good, but shuffled arrays [3, 1, 5, 1], [1, 1, 3, 5] and [1, 1, 5, 3] aren't. It's guaranteed that it's always possible to shuffle an array to meet this condition. Input The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case contains one integer n (1 ≤ n ≤ 100) — the length of array a. The second line of each test case contains n integers a_1, a_2, ... , a_n (1 ≤ a_i ≤ 100). Output For each test case print the shuffled version of the array a which is good. Example Input 3 1 7 4 1 1 3 5 6 3 2 1 5 6 4 Output 7 1 5 1 3 2 4 6 1 3 5 Submitted Solution: ``` for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) for i in range(n): a[i] = int(a[i]) a.sort(reverse = True) print(*a) ```
instruction
0
29,262
12
58,524
Yes
output
1
29,262
12
58,525
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a_1, a_2, ... , a_n. Array is good if for each pair of indexes i < j the condition j - a_j ≠ i - a_i holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option). For example, if a = [1, 1, 3, 5], then shuffled arrays [1, 3, 5, 1], [3, 5, 1, 1] and [5, 3, 1, 1] are good, but shuffled arrays [3, 1, 5, 1], [1, 1, 3, 5] and [1, 1, 5, 3] aren't. It's guaranteed that it's always possible to shuffle an array to meet this condition. Input The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case contains one integer n (1 ≤ n ≤ 100) — the length of array a. The second line of each test case contains n integers a_1, a_2, ... , a_n (1 ≤ a_i ≤ 100). Output For each test case print the shuffled version of the array a which is good. Example Input 3 1 7 4 1 1 3 5 6 3 2 1 5 6 4 Output 7 1 5 1 3 2 4 6 1 3 5 Submitted Solution: ``` from random import randint, uniform,random def verificar(bandera, espejo): bandera = False for i in range(len(espejo)): if bandera == True: break j = i+1 while j < len(espejo): if espejo[i] == espejo[j]: bandera = True break j = j + 1 return bandera for _ in range(int(input())): tam = int(input()) numeros = list(map(int,input().split())) espejo = [] for i in range(tam): espejo.append(i-numeros[i]) bandera = True while verificar(bandera, espejo): a = randint(0,tam-1) b = randint(0,tam-1) if a == b: continue aux = numeros[a] numeros[a] = numeros[b] numeros[b] = aux for i in range(tam): espejo.clear() espejo.append(i-numeros[i]) for i in range(tam): print(numeros[i], end=" ") print("") ```
instruction
0
29,263
12
58,526
No
output
1
29,263
12
58,527
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a_1, a_2, ... , a_n. Array is good if for each pair of indexes i < j the condition j - a_j ≠ i - a_i holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option). For example, if a = [1, 1, 3, 5], then shuffled arrays [1, 3, 5, 1], [3, 5, 1, 1] and [5, 3, 1, 1] are good, but shuffled arrays [3, 1, 5, 1], [1, 1, 3, 5] and [1, 1, 5, 3] aren't. It's guaranteed that it's always possible to shuffle an array to meet this condition. Input The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case contains one integer n (1 ≤ n ≤ 100) — the length of array a. The second line of each test case contains n integers a_1, a_2, ... , a_n (1 ≤ a_i ≤ 100). Output For each test case print the shuffled version of the array a which is good. Example Input 3 1 7 4 1 1 3 5 6 3 2 1 5 6 4 Output 7 1 5 1 3 2 4 6 1 3 5 Submitted Solution: ``` t=int(input()) while(t!=0): t=t-1 n=int(input()) arr=list(map(int,input().strip().split()))[:n] arr.sort(reverse=True) print(arr) ```
instruction
0
29,264
12
58,528
No
output
1
29,264
12
58,529
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a_1, a_2, ... , a_n. Array is good if for each pair of indexes i < j the condition j - a_j ≠ i - a_i holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option). For example, if a = [1, 1, 3, 5], then shuffled arrays [1, 3, 5, 1], [3, 5, 1, 1] and [5, 3, 1, 1] are good, but shuffled arrays [3, 1, 5, 1], [1, 1, 3, 5] and [1, 1, 5, 3] aren't. It's guaranteed that it's always possible to shuffle an array to meet this condition. Input The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case contains one integer n (1 ≤ n ≤ 100) — the length of array a. The second line of each test case contains n integers a_1, a_2, ... , a_n (1 ≤ a_i ≤ 100). Output For each test case print the shuffled version of the array a which is good. Example Input 3 1 7 4 1 1 3 5 6 3 2 1 5 6 4 Output 7 1 5 1 3 2 4 6 1 3 5 Submitted Solution: ``` t=input() a=[] for i in t: n=input() a=[int(b) for b in input().split()] print(list(reversed(a))) ```
instruction
0
29,265
12
58,530
No
output
1
29,265
12
58,531
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a_1, a_2, ... , a_n. Array is good if for each pair of indexes i < j the condition j - a_j ≠ i - a_i holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option). For example, if a = [1, 1, 3, 5], then shuffled arrays [1, 3, 5, 1], [3, 5, 1, 1] and [5, 3, 1, 1] are good, but shuffled arrays [3, 1, 5, 1], [1, 1, 3, 5] and [1, 1, 5, 3] aren't. It's guaranteed that it's always possible to shuffle an array to meet this condition. Input The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case contains one integer n (1 ≤ n ≤ 100) — the length of array a. The second line of each test case contains n integers a_1, a_2, ... , a_n (1 ≤ a_i ≤ 100). Output For each test case print the shuffled version of the array a which is good. Example Input 3 1 7 4 1 1 3 5 6 3 2 1 5 6 4 Output 7 1 5 1 3 2 4 6 1 3 5 Submitted Solution: ``` t = int(input()) for loop in range(t): n = int(input()) a = list(map(int,input().split())) a.sort() a.reverse() for i in range(n): if a[i] == i+1: if a[0] != i+1 and a[i] != 1: x = a[0] a[0] = a[i] a[i] = x else: x = a[-1] a[-1] = a[i] a[i] = x print (" ".join(map(str,a))) ```
instruction
0
29,266
12
58,532
No
output
1
29,266
12
58,533
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's denote the following function f. This function takes an array a of length n and returns an array. Initially the result is an empty array. For each integer i from 1 to n we add element a_i to the end of the resulting array if it is greater than all previous elements (more formally, if a_i > max_{1 ≤ j < i}a_j). Some examples of the function f: 1. if a = [3, 1, 2, 7, 7, 3, 6, 7, 8] then f(a) = [3, 7, 8]; 2. if a = [1] then f(a) = [1]; 3. if a = [4, 1, 1, 2, 3] then f(a) = [4]; 4. if a = [1, 3, 1, 2, 6, 8, 7, 7, 4, 11, 10] then f(a) = [1, 3, 6, 8, 11]. You are given two arrays: array a_1, a_2, ... , a_n and array b_1, b_2, ... , b_m. You can delete some elements of array a (possibly zero). To delete the element a_i, you have to pay p_i coins (the value of p_i can be negative, then you get |p_i| coins, if you delete this element). Calculate the minimum number of coins (possibly negative) you have to spend for fulfilling equality f(a) = b. Input The first line contains one integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the length of array a. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) — the array a. The third line contains n integers p_1, p_2, ..., p_n (|p_i| ≤ 10^9) — the array p. The fourth line contains one integer m (1 ≤ m ≤ n) — the length of array b. The fifth line contains m integers b_1, b_2, ..., b_m (1 ≤ b_i ≤ n, b_{i-1} < b_i) — the array b. Output If the answer exists, in the first line print YES. In the second line, print the minimum number of coins you have to spend for fulfilling equality f(a) = b. Otherwise in only line print NO. Examples Input 11 4 1 3 3 7 8 7 9 10 7 11 3 5 0 -2 5 3 6 7 8 2 4 3 3 7 10 Output YES 20 Input 6 2 1 5 3 6 5 3 -9 0 16 22 -14 4 2 3 5 6 Output NO Submitted Solution: ``` n=int(input()) a=input() la=a.split(' ') p=input() lp=p.split(' ') m=int(input()) b=input() lb=b.split(' ') val=0 i=0 while i<len(la): if la[i]!=lb[0]: del la[i] val=val+int(lp[i]) del lp[i] else: i=len(la) j=1 maxi=lb[0] l=[] if lb[0] in la: l.append(lb[0]) k=len(la) i=1 compt=1 while compt<k: if int(la[i])>int(maxi): if la[i]==lb[j]: l.append(la[i]) maxi=lb[j] if j<len(lb)-1: j=j+1 else: j=j i=i+1 else: del la[i] val=val+int(lp[i]) del lp[i] else: if la[i]==maxi and int(lp[i])<0: del la[i] val=val+int(lp[i]) del lp[i] else: i+=1 compt+=1 if l==lb: print("YES") print(val) else: print("NO") print(la) ```
instruction
0
29,267
12
58,534
No
output
1
29,267
12
58,535
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's denote the following function f. This function takes an array a of length n and returns an array. Initially the result is an empty array. For each integer i from 1 to n we add element a_i to the end of the resulting array if it is greater than all previous elements (more formally, if a_i > max_{1 ≤ j < i}a_j). Some examples of the function f: 1. if a = [3, 1, 2, 7, 7, 3, 6, 7, 8] then f(a) = [3, 7, 8]; 2. if a = [1] then f(a) = [1]; 3. if a = [4, 1, 1, 2, 3] then f(a) = [4]; 4. if a = [1, 3, 1, 2, 6, 8, 7, 7, 4, 11, 10] then f(a) = [1, 3, 6, 8, 11]. You are given two arrays: array a_1, a_2, ... , a_n and array b_1, b_2, ... , b_m. You can delete some elements of array a (possibly zero). To delete the element a_i, you have to pay p_i coins (the value of p_i can be negative, then you get |p_i| coins, if you delete this element). Calculate the minimum number of coins (possibly negative) you have to spend for fulfilling equality f(a) = b. Input The first line contains one integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the length of array a. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) — the array a. The third line contains n integers p_1, p_2, ..., p_n (|p_i| ≤ 10^9) — the array p. The fourth line contains one integer m (1 ≤ m ≤ n) — the length of array b. The fifth line contains m integers b_1, b_2, ..., b_m (1 ≤ b_i ≤ n, b_{i-1} < b_i) — the array b. Output If the answer exists, in the first line print YES. In the second line, print the minimum number of coins you have to spend for fulfilling equality f(a) = b. Otherwise in only line print NO. Examples Input 11 4 1 3 3 7 8 7 9 10 7 11 3 5 0 -2 5 3 6 7 8 2 4 3 3 7 10 Output YES 20 Input 6 2 1 5 3 6 5 3 -9 0 16 22 -14 4 2 3 5 6 Output NO Submitted Solution: ``` n = int(input()) li = list(map(int,input().split(" "))) p = list(map(int,input().split(" "))) req = int(input()) opt = list(map(int,input().split(" "))) i = 0 j = 0 ans = 0 ma = -pow(10, 9) ma = ma - 1 while i < n: if li[i] > ma: if j<req: if li[i] != opt[j]: ans += p[i] else: ma=li[i] j += 1 else: ans+=p[i] else: if p[i] < 0: ans += p[i] i += 1 if j == req: print("YES") print(ans) else: print("NO") ```
instruction
0
29,268
12
58,536
No
output
1
29,268
12
58,537
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's denote the following function f. This function takes an array a of length n and returns an array. Initially the result is an empty array. For each integer i from 1 to n we add element a_i to the end of the resulting array if it is greater than all previous elements (more formally, if a_i > max_{1 ≤ j < i}a_j). Some examples of the function f: 1. if a = [3, 1, 2, 7, 7, 3, 6, 7, 8] then f(a) = [3, 7, 8]; 2. if a = [1] then f(a) = [1]; 3. if a = [4, 1, 1, 2, 3] then f(a) = [4]; 4. if a = [1, 3, 1, 2, 6, 8, 7, 7, 4, 11, 10] then f(a) = [1, 3, 6, 8, 11]. You are given two arrays: array a_1, a_2, ... , a_n and array b_1, b_2, ... , b_m. You can delete some elements of array a (possibly zero). To delete the element a_i, you have to pay p_i coins (the value of p_i can be negative, then you get |p_i| coins, if you delete this element). Calculate the minimum number of coins (possibly negative) you have to spend for fulfilling equality f(a) = b. Input The first line contains one integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the length of array a. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) — the array a. The third line contains n integers p_1, p_2, ..., p_n (|p_i| ≤ 10^9) — the array p. The fourth line contains one integer m (1 ≤ m ≤ n) — the length of array b. The fifth line contains m integers b_1, b_2, ..., b_m (1 ≤ b_i ≤ n, b_{i-1} < b_i) — the array b. Output If the answer exists, in the first line print YES. In the second line, print the minimum number of coins you have to spend for fulfilling equality f(a) = b. Otherwise in only line print NO. Examples Input 11 4 1 3 3 7 8 7 9 10 7 11 3 5 0 -2 5 3 6 7 8 2 4 3 3 7 10 Output YES 20 Input 6 2 1 5 3 6 5 3 -9 0 16 22 -14 4 2 3 5 6 Output NO Submitted Solution: ``` m=int(input()) a=list(map(int,input().split())) p=list(map(int,input().split())) n=int(input()) b=list(map(int,input().split())) ind=[] for i in b: ind.append(a.index(i)) copy=ind[:] copy.sort() flag=True if copy!=ind: print("NO") flag=False if flag: c={} a_copy=a[:] for j in b: if b not in a: print("NO") flag=False if flag: for i in range(m): if a[i] in c: c[a[i]].append(p[i]) else: c[a[i]]=[p[i]] set(b) coins=0 for i in range(m): if a[i] not in b: coins+=p[i] for i in b: if len(c[i])>1: c[i].sort() for j in range(len(c[i])-1): if c[i][j]<0: coins+=c[i][j] else: break print(coins) ```
instruction
0
29,269
12
58,538
No
output
1
29,269
12
58,539
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's denote the following function f. This function takes an array a of length n and returns an array. Initially the result is an empty array. For each integer i from 1 to n we add element a_i to the end of the resulting array if it is greater than all previous elements (more formally, if a_i > max_{1 ≤ j < i}a_j). Some examples of the function f: 1. if a = [3, 1, 2, 7, 7, 3, 6, 7, 8] then f(a) = [3, 7, 8]; 2. if a = [1] then f(a) = [1]; 3. if a = [4, 1, 1, 2, 3] then f(a) = [4]; 4. if a = [1, 3, 1, 2, 6, 8, 7, 7, 4, 11, 10] then f(a) = [1, 3, 6, 8, 11]. You are given two arrays: array a_1, a_2, ... , a_n and array b_1, b_2, ... , b_m. You can delete some elements of array a (possibly zero). To delete the element a_i, you have to pay p_i coins (the value of p_i can be negative, then you get |p_i| coins, if you delete this element). Calculate the minimum number of coins (possibly negative) you have to spend for fulfilling equality f(a) = b. Input The first line contains one integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the length of array a. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) — the array a. The third line contains n integers p_1, p_2, ..., p_n (|p_i| ≤ 10^9) — the array p. The fourth line contains one integer m (1 ≤ m ≤ n) — the length of array b. The fifth line contains m integers b_1, b_2, ..., b_m (1 ≤ b_i ≤ n, b_{i-1} < b_i) — the array b. Output If the answer exists, in the first line print YES. In the second line, print the minimum number of coins you have to spend for fulfilling equality f(a) = b. Otherwise in only line print NO. Examples Input 11 4 1 3 3 7 8 7 9 10 7 11 3 5 0 -2 5 3 6 7 8 2 4 3 3 7 10 Output YES 20 Input 6 2 1 5 3 6 5 3 -9 0 16 22 -14 4 2 3 5 6 Output NO Submitted Solution: ``` n=int(input()) a=input() la=a.split(' ') p=input() lp=p.split(' ') m=int(input()) b=input() lb=b.split(' ') val=0 i=0 while i<len(la): if la[i]!=lb[0]: del la[i] val=val+int(lp[i]) del lp[i] else: i=len(la) j=1 maxi=lb[0] l=[maxi] k=len(la) i=1 compt=1 while compt<k and len(a)>0: if int(la[i])>int(maxi): if la[i]==lb[j]: l.append(la[i]) maxi=lb[j] if j<len(lb)-1: j=j+1 else: j=j i=i+1 else: del la[i] val=val+int(lp[i]) del lp[i] else: if la[i]==maxi and int(lp[i])<0: del la[i] val=val+int(lp[i]) del lp[i] else: i+=1 compt+=1 print(la) if l==lb: print("YES") print(val) else: print("NO") ```
instruction
0
29,270
12
58,540
No
output
1
29,270
12
58,541
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n integers. In one move, you can choose some index i (1 ≤ i ≤ n - 2) and shift the segment [a_i, a_{i + 1}, a_{i + 2}] cyclically to the right (i.e. replace the segment [a_i, a_{i + 1}, a_{i + 2}] with [a_{i + 2}, a_i, a_{i + 1}]). Your task is to sort the initial array by no more than n^2 such operations or say that it is impossible to do that. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (3 ≤ n ≤ 500) — the length of a. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 500), where a_i is the i-th element a. It is guaranteed that the sum of n does not exceed 500. Output For each test case, print the answer: -1 on the only line if it is impossible to sort the given array using operations described in the problem statement, or the number of operations ans on the first line and ans integers idx_1, idx_2, ..., idx_{ans} (1 ≤ idx_i ≤ n - 2), where idx_i is the index of left border of the segment for the i-th operation. You should print indices in order of performing operations. Example Input 5 5 1 2 3 4 5 5 5 4 3 2 1 8 8 4 5 2 3 6 7 3 7 5 2 1 6 4 7 3 6 1 2 3 3 6 4 Output 0 6 3 1 3 2 2 3 13 2 1 1 6 4 2 4 3 3 4 4 6 6 -1 4 3 3 4 4
instruction
0
29,287
12
58,574
Tags: brute force, constructive algorithms, implementation, sortings Correct Solution: ``` import io import os from collections import Counter, deque DEBUG = False def solve(N, A): original = list(A) sortedA = sorted(A) if False and N <= 5: # Bruteforce for small N def doMove(A, i): assert i + 2 < N A = list(A) return tuple(A[:i] + [A[i + 2], A[i], A[i + 1]] + A[i + 3 :]) moves = None source = tuple(A) dest = tuple(sortedA) q = deque([source]) moveFromParent = {source: None} while q: node = q.popleft() if node == dest: moves = [] while moveFromParent[node] is not None: i = moveFromParent[node] moves.append(i) node = doMove(node, i) node = doMove(node, i) moves = moves[::-1] break for i in range(N - 2): nbr = doMove(node, i) if nbr not in moveFromParent: q.append(nbr) moveFromParent[nbr] = i if moves is None: return -1 else: # Larger N should be fine since fixing each element only cost N / 2 + small moves = [] for i, target in enumerate(sortedA): # A is unsorted portion, find target and move it to i index = A.index(target) del A[index] j = i + index while j >= i + 2: j -= 2 moves.append(j) assert i <= j <= i + 1 if j == i + 1: # current array looks like: # sortedA[:i] + [A[0], target] + A[1:] assert len(A) > 0 if len(A) >= 2: # Rotate twice: # A[0], target, A[1] # A[1], A[0], target # target, A[1], A[0] moves.append(i) moves.append(i) A[0], A[1] = A[1], A[0] else: assert len(A) == 1 # Last two elements are A[0] and target if A[0] == target: # Already good break if sortedA[i - 1] == target: # sortedA[i-1], A[0], target # target, sortedA[i-1], A[0] moves.append(i - 1) break assert sortedA[i - 1] < target < A[0] # Otherwise can only be fixed if we have duplicates somewhere? dupes = set(k for k, v in Counter(sortedA).items() if v > 1) if not dupes: return -1 # want N - 2 so need to break parity assert j == N - 1 while sortedA[j - 1] not in dupes: # Target is dragged by 2 until it hit dupes (which are always next to each other so can't be missed) moves.append(j - 2) j -= 2 assert sortedA[j - 1] in dupes if sortedA[j] in dupes: # moved target to in between j-1 and j # dupe, target, dupe # dupe, dupe, target moves.append(j - 1) j += 1 else: assert sortedA[j - 2] in dupes # dupe, dupe, target # target, dupe, dupe # dupe, target, dupe moves.append(j - 2) moves.append(j - 2) j -= 1 # Broke parity of j, move it back to the end while j != N - 2: moves.append(j) moves.append(j) j += 2 break # print(sortedA[: i + 1], A) if DEBUG: # Sanity check A = original for i in moves: assert i + 3 <= N A[i : i + 3] = A[i + 2], A[i], A[i + 1] assert A == sortedA if len(moves) <= N * N: return str(len(moves)) + "\n" + " ".join(str(x + 1) for x in moves) return -1 if DEBUG: import random random.seed(0) for t in range(1000): A = [random.randint(0, 10) for i in range(100)] solve(len(A), A) A = [1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 11] print(solve(len(A), A)) A = [1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 11] print(solve(len(A), A)) exit() if __name__ == "__main__": input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline T = int(input()) for t in range(T): (N,) = [int(x) for x in input().split()] A = [int(x) for x in input().split()] ans = solve(N, A) print(ans) ```
output
1
29,287
12
58,575
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n integers. In one move, you can choose some index i (1 ≤ i ≤ n - 2) and shift the segment [a_i, a_{i + 1}, a_{i + 2}] cyclically to the right (i.e. replace the segment [a_i, a_{i + 1}, a_{i + 2}] with [a_{i + 2}, a_i, a_{i + 1}]). Your task is to sort the initial array by no more than n^2 such operations or say that it is impossible to do that. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (3 ≤ n ≤ 500) — the length of a. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 500), where a_i is the i-th element a. It is guaranteed that the sum of n does not exceed 500. Output For each test case, print the answer: -1 on the only line if it is impossible to sort the given array using operations described in the problem statement, or the number of operations ans on the first line and ans integers idx_1, idx_2, ..., idx_{ans} (1 ≤ idx_i ≤ n - 2), where idx_i is the index of left border of the segment for the i-th operation. You should print indices in order of performing operations. Example Input 5 5 1 2 3 4 5 5 5 4 3 2 1 8 8 4 5 2 3 6 7 3 7 5 2 1 6 4 7 3 6 1 2 3 3 6 4 Output 0 6 3 1 3 2 2 3 13 2 1 1 6 4 2 4 3 3 4 4 6 6 -1 4 3 3 4 4
instruction
0
29,288
12
58,576
Tags: brute force, constructive algorithms, implementation, sortings Correct Solution: ``` t = int(input()) for _ in range(t): n = int(input()) l = list(map(lambda x: int(x)- 1, input().split())) out = [] ll = [(l[i], i) for i in range(n)] ll.sort() swap = (-1,-1) for i in range(n - 1): if ll[i][0] == ll[i + 1][0]:swap = (ll[i][1],ll[i+1][1]) newl = [0]*n for i in range(n):newl[ll[i][1]] = i l = newl swapN = 0 for i in range(n): for j in range(i + 1, n): if l[i] > l[j]:swapN += 1 if swapN & 1:l[swap[0]],l[swap[1]] = l[swap[1]],l[swap[0]] def shift(i):out.append(i + 1);l[i],l[i+1],l[i+2] = l[i+2],l[i],l[i+1] works,done = True,False while not done: for i in range(n): if l[i] != i:break else:done = True if done:break for find in range(i + 1, n): if l[find] == i:break while find - i >= 2: find -= 2 shift(find) if find - i == 1: if find <= n - 2:shift(find - 1);shift(find - 1) else:works = False;break if works: print(len(out)) print(' '.join(map(str,out))) else: print(-1) ```
output
1
29,288
12
58,577
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n integers. In one move, you can choose some index i (1 ≤ i ≤ n - 2) and shift the segment [a_i, a_{i + 1}, a_{i + 2}] cyclically to the right (i.e. replace the segment [a_i, a_{i + 1}, a_{i + 2}] with [a_{i + 2}, a_i, a_{i + 1}]). Your task is to sort the initial array by no more than n^2 such operations or say that it is impossible to do that. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (3 ≤ n ≤ 500) — the length of a. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 500), where a_i is the i-th element a. It is guaranteed that the sum of n does not exceed 500. Output For each test case, print the answer: -1 on the only line if it is impossible to sort the given array using operations described in the problem statement, or the number of operations ans on the first line and ans integers idx_1, idx_2, ..., idx_{ans} (1 ≤ idx_i ≤ n - 2), where idx_i is the index of left border of the segment for the i-th operation. You should print indices in order of performing operations. Example Input 5 5 1 2 3 4 5 5 5 4 3 2 1 8 8 4 5 2 3 6 7 3 7 5 2 1 6 4 7 3 6 1 2 3 3 6 4 Output 0 6 3 1 3 2 2 3 13 2 1 1 6 4 2 4 3 3 4 4 6 6 -1 4 3 3 4 4
instruction
0
29,289
12
58,578
Tags: brute force, constructive algorithms, implementation, sortings Correct Solution: ``` import sys def rs(): return sys.stdin.readline().rstrip() def ri(): return int(sys.stdin.readline()) def ria(): return list(map(int, sys.stdin.readline().split())) def ws(s): sys.stdout.write(s + '\n') def wi(n): sys.stdout.write(str(n) + '\n') def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n') def rotate(a, i): t = a[i+2] a[i + 2] = a[i + 1] a[i + 1] = a[i] a[i] = t def solve(n, a): sa = sorted(a) s = [] rolled = False i = 0 while i < n: for j in range(i, n): if a[j] == sa[i]: break while j - i >= 2: j -= 2 rotate(a, j) s.append(j+1) if i+1 == j: if i+2 < n: rotate(a, i) rotate(a, i) s.append(i+1) s.append(i+1) else: if rolled: wi(-1) return found = False for k in range(n-2, 0, -1): if len(set(a[k-1:k+2])) == 2: found = True break if found: if a[k-1] == a[k]: rotate(a, k - 1) rotate(a, k - 1) s.append(k) s.append(k) else: rotate(a, k - 1) s.append(k) rolled = True i = k-2 else: wi(-1) return i += 1 if len(s) <= n*n: wi(len(s)) wia(s) else: wi(-1) def main(): for _ in range(ri()): n = ri() a = ria() solve(n, a) if __name__ == '__main__': main() ```
output
1
29,289
12
58,579
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n integers. In one move, you can choose some index i (1 ≤ i ≤ n - 2) and shift the segment [a_i, a_{i + 1}, a_{i + 2}] cyclically to the right (i.e. replace the segment [a_i, a_{i + 1}, a_{i + 2}] with [a_{i + 2}, a_i, a_{i + 1}]). Your task is to sort the initial array by no more than n^2 such operations or say that it is impossible to do that. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (3 ≤ n ≤ 500) — the length of a. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 500), where a_i is the i-th element a. It is guaranteed that the sum of n does not exceed 500. Output For each test case, print the answer: -1 on the only line if it is impossible to sort the given array using operations described in the problem statement, or the number of operations ans on the first line and ans integers idx_1, idx_2, ..., idx_{ans} (1 ≤ idx_i ≤ n - 2), where idx_i is the index of left border of the segment for the i-th operation. You should print indices in order of performing operations. Example Input 5 5 1 2 3 4 5 5 5 4 3 2 1 8 8 4 5 2 3 6 7 3 7 5 2 1 6 4 7 3 6 1 2 3 3 6 4 Output 0 6 3 1 3 2 2 3 13 2 1 1 6 4 2 4 3 3 4 4 6 6 -1 4 3 3 4 4
instruction
0
29,290
12
58,580
Tags: brute force, constructive algorithms, implementation, sortings Correct Solution: ``` for _ in range(int(input())): n,l,out = int(input()),list(map(lambda x: int(x)- 1, input().split())),[];ll = sorted([(l[i], i) for i in range(n)]);swap = (-1,-1);newl = [0]*n for i in range(n - 1): if ll[i][0] == ll[i + 1][0]:swap = (ll[i][1],ll[i+1][1]) for i in range(n):newl[ll[i][1]] = i l,swapN = newl,0;works,done = True,False for i in range(n): for j in range(i + 1, n): if l[i] > l[j]:swapN += 1 if swapN & 1:l[swap[0]],l[swap[1]] = l[swap[1]],l[swap[0]] def shift(i):out.append(i + 1);l[i],l[i+1],l[i+2] = l[i+2],l[i],l[i+1] while not done: for i in range(n): if l[i] != i:break else:done = True if done:break for find in range(i + 1, n): if l[find] == i:break while find - i >= 2:find -= 2;shift(find) if find - i == 1: if find <= n - 2:shift(find - 1);shift(find - 1) else:works = False;break if works:print(len(out));print(' '.join(map(str,out))) else:print(-1) ```
output
1
29,290
12
58,581
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n integers. In one move, you can choose some index i (1 ≤ i ≤ n - 2) and shift the segment [a_i, a_{i + 1}, a_{i + 2}] cyclically to the right (i.e. replace the segment [a_i, a_{i + 1}, a_{i + 2}] with [a_{i + 2}, a_i, a_{i + 1}]). Your task is to sort the initial array by no more than n^2 such operations or say that it is impossible to do that. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (3 ≤ n ≤ 500) — the length of a. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 500), where a_i is the i-th element a. It is guaranteed that the sum of n does not exceed 500. Output For each test case, print the answer: -1 on the only line if it is impossible to sort the given array using operations described in the problem statement, or the number of operations ans on the first line and ans integers idx_1, idx_2, ..., idx_{ans} (1 ≤ idx_i ≤ n - 2), where idx_i is the index of left border of the segment for the i-th operation. You should print indices in order of performing operations. Example Input 5 5 1 2 3 4 5 5 5 4 3 2 1 8 8 4 5 2 3 6 7 3 7 5 2 1 6 4 7 3 6 1 2 3 3 6 4 Output 0 6 3 1 3 2 2 3 13 2 1 1 6 4 2 4 3 3 4 4 6 6 -1 4 3 3 4 4
instruction
0
29,291
12
58,582
Tags: brute force, constructive algorithms, implementation, sortings Correct Solution: ``` for _ in range(int(input())): n=int(input()) l=list(map(int,input().split())) s=[] for i in range(n): for j in range(n-2): if(l[j]>l[j+1]): l[j],l[j+2]=l[j+2],l[j] l[j],l[j+1]=l[j+1],l[j] s.append(j+1) s.append(j+1) elif(l[j+1]>l[j+2]): l[j],l[j+1]=l[j+1],l[j] l[j],l[j+2]=l[j+2],l[j] s.append(j+1) if(l!=sorted(l)): print(-1) else: print(len(s)) print(*s) ```
output
1
29,291
12
58,583
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n integers. In one move, you can choose some index i (1 ≤ i ≤ n - 2) and shift the segment [a_i, a_{i + 1}, a_{i + 2}] cyclically to the right (i.e. replace the segment [a_i, a_{i + 1}, a_{i + 2}] with [a_{i + 2}, a_i, a_{i + 1}]). Your task is to sort the initial array by no more than n^2 such operations or say that it is impossible to do that. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (3 ≤ n ≤ 500) — the length of a. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 500), where a_i is the i-th element a. It is guaranteed that the sum of n does not exceed 500. Output For each test case, print the answer: -1 on the only line if it is impossible to sort the given array using operations described in the problem statement, or the number of operations ans on the first line and ans integers idx_1, idx_2, ..., idx_{ans} (1 ≤ idx_i ≤ n - 2), where idx_i is the index of left border of the segment for the i-th operation. You should print indices in order of performing operations. Example Input 5 5 1 2 3 4 5 5 5 4 3 2 1 8 8 4 5 2 3 6 7 3 7 5 2 1 6 4 7 3 6 1 2 3 3 6 4 Output 0 6 3 1 3 2 2 3 13 2 1 1 6 4 2 4 3 3 4 4 6 6 -1 4 3 3 4 4
instruction
0
29,292
12
58,584
Tags: brute force, constructive algorithms, implementation, sortings Correct Solution: ``` #!/usr/bin/env python3 import heapq import sys input=sys.stdin.readline t=int(input()) for _ in range(t): n=int(input()) arr=list(map(int,input().split())) q=[] for i in range(n): heapq.heappush(q,arr[i]) pos=0 cnt=0 ans=[] while pos<n-2: tmp=heapq.heappop(q) if arr[pos]==tmp: pos+=1 continue else: tpos=pos+arr[pos:].index(tmp) while tpos-pos>=2: cnt+=1 tpos-=2 ans.append(tpos+1) arr[tpos],arr[tpos+1],arr[tpos+2]=arr[tpos+2],arr[tpos],arr[tpos+1] if tpos-pos==1: cnt+=2 tpos-=1 ans.append(tpos+1) ans.append(tpos+1) arr[tpos],arr[tpos+1],arr[tpos+2]=arr[tpos+1],arr[tpos+2],arr[tpos] pos+=1 if arr[n-2]<=arr[n-1]: print(cnt) print(*ans) else: ttpos=-1 for i in range(n-2,-1,-1): if arr[i]==arr[i+1]: ttpos=i break if ttpos==-1: cnt+=1 ans.append(n-2) arr[n-3],arr[n-2],arr[n-1]=arr[n-1],arr[n-3],arr[n-2] if arr[n-3]<=arr[n-2]<=arr[n-1]: print(cnt) print(*ans) else: cnt+=1 ans.append(n-2) arr[n-3],arr[n-2],arr[n-1]=arr[n-1],arr[n-3],arr[n-2] if arr[n-3]<=arr[n-2]<=arr[n-1]: print(cnt) print(*ans) else: print(-1) else: cnt+=2 ans.append(ttpos+1) ans.append(ttpos+1) arr[ttpos],arr[ttpos+1],arr[ttpos+2]=arr[ttpos+1],arr[ttpos+2],arr[ttpos] q=[] for i in range(n): heapq.heappush(q,arr[i]) pos=0 while pos<n-2: tmp=heapq.heappop(q) if arr[pos]==tmp: pos+=1 continue else: tpos=pos+arr[pos:].index(tmp) while tpos-pos>=2: cnt+=1 tpos-=2 ans.append(tpos+1) arr[tpos],arr[tpos+1],arr[tpos+2]=arr[tpos+2],arr[tpos],arr[tpos+1] if tpos-pos==1: cnt+=2 tpos-=1 ans.append(tpos+1) ans.append(tpos+1) arr[tpos],arr[tpos+1],arr[tpos+2]=arr[tpos+1],arr[tpos+2],arr[tpos] pos+=1 print(cnt) print(*ans) ```
output
1
29,292
12
58,585
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n integers. In one move, you can choose some index i (1 ≤ i ≤ n - 2) and shift the segment [a_i, a_{i + 1}, a_{i + 2}] cyclically to the right (i.e. replace the segment [a_i, a_{i + 1}, a_{i + 2}] with [a_{i + 2}, a_i, a_{i + 1}]). Your task is to sort the initial array by no more than n^2 such operations or say that it is impossible to do that. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (3 ≤ n ≤ 500) — the length of a. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 500), where a_i is the i-th element a. It is guaranteed that the sum of n does not exceed 500. Output For each test case, print the answer: -1 on the only line if it is impossible to sort the given array using operations described in the problem statement, or the number of operations ans on the first line and ans integers idx_1, idx_2, ..., idx_{ans} (1 ≤ idx_i ≤ n - 2), where idx_i is the index of left border of the segment for the i-th operation. You should print indices in order of performing operations. Example Input 5 5 1 2 3 4 5 5 5 4 3 2 1 8 8 4 5 2 3 6 7 3 7 5 2 1 6 4 7 3 6 1 2 3 3 6 4 Output 0 6 3 1 3 2 2 3 13 2 1 1 6 4 2 4 3 3 4 4 6 6 -1 4 3 3 4 4
instruction
0
29,293
12
58,586
Tags: brute force, constructive algorithms, implementation, sortings Correct Solution: ``` #!/usr/bin/env pypy3 def swaps(A): # assume A is a permutation of range(0, len(A)) ret = [] for k in range(len(A)-1, 1, -1): assert(A.index(k) <= k) # print(f"putting {k} in the correct position") while A.index(k) < k: s = max(A.index(k)-1, 0) ret += [s] A[s], A[s+1], A[s+2] = A[s+2], A[s], A[s+1] # print(f"A={A}") if sorted(A) != A: return None return [x+1 for x in ret] def ans(A): seen = set() duplicate = None for a in A: if a in seen: duplicate = a break else: seen.add(a) A = [(e, i) for i, e in enumerate(A)] A = sorted(A) A = [(i, j, e) for j, (e, i) in enumerate(A)] A = sorted(A) A2 = None if duplicate is not None: duplicate_indices = set() for i, (_, _, e) in enumerate(A): if e == duplicate: duplicate_indices.add(i) assert(len(duplicate_indices) >= 2) p, q = list(duplicate_indices)[0:2] A2 = A[:] A2[p], A2[q] = A2[q], A2[p] A2 = [j for (i, j, e) in A2] A = [j for (i, j, e) in A] # if A2 is None: # print(f"A={A}") # else: # print(f"A={A} A2={A2}") s = swaps(A) s2 = None if A2 is not None: s2 = swaps(A2) if s is not None: print(len(s)) print(*s) elif s2 is not None: print(len(s2)) print(*s2) else: print(-1) T = int(input()) for _ in range(T): input() A = input().split(' ') A = list(map(int, A)) ans(A) ```
output
1
29,293
12
58,587
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n integers. In one move, you can choose some index i (1 ≤ i ≤ n - 2) and shift the segment [a_i, a_{i + 1}, a_{i + 2}] cyclically to the right (i.e. replace the segment [a_i, a_{i + 1}, a_{i + 2}] with [a_{i + 2}, a_i, a_{i + 1}]). Your task is to sort the initial array by no more than n^2 such operations or say that it is impossible to do that. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (3 ≤ n ≤ 500) — the length of a. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 500), where a_i is the i-th element a. It is guaranteed that the sum of n does not exceed 500. Output For each test case, print the answer: -1 on the only line if it is impossible to sort the given array using operations described in the problem statement, or the number of operations ans on the first line and ans integers idx_1, idx_2, ..., idx_{ans} (1 ≤ idx_i ≤ n - 2), where idx_i is the index of left border of the segment for the i-th operation. You should print indices in order of performing operations. Example Input 5 5 1 2 3 4 5 5 5 4 3 2 1 8 8 4 5 2 3 6 7 3 7 5 2 1 6 4 7 3 6 1 2 3 3 6 4 Output 0 6 3 1 3 2 2 3 13 2 1 1 6 4 2 4 3 3 4 4 6 6 -1 4 3 3 4 4
instruction
0
29,294
12
58,588
Tags: brute force, constructive algorithms, implementation, sortings Correct Solution: ``` t=1 t=int(input()) for _ in range(t): n=int(input()) a=list(map(int,input().split())) a=[(a[i],i) for i in range(n)] a.sort() rev=0 for i in range(n): val,id=a[i] for j in range(i): sval,sid=a[j] if sid>id: rev+=1 if rev%2==1: for i in range(1,n): if a[i][0]==a[i-1][0]: a[i-1],a[i]=a[i],a[i-1] break else: print(-1) continue A=[-1]*n for i in range(n): val,id=a[i] A[id]=i+1 a=[0]+A ID=[-1]*(n+1) for i in range(1,n+1): ID[a[i]]=i goal=1 res=[] def swap(i): res.append(i) ID[a[i]],ID[a[i+1]],ID[a[i+2]]=i+1,i+2,i a[i],a[i+1],a[i+2]=a[i+2],a[i],a[i+1] while n>=goal: start=ID[goal] if (start-goal)%2==1: if start==n: swap(start-2) swap(start-2) start=ID[goal] else: swap(start-1) start=ID[goal] while start!=goal: swap(start-2) start=ID[goal] goal+=1 print(len(res)) print(*res) ```
output
1
29,294
12
58,589
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a consisting of n integers. In one move, you can choose some index i (1 ≤ i ≤ n - 2) and shift the segment [a_i, a_{i + 1}, a_{i + 2}] cyclically to the right (i.e. replace the segment [a_i, a_{i + 1}, a_{i + 2}] with [a_{i + 2}, a_i, a_{i + 1}]). Your task is to sort the initial array by no more than n^2 such operations or say that it is impossible to do that. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (3 ≤ n ≤ 500) — the length of a. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 500), where a_i is the i-th element a. It is guaranteed that the sum of n does not exceed 500. Output For each test case, print the answer: -1 on the only line if it is impossible to sort the given array using operations described in the problem statement, or the number of operations ans on the first line and ans integers idx_1, idx_2, ..., idx_{ans} (1 ≤ idx_i ≤ n - 2), where idx_i is the index of left border of the segment for the i-th operation. You should print indices in order of performing operations. Example Input 5 5 1 2 3 4 5 5 5 4 3 2 1 8 8 4 5 2 3 6 7 3 7 5 2 1 6 4 7 3 6 1 2 3 3 6 4 Output 0 6 3 1 3 2 2 3 13 2 1 1 6 4 2 4 3 3 4 4 6 6 -1 4 3 3 4 4 Submitted Solution: ``` def swap(i): tmp = a[i+2] a[i+2] = a[i+1] a[i+1] = a[i] a[i] = tmp ans.append(i+1) #print (*a) tt = int(input()) for loop in range(tt): n = int(input()) a = list(map(int,input().split())) sa = 0.0001 lis = [sa] * 501 b1 = [] b2 = [] f2 = True for i in range(n): if lis[a[i]] != sa and f2: b1.append(a[i] + lis[a[i]]) b2.append(a[i]) f2 = False else: b1.append(a[i] + lis[a[i]]) b2.append(a[i] + lis[a[i]]) lis[a[i]] += sa #print (b1) #print (b2) ans = [] a = b1 for last in range(n-3): mi = last for i in range(last,n): if a[i] < a[mi]: mi = i while mi != last: if mi - last >= 2: swap(mi-2) mi -= 2 else: swap(mi) mi += 1 while not ( a[-3] < a[-2] and a[-2] < a[-1] ): swap(n-3) if len(ans) > n**2: break if len(ans) <= n**2: print (len(ans)) print (*ans) continue ans = [] a = b2 for last in range(n-3): mi = last for i in range(last,n): if a[i] < a[mi]: mi = i while mi != last: if mi - last >= 2: swap(mi-2) mi -= 2 else: swap(mi) mi += 1 while not ( a[-3] < a[-2] and a[-2] < a[-1] ): swap(n-3) if len(ans) > n**2: break if len(ans) <= n**2: print (len(ans)) print (*ans) continue print (-1) ```
instruction
0
29,295
12
58,590
Yes
output
1
29,295
12
58,591
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a consisting of n integers. In one move, you can choose some index i (1 ≤ i ≤ n - 2) and shift the segment [a_i, a_{i + 1}, a_{i + 2}] cyclically to the right (i.e. replace the segment [a_i, a_{i + 1}, a_{i + 2}] with [a_{i + 2}, a_i, a_{i + 1}]). Your task is to sort the initial array by no more than n^2 such operations or say that it is impossible to do that. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (3 ≤ n ≤ 500) — the length of a. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 500), where a_i is the i-th element a. It is guaranteed that the sum of n does not exceed 500. Output For each test case, print the answer: -1 on the only line if it is impossible to sort the given array using operations described in the problem statement, or the number of operations ans on the first line and ans integers idx_1, idx_2, ..., idx_{ans} (1 ≤ idx_i ≤ n - 2), where idx_i is the index of left border of the segment for the i-th operation. You should print indices in order of performing operations. Example Input 5 5 1 2 3 4 5 5 5 4 3 2 1 8 8 4 5 2 3 6 7 3 7 5 2 1 6 4 7 3 6 1 2 3 3 6 4 Output 0 6 3 1 3 2 2 3 13 2 1 1 6 4 2 4 3 3 4 4 6 6 -1 4 3 3 4 4 Submitted Solution: ``` t = int(input()) for _ in range(t): n = int(input()) l = list(map(lambda x: int(x)- 1, input().split())) out = [] ll = sorted([(l[i], i) for i in range(n)]) swap = (-1,-1) for i in range(n - 1): if ll[i][0] == ll[i + 1][0]:swap = (ll[i][1],ll[i+1][1]) newl = [0]*n for i in range(n):newl[ll[i][1]] = i l = newl swapN = 0 for i in range(n): for j in range(i + 1, n): if l[i] > l[j]:swapN += 1 if swapN & 1:l[swap[0]],l[swap[1]] = l[swap[1]],l[swap[0]] def shift(i):out.append(i + 1);l[i],l[i+1],l[i+2] = l[i+2],l[i],l[i+1] works,done = True,False while not done: for i in range(n): if l[i] != i:break else:done = True if done:break for find in range(i + 1, n): if l[find] == i:break while find - i >= 2:find -= 2;shift(find) if find - i == 1: if find <= n - 2:shift(find - 1);shift(find - 1) else:works = False;break if works:print(len(out));print(' '.join(map(str,out))) else:print(-1) ```
instruction
0
29,296
12
58,592
Yes
output
1
29,296
12
58,593
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a consisting of n integers. In one move, you can choose some index i (1 ≤ i ≤ n - 2) and shift the segment [a_i, a_{i + 1}, a_{i + 2}] cyclically to the right (i.e. replace the segment [a_i, a_{i + 1}, a_{i + 2}] with [a_{i + 2}, a_i, a_{i + 1}]). Your task is to sort the initial array by no more than n^2 such operations or say that it is impossible to do that. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (3 ≤ n ≤ 500) — the length of a. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 500), where a_i is the i-th element a. It is guaranteed that the sum of n does not exceed 500. Output For each test case, print the answer: -1 on the only line if it is impossible to sort the given array using operations described in the problem statement, or the number of operations ans on the first line and ans integers idx_1, idx_2, ..., idx_{ans} (1 ≤ idx_i ≤ n - 2), where idx_i is the index of left border of the segment for the i-th operation. You should print indices in order of performing operations. Example Input 5 5 1 2 3 4 5 5 5 4 3 2 1 8 8 4 5 2 3 6 7 3 7 5 2 1 6 4 7 3 6 1 2 3 3 6 4 Output 0 6 3 1 3 2 2 3 13 2 1 1 6 4 2 4 3 3 4 4 6 6 -1 4 3 3 4 4 Submitted Solution: ``` import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # ------------------------------ def RL(): return map(int, sys.stdin.readline().rstrip().split()) def RLL(): return list(map(int, sys.stdin.readline().rstrip().split())) def N(): return int(input()) def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0 def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0 def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2) mod = 998244353 INF = float('inf') from math import factorial from collections import Counter, defaultdict, deque from heapq import heapify, heappop, heappush # ------------------------------ # f = open('../input.txt') # sys.stdin = f def main(): for _ in range(N()): n = N() arr = RLL() sarr = sorted(arr) res = [] def swap(i): res.append(i+1) arr[i], arr[i+1], arr[i+2] = arr[i+2], arr[i], arr[i+1] for i in range(n-2): now = arr[i] if now==sarr[i]: continue for j in range(i+1, n): if arr[j]==sarr[i]: ind = j while ind-2>=i: swap(ind-2) ind-=2 if ind!=i: swap(i) swap(i) for i in range(n-1, 1, -1): now = arr[i] if now==sarr[i]: continue for j in range(i-1, -1, -1): if arr[j]==sarr[i]: ind = j while ind+2<=i: swap(ind) swap(ind) ind+=2 if ind!=i: swap(ind-1) if sarr!=arr: print(-1) else: print(len(res)) print(*res) if __name__ == "__main__": main() ```
instruction
0
29,297
12
58,594
Yes
output
1
29,297
12
58,595
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a consisting of n integers. In one move, you can choose some index i (1 ≤ i ≤ n - 2) and shift the segment [a_i, a_{i + 1}, a_{i + 2}] cyclically to the right (i.e. replace the segment [a_i, a_{i + 1}, a_{i + 2}] with [a_{i + 2}, a_i, a_{i + 1}]). Your task is to sort the initial array by no more than n^2 such operations or say that it is impossible to do that. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (3 ≤ n ≤ 500) — the length of a. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 500), where a_i is the i-th element a. It is guaranteed that the sum of n does not exceed 500. Output For each test case, print the answer: -1 on the only line if it is impossible to sort the given array using operations described in the problem statement, or the number of operations ans on the first line and ans integers idx_1, idx_2, ..., idx_{ans} (1 ≤ idx_i ≤ n - 2), where idx_i is the index of left border of the segment for the i-th operation. You should print indices in order of performing operations. Example Input 5 5 1 2 3 4 5 5 5 4 3 2 1 8 8 4 5 2 3 6 7 3 7 5 2 1 6 4 7 3 6 1 2 3 3 6 4 Output 0 6 3 1 3 2 2 3 13 2 1 1 6 4 2 4 3 3 4 4 6 6 -1 4 3 3 4 4 Submitted Solution: ``` def change(i,j,k): global a a[i],a[j],a[k] = a[k],a[i],a[j] for nt in range(int(input())): n = int(input()) a = list(map(int,input().split())) arr = a[::] b = sorted(a) if a==b: print (0) print () continue i = 0 ans = [] flag = 0 while i<n: if a[i]==b[i]: i += 1 continue ind = a[i:].index(b[i])+i # print (ind) while a[i]!=b[i]: if ind==i+1: if ind+1>=len(a): flag = 1 break ans.append((i,ind,ind+1)) change(i,ind,ind+1) ans.append((i,ind,ind+1)) change(i,ind,ind+1) break else: ans.append((ind-2,ind-1,ind)) change(ind-2,ind-1,ind) ind -= 2 if flag: break i += 1 # print (a) if flag: if len(set(a))==n: print (-1) continue else: if a[-3]==a[-1]: ans.append((n-3,n-2,n-1)) else: ans = [] a = arr[::] flag2 = 0 temp = sorted(a,reverse=True) for i in range(1,n): if temp[i]==temp[i-1]: number = temp[i] break i = 0 while i<n: if a[i]==b[i] and (i==0 or a[i]!=a[i-1] or flag2): i += 1 continue elif i!=0 and a[i]==a[i-1]: if not flag2 and a[i]==number: ans.append((i-1,i,i+1)) change(i-1,i,i+1) ans.append((i-1,i,i+1)) change(i-1,i,i+1) ans.append((i,i+1,i+1)) change(i,i+1,i+2) ans.append((i,i+1,i+2)) change(i,i+1,i+2) flag2 = 1 i += 1 continue # print (i,a,b) ind = a[i:].index(b[i])+i # print (ind) while a[i]!=b[i]: if ind==i+1: ans.append((i,ind,ind+1)) change(i,ind,ind+1) ans.append((i,ind,ind+1)) change(i,ind,ind+1) break else: ans.append((ind-2,ind-1,ind)) change(ind-2,ind-1,ind) ind -= 2 # print (a,i) if i!=0 and a[i]==a[i-1] and flag2==0 and a[i]==number: ans.append((i-1,i,i+1)) change(i-1,i,i+1) ans.append((i-1,i,i+1)) change(i-1,i,i+1) ans.append((i,i+1,i+1)) change(i,i+1,i+2) ans.append((i,i+1,i+2)) change(i,i+1,i+2) flag2 = 1 i += 1 # print (a) print (len(ans)) for i in ans: print (i[0]+1,end=" ") print () ```
instruction
0
29,298
12
58,596
Yes
output
1
29,298
12
58,597
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a consisting of n integers. In one move, you can choose some index i (1 ≤ i ≤ n - 2) and shift the segment [a_i, a_{i + 1}, a_{i + 2}] cyclically to the right (i.e. replace the segment [a_i, a_{i + 1}, a_{i + 2}] with [a_{i + 2}, a_i, a_{i + 1}]). Your task is to sort the initial array by no more than n^2 such operations or say that it is impossible to do that. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (3 ≤ n ≤ 500) — the length of a. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 500), where a_i is the i-th element a. It is guaranteed that the sum of n does not exceed 500. Output For each test case, print the answer: -1 on the only line if it is impossible to sort the given array using operations described in the problem statement, or the number of operations ans on the first line and ans integers idx_1, idx_2, ..., idx_{ans} (1 ≤ idx_i ≤ n - 2), where idx_i is the index of left border of the segment for the i-th operation. You should print indices in order of performing operations. Example Input 5 5 1 2 3 4 5 5 5 4 3 2 1 8 8 4 5 2 3 6 7 3 7 5 2 1 6 4 7 3 6 1 2 3 3 6 4 Output 0 6 3 1 3 2 2 3 13 2 1 1 6 4 2 4 3 3 4 4 6 6 -1 4 3 3 4 4 Submitted Solution: ``` for testcase in range(int(input())): n = int(input()) a = list(map(int, input().split())) ans = [] def shift(pos): a[pos], a[pos + 1], a[pos + 2] = a[pos + 2], a[pos], a[pos + 1] ans.append(pos + 1) def shiftable(a): val, pos = min((val, pos) for pos, val in enumerate(a)) for i in range(1, len(a)): if a[(pos + i) % len(a)] < a[(pos + i - 1) % len(a)]: return False return True for i in range(n - 3): val, pos = min((val, pos) for pos, val in enumerate(a[i:], i)) # print(a, val, pos) while pos > i + 1: shift(pos - 2) pos -= 2 if pos == i + 1: shift(i) shift(i) # print(a) has_ans = True if not shiftable(a[-3:]): eq_pos = -1 for i in range(n - 3): if a[i] == a[i + 1]: eq_pos = i if eq_pos == -1: has_ans = False else: for i in range(eq_pos, n - 4): shift(i) shift(n - 3) shift(n - 4) for i in reversed(range(eq_pos, n - 4)): shift(i) if has_ans: assert(shiftable(a[-3:])) while a[- 3:] != list(sorted(a[- 3:])): shift(n - 3) if not has_ans: print(-1) else: print(len(ans)) print(' '.join(map(str, ans))) ```
instruction
0
29,299
12
58,598
No
output
1
29,299
12
58,599
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a consisting of n integers. In one move, you can choose some index i (1 ≤ i ≤ n - 2) and shift the segment [a_i, a_{i + 1}, a_{i + 2}] cyclically to the right (i.e. replace the segment [a_i, a_{i + 1}, a_{i + 2}] with [a_{i + 2}, a_i, a_{i + 1}]). Your task is to sort the initial array by no more than n^2 such operations or say that it is impossible to do that. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (3 ≤ n ≤ 500) — the length of a. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 500), where a_i is the i-th element a. It is guaranteed that the sum of n does not exceed 500. Output For each test case, print the answer: -1 on the only line if it is impossible to sort the given array using operations described in the problem statement, or the number of operations ans on the first line and ans integers idx_1, idx_2, ..., idx_{ans} (1 ≤ idx_i ≤ n - 2), where idx_i is the index of left border of the segment for the i-th operation. You should print indices in order of performing operations. Example Input 5 5 1 2 3 4 5 5 5 4 3 2 1 8 8 4 5 2 3 6 7 3 7 5 2 1 6 4 7 3 6 1 2 3 3 6 4 Output 0 6 3 1 3 2 2 3 13 2 1 1 6 4 2 4 3 3 4 4 6 6 -1 4 3 3 4 4 Submitted Solution: ``` import sys def rs(): return sys.stdin.readline().rstrip() def ri(): return int(sys.stdin.readline()) def ria(): return list(map(int, sys.stdin.readline().split())) def ws(s): sys.stdout.write(s + '\n') def wi(n): sys.stdout.write(str(n) + '\n') def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n') def rotate(a, i): t = a[i+2] a[i + 2] = a[i + 1] a[i + 1] = a[i] a[i] = t def solve(n, a): sa = sorted(a) s = [] rolled = False i = 0 while i < n: for j in range(i, n): if a[j] == sa[i]: break while j - i >= 2: j -= 2 rotate(a, j) s.append(j+1) if i+1 == j: if i+2 < n: rotate(a, i) rotate(a, i) s.append(i+1) s.append(i+1) else: if rolled: wi(-1) return found = False for k in range(i, 0, -1): if a[k-1] == a[k]: found = True break if found: rotate(a, k-1) rotate(a, k-1) s.append(k) s.append(k) rolled = True i = k-2 else: wi(-1) return i += 1 if len(s) <= n*n: wi(len(s)) wia(s) else: wi(-1) def main(): for _ in range(ri()): n = ri() a = ria() solve(n, a) if __name__ == '__main__': main() ```
instruction
0
29,300
12
58,600
No
output
1
29,300
12
58,601
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a consisting of n integers. In one move, you can choose some index i (1 ≤ i ≤ n - 2) and shift the segment [a_i, a_{i + 1}, a_{i + 2}] cyclically to the right (i.e. replace the segment [a_i, a_{i + 1}, a_{i + 2}] with [a_{i + 2}, a_i, a_{i + 1}]). Your task is to sort the initial array by no more than n^2 such operations or say that it is impossible to do that. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (3 ≤ n ≤ 500) — the length of a. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 500), where a_i is the i-th element a. It is guaranteed that the sum of n does not exceed 500. Output For each test case, print the answer: -1 on the only line if it is impossible to sort the given array using operations described in the problem statement, or the number of operations ans on the first line and ans integers idx_1, idx_2, ..., idx_{ans} (1 ≤ idx_i ≤ n - 2), where idx_i is the index of left border of the segment for the i-th operation. You should print indices in order of performing operations. Example Input 5 5 1 2 3 4 5 5 5 4 3 2 1 8 8 4 5 2 3 6 7 3 7 5 2 1 6 4 7 3 6 1 2 3 3 6 4 Output 0 6 3 1 3 2 2 3 13 2 1 1 6 4 2 4 3 3 4 4 6 6 -1 4 3 3 4 4 Submitted Solution: ``` import collections line = input() t = int(line) for _ in range(t): line = input() n = int(line) line = input() nums = [int(i) for i in line.split(' ')] res = collections.deque() for i in range(n - 2): for j in range(n - 3, i-1, -1): if nums[j + 2] < nums[j + 1] and nums[j + 2] < nums[j]: a, b, c = nums[j + 2], nums[j + 1], nums[j] nums[j], nums[j + 1], nums[j + 2] = a, c, b res.append(j + 1) if nums[i] > nums[i + 1]: a, b, c = nums[i], nums[i + 1], nums[i + 2] nums[i], nums[i + 1], nums[i + 2] = b, c, a res.append(i + 1) res.append(i + 1) if n == 3 and nums[i] == nums[i+2]: if nums[i + 1] > nums[i]: res.append(1) else: res.append(1) res.append(1) nums.sort() # print(nums) if nums[-1] < nums[-2]: i = n - 2 while i >= 0 and nums[i] != nums[i + 1]: i -= 1 if i < 0: print(-1) else: while i < n - 2: res.append(i + 1) res.append(i + 1) i += 1 print(len(res)) for i in res: print(i, end= ' ') print() else: print(len(res)) for i in res: print(i, end= ' ') print() ```
instruction
0
29,301
12
58,602
No
output
1
29,301
12
58,603
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a consisting of n integers. In one move, you can choose some index i (1 ≤ i ≤ n - 2) and shift the segment [a_i, a_{i + 1}, a_{i + 2}] cyclically to the right (i.e. replace the segment [a_i, a_{i + 1}, a_{i + 2}] with [a_{i + 2}, a_i, a_{i + 1}]). Your task is to sort the initial array by no more than n^2 such operations or say that it is impossible to do that. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (3 ≤ n ≤ 500) — the length of a. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 500), where a_i is the i-th element a. It is guaranteed that the sum of n does not exceed 500. Output For each test case, print the answer: -1 on the only line if it is impossible to sort the given array using operations described in the problem statement, or the number of operations ans on the first line and ans integers idx_1, idx_2, ..., idx_{ans} (1 ≤ idx_i ≤ n - 2), where idx_i is the index of left border of the segment for the i-th operation. You should print indices in order of performing operations. Example Input 5 5 1 2 3 4 5 5 5 4 3 2 1 8 8 4 5 2 3 6 7 3 7 5 2 1 6 4 7 3 6 1 2 3 3 6 4 Output 0 6 3 1 3 2 2 3 13 2 1 1 6 4 2 4 3 3 4 4 6 6 -1 4 3 3 4 4 Submitted Solution: ``` import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) def input(): return sys.stdin.readline().rstrip("\r\n") import traceback for T in range(int(input())): n = int(input()) d = {} li = [int(i)<<1 for i in input().split(' ')] print(len(li)) sol = False tar = -1 invs = 0 for i in li: if i in d: sol = True tar = i d[i] = 1+d.get(i,0) for k,v in d.items(): if k > i: invs += v if invs&1 and sol == False: print(-1) continue if invs == 0: print(0) print() continue ansQ = [] ans = 0 c = False if sol and invs&1: for i in range(len(li)): if li[-i-1] == tar: if c: li[-i-1]+=1 break else: c=True il = sorted(li) try: for p,i in enumerate(il): if il[p]!=li[p]: pos = li.index(i,p) try: while pos != p: if pos - p >1: li[pos],li[pos-1],li[pos-2] = li[pos-1],li[pos-2],li[pos] ansQ.append(pos-2+1) ans += 1 pos -= 2 else: li[pos-1],li[pos],li[pos+1] = li[pos],li[pos+1],li[pos-1] ans += 2 ansQ.append(pos-1+1) ansQ.append(pos-1+1) pos -= 1 except: print(*li[-20:]) print(*il[-20:]) print(tar) print(sol) #print(traceback.format_exc()) except: print(traceback.format_exc()) if ans<= n**2: print(ans) print(*ansQ) else: print(-1) ```
instruction
0
29,302
12
58,604
No
output
1
29,302
12
58,605
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a_1, a_2, ... , a_n consisting of integers from 0 to 9. A subarray a_l, a_{l+1}, a_{l+2}, ... , a_{r-1}, a_r is good if the sum of elements of this subarray is equal to the length of this subarray (∑_{i=l}^{r} a_i = r - l + 1). For example, if a = [1, 2, 0], then there are 3 good subarrays: a_{1 ... 1} = [1], a_{2 ... 3} = [2, 0] and a_{1 ... 3} = [1, 2, 0]. Calculate the number of good subarrays of the array a. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains one integer n (1 ≤ n ≤ 10^5) — the length of the array a. The second line of each test case contains a string consisting of n decimal digits, where the i-th digit is equal to the value of a_i. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case print one integer — the number of good subarrays of the array a. Example Input 3 3 120 5 11011 6 600005 Output 3 6 1 Note The first test case is considered in the statement. In the second test case, there are 6 good subarrays: a_{1 ... 1}, a_{2 ... 2}, a_{1 ... 2}, a_{4 ... 4}, a_{5 ... 5} and a_{4 ... 5}. In the third test case there is only one good subarray: a_{2 ... 6}.
instruction
0
29,303
12
58,606
Tags: data structures, dp, math Correct Solution: ``` for _ in range(int(input())): n = int(input()) a = input() prefix_sum = [0] for i in a: prefix_sum.append(prefix_sum[-1]+int(i)) for i in range(n+1): prefix_sum[i] = prefix_sum[i]-i count = {} for i in prefix_sum: count[i] = count.get(i, 0)+1 sum = 0 for i in count: sum+=(count[i]*(count[i]-1))//2 print(sum) ```
output
1
29,303
12
58,607
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a_1, a_2, ... , a_n consisting of integers from 0 to 9. A subarray a_l, a_{l+1}, a_{l+2}, ... , a_{r-1}, a_r is good if the sum of elements of this subarray is equal to the length of this subarray (∑_{i=l}^{r} a_i = r - l + 1). For example, if a = [1, 2, 0], then there are 3 good subarrays: a_{1 ... 1} = [1], a_{2 ... 3} = [2, 0] and a_{1 ... 3} = [1, 2, 0]. Calculate the number of good subarrays of the array a. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains one integer n (1 ≤ n ≤ 10^5) — the length of the array a. The second line of each test case contains a string consisting of n decimal digits, where the i-th digit is equal to the value of a_i. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case print one integer — the number of good subarrays of the array a. Example Input 3 3 120 5 11011 6 600005 Output 3 6 1 Note The first test case is considered in the statement. In the second test case, there are 6 good subarrays: a_{1 ... 1}, a_{2 ... 2}, a_{1 ... 2}, a_{4 ... 4}, a_{5 ... 5} and a_{4 ... 5}. In the third test case there is only one good subarray: a_{2 ... 6}.
instruction
0
29,304
12
58,608
Tags: data structures, dp, math Correct Solution: ``` t = int(input()) for _ in range(t): n = int(input()) a = [int(i) for i in list(input())] s = 0 dp = [0]*(9*n) cnt = 0 dp[0] = 1 for i in range(n): s += a[i] cnt += dp[s-i-1] dp[s-i-1]+=1 print(cnt) ```
output
1
29,304
12
58,609
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a_1, a_2, ... , a_n consisting of integers from 0 to 9. A subarray a_l, a_{l+1}, a_{l+2}, ... , a_{r-1}, a_r is good if the sum of elements of this subarray is equal to the length of this subarray (∑_{i=l}^{r} a_i = r - l + 1). For example, if a = [1, 2, 0], then there are 3 good subarrays: a_{1 ... 1} = [1], a_{2 ... 3} = [2, 0] and a_{1 ... 3} = [1, 2, 0]. Calculate the number of good subarrays of the array a. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains one integer n (1 ≤ n ≤ 10^5) — the length of the array a. The second line of each test case contains a string consisting of n decimal digits, where the i-th digit is equal to the value of a_i. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case print one integer — the number of good subarrays of the array a. Example Input 3 3 120 5 11011 6 600005 Output 3 6 1 Note The first test case is considered in the statement. In the second test case, there are 6 good subarrays: a_{1 ... 1}, a_{2 ... 2}, a_{1 ... 2}, a_{4 ... 4}, a_{5 ... 5} and a_{4 ... 5}. In the third test case there is only one good subarray: a_{2 ... 6}.
instruction
0
29,305
12
58,610
Tags: data structures, dp, math Correct Solution: ``` t = int(input()) for i in range(t): n = input() s = input() dp = { 0: 1 } prv = 0 for i in range(0,len(s)): y = prv + int(s[i]) x = i + 1 c = y - x if c in dp: dp[c] += 1 else : dp[c] = 1 prv = y ans = 0 for val in dp.values(): ans += int((val * (val-1))/2) print(ans) ```
output
1
29,305
12
58,611
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a_1, a_2, ... , a_n consisting of integers from 0 to 9. A subarray a_l, a_{l+1}, a_{l+2}, ... , a_{r-1}, a_r is good if the sum of elements of this subarray is equal to the length of this subarray (∑_{i=l}^{r} a_i = r - l + 1). For example, if a = [1, 2, 0], then there are 3 good subarrays: a_{1 ... 1} = [1], a_{2 ... 3} = [2, 0] and a_{1 ... 3} = [1, 2, 0]. Calculate the number of good subarrays of the array a. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains one integer n (1 ≤ n ≤ 10^5) — the length of the array a. The second line of each test case contains a string consisting of n decimal digits, where the i-th digit is equal to the value of a_i. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case print one integer — the number of good subarrays of the array a. Example Input 3 3 120 5 11011 6 600005 Output 3 6 1 Note The first test case is considered in the statement. In the second test case, there are 6 good subarrays: a_{1 ... 1}, a_{2 ... 2}, a_{1 ... 2}, a_{4 ... 4}, a_{5 ... 5} and a_{4 ... 5}. In the third test case there is only one good subarray: a_{2 ... 6}.
instruction
0
29,306
12
58,612
Tags: data structures, dp, math Correct Solution: ``` tests = int(input()) for t in range(tests): b= int(input()) ls = [int(x) for x in input()] res = 0 p_dict = {0:1} p_sum = 0 for item in ls: item -= 1 p_sum += item if p_sum in p_dict: res += p_dict[p_sum] p_dict[p_sum] += 1 else: p_dict[p_sum] = 1 print(res) ```
output
1
29,306
12
58,613
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a_1, a_2, ... , a_n consisting of integers from 0 to 9. A subarray a_l, a_{l+1}, a_{l+2}, ... , a_{r-1}, a_r is good if the sum of elements of this subarray is equal to the length of this subarray (∑_{i=l}^{r} a_i = r - l + 1). For example, if a = [1, 2, 0], then there are 3 good subarrays: a_{1 ... 1} = [1], a_{2 ... 3} = [2, 0] and a_{1 ... 3} = [1, 2, 0]. Calculate the number of good subarrays of the array a. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains one integer n (1 ≤ n ≤ 10^5) — the length of the array a. The second line of each test case contains a string consisting of n decimal digits, where the i-th digit is equal to the value of a_i. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case print one integer — the number of good subarrays of the array a. Example Input 3 3 120 5 11011 6 600005 Output 3 6 1 Note The first test case is considered in the statement. In the second test case, there are 6 good subarrays: a_{1 ... 1}, a_{2 ... 2}, a_{1 ... 2}, a_{4 ... 4}, a_{5 ... 5} and a_{4 ... 5}. In the third test case there is only one good subarray: a_{2 ... 6}.
instruction
0
29,307
12
58,614
Tags: data structures, dp, math Correct Solution: ``` t = int(input()) for ii in range(t): n = int(input()) s = list(input()) count = 0 for i in range(n): s[i] = int(s[i])-1 m = {} sm = 0 count = 0 for i in range(n): sm += s[i] diff = sm if sm == 0: count+=1 if diff in m: count+=m[diff] if sm in m: m[sm] += 1 else: m[sm] = 1 # print(s, sm, m, count) print(count) ```
output
1
29,307
12
58,615
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a_1, a_2, ... , a_n consisting of integers from 0 to 9. A subarray a_l, a_{l+1}, a_{l+2}, ... , a_{r-1}, a_r is good if the sum of elements of this subarray is equal to the length of this subarray (∑_{i=l}^{r} a_i = r - l + 1). For example, if a = [1, 2, 0], then there are 3 good subarrays: a_{1 ... 1} = [1], a_{2 ... 3} = [2, 0] and a_{1 ... 3} = [1, 2, 0]. Calculate the number of good subarrays of the array a. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains one integer n (1 ≤ n ≤ 10^5) — the length of the array a. The second line of each test case contains a string consisting of n decimal digits, where the i-th digit is equal to the value of a_i. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case print one integer — the number of good subarrays of the array a. Example Input 3 3 120 5 11011 6 600005 Output 3 6 1 Note The first test case is considered in the statement. In the second test case, there are 6 good subarrays: a_{1 ... 1}, a_{2 ... 2}, a_{1 ... 2}, a_{4 ... 4}, a_{5 ... 5} and a_{4 ... 5}. In the third test case there is only one good subarray: a_{2 ... 6}.
instruction
0
29,308
12
58,616
Tags: data structures, dp, math Correct Solution: ``` t = int(input()) for _ in range(0,t) : n = int(input()) v = input() prefix = [0 for i in range(0,n+1)] for i in range(0,n): prefix[i+1] = (int(v[i]) - int('0')) + prefix[i] d = {1 : 1}; ans = 0 for i in range(0,n): if prefix[i+1] - i in d.keys(): ans += d[prefix[i+1] - i] if prefix[i+1] - i in d.keys() : d[prefix[i+1] - i] += 1 else : d[prefix[i+1] - i] = 1 print(ans) ```
output
1
29,308
12
58,617
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a_1, a_2, ... , a_n consisting of integers from 0 to 9. A subarray a_l, a_{l+1}, a_{l+2}, ... , a_{r-1}, a_r is good if the sum of elements of this subarray is equal to the length of this subarray (∑_{i=l}^{r} a_i = r - l + 1). For example, if a = [1, 2, 0], then there are 3 good subarrays: a_{1 ... 1} = [1], a_{2 ... 3} = [2, 0] and a_{1 ... 3} = [1, 2, 0]. Calculate the number of good subarrays of the array a. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains one integer n (1 ≤ n ≤ 10^5) — the length of the array a. The second line of each test case contains a string consisting of n decimal digits, where the i-th digit is equal to the value of a_i. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case print one integer — the number of good subarrays of the array a. Example Input 3 3 120 5 11011 6 600005 Output 3 6 1 Note The first test case is considered in the statement. In the second test case, there are 6 good subarrays: a_{1 ... 1}, a_{2 ... 2}, a_{1 ... 2}, a_{4 ... 4}, a_{5 ... 5} and a_{4 ... 5}. In the third test case there is only one good subarray: a_{2 ... 6}.
instruction
0
29,309
12
58,618
Tags: data structures, dp, math Correct Solution: ``` from itertools import accumulate from collections import defaultdict t = int(input()) for _ in range(t): jisho = defaultdict(int) n = int(input()) A = list(map(int, list(input()))) cumsumA = list(accumulate([0] + A)) for i in range(n + 1): temp = cumsumA[i] - i jisho[temp] += 1 ans = 0 for key, val in jisho.items(): ans += val * (val - 1) // 2 print(ans) ```
output
1
29,309
12
58,619
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a_1, a_2, ... , a_n consisting of integers from 0 to 9. A subarray a_l, a_{l+1}, a_{l+2}, ... , a_{r-1}, a_r is good if the sum of elements of this subarray is equal to the length of this subarray (∑_{i=l}^{r} a_i = r - l + 1). For example, if a = [1, 2, 0], then there are 3 good subarrays: a_{1 ... 1} = [1], a_{2 ... 3} = [2, 0] and a_{1 ... 3} = [1, 2, 0]. Calculate the number of good subarrays of the array a. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains one integer n (1 ≤ n ≤ 10^5) — the length of the array a. The second line of each test case contains a string consisting of n decimal digits, where the i-th digit is equal to the value of a_i. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case print one integer — the number of good subarrays of the array a. Example Input 3 3 120 5 11011 6 600005 Output 3 6 1 Note The first test case is considered in the statement. In the second test case, there are 6 good subarrays: a_{1 ... 1}, a_{2 ... 2}, a_{1 ... 2}, a_{4 ... 4}, a_{5 ... 5} and a_{4 ... 5}. In the third test case there is only one good subarray: a_{2 ... 6}.
instruction
0
29,310
12
58,620
Tags: data structures, dp, math Correct Solution: ``` for i in range(int(input())): n=int(input()) s=input() l=[int(i) for i in s] cum= [l[0]] for i in range(1,n): cum.append(cum[-1]+l[i]) d={1:1} for i in range(n): if d.get(cum[i]-i): d[cum[i]-i]+=1 else: d[cum[i]-i]=1 ct=0 for i in d: ct+=d[i]*(d[i]-1)//2 print(ct) ```
output
1
29,310
12
58,621
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a_1, a_2, ... , a_n consisting of integers from 0 to 9. A subarray a_l, a_{l+1}, a_{l+2}, ... , a_{r-1}, a_r is good if the sum of elements of this subarray is equal to the length of this subarray (∑_{i=l}^{r} a_i = r - l + 1). For example, if a = [1, 2, 0], then there are 3 good subarrays: a_{1 ... 1} = [1], a_{2 ... 3} = [2, 0] and a_{1 ... 3} = [1, 2, 0]. Calculate the number of good subarrays of the array a. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains one integer n (1 ≤ n ≤ 10^5) — the length of the array a. The second line of each test case contains a string consisting of n decimal digits, where the i-th digit is equal to the value of a_i. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case print one integer — the number of good subarrays of the array a. Example Input 3 3 120 5 11011 6 600005 Output 3 6 1 Note The first test case is considered in the statement. In the second test case, there are 6 good subarrays: a_{1 ... 1}, a_{2 ... 2}, a_{1 ... 2}, a_{4 ... 4}, a_{5 ... 5} and a_{4 ... 5}. In the third test case there is only one good subarray: a_{2 ... 6}. Submitted Solution: ``` import sys input = sys.stdin.readline t = int(input()) for _ in range(t): y = int(input()) x = input().rstrip() arr = [0] total = 0 for char in x: total += int(char) - 1 arr.append(total) seen = {} segm = [] J = {} for i in range(len(arr)): if arr[i] not in seen: seen[arr[i]] = i else: x = seen[arr[i]] segm.append((x,i)) J[x] = i seen[arr[i]] = i bonus = [] #print(J) V = set([]) for seg in segm: c = 1 x = seg[1] if x not in V: V.add(x) while x in J: c+=1 x = J[x] V.add(x) bonus.append((c*(c+1))//2) print(sum(bonus)) ```
instruction
0
29,311
12
58,622
Yes
output
1
29,311
12
58,623
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a_1, a_2, ... , a_n consisting of integers from 0 to 9. A subarray a_l, a_{l+1}, a_{l+2}, ... , a_{r-1}, a_r is good if the sum of elements of this subarray is equal to the length of this subarray (∑_{i=l}^{r} a_i = r - l + 1). For example, if a = [1, 2, 0], then there are 3 good subarrays: a_{1 ... 1} = [1], a_{2 ... 3} = [2, 0] and a_{1 ... 3} = [1, 2, 0]. Calculate the number of good subarrays of the array a. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains one integer n (1 ≤ n ≤ 10^5) — the length of the array a. The second line of each test case contains a string consisting of n decimal digits, where the i-th digit is equal to the value of a_i. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case print one integer — the number of good subarrays of the array a. Example Input 3 3 120 5 11011 6 600005 Output 3 6 1 Note The first test case is considered in the statement. In the second test case, there are 6 good subarrays: a_{1 ... 1}, a_{2 ... 2}, a_{1 ... 2}, a_{4 ... 4}, a_{5 ... 5} and a_{4 ... 5}. In the third test case there is only one good subarray: a_{2 ... 6}. Submitted Solution: ``` import math from decimal import * import random try: for _ in range(int(input())): d = {0:1} n = int(input()) arr = list(input()) ans,s = 0,0 for i in range(n): s+=int(arr[i]) tmp = s-i-1 if(tmp not in d): d[tmp] =0 d[tmp]+=1 ans+=d[tmp]-1 print(ans) except EOFError as e: pass ```
instruction
0
29,312
12
58,624
Yes
output
1
29,312
12
58,625
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a_1, a_2, ... , a_n consisting of integers from 0 to 9. A subarray a_l, a_{l+1}, a_{l+2}, ... , a_{r-1}, a_r is good if the sum of elements of this subarray is equal to the length of this subarray (∑_{i=l}^{r} a_i = r - l + 1). For example, if a = [1, 2, 0], then there are 3 good subarrays: a_{1 ... 1} = [1], a_{2 ... 3} = [2, 0] and a_{1 ... 3} = [1, 2, 0]. Calculate the number of good subarrays of the array a. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains one integer n (1 ≤ n ≤ 10^5) — the length of the array a. The second line of each test case contains a string consisting of n decimal digits, where the i-th digit is equal to the value of a_i. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case print one integer — the number of good subarrays of the array a. Example Input 3 3 120 5 11011 6 600005 Output 3 6 1 Note The first test case is considered in the statement. In the second test case, there are 6 good subarrays: a_{1 ... 1}, a_{2 ... 2}, a_{1 ... 2}, a_{4 ... 4}, a_{5 ... 5} and a_{4 ... 5}. In the third test case there is only one good subarray: a_{2 ... 6}. Submitted Solution: ``` from sys import stdin,stdout for _ in range(int(stdin.readline())): n=int(stdin.readline()) # a=list(map(int,stdin.readline().split())) a=[int(ch)-1 for ch in input()] s=ans=0;d={0:1} for v in a: s+=v ans+=d.get(s,0) d[s]=d.get(s,0)+1 print(ans) ```
instruction
0
29,313
12
58,626
Yes
output
1
29,313
12
58,627
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a_1, a_2, ... , a_n consisting of integers from 0 to 9. A subarray a_l, a_{l+1}, a_{l+2}, ... , a_{r-1}, a_r is good if the sum of elements of this subarray is equal to the length of this subarray (∑_{i=l}^{r} a_i = r - l + 1). For example, if a = [1, 2, 0], then there are 3 good subarrays: a_{1 ... 1} = [1], a_{2 ... 3} = [2, 0] and a_{1 ... 3} = [1, 2, 0]. Calculate the number of good subarrays of the array a. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains one integer n (1 ≤ n ≤ 10^5) — the length of the array a. The second line of each test case contains a string consisting of n decimal digits, where the i-th digit is equal to the value of a_i. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case print one integer — the number of good subarrays of the array a. Example Input 3 3 120 5 11011 6 600005 Output 3 6 1 Note The first test case is considered in the statement. In the second test case, there are 6 good subarrays: a_{1 ... 1}, a_{2 ... 2}, a_{1 ... 2}, a_{4 ... 4}, a_{5 ... 5} and a_{4 ... 5}. In the third test case there is only one good subarray: a_{2 ... 6}. Submitted Solution: ``` def choose(n): if n<2: return 0 return(n*(n-1))//2 t=int(input()) for _ in range(t): n=int(input()) arr=list(input()) cs=[0]*(n+1) cs[0]=0 for i in range(1,n+1): cs[i]=-1+cs[i-1]+int(arr[i-1]) cs.sort() seen=[] seen2=[] ans=0 #print(cs) cur=cs[0] val=0 for i in range(1,len(cs)): if cur==cs[i]: val+=1 else: ans+=choose(val+1) val=0 cur=cs[i] ans+=choose(val+1) print(ans) ```
instruction
0
29,314
12
58,628
Yes
output
1
29,314
12
58,629
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a_1, a_2, ... , a_n consisting of integers from 0 to 9. A subarray a_l, a_{l+1}, a_{l+2}, ... , a_{r-1}, a_r is good if the sum of elements of this subarray is equal to the length of this subarray (∑_{i=l}^{r} a_i = r - l + 1). For example, if a = [1, 2, 0], then there are 3 good subarrays: a_{1 ... 1} = [1], a_{2 ... 3} = [2, 0] and a_{1 ... 3} = [1, 2, 0]. Calculate the number of good subarrays of the array a. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains one integer n (1 ≤ n ≤ 10^5) — the length of the array a. The second line of each test case contains a string consisting of n decimal digits, where the i-th digit is equal to the value of a_i. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case print one integer — the number of good subarrays of the array a. Example Input 3 3 120 5 11011 6 600005 Output 3 6 1 Note The first test case is considered in the statement. In the second test case, there are 6 good subarrays: a_{1 ... 1}, a_{2 ... 2}, a_{1 ... 2}, a_{4 ... 4}, a_{5 ... 5} and a_{4 ... 5}. In the third test case there is only one good subarray: a_{2 ... 6}. Submitted Solution: ``` def solve(): n = int(input()) a = input() s = [0]*(n+1) for i in range(n): s[i+1] = s[i] + int(a[i]) ans = 0 for i in range(1, n+1): for j in range(1, min(10, i+1)): if j == s[i]-s[i-j]: ans += 1 print(ans) for t in range(int(input())): solve() ```
instruction
0
29,315
12
58,630
No
output
1
29,315
12
58,631
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a_1, a_2, ... , a_n consisting of integers from 0 to 9. A subarray a_l, a_{l+1}, a_{l+2}, ... , a_{r-1}, a_r is good if the sum of elements of this subarray is equal to the length of this subarray (∑_{i=l}^{r} a_i = r - l + 1). For example, if a = [1, 2, 0], then there are 3 good subarrays: a_{1 ... 1} = [1], a_{2 ... 3} = [2, 0] and a_{1 ... 3} = [1, 2, 0]. Calculate the number of good subarrays of the array a. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains one integer n (1 ≤ n ≤ 10^5) — the length of the array a. The second line of each test case contains a string consisting of n decimal digits, where the i-th digit is equal to the value of a_i. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case print one integer — the number of good subarrays of the array a. Example Input 3 3 120 5 11011 6 600005 Output 3 6 1 Note The first test case is considered in the statement. In the second test case, there are 6 good subarrays: a_{1 ... 1}, a_{2 ... 2}, a_{1 ... 2}, a_{4 ... 4}, a_{5 ... 5} and a_{4 ... 5}. In the third test case there is only one good subarray: a_{2 ... 6}. Submitted Solution: ``` import sys input = sys.stdin.readline ins = lambda: input().rstrip() ini = lambda: int(input().rstrip()) inm = lambda: map(int, input().split()) inl = lambda: list(map(int, input().split())) ans = [] t = ini() for _ in range(t): n = ini() s = ins() tmp = 0 sum = 0 count = [0] * 10**5 count[0] = 1 for i in s: sum += int(i) - 1 tmp += count[sum] count[sum] += 1 ans.append(tmp) print('\n'.join(map(str, ans))) ```
instruction
0
29,316
12
58,632
No
output
1
29,316
12
58,633
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a_1, a_2, ... , a_n consisting of integers from 0 to 9. A subarray a_l, a_{l+1}, a_{l+2}, ... , a_{r-1}, a_r is good if the sum of elements of this subarray is equal to the length of this subarray (∑_{i=l}^{r} a_i = r - l + 1). For example, if a = [1, 2, 0], then there are 3 good subarrays: a_{1 ... 1} = [1], a_{2 ... 3} = [2, 0] and a_{1 ... 3} = [1, 2, 0]. Calculate the number of good subarrays of the array a. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains one integer n (1 ≤ n ≤ 10^5) — the length of the array a. The second line of each test case contains a string consisting of n decimal digits, where the i-th digit is equal to the value of a_i. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case print one integer — the number of good subarrays of the array a. Example Input 3 3 120 5 11011 6 600005 Output 3 6 1 Note The first test case is considered in the statement. In the second test case, there are 6 good subarrays: a_{1 ... 1}, a_{2 ... 2}, a_{1 ... 2}, a_{4 ... 4}, a_{5 ... 5} and a_{4 ... 5}. In the third test case there is only one good subarray: a_{2 ... 6}. Submitted Solution: ``` #############<------------ Xorcestor_X ---------------->############ from math import * def is_even(p): n=len(p) count=0 for i in range(n): index=p.index(i,i,n) if i==index: pass else: count+=1 temp=p[i] p[i]=p[index] p[index]=temp # print(p) if count%2==0: return True else: return False prime=[] def SieveOfEratosthenes(): global prime prime=[1]*2000010 prime[1]=0 p=2 while p*p<=2000001: if prime[p]: for i in range(p*p,2000002,p): prime[i]=0 lpf=[] def precompute(): global lpf lpf=[0]*1000001 for i in range(2,1000001): if not lpf[i]: for j in range(i,1000001,i): if not lpf[j]: lpf[j]=i def binpow(a,b): res=1 while b>0: if b&1: res*=a a*=a b>>=1 return res def modpow(a,b,x): res=1 while b>0: if b&1: res*=a res%=x a*=a a%=x b>>=1 return res cont=[] def f(x): global cont total=0 for i in cont: total+=abs(i-x) return total def bs(uv,low,high,target): while low+3<high: mid=(low+high)/2 if uv[mid]<target: low=mid else: high=mid-1 for i in range(high,low-1,-1): if uv[i]<target: return i return -1 def ternary_search(l,r): while r-l>10: m1=l+(r-l)/3 m2=r-(r-l)/3 f1=f(m1) f2=f(m2) if f1>f2: l=m1 else: r=m2 mino=f(l) for i in range(l,r+1): mino=min(mino,f(i)) return mino for _ in range(int(input())): n=int(input()) s=input() if n==1: if s[0]=='1': print(1) else: print(0) else: dic={} dic[0]={} dic[0][int(s[0])-1]=1 ans=dic[0].get(0,0) for i in range(1,n): dic[i]={} diff=int(s[i])-1 for a in dic[i-1]: dic[i][a+diff]=dic[i-1][a] dic[i][diff]=dic[i].get(diff,0)+1 ans+=dic[i].get(0,0) # print(dic) print(ans) ```
instruction
0
29,317
12
58,634
No
output
1
29,317
12
58,635
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a_1, a_2, ... , a_n consisting of integers from 0 to 9. A subarray a_l, a_{l+1}, a_{l+2}, ... , a_{r-1}, a_r is good if the sum of elements of this subarray is equal to the length of this subarray (∑_{i=l}^{r} a_i = r - l + 1). For example, if a = [1, 2, 0], then there are 3 good subarrays: a_{1 ... 1} = [1], a_{2 ... 3} = [2, 0] and a_{1 ... 3} = [1, 2, 0]. Calculate the number of good subarrays of the array a. Input The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains one integer n (1 ≤ n ≤ 10^5) — the length of the array a. The second line of each test case contains a string consisting of n decimal digits, where the i-th digit is equal to the value of a_i. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case print one integer — the number of good subarrays of the array a. Example Input 3 3 120 5 11011 6 600005 Output 3 6 1 Note The first test case is considered in the statement. In the second test case, there are 6 good subarrays: a_{1 ... 1}, a_{2 ... 2}, a_{1 ... 2}, a_{4 ... 4}, a_{5 ... 5} and a_{4 ... 5}. In the third test case there is only one good subarray: a_{2 ... 6}. Submitted Solution: ``` # ---------------------------iye ha aam zindegi--------------------------------------------- import math import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys mod = 10 ** 9 + 7 mod1 = 998244353 #setrecursionlimit(300000) # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 sys.setrecursionlimit(300000) class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # -------------------game starts now----------------------------------------------------import math class SegmentTree: def __init__(self, data, default=0, func=lambda a, b: a + b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------------------iye ha chutiya zindegi------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD # --------------------------------------iye ha combinations ka zindegi--------------------------------- def powm(a, n, m): if a == 1 or n == 0: return 1 if n % 2 == 0: s = powm(a, n // 2, m) return s * s % m else: return a * powm(a, n - 1, m) % m # --------------------------------------iye ha power ka zindegi--------------------------------- def sort_list(list1, list2): zipped_pairs = zip(list2, list1) z = [x for _, x in sorted(zipped_pairs)] return z # --------------------------------------------------product---------------------------------------- def product(l): por = 1 for i in range(len(l)): por *= l[i] return por # --------------------------------------------------binary---------------------------------------- def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left) / 2) # Check if middle element is # less than or equal to key if (arr[mid] < key): count = mid + 1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # --------------------------------------------------binary---------------------------------------- def countdig(n): c = 0 while (n > 0): n //= 10 c += 1 return c def binary(x, length): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y def countGreater(arr, n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) if (arr[m] >= k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) # --------------------------------------------------binary------------------------------------ class BinaryTrie: class Node: def __init__(self, bit: bool = False): self.bit = bit # Stores the current bit (False if 0, True if 1) self.children = [] self.count = 0 # stores number of keys finishing at this bit self.counter = 1 # stores number of keys with this bit as prefix def __init__(self, size): self.root = BinaryTrie.Node() self.size = size # Maximum size of each key def convert(self, key): """Converts key from string/integer to a list of boolean values!""" bits = [] if isinstance(key, int): key = bin(key)[2:] if isinstance(key, str): for i in range(self.size - len(key)): bits += [False] for i in key: if i == "0": bits += [False] else: bits += [True] else: return list(key) return bits def add(self, key): """Add a key to the trie!""" node = self.root bits = self.convert(key) for bit in bits: found_in_child = False for child in node.children: if child.bit == bit: child.counter += 1 node = child found_in_child = True break if not found_in_child: new_node = BinaryTrie.Node(bit) node.children.append(new_node) node = new_node node.count += 1 def remove(self, key): """Removes a key from the trie! If there are multiple occurences, it removes only one of them.""" node = self.root bits = self.convert(key) nodelist = [node] for bit in bits: for child in node.children: if child.bit == bit: node = child node.counter -= 1 nodelist.append(node) break node.count -= 1 if not node.children and not node.count: for i in range(len(nodelist) - 2, -1, -1): nodelist[i].children.remove(nodelist[i + 1]) if nodelist[i].children or nodelist[i].count: break def query(self, prefix, root=None): """Search for a prefix in the trie! Returns the node if found, otherwise 0.""" if not root: root = self.root node = root if not root.children: return 0 for bit in prefix: bit_not_found = True for child in node.children: if child.bit == bit: bit_not_found = False node = child break if bit_not_found: return 0 return node #--------------------------------------------trie------------------------------------------------- class TrieNode: # Trie node class def __init__(self): self.children = [None] * 26 self.data=0 self.isEndOfWord = False class Trie: # Trie data structure class def __init__(self): self.root = self.getNode() def getNode(self): # Returns new trie node (initialized to NULLs) return TrieNode() def _charToIndex(self, ch): # private helper function # Converts key current character into index # use only 'a' through 'z' and lower case return ord(ch) - ord('a') def insert(self, key,val): pCrawl = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) # if current character is not present if not pCrawl.children[index]: pCrawl.children[index] = self.getNode() pCrawl = pCrawl.children[index] pCrawl.data+=val pCrawl.isEndOfWord = True def search(self, key): # Search key in the trie # Returns true if key presents # in trie, else false pCrawl = self.root length = len(key) c=0 for level in range(length): index = self._charToIndex(key[level]) if not pCrawl.children[index]: return False pCrawl = pCrawl.children[index] return pCrawl!=None def present(self, key): ans=0 pCrawl = self.root length = len(key) c=0 for level in range(length): index = self._charToIndex(key[level]) if not pCrawl.children[index]: return False pCrawl = pCrawl.children[index] ans+=pCrawl.data if pCrawl!=None: return ans return -1 #----------------------------------trie---------------------------- for ik in range(int(input())): n=int(input()) l=list(input()) l=[int(l[i]) for i in range(n)] dp=[0 for i in range(n)] last=defaultdict(int) if l[0]==1: dp[0]=1 tot=1-l[0] last[tot]=1 for i in range(1,n): #print(last) c=1-l[i] tot+=1-l[i] #print(last[tot]) if last[tot]!=0: dp[i]+=dp[last[tot]-1]+1 if c==0 and last[tot]!=i: dp[i]+=1 if tot==0 and last[tot]==0: dp[i]+=1 last[c]=i+1 last[tot]=i+1 #print(tot,dp) print(sum(dp)) #print(dp) ```
instruction
0
29,318
12
58,636
No
output
1
29,318
12
58,637
Provide tags and a correct Python 3 solution for this coding contest problem. An array is called beautiful if all the elements in the array are equal. You can transform an array using the following steps any number of times: 1. Choose two indices i and j (1 ≤ i,j ≤ n), and an integer x (1 ≤ x ≤ a_i). Let i be the source index and j be the sink index. 2. Decrease the i-th element by x, and increase the j-th element by x. The resulting values at i-th and j-th index are a_i-x and a_j+x respectively. 3. The cost of this operation is x ⋅ |j-i| . 4. Now the i-th index can no longer be the sink and the j-th index can no longer be the source. The total cost of a transformation is the sum of all the costs in step 3. For example, array [0, 2, 3, 3] can be transformed into a beautiful array [2, 2, 2, 2] with total cost 1 ⋅ |1-3| + 1 ⋅ |1-4| = 5. An array is called balanced, if it can be transformed into a beautiful array, and the cost of such transformation is uniquely defined. In other words, the minimum cost of transformation into a beautiful array equals the maximum cost. You are given an array a_1, a_2, …, a_n of length n, consisting of non-negative integers. Your task is to find the number of balanced arrays which are permutations of the given array. Two arrays are considered different, if elements at some position differ. Since the answer can be large, output it modulo 10^9 + 7. Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the size of the array. The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Output Output a single integer — the number of balanced permutations modulo 10^9+7. Examples Input 3 1 2 3 Output 6 Input 4 0 4 0 4 Output 2 Input 5 0 11 12 13 14 Output 120 Note In the first example, [1, 2, 3] is a valid permutation as we can consider the index with value 3 as the source and index with value 1 as the sink. Thus, after conversion we get a beautiful array [2, 2, 2], and the total cost would be 2. We can show that this is the only transformation of this array that leads to a beautiful array. Similarly, we can check for other permutations too. In the second example, [0, 0, 4, 4] and [4, 4, 0, 0] are balanced permutations. In the third example, all permutations are balanced.
instruction
0
29,365
12
58,730
Tags: combinatorics, constructive algorithms, math, sortings Correct Solution: ``` a=*map(int,[*open(0)][1].split()),;n=len(a);s=sum(a) if s%n:print(0);exit() M=10**9+7;s//=n;f=[1]*(n+1);b=[0]*3;d=dict() for i in range(2,n+1):f[i]=f[i-1]*i%M for x in a: b[(x>s)-(x<s)]+=1 try:d[x]+=1 except:d[x]=1 k=1 for x in d:k*=f[d[x]] k=f[n]*pow(k,M-2,M) print([k%M,f[b[1]]*f[b[-1]]*2*pow(f[n-b[0]],M-2,M)*k%M][b[1]>1and b[-1]>1]) ```
output
1
29,365
12
58,731
Provide tags and a correct Python 3 solution for this coding contest problem. An array is called beautiful if all the elements in the array are equal. You can transform an array using the following steps any number of times: 1. Choose two indices i and j (1 ≤ i,j ≤ n), and an integer x (1 ≤ x ≤ a_i). Let i be the source index and j be the sink index. 2. Decrease the i-th element by x, and increase the j-th element by x. The resulting values at i-th and j-th index are a_i-x and a_j+x respectively. 3. The cost of this operation is x ⋅ |j-i| . 4. Now the i-th index can no longer be the sink and the j-th index can no longer be the source. The total cost of a transformation is the sum of all the costs in step 3. For example, array [0, 2, 3, 3] can be transformed into a beautiful array [2, 2, 2, 2] with total cost 1 ⋅ |1-3| + 1 ⋅ |1-4| = 5. An array is called balanced, if it can be transformed into a beautiful array, and the cost of such transformation is uniquely defined. In other words, the minimum cost of transformation into a beautiful array equals the maximum cost. You are given an array a_1, a_2, …, a_n of length n, consisting of non-negative integers. Your task is to find the number of balanced arrays which are permutations of the given array. Two arrays are considered different, if elements at some position differ. Since the answer can be large, output it modulo 10^9 + 7. Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the size of the array. The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Output Output a single integer — the number of balanced permutations modulo 10^9+7. Examples Input 3 1 2 3 Output 6 Input 4 0 4 0 4 Output 2 Input 5 0 11 12 13 14 Output 120 Note In the first example, [1, 2, 3] is a valid permutation as we can consider the index with value 3 as the source and index with value 1 as the sink. Thus, after conversion we get a beautiful array [2, 2, 2], and the total cost would be 2. We can show that this is the only transformation of this array that leads to a beautiful array. Similarly, we can check for other permutations too. In the second example, [0, 0, 4, 4] and [4, 4, 0, 0] are balanced permutations. In the third example, all permutations are balanced.
instruction
0
29,366
12
58,732
Tags: combinatorics, constructive algorithms, math, sortings Correct Solution: ``` a=*map(int,[*open(0)][1].split()),;n=len(a);s=sum(a) if s%n:exit(print(0)) M=10**9+7;s//=n;f=[1]*(n+1);b=[0]*3;d={};k=1 for i in range(2,n+1):f[i]=f[i-1]*i%M for x in a:b[(x>s)-(x<s)]+=1;d[x]=d[x]+1if x in d else 1 for x in d:k*=f[d[x]] print([1,f[b[1]]*f[b[2]]*2*pow(f[n-b[0]],M-2,M)][b[1]>1and b[2]>1]*f[n]*pow(k,M-2,M)%M) ```
output
1
29,366
12
58,733
Provide tags and a correct Python 3 solution for this coding contest problem. An array is called beautiful if all the elements in the array are equal. You can transform an array using the following steps any number of times: 1. Choose two indices i and j (1 ≤ i,j ≤ n), and an integer x (1 ≤ x ≤ a_i). Let i be the source index and j be the sink index. 2. Decrease the i-th element by x, and increase the j-th element by x. The resulting values at i-th and j-th index are a_i-x and a_j+x respectively. 3. The cost of this operation is x ⋅ |j-i| . 4. Now the i-th index can no longer be the sink and the j-th index can no longer be the source. The total cost of a transformation is the sum of all the costs in step 3. For example, array [0, 2, 3, 3] can be transformed into a beautiful array [2, 2, 2, 2] with total cost 1 ⋅ |1-3| + 1 ⋅ |1-4| = 5. An array is called balanced, if it can be transformed into a beautiful array, and the cost of such transformation is uniquely defined. In other words, the minimum cost of transformation into a beautiful array equals the maximum cost. You are given an array a_1, a_2, …, a_n of length n, consisting of non-negative integers. Your task is to find the number of balanced arrays which are permutations of the given array. Two arrays are considered different, if elements at some position differ. Since the answer can be large, output it modulo 10^9 + 7. Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the size of the array. The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Output Output a single integer — the number of balanced permutations modulo 10^9+7. Examples Input 3 1 2 3 Output 6 Input 4 0 4 0 4 Output 2 Input 5 0 11 12 13 14 Output 120 Note In the first example, [1, 2, 3] is a valid permutation as we can consider the index with value 3 as the source and index with value 1 as the sink. Thus, after conversion we get a beautiful array [2, 2, 2], and the total cost would be 2. We can show that this is the only transformation of this array that leads to a beautiful array. Similarly, we can check for other permutations too. In the second example, [0, 0, 4, 4] and [4, 4, 0, 0] are balanced permutations. In the third example, all permutations are balanced.
instruction
0
29,367
12
58,734
Tags: combinatorics, constructive algorithms, math, sortings Correct Solution: ``` def pow(a, n): if n == 0: return 1 if n % 2 == 0: return pow(a ** 2 % MOD, n // 2) return a * pow(a, n - 1) % MOD def C(n, k): return fact[n] * pow(fact[n - k], MOD - 2) * pow(fact[k], MOD - 2) % MOD MOD = 10 ** 9 + 7 n = int(input()) a = list(map(int, input().split())) fact = [1] * (n + 1) for i in range(2, n + 1): fact[i] = fact[i - 1] * i % MOD s = sum(a) cnt = {} for x in a: if x not in cnt: cnt[x] = 0 cnt[x] += 1 cnt = sorted(cnt.items()) avg = s // n mid = a.count(avg) if avg * n != s: print(0) elif mid == n: print(1) else: small = sum(map(lambda x: 1 if x < avg else 0, a)) big = n - small - mid if small == 1 and big > 1: ans = (big + small) * fact[big] elif big == 1 and small > 1: ans = (big + small) * fact[small] else: ans = 2 * fact[small] * fact[big] for x, count in cnt: if x != avg: ans = ans * pow(fact[count], MOD - 2) % MOD ans = ans * C(n, mid) % MOD print(ans) ```
output
1
29,367
12
58,735
Provide tags and a correct Python 3 solution for this coding contest problem. An array is called beautiful if all the elements in the array are equal. You can transform an array using the following steps any number of times: 1. Choose two indices i and j (1 ≤ i,j ≤ n), and an integer x (1 ≤ x ≤ a_i). Let i be the source index and j be the sink index. 2. Decrease the i-th element by x, and increase the j-th element by x. The resulting values at i-th and j-th index are a_i-x and a_j+x respectively. 3. The cost of this operation is x ⋅ |j-i| . 4. Now the i-th index can no longer be the sink and the j-th index can no longer be the source. The total cost of a transformation is the sum of all the costs in step 3. For example, array [0, 2, 3, 3] can be transformed into a beautiful array [2, 2, 2, 2] with total cost 1 ⋅ |1-3| + 1 ⋅ |1-4| = 5. An array is called balanced, if it can be transformed into a beautiful array, and the cost of such transformation is uniquely defined. In other words, the minimum cost of transformation into a beautiful array equals the maximum cost. You are given an array a_1, a_2, …, a_n of length n, consisting of non-negative integers. Your task is to find the number of balanced arrays which are permutations of the given array. Two arrays are considered different, if elements at some position differ. Since the answer can be large, output it modulo 10^9 + 7. Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the size of the array. The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Output Output a single integer — the number of balanced permutations modulo 10^9+7. Examples Input 3 1 2 3 Output 6 Input 4 0 4 0 4 Output 2 Input 5 0 11 12 13 14 Output 120 Note In the first example, [1, 2, 3] is a valid permutation as we can consider the index with value 3 as the source and index with value 1 as the sink. Thus, after conversion we get a beautiful array [2, 2, 2], and the total cost would be 2. We can show that this is the only transformation of this array that leads to a beautiful array. Similarly, we can check for other permutations too. In the second example, [0, 0, 4, 4] and [4, 4, 0, 0] are balanced permutations. In the third example, all permutations are balanced.
instruction
0
29,368
12
58,736
Tags: combinatorics, constructive algorithms, math, sortings Correct Solution: ``` import sys sys.setrecursionlimit(10**5) int1 = lambda x: int(x)-1 p2D = lambda x: print(*x, sep="\n") def II(): return int(sys.stdin.buffer.readline()) def LI(): return list(map(int, sys.stdin.buffer.readline().split())) def LI1(): return list(map(int1, sys.stdin.buffer.readline().split())) def LLI(rows_number): return [LI() for _ in range(rows_number)] def LLI1(rows_number): return [LI1() for _ in range(rows_number)] def BI(): return sys.stdin.buffer.readline().rstrip() def SI(): return sys.stdin.buffer.readline().rstrip().decode() # dij = [(0, 1), (-1, 0), (0, -1), (1, 0)] dij = [(0, 1), (-1, 0), (0, -1), (1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)] inf = 10**16 # md = 998244353 md = 10**9+7 def nHr(hn, hr): return nCr(hn+hr-1, hr-1) def nPr(com_n, com_r): if com_r < 0: return 0 if com_n < com_r: return 0 return fac[com_n]*ifac[com_n-com_r]%md def nCr(com_n, com_r): if com_r < 0: return 0 if com_n < com_r: return 0 return fac[com_n]*ifac[com_r]%md*ifac[com_n-com_r]%md # 準備 n_max = 100005 fac = [1] for i in range(1, n_max+1): fac.append(fac[-1]*i%md) ifac = [1]*(n_max+1) ifac[n_max] = pow(fac[n_max], md-2, md) for i in range(n_max-1, 1, -1): ifac[i] = ifac[i+1]*(i+1)%md from collections import defaultdict, Counter n = II() aa = LI() s = sum(aa) if s%n: print(0) exit() border = s//n ll = defaultdict(int) mid = 0 rr = defaultdict(int) for a in aa: if a < border: ll[a] += 1 elif a == border: mid += 1 else: rr[a] += 1 if mid == n: print(1) exit() if sum(ll.values()) == 1 or sum(rr.values()) == 1: ans = fac[n] for c in Counter(aa).values(): ans = ans*ifac[c]%md print(ans) exit() sl = sum(ll.values()) ans = fac[sl] for c in ll.values(): ans = ans*ifac[c]%md sr = sum(rr.values()) ans = ans*fac[sr]%md for c in rr.values(): ans = ans*ifac[c]%md ans = ans*nCr(sl+sr+mid, mid)%md print(ans*2%md) ```
output
1
29,368
12
58,737
Provide tags and a correct Python 3 solution for this coding contest problem. An array is called beautiful if all the elements in the array are equal. You can transform an array using the following steps any number of times: 1. Choose two indices i and j (1 ≤ i,j ≤ n), and an integer x (1 ≤ x ≤ a_i). Let i be the source index and j be the sink index. 2. Decrease the i-th element by x, and increase the j-th element by x. The resulting values at i-th and j-th index are a_i-x and a_j+x respectively. 3. The cost of this operation is x ⋅ |j-i| . 4. Now the i-th index can no longer be the sink and the j-th index can no longer be the source. The total cost of a transformation is the sum of all the costs in step 3. For example, array [0, 2, 3, 3] can be transformed into a beautiful array [2, 2, 2, 2] with total cost 1 ⋅ |1-3| + 1 ⋅ |1-4| = 5. An array is called balanced, if it can be transformed into a beautiful array, and the cost of such transformation is uniquely defined. In other words, the minimum cost of transformation into a beautiful array equals the maximum cost. You are given an array a_1, a_2, …, a_n of length n, consisting of non-negative integers. Your task is to find the number of balanced arrays which are permutations of the given array. Two arrays are considered different, if elements at some position differ. Since the answer can be large, output it modulo 10^9 + 7. Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the size of the array. The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Output Output a single integer — the number of balanced permutations modulo 10^9+7. Examples Input 3 1 2 3 Output 6 Input 4 0 4 0 4 Output 2 Input 5 0 11 12 13 14 Output 120 Note In the first example, [1, 2, 3] is a valid permutation as we can consider the index with value 3 as the source and index with value 1 as the sink. Thus, after conversion we get a beautiful array [2, 2, 2], and the total cost would be 2. We can show that this is the only transformation of this array that leads to a beautiful array. Similarly, we can check for other permutations too. In the second example, [0, 0, 4, 4] and [4, 4, 0, 0] are balanced permutations. In the third example, all permutations are balanced.
instruction
0
29,369
12
58,738
Tags: combinatorics, constructive algorithms, math, sortings Correct Solution: ``` a=*map(int,[*open(0)][1].split()),;n=len(a);s=sum(a) if s%n:print(0);exit() M=10**9+7;s//=n;f=[1]*(n+1);b=[0]*3;d=dict() for i in range(2,n+1):f[i]=f[i-1]*i%M for x in a:b[(x>s)-(x<s)]+=1;d[x]=d[x]+1if x in d else 1 k=1 for x in d:k*=f[d[x]] k=f[n]*pow(k,M-2,M) print([k%M,f[b[1]]*f[b[-1]]*2*pow(f[n-b[0]],M-2,M)*k%M][b[1]>1and b[-1]>1]) ```
output
1
29,369
12
58,739
Provide tags and a correct Python 3 solution for this coding contest problem. An array is called beautiful if all the elements in the array are equal. You can transform an array using the following steps any number of times: 1. Choose two indices i and j (1 ≤ i,j ≤ n), and an integer x (1 ≤ x ≤ a_i). Let i be the source index and j be the sink index. 2. Decrease the i-th element by x, and increase the j-th element by x. The resulting values at i-th and j-th index are a_i-x and a_j+x respectively. 3. The cost of this operation is x ⋅ |j-i| . 4. Now the i-th index can no longer be the sink and the j-th index can no longer be the source. The total cost of a transformation is the sum of all the costs in step 3. For example, array [0, 2, 3, 3] can be transformed into a beautiful array [2, 2, 2, 2] with total cost 1 ⋅ |1-3| + 1 ⋅ |1-4| = 5. An array is called balanced, if it can be transformed into a beautiful array, and the cost of such transformation is uniquely defined. In other words, the minimum cost of transformation into a beautiful array equals the maximum cost. You are given an array a_1, a_2, …, a_n of length n, consisting of non-negative integers. Your task is to find the number of balanced arrays which are permutations of the given array. Two arrays are considered different, if elements at some position differ. Since the answer can be large, output it modulo 10^9 + 7. Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the size of the array. The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Output Output a single integer — the number of balanced permutations modulo 10^9+7. Examples Input 3 1 2 3 Output 6 Input 4 0 4 0 4 Output 2 Input 5 0 11 12 13 14 Output 120 Note In the first example, [1, 2, 3] is a valid permutation as we can consider the index with value 3 as the source and index with value 1 as the sink. Thus, after conversion we get a beautiful array [2, 2, 2], and the total cost would be 2. We can show that this is the only transformation of this array that leads to a beautiful array. Similarly, we can check for other permutations too. In the second example, [0, 0, 4, 4] and [4, 4, 0, 0] are balanced permutations. In the third example, all permutations are balanced.
instruction
0
29,370
12
58,740
Tags: combinatorics, constructive algorithms, math, sortings Correct Solution: ``` a=*map(int,[*open(0)][1].split()),;n=len(a);s=sum(a) if s%n:print(0);exit(0) M=10**9+7;s//=n;f=[1]*(n+1);b=[0]*3;d=dict() for i in range(2,n+1):f[i]=f[i-1]*i%M for x in a: b[(x>s)-(x<s)]+=1 try:d[x]+=1 except:d[x]=1 k=1 for x in d.values():k*=f[x] k=f[n]*pow(k,M-2,M) print([k%M,f[b[1]]*f[b[-1]]*2*pow(f[n-b[0]],M-2,M)*k%M][b[1]>1and b[-1]>1]) ```
output
1
29,370
12
58,741
Provide tags and a correct Python 3 solution for this coding contest problem. An array is called beautiful if all the elements in the array are equal. You can transform an array using the following steps any number of times: 1. Choose two indices i and j (1 ≤ i,j ≤ n), and an integer x (1 ≤ x ≤ a_i). Let i be the source index and j be the sink index. 2. Decrease the i-th element by x, and increase the j-th element by x. The resulting values at i-th and j-th index are a_i-x and a_j+x respectively. 3. The cost of this operation is x ⋅ |j-i| . 4. Now the i-th index can no longer be the sink and the j-th index can no longer be the source. The total cost of a transformation is the sum of all the costs in step 3. For example, array [0, 2, 3, 3] can be transformed into a beautiful array [2, 2, 2, 2] with total cost 1 ⋅ |1-3| + 1 ⋅ |1-4| = 5. An array is called balanced, if it can be transformed into a beautiful array, and the cost of such transformation is uniquely defined. In other words, the minimum cost of transformation into a beautiful array equals the maximum cost. You are given an array a_1, a_2, …, a_n of length n, consisting of non-negative integers. Your task is to find the number of balanced arrays which are permutations of the given array. Two arrays are considered different, if elements at some position differ. Since the answer can be large, output it modulo 10^9 + 7. Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the size of the array. The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Output Output a single integer — the number of balanced permutations modulo 10^9+7. Examples Input 3 1 2 3 Output 6 Input 4 0 4 0 4 Output 2 Input 5 0 11 12 13 14 Output 120 Note In the first example, [1, 2, 3] is a valid permutation as we can consider the index with value 3 as the source and index with value 1 as the sink. Thus, after conversion we get a beautiful array [2, 2, 2], and the total cost would be 2. We can show that this is the only transformation of this array that leads to a beautiful array. Similarly, we can check for other permutations too. In the second example, [0, 0, 4, 4] and [4, 4, 0, 0] are balanced permutations. In the third example, all permutations are balanced.
instruction
0
29,371
12
58,742
Tags: combinatorics, constructive algorithms, math, sortings Correct Solution: ``` from bisect import * from collections import * from math import gcd,ceil,sqrt,floor,inf from heapq import * from itertools import * from operator import add,mul,sub,xor,truediv,floordiv from functools import * #------------------------------------------------------------------------ import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #------------------------------------------------------------------------ def RL(): return map(int, sys.stdin.readline().rstrip().split()) def RLL(): return list(map(int, sys.stdin.readline().rstrip().split())) def N(): return int(input()) def A(n):return [0]*n def AI(n,x): return [x]*n def A2(n,m): return [[0]*m for i in range(n)] def G(n): return [[] for i in range(n)] def GP(it): return [[ch,len(list(g))] for ch,g in groupby(it)] #------------------------------------------------------------------------ from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc mod=10**9+7 farr=[1] ifa=[] def fact(x,mod=0): if mod: while x>=len(farr): farr.append(farr[-1]*len(farr)%mod) else: while x>=len(farr): farr.append(farr[-1]*len(farr)) return farr[x] def ifact(x,mod): global ifa fact(x,mod) ifa.append(pow(farr[-1],mod-2,mod)) for i in range(x,0,-1): ifa.append(ifa[-1]*i%mod) ifa.reverse() def per(i,j,mod=0): if i<j: return 0 if not mod: return fact(i)//fact(i-j) return farr[i]*ifa[i-j]%mod def com(i,j,mod=0): if i<j: return 0 if not mod: return per(i,j)//fact(j) return per(i,j,mod)*ifa[j]%mod def catalan(n): return com(2*n,n)//(n+1) def isprime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True def floorsum(a,b,c,n):#sum((a*i+b)//c for i in range(n+1)) if a==0:return b//c*(n+1) if a>=c or b>=c: return floorsum(a%c,b%c,c,n)+b//c*(n+1)+a//c*n*(n+1)//2 m=(a*n+b)//c return n*m-floorsum(c,c-b-1,a,m-1) def inverse(a,m): a%=m if a<=1: return a return ((1-inverse(m,a)*m)//a)%m def lowbit(n): return n&-n class BIT: def __init__(self,arr): self.arr=arr self.n=len(arr)-1 def update(self,x,v): while x<=self.n: self.arr[x]+=v x+=x&-x def query(self,x): ans=0 while x: ans+=self.arr[x] x&=x-1 return ans class ST: def __init__(self,arr):#n!=0 n=len(arr) mx=n.bit_length()#取不到 self.st=[[0]*mx for i in range(n)] for i in range(n): self.st[i][0]=arr[i] for j in range(1,mx): for i in range(n-(1<<j)+1): self.st[i][j]=max(self.st[i][j-1],self.st[i+(1<<j-1)][j-1]) def query(self,l,r): if l>r:return -inf s=(r+1-l).bit_length()-1 return max(self.st[l][s],self.st[r-(1<<s)+1][s]) ''' class DSU:#容量+路径压缩 def __init__(self,n): self.c=[-1]*n def same(self,x,y): return self.find(x)==self.find(y) def find(self,x): if self.c[x]<0: return x self.c[x]=self.find(self.c[x]) return self.c[x] def union(self,u,v): u,v=self.find(u),self.find(v) if u==v: return False if self.c[u]>self.c[v]: u,v=v,u self.c[u]+=self.c[v] self.c[v]=u return True def size(self,x): return -self.c[self.find(x)]''' class UFS:#秩+路径 def __init__(self,n): self.parent=[i for i in range(n)] self.ranks=[0]*n def find(self,x): if x!=self.parent[x]: self.parent[x]=self.find(self.parent[x]) return self.parent[x] def union(self,u,v): pu,pv=self.find(u),self.find(v) if pu==pv: return False if self.ranks[pu]>=self.ranks[pv]: self.parent[pv]=pu if self.ranks[pv]==self.ranks[pu]: self.ranks[pu]+=1 else: self.parent[pu]=pv def Prime(n): c=0 prime=[] flag=[0]*(n+1) for i in range(2,n+1): if not flag[i]: prime.append(i) c+=1 for j in range(c): if i*prime[j]>n: break flag[i*prime[j]]=prime[j] if i%prime[j]==0: break return prime def dij(s,graph): d={} d[s]=0 heap=[(0,s)] seen=set() while heap: dis,u=heappop(heap) if u in seen: continue seen.add(u) for v,w in graph[u]: if v not in d or d[v]>d[u]+w: d[v]=d[u]+w heappush(heap,(d[v],v)) return d def bell(s,g):#bellman-Ford dis=AI(n,inf) dis[s]=0 for i in range(n-1): for u,v,w in edge: if dis[v]>dis[u]+w: dis[v]=dis[u]+w change=A(n) for i in range(n): for u,v,w in edge: if dis[v]>dis[u]+w: dis[v]=dis[u]+w change[v]=1 return dis def lcm(a,b): return a*b//gcd(a,b) def lis(nums): res=[] for k in nums: i=bisect.bisect_left(res,k) if i==len(res): res.append(k) else: res[i]=k return len(res) def RP(nums):#逆序对 n = len(nums) s=set(nums) d={} for i,k in enumerate(sorted(s),1): d[k]=i bi=BIT([0]*(len(s)+1)) ans=0 for i in range(n-1,-1,-1): ans+=bi.query(d[nums[i]]-1) bi.update(d[nums[i]],1) return ans class DLN: def __init__(self,val): self.val=val self.pre=None self.next=None def nb(i,j,n,m): for ni,nj in [[i+1,j],[i-1,j],[i,j-1],[i,j+1]]: if 0<=ni<n and 0<=nj<m: yield ni,nj def topo(n): q=deque() res=[] for i in range(1,n+1): if ind[i]==0: q.append(i) res.append(i) while q: u=q.popleft() for v in g[u]: ind[v]-=1 if ind[v]==0: q.append(v) res.append(v) return res @bootstrap def gdfs(r,p): for ch in g[r]: if ch!=p: yield gdfs(ch,r) yield None @bootstrap def dfs(r,p,path): path[c[r]]+=1 if path[c[r]]==1: ans.append(r+1) for ch in g[r]: if ch!=p: yield dfs(ch,r,path) path[c[r]]-=1 yield None t=1 for i in range(t): n=N() a=RLL() s=sum(a) ifact(n,mod) cb=Counter() cs=Counter() if s%n!=0: print(0) else: s=s//n b=sm=0 for i in range(n): if a[i]>s: b+=1 cb[a[i]]+=1 elif a[i]<s: sm+=1 cs[a[i]]+=1 ans=com(n,n-sm-b,mod) if b==1: ans=ans*per(sm+b,b,mod)%mod*fact(sm,mod)%mod for k in cs: ans=ans*ifa[cs[k]]%mod elif sm==1: ans=ans*per(sm+b,sm,mod)%mod*fact(b,mod)%mod for k in cb: ans=ans*ifa[cb[k]]%mod else: if b: ans*=2*fact(sm,mod)%mod*fact(b,mod)%mod ans%=mod for k in cb: ans=ans*ifa[cb[k]]%mod for k in cs: ans=ans*ifa[cs[k]]%mod print(ans) ''' sys.setrecursionlimit(200000) import threading threading.stack_size(10**8) t=threading.Thr ead(target=main) t.start() t.join() ''' ```
output
1
29,371
12
58,743