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
Provide tags and a correct Python 3 solution for this coding contest problem. One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array A. Lesha is tired now so he asked you to split the array. Help Lesha! Input The first line contains single integer n (1 ≀ n ≀ 100) β€” the number of elements in the array A. The next line contains n integers a1, a2, ..., an ( - 103 ≀ ai ≀ 103) β€” the elements of the array A. Output If it is not possible to split the array A and satisfy all the constraints, print single line containing "NO" (without quotes). Otherwise in the first line print "YES" (without quotes). In the next line print single integer k β€” the number of new arrays. In each of the next k lines print two integers li and ri which denote the subarray A[li... ri] of the initial array A being the i-th new array. Integers li, ri should satisfy the following conditions: * l1 = 1 * rk = n * ri + 1 = li + 1 for each 1 ≀ i < k. If there are multiple answers, print any of them. Examples Input 3 1 2 -3 Output YES 2 1 2 3 3 Input 8 9 -12 3 4 -4 -10 7 3 Output YES 2 1 2 3 8 Input 1 0 Output NO Input 4 1 2 3 -5 Output YES 4 1 1 2 2 3 3 4 4
instruction
0
89,761
12
179,522
Tags: constructive algorithms, greedy, implementation Correct Solution: ``` #!/usr/bin/env python3 # -*- coding: utf-8 -*- N = int(input()) As = list(map(int,input().split())) if min(As) == max(As) == 0: print("NO") else: print("YES") if sum(As) != 0: print("1") print("{} {}".format(1,N)) else: Bs = [] i = 0 while sum(Bs) == 0: Bs.append(As[i]) i += 1 print("2") print(1, i) print(i+1, N) ```
output
1
89,761
12
179,523
Provide tags and a correct Python 3 solution for this coding contest problem. One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array A. Lesha is tired now so he asked you to split the array. Help Lesha! Input The first line contains single integer n (1 ≀ n ≀ 100) β€” the number of elements in the array A. The next line contains n integers a1, a2, ..., an ( - 103 ≀ ai ≀ 103) β€” the elements of the array A. Output If it is not possible to split the array A and satisfy all the constraints, print single line containing "NO" (without quotes). Otherwise in the first line print "YES" (without quotes). In the next line print single integer k β€” the number of new arrays. In each of the next k lines print two integers li and ri which denote the subarray A[li... ri] of the initial array A being the i-th new array. Integers li, ri should satisfy the following conditions: * l1 = 1 * rk = n * ri + 1 = li + 1 for each 1 ≀ i < k. If there are multiple answers, print any of them. Examples Input 3 1 2 -3 Output YES 2 1 2 3 3 Input 8 9 -12 3 4 -4 -10 7 3 Output YES 2 1 2 3 8 Input 1 0 Output NO Input 4 1 2 3 -5 Output YES 4 1 1 2 2 3 3 4 4
instruction
0
89,762
12
179,524
Tags: constructive algorithms, greedy, implementation Correct Solution: ``` n = int(input()) arr = list(map(int,input().split())) sm = sum(arr) if sm!=0: print("YES") print(1) print(1,n) else: sm = 0 done = False for i in range(n): sm += arr[i] if sm!=0: print("YES") print(2) print(1,i+1) print(i+2,n) done = True break if not done: print("NO") ```
output
1
89,762
12
179,525
Provide tags and a correct Python 3 solution for this coding contest problem. One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array A. Lesha is tired now so he asked you to split the array. Help Lesha! Input The first line contains single integer n (1 ≀ n ≀ 100) β€” the number of elements in the array A. The next line contains n integers a1, a2, ..., an ( - 103 ≀ ai ≀ 103) β€” the elements of the array A. Output If it is not possible to split the array A and satisfy all the constraints, print single line containing "NO" (without quotes). Otherwise in the first line print "YES" (without quotes). In the next line print single integer k β€” the number of new arrays. In each of the next k lines print two integers li and ri which denote the subarray A[li... ri] of the initial array A being the i-th new array. Integers li, ri should satisfy the following conditions: * l1 = 1 * rk = n * ri + 1 = li + 1 for each 1 ≀ i < k. If there are multiple answers, print any of them. Examples Input 3 1 2 -3 Output YES 2 1 2 3 3 Input 8 9 -12 3 4 -4 -10 7 3 Output YES 2 1 2 3 8 Input 1 0 Output NO Input 4 1 2 3 -5 Output YES 4 1 1 2 2 3 3 4 4
instruction
0
89,763
12
179,526
Tags: constructive algorithms, greedy, implementation Correct Solution: ``` n = int(input()) lst = list(map(int, input().split())) if sum(lst) != 0: print("YES\n1\n1 %d" % (n)) else: for i in range(1, n): if sum(lst[:i]) != 0: print("YES\n2\n1 %d\n%d %d" % (i, i+1, n)) quit() print("NO") ```
output
1
89,763
12
179,527
Provide tags and a correct Python 3 solution for this coding contest problem. One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array A. Lesha is tired now so he asked you to split the array. Help Lesha! Input The first line contains single integer n (1 ≀ n ≀ 100) β€” the number of elements in the array A. The next line contains n integers a1, a2, ..., an ( - 103 ≀ ai ≀ 103) β€” the elements of the array A. Output If it is not possible to split the array A and satisfy all the constraints, print single line containing "NO" (without quotes). Otherwise in the first line print "YES" (without quotes). In the next line print single integer k β€” the number of new arrays. In each of the next k lines print two integers li and ri which denote the subarray A[li... ri] of the initial array A being the i-th new array. Integers li, ri should satisfy the following conditions: * l1 = 1 * rk = n * ri + 1 = li + 1 for each 1 ≀ i < k. If there are multiple answers, print any of them. Examples Input 3 1 2 -3 Output YES 2 1 2 3 3 Input 8 9 -12 3 4 -4 -10 7 3 Output YES 2 1 2 3 8 Input 1 0 Output NO Input 4 1 2 3 -5 Output YES 4 1 1 2 2 3 3 4 4
instruction
0
89,764
12
179,528
Tags: constructive algorithms, greedy, implementation Correct Solution: ``` n=int(input()) a=list(map(int, input().split())) if a.count(0)==n: print("NO") else: print("YES") if sum(a)==0: for i in range(n): if sum(a[:i])!=0: print("2") print("1 "+str(i)) print(str(i+1)+" "+str(n)) break else: print("1") print("1 "+str(n)) ```
output
1
89,764
12
179,529
Provide tags and a correct Python 3 solution for this coding contest problem. One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array A. Lesha is tired now so he asked you to split the array. Help Lesha! Input The first line contains single integer n (1 ≀ n ≀ 100) β€” the number of elements in the array A. The next line contains n integers a1, a2, ..., an ( - 103 ≀ ai ≀ 103) β€” the elements of the array A. Output If it is not possible to split the array A and satisfy all the constraints, print single line containing "NO" (without quotes). Otherwise in the first line print "YES" (without quotes). In the next line print single integer k β€” the number of new arrays. In each of the next k lines print two integers li and ri which denote the subarray A[li... ri] of the initial array A being the i-th new array. Integers li, ri should satisfy the following conditions: * l1 = 1 * rk = n * ri + 1 = li + 1 for each 1 ≀ i < k. If there are multiple answers, print any of them. Examples Input 3 1 2 -3 Output YES 2 1 2 3 3 Input 8 9 -12 3 4 -4 -10 7 3 Output YES 2 1 2 3 8 Input 1 0 Output NO Input 4 1 2 3 -5 Output YES 4 1 1 2 2 3 3 4 4
instruction
0
89,765
12
179,530
Tags: constructive algorithms, greedy, implementation Correct Solution: ``` n=int(input()) a=list(map(int,input().split())) sum = 0 for i in range(n): sum = sum + a[i] if sum: print ("YES") print ("1") print ("1",n) else: teksum,ans = 0,0 for i in range(n): if teksum: ans=i break else: teksum = teksum + a[i] if ans == 0: print("NO") else: print("YES") print("2") print("1",ans) ans = ans +1 print(ans,n) ```
output
1
89,765
12
179,531
Provide tags and a correct Python 3 solution for this coding contest problem. One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array A. Lesha is tired now so he asked you to split the array. Help Lesha! Input The first line contains single integer n (1 ≀ n ≀ 100) β€” the number of elements in the array A. The next line contains n integers a1, a2, ..., an ( - 103 ≀ ai ≀ 103) β€” the elements of the array A. Output If it is not possible to split the array A and satisfy all the constraints, print single line containing "NO" (without quotes). Otherwise in the first line print "YES" (without quotes). In the next line print single integer k β€” the number of new arrays. In each of the next k lines print two integers li and ri which denote the subarray A[li... ri] of the initial array A being the i-th new array. Integers li, ri should satisfy the following conditions: * l1 = 1 * rk = n * ri + 1 = li + 1 for each 1 ≀ i < k. If there are multiple answers, print any of them. Examples Input 3 1 2 -3 Output YES 2 1 2 3 3 Input 8 9 -12 3 4 -4 -10 7 3 Output YES 2 1 2 3 8 Input 1 0 Output NO Input 4 1 2 3 -5 Output YES 4 1 1 2 2 3 3 4 4
instruction
0
89,766
12
179,532
Tags: constructive algorithms, greedy, implementation Correct Solution: ``` n = int(input()) a = [int(b) for b in input().split()] ans = 0 indexes = [] if len(set(a)) == 1 and a[0] == 0: print("NO") exit() if sum(a) != 0: print("YES") print(1) print(1, n) exit() for i in range(n): if a[i] != 0: indexes.append(i) print("YES") print(2) print(1, indexes[0]+1) print(indexes[0]+2, n) ```
output
1
89,766
12
179,533
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array A. Lesha is tired now so he asked you to split the array. Help Lesha! Input The first line contains single integer n (1 ≀ n ≀ 100) β€” the number of elements in the array A. The next line contains n integers a1, a2, ..., an ( - 103 ≀ ai ≀ 103) β€” the elements of the array A. Output If it is not possible to split the array A and satisfy all the constraints, print single line containing "NO" (without quotes). Otherwise in the first line print "YES" (without quotes). In the next line print single integer k β€” the number of new arrays. In each of the next k lines print two integers li and ri which denote the subarray A[li... ri] of the initial array A being the i-th new array. Integers li, ri should satisfy the following conditions: * l1 = 1 * rk = n * ri + 1 = li + 1 for each 1 ≀ i < k. If there are multiple answers, print any of them. Examples Input 3 1 2 -3 Output YES 2 1 2 3 3 Input 8 9 -12 3 4 -4 -10 7 3 Output YES 2 1 2 3 8 Input 1 0 Output NO Input 4 1 2 3 -5 Output YES 4 1 1 2 2 3 3 4 4 Submitted Solution: ``` n = int(input()) a = [int(i) for i in input().split()] if sum(a) != 0: print('YES') print(1) print(1, n) exit() if n == 1 or a.count(0) == n: print('NO') exit() i = 0 while a[i] == 0: i += 1 print('YES') print(2) print(1, i + 1) print(i + 2, n) ```
instruction
0
89,767
12
179,534
Yes
output
1
89,767
12
179,535
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array A. Lesha is tired now so he asked you to split the array. Help Lesha! Input The first line contains single integer n (1 ≀ n ≀ 100) β€” the number of elements in the array A. The next line contains n integers a1, a2, ..., an ( - 103 ≀ ai ≀ 103) β€” the elements of the array A. Output If it is not possible to split the array A and satisfy all the constraints, print single line containing "NO" (without quotes). Otherwise in the first line print "YES" (without quotes). In the next line print single integer k β€” the number of new arrays. In each of the next k lines print two integers li and ri which denote the subarray A[li... ri] of the initial array A being the i-th new array. Integers li, ri should satisfy the following conditions: * l1 = 1 * rk = n * ri + 1 = li + 1 for each 1 ≀ i < k. If there are multiple answers, print any of them. Examples Input 3 1 2 -3 Output YES 2 1 2 3 3 Input 8 9 -12 3 4 -4 -10 7 3 Output YES 2 1 2 3 8 Input 1 0 Output NO Input 4 1 2 3 -5 Output YES 4 1 1 2 2 3 3 4 4 Submitted Solution: ``` import sys,math n = int(input()) array = list(map(int,input().split())) if array.count(0)==n: print('NO') sys.exit() if sum(array)==0: print('YES') print(2) i = 1 while sum(array[0:i]) ==0 or sum(array[i:])==0: i+=1 print(1,i) print(i+1,n) else: print('YES') print(1) print(1,n) ```
instruction
0
89,768
12
179,536
Yes
output
1
89,768
12
179,537
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array A. Lesha is tired now so he asked you to split the array. Help Lesha! Input The first line contains single integer n (1 ≀ n ≀ 100) β€” the number of elements in the array A. The next line contains n integers a1, a2, ..., an ( - 103 ≀ ai ≀ 103) β€” the elements of the array A. Output If it is not possible to split the array A and satisfy all the constraints, print single line containing "NO" (without quotes). Otherwise in the first line print "YES" (without quotes). In the next line print single integer k β€” the number of new arrays. In each of the next k lines print two integers li and ri which denote the subarray A[li... ri] of the initial array A being the i-th new array. Integers li, ri should satisfy the following conditions: * l1 = 1 * rk = n * ri + 1 = li + 1 for each 1 ≀ i < k. If there are multiple answers, print any of them. Examples Input 3 1 2 -3 Output YES 2 1 2 3 3 Input 8 9 -12 3 4 -4 -10 7 3 Output YES 2 1 2 3 8 Input 1 0 Output NO Input 4 1 2 3 -5 Output YES 4 1 1 2 2 3 3 4 4 Submitted Solution: ``` def check_zero(ar): for i in range(n): if ar[i] != 0: return False return True n = int(input()) ls = list(map(int, input().split())) sm = sum(ls) if sm: print('YES') print(1) print(1, n) else: if check_zero(ls): print('NO') else: tsm = 0 for i in range(n): tsm += ls[i] if tsm != 0: print('YES') print(2) print(1, i + 1) print(i + 2, n) break ```
instruction
0
89,769
12
179,538
Yes
output
1
89,769
12
179,539
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array A. Lesha is tired now so he asked you to split the array. Help Lesha! Input The first line contains single integer n (1 ≀ n ≀ 100) β€” the number of elements in the array A. The next line contains n integers a1, a2, ..., an ( - 103 ≀ ai ≀ 103) β€” the elements of the array A. Output If it is not possible to split the array A and satisfy all the constraints, print single line containing "NO" (without quotes). Otherwise in the first line print "YES" (without quotes). In the next line print single integer k β€” the number of new arrays. In each of the next k lines print two integers li and ri which denote the subarray A[li... ri] of the initial array A being the i-th new array. Integers li, ri should satisfy the following conditions: * l1 = 1 * rk = n * ri + 1 = li + 1 for each 1 ≀ i < k. If there are multiple answers, print any of them. Examples Input 3 1 2 -3 Output YES 2 1 2 3 3 Input 8 9 -12 3 4 -4 -10 7 3 Output YES 2 1 2 3 8 Input 1 0 Output NO Input 4 1 2 3 -5 Output YES 4 1 1 2 2 3 3 4 4 Submitted Solution: ``` n=int(input()) l=list(map(int,input().split())) if(l.count(0)==n): print("NO") else: s=0 t=[1] d=[] for i in range(n): s=s+l[i] if(l[i]!=0 and s==0): t.append(i) d.append(t) t=[i+1] s=l[i] t.append(n) d.append(t) print("YES") print(len(d)) for i in d: print(i[0],i[1]) ```
instruction
0
89,770
12
179,540
Yes
output
1
89,770
12
179,541
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array A. Lesha is tired now so he asked you to split the array. Help Lesha! Input The first line contains single integer n (1 ≀ n ≀ 100) β€” the number of elements in the array A. The next line contains n integers a1, a2, ..., an ( - 103 ≀ ai ≀ 103) β€” the elements of the array A. Output If it is not possible to split the array A and satisfy all the constraints, print single line containing "NO" (without quotes). Otherwise in the first line print "YES" (without quotes). In the next line print single integer k β€” the number of new arrays. In each of the next k lines print two integers li and ri which denote the subarray A[li... ri] of the initial array A being the i-th new array. Integers li, ri should satisfy the following conditions: * l1 = 1 * rk = n * ri + 1 = li + 1 for each 1 ≀ i < k. If there are multiple answers, print any of them. Examples Input 3 1 2 -3 Output YES 2 1 2 3 3 Input 8 9 -12 3 4 -4 -10 7 3 Output YES 2 1 2 3 8 Input 1 0 Output NO Input 4 1 2 3 -5 Output YES 4 1 1 2 2 3 3 4 4 Submitted Solution: ``` n = int(input()) a = list(map(int, input().split())) ss = 0 if a.count('0') == n: print('NO') else: print('YES') print(1, end = ' ') for i in range(0, n): ss += a[i] if ss == 0 and a[i] != 0: print(i) print(i+1, end = ' ') print(n) ```
instruction
0
89,771
12
179,542
No
output
1
89,771
12
179,543
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array A. Lesha is tired now so he asked you to split the array. Help Lesha! Input The first line contains single integer n (1 ≀ n ≀ 100) β€” the number of elements in the array A. The next line contains n integers a1, a2, ..., an ( - 103 ≀ ai ≀ 103) β€” the elements of the array A. Output If it is not possible to split the array A and satisfy all the constraints, print single line containing "NO" (without quotes). Otherwise in the first line print "YES" (without quotes). In the next line print single integer k β€” the number of new arrays. In each of the next k lines print two integers li and ri which denote the subarray A[li... ri] of the initial array A being the i-th new array. Integers li, ri should satisfy the following conditions: * l1 = 1 * rk = n * ri + 1 = li + 1 for each 1 ≀ i < k. If there are multiple answers, print any of them. Examples Input 3 1 2 -3 Output YES 2 1 2 3 3 Input 8 9 -12 3 4 -4 -10 7 3 Output YES 2 1 2 3 8 Input 1 0 Output NO Input 4 1 2 3 -5 Output YES 4 1 1 2 2 3 3 4 4 Submitted Solution: ``` n = int(input()) t= list(map(int,input().split())) f=[] s=99999 for j in range(n): if t[j]!=0: if s==99999: f.append([j+1,j+1]) else: f.append([s,j+1]) s=99999 else: s=j+1 if len(f)==0: print('NO') else: if s!=99999: a=f.pop()[0] f.append([a,n]) print('YES') print(len(f)) for j in f: print(*j) ```
instruction
0
89,772
12
179,544
No
output
1
89,772
12
179,545
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array A. Lesha is tired now so he asked you to split the array. Help Lesha! Input The first line contains single integer n (1 ≀ n ≀ 100) β€” the number of elements in the array A. The next line contains n integers a1, a2, ..., an ( - 103 ≀ ai ≀ 103) β€” the elements of the array A. Output If it is not possible to split the array A and satisfy all the constraints, print single line containing "NO" (without quotes). Otherwise in the first line print "YES" (without quotes). In the next line print single integer k β€” the number of new arrays. In each of the next k lines print two integers li and ri which denote the subarray A[li... ri] of the initial array A being the i-th new array. Integers li, ri should satisfy the following conditions: * l1 = 1 * rk = n * ri + 1 = li + 1 for each 1 ≀ i < k. If there are multiple answers, print any of them. Examples Input 3 1 2 -3 Output YES 2 1 2 3 3 Input 8 9 -12 3 4 -4 -10 7 3 Output YES 2 1 2 3 8 Input 1 0 Output NO Input 4 1 2 3 -5 Output YES 4 1 1 2 2 3 3 4 4 Submitted Solution: ``` n = int(input()) a = [int(x) for x in input().split()] T = {} def split_nonzero(a, T, begin, end): if begin == end: T[(begin, end)] = [] elif begin == end - 1: if a[begin] == 0: T[(begin, end)] = 'NO' else: T[(begin, end)] = [(begin, begin)] else: for k in range(end - 1, begin, -1): if (begin, k) in T: fr = T[(begin, k)] else: fr = split_nonzero(a, T, begin, k) if fr != 'NO': if (k, end) in T: sr = T[(k, end)] else: sr = split_nonzero(a, T, k, end) if sr != 'NO': T[(begin, end)] = [(begin, k - 1)] + sr break else: T[(begin, end)] = 'NO' return T[(begin, end)] result = split_nonzero(a, T, 0, len(a)) if result == 'NO': print('NO') else: print('YES') print(len(result)) for (i, j) in result: print(i + 1, j + 1) ```
instruction
0
89,773
12
179,546
No
output
1
89,773
12
179,547
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array A. Lesha is tired now so he asked you to split the array. Help Lesha! Input The first line contains single integer n (1 ≀ n ≀ 100) β€” the number of elements in the array A. The next line contains n integers a1, a2, ..., an ( - 103 ≀ ai ≀ 103) β€” the elements of the array A. Output If it is not possible to split the array A and satisfy all the constraints, print single line containing "NO" (without quotes). Otherwise in the first line print "YES" (without quotes). In the next line print single integer k β€” the number of new arrays. In each of the next k lines print two integers li and ri which denote the subarray A[li... ri] of the initial array A being the i-th new array. Integers li, ri should satisfy the following conditions: * l1 = 1 * rk = n * ri + 1 = li + 1 for each 1 ≀ i < k. If there are multiple answers, print any of them. Examples Input 3 1 2 -3 Output YES 2 1 2 3 3 Input 8 9 -12 3 4 -4 -10 7 3 Output YES 2 1 2 3 8 Input 1 0 Output NO Input 4 1 2 3 -5 Output YES 4 1 1 2 2 3 3 4 4 Submitted Solution: ``` N = int(input()) A = [int(x) for x in input().split()] if all(A[i] == 0 for i in range(N)): print("NO") else: print("YES") ans = [] nz_l, nz_r = 0, N-1 while A[nz_l] == 0: nz_l += 1 while A[nz_r] == 0: nz_r -= 1 now = nz_l while now <= nz_r: total = 0 for i in range(now, N): total += A[i] if A[i] != 0: ans.append([now, i]) now = i + 1 break ans[0][0] = 0 ans[-1][1] = N-1 for l, r in ans: print(l+1, r+1) ```
instruction
0
89,774
12
179,548
No
output
1
89,774
12
179,549
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions is a number of elements in the array. You are given an array a consisting of n integers. The value of the i-th element of the array is a_i. You are also given a set of m segments. The j-th segment is [l_j; r_j], where 1 ≀ l_j ≀ r_j ≀ n. You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array a = [0, 0, 0, 0, 0] and the given segments are [1; 3] and [2; 4] then you can choose both of them and the array will become b = [-1, -2, -2, -1, 0]. You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array a and obtain the array b then the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i will be maximum possible. Note that you can choose the empty set. If there are multiple answers, you can print any. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and m (1 ≀ n ≀ 10^5, 0 ≀ m ≀ 300) β€” the length of the array a and the number of segments, respectively. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^6 ≀ a_i ≀ 10^6), where a_i is the value of the i-th element of the array a. The next m lines are contain two integers each. The j-th of them contains two integers l_j and r_j (1 ≀ l_j ≀ r_j ≀ n), where l_j and r_j are the ends of the j-th segment. Output In the first line of the output print one integer d β€” the maximum possible value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i if b is the array obtained by applying some subset of the given segments to the array a. In the second line of the output print one integer q (0 ≀ q ≀ m) β€” the number of segments you apply. In the third line print q distinct integers c_1, c_2, ..., c_q in any order (1 ≀ c_k ≀ m) β€” indices of segments you apply to the array a in such a way that the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i of the obtained array b is maximum possible. If there are multiple answers, you can print any. Examples Input 5 4 2 -2 3 1 2 1 3 4 5 2 5 1 3 Output 6 2 4 1 Input 5 4 2 -2 3 1 4 3 5 3 4 2 4 2 5 Output 7 2 3 2 Input 1 0 1000000 Output 0 0 Note In the first example the obtained array b will be [0, -4, 1, 1, 2] so the answer is 6. In the second example the obtained array b will be [2, -3, 1, -1, 4] so the answer is 7. In the third example you cannot do anything so the answer is 0.
instruction
0
90,154
12
180,308
Tags: data structures, implementation Correct Solution: ``` n, m = map(int, input().split()) A = list(map(int, input().split())) Lf = [[] for _ in range(n)] Rb = [[] for _ in range(n)] LR = [] for i in range(m): l, r = map(int, input().split()) l, r = l-1, r-1 Lf[r].append(l) Rb[l].append(r) LR.append((l, r)) minus = [0]*n INF = 10**18 ans = [-INF]*n mn = A[0] for i in range(n): ans[i] = max(ans[i], A[i]-mn) for l in Lf[i]: for j in range(l, i+1): minus[j] -= 1 mn = min(mn, A[j]+minus[j]) mn = min(mn, A[i]+minus[i]) minus = [0]*n mn = A[n-1] for i in reversed(range(n)): ans[i] = max(ans[i], A[i]-mn) for r in Rb[i]: for j in range(i, r+1): minus[j] -= 1 mn = min(mn, A[j]+minus[j]) mn = min(mn, A[i]+minus[i]) ans_ = max(ans) res = [] for i in range(n): if ans[i] == ans_: for j in range(m): l, r = LR[j] if not (l <= i and i <= r): res.append(j+1) break print(ans_) print(len(res)) print(*res) ```
output
1
90,154
12
180,309
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions is a number of elements in the array. You are given an array a consisting of n integers. The value of the i-th element of the array is a_i. You are also given a set of m segments. The j-th segment is [l_j; r_j], where 1 ≀ l_j ≀ r_j ≀ n. You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array a = [0, 0, 0, 0, 0] and the given segments are [1; 3] and [2; 4] then you can choose both of them and the array will become b = [-1, -2, -2, -1, 0]. You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array a and obtain the array b then the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i will be maximum possible. Note that you can choose the empty set. If there are multiple answers, you can print any. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and m (1 ≀ n ≀ 10^5, 0 ≀ m ≀ 300) β€” the length of the array a and the number of segments, respectively. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^6 ≀ a_i ≀ 10^6), where a_i is the value of the i-th element of the array a. The next m lines are contain two integers each. The j-th of them contains two integers l_j and r_j (1 ≀ l_j ≀ r_j ≀ n), where l_j and r_j are the ends of the j-th segment. Output In the first line of the output print one integer d β€” the maximum possible value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i if b is the array obtained by applying some subset of the given segments to the array a. In the second line of the output print one integer q (0 ≀ q ≀ m) β€” the number of segments you apply. In the third line print q distinct integers c_1, c_2, ..., c_q in any order (1 ≀ c_k ≀ m) β€” indices of segments you apply to the array a in such a way that the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i of the obtained array b is maximum possible. If there are multiple answers, you can print any. Examples Input 5 4 2 -2 3 1 2 1 3 4 5 2 5 1 3 Output 6 2 4 1 Input 5 4 2 -2 3 1 4 3 5 3 4 2 4 2 5 Output 7 2 3 2 Input 1 0 1000000 Output 0 0 Note In the first example the obtained array b will be [0, -4, 1, 1, 2] so the answer is 6. In the second example the obtained array b will be [2, -3, 1, -1, 4] so the answer is 7. In the third example you cannot do anything so the answer is 0.
instruction
0
90,155
12
180,310
Tags: data structures, implementation Correct Solution: ``` # Author : nitish420 -------------------------------------------------------------------- import os import sys from io import BytesIO, IOBase def main(): n,m=map(int,input().split()) arr=list(map(int,input().split())) left=[[] for _ in range(n)] right=[[] for _ in range(n)] seg=[] for _ in range(m): l,r=map(int,input().split()) l-=1 r-=1 left[r].append(l) right[l].append(r) seg.append((l,r)) dff=[0]*n ans=[-10**10]*n mm=arr[0] for i in range(n): ans[i]=max(ans[i],arr[i]-mm) for l in left[i]: for j in range(l,i+1): dff[j]-=1 mm=min(mm,arr[j]+dff[j]) mm=min(mm,arr[i]+dff[i]) dff=[0]*n mm=arr[n-1] for i in range(n-1,-1,-1): ans[i]=max(ans[i],arr[i]-mm) for r in right[i]: for j in range(i,r+1): dff[j]-=1 mm=min(mm,arr[j]+dff[j]) mm=min(mm,arr[i]+dff[i]) final=max(ans) idx=ans.index(final) que=[] for i,item in enumerate(seg): l,r=item if l<=idx<=r: continue que.append(i+1) print(final) print(len(que)) print(*que) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = 'x' in file.mode or 'r' not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b'\n') + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode('ascii')) self.read = lambda: self.buffer.read().decode('ascii') self.readline = lambda: self.buffer.readline().decode('ascii') sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip('\r\n') # endregion if __name__ == '__main__': main() ```
output
1
90,155
12
180,311
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions is a number of elements in the array. You are given an array a consisting of n integers. The value of the i-th element of the array is a_i. You are also given a set of m segments. The j-th segment is [l_j; r_j], where 1 ≀ l_j ≀ r_j ≀ n. You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array a = [0, 0, 0, 0, 0] and the given segments are [1; 3] and [2; 4] then you can choose both of them and the array will become b = [-1, -2, -2, -1, 0]. You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array a and obtain the array b then the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i will be maximum possible. Note that you can choose the empty set. If there are multiple answers, you can print any. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and m (1 ≀ n ≀ 10^5, 0 ≀ m ≀ 300) β€” the length of the array a and the number of segments, respectively. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^6 ≀ a_i ≀ 10^6), where a_i is the value of the i-th element of the array a. The next m lines are contain two integers each. The j-th of them contains two integers l_j and r_j (1 ≀ l_j ≀ r_j ≀ n), where l_j and r_j are the ends of the j-th segment. Output In the first line of the output print one integer d β€” the maximum possible value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i if b is the array obtained by applying some subset of the given segments to the array a. In the second line of the output print one integer q (0 ≀ q ≀ m) β€” the number of segments you apply. In the third line print q distinct integers c_1, c_2, ..., c_q in any order (1 ≀ c_k ≀ m) β€” indices of segments you apply to the array a in such a way that the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i of the obtained array b is maximum possible. If there are multiple answers, you can print any. Examples Input 5 4 2 -2 3 1 2 1 3 4 5 2 5 1 3 Output 6 2 4 1 Input 5 4 2 -2 3 1 4 3 5 3 4 2 4 2 5 Output 7 2 3 2 Input 1 0 1000000 Output 0 0 Note In the first example the obtained array b will be [0, -4, 1, 1, 2] so the answer is 6. In the second example the obtained array b will be [2, -3, 1, -1, 4] so the answer is 7. In the third example you cannot do anything so the answer is 0.
instruction
0
90,156
12
180,312
Tags: data structures, implementation Correct Solution: ``` import sys # a very nice implementation of a minimum segment tree with # some inspiration taken from https://codeforces.com/blog/entry/18051 # this implementation should be able to be modified to do pretty # much anything one would want to do with segment trees apart from # persistance. # note that especially in python this implementation is much much better # than most other approches because how slow python can be with function # calls. # currently it allows for two operations, both running in o(log n), # 'add(l,r,value)' adds value to [l,r) # 'find_min(l,r)' finds the index with the smallest value big = 10**9 class super_seg: def __init__(self,data): n = len(data) m = 1 while m<n: m *= 2 self.n = n self.m = m self.data = [big]*(2*m) for i in range(n): self.data[i+m] = data[i] for i in reversed(range(m)): self.data[i] = min(self.data[2*i], self.data[2*i+1]) self.query = [0]*(2*m) # push the query on seg_ind to its children def push(self,seg_ind): # let the children know of the queries q = self.query[seg_ind] self.query[2*seg_ind] += q self.query[2*seg_ind+1] += q self.data[2*seg_ind] += q self.data[2*seg_ind+1] += q # remove queries from seg_ind self.data[seg_ind] = min(self.data[2*seg_ind],self.data[2*seg_ind+1]) self.query[seg_ind] = 0 # updates the node seg_ind to know of all queries # applied to it via its ancestors def update(self,seg_ind): # find all indecies to be updated seg_ind //= 2 inds = [] while seg_ind>0: inds.append(seg_ind) seg_ind//=2 # push the queries down the segment tree for ind in reversed(inds): self.push(ind) # make the changes to seg_ind be known to its ancestors def build(self,seg_ind): seg_ind//=2 while seg_ind>0: self.data[seg_ind] = min(self.data[2*seg_ind], self.data[2*seg_ind+1]) + self.query[seg_ind] seg_ind //= 2 # lazily add value to [l,r) def add(self,l,r,value): l += self.m r += self.m l0 = l r0 = r while l<r: if l%2==1: self.query[l]+= value self.data[l] += value l+=1 if r%2==1: r-=1 self.query[r]+= value self.data[r] += value l//=2 r//=2 # tell all nodes above of the updated # area of the updates self.build(l0) self.build(r0-1) # min of data[l,r) def min(self,l,r): l += self.m r += self.m # apply all the lazily stored queries self.update(l) self.update(r-1) segs = [] while l<r: if l%2==1: segs.append(l) l+=1 if r%2==1: r-=1 segs.append(r) l//=2 r//=2 return min(self.data[ind] for ind in segs) # find index of smallest value in data[l,r) def find_min(self,l,r): l += self.m r += self.m # apply all the lazily stored queries self.update(l) self.update(r-1) segs = [] while l<r: if l%2==1: segs.append(l) l+=1 if r%2==1: r-=1 segs.append(r) l//=2 r//=2 ind = min(segs, key=lambda i:self.data[i]) mini = self.data[ind] # dig down in search of mini while ind<self.m: self.push(ind) if self.data[2*ind]==mini: ind *= 2 else: ind = 2*ind+1 return ind-self.m,mini n,m = [int(x) for x in input().split()] A = [int(x) for x in input().split()] inter = [] inter2 = [] for _ in range(m): l,r = [int(x) for x in input().split()] l -= 1 inter.append((l,r)) inter2.append((r,l)) inter_copy = inter[:] inter.sort() inter2.sort() Aneg = super_seg([-a for a in A]) besta = -1 besta_ind = -1 j1 = 0 j2 = 0 for i in range(n): # Only segments containing i should be active # Activate while j1<m and inter[j1][0]<=i: l,r = inter[j1] Aneg.add(l,r,1) j1 += 1 # Deactivate while j2<m and inter2[j2][0]<=i: r,l = inter2[j2] Aneg.add(l,r,-1) j2 += 1 Amax = -Aneg.data[1] Ai = A[i]-(j1-j2) if Amax-Ai>besta: besta = Amax-Ai besta_ind = i ints = [i for i in range(m) if inter_copy[i][0]<=besta_ind<inter_copy[i][1]] print(besta) print(len(ints)) print(*[x+1 for x in ints]) ```
output
1
90,156
12
180,313
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions is a number of elements in the array. You are given an array a consisting of n integers. The value of the i-th element of the array is a_i. You are also given a set of m segments. The j-th segment is [l_j; r_j], where 1 ≀ l_j ≀ r_j ≀ n. You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array a = [0, 0, 0, 0, 0] and the given segments are [1; 3] and [2; 4] then you can choose both of them and the array will become b = [-1, -2, -2, -1, 0]. You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array a and obtain the array b then the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i will be maximum possible. Note that you can choose the empty set. If there are multiple answers, you can print any. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and m (1 ≀ n ≀ 10^5, 0 ≀ m ≀ 300) β€” the length of the array a and the number of segments, respectively. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^6 ≀ a_i ≀ 10^6), where a_i is the value of the i-th element of the array a. The next m lines are contain two integers each. The j-th of them contains two integers l_j and r_j (1 ≀ l_j ≀ r_j ≀ n), where l_j and r_j are the ends of the j-th segment. Output In the first line of the output print one integer d β€” the maximum possible value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i if b is the array obtained by applying some subset of the given segments to the array a. In the second line of the output print one integer q (0 ≀ q ≀ m) β€” the number of segments you apply. In the third line print q distinct integers c_1, c_2, ..., c_q in any order (1 ≀ c_k ≀ m) β€” indices of segments you apply to the array a in such a way that the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i of the obtained array b is maximum possible. If there are multiple answers, you can print any. Examples Input 5 4 2 -2 3 1 2 1 3 4 5 2 5 1 3 Output 6 2 4 1 Input 5 4 2 -2 3 1 4 3 5 3 4 2 4 2 5 Output 7 2 3 2 Input 1 0 1000000 Output 0 0 Note In the first example the obtained array b will be [0, -4, 1, 1, 2] so the answer is 6. In the second example the obtained array b will be [2, -3, 1, -1, 4] so the answer is 7. In the third example you cannot do anything so the answer is 0.
instruction
0
90,157
12
180,314
Tags: data structures, implementation Correct Solution: ``` def main(): n, m = map(int, input().split()) aa = list(map(int, input().split())) res = max(aa) - min(aa) ll, rr = [n + 1], [n + 1] segments = res_segments = [False] * (m + 1) bounds = {0, n, n + 1} for _ in range(m): l, r = map(int, input().split()) l -= 1 ll.append(l) rr.append(r) bounds.add(l) bounds.add(r) xlat = sorted(bounds) mi, ma = [], [] for l, r in zip(xlat, xlat[1:-1]): t = aa[l:r] mi.append(min(t)) ma.append(max(t)) bounds = {x: i for i, x in enumerate(xlat)} for xx in (ll, rr): for i, x in enumerate(xx): xx[i] = bounds[x] il, ir = (sorted(range(m + 1), key=xx.__getitem__, reverse=True) for xx in (ll, rr)) for i in range(len(xlat) - 1): while True: k = il[-1] lo = ll[k] if lo > i: break segments[k] = True for j in range(lo, rr[k]): mi[j] -= 1 ma[j] -= 1 del il[-1] x = max(ma) - min(mi) if res < x: res = x res_segments = segments[:] while True: k = ir[-1] hi = rr[k] if hi > i: break segments[k] = False for j in range(ll[k], hi): mi[j] += 1 ma[j] += 1 del ir[-1] print(res) segments = [i for i, f in enumerate(res_segments) if f] print(len(segments)) print(*segments) if __name__ == '__main__': main() ```
output
1
90,157
12
180,315
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions is a number of elements in the array. You are given an array a consisting of n integers. The value of the i-th element of the array is a_i. You are also given a set of m segments. The j-th segment is [l_j; r_j], where 1 ≀ l_j ≀ r_j ≀ n. You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array a = [0, 0, 0, 0, 0] and the given segments are [1; 3] and [2; 4] then you can choose both of them and the array will become b = [-1, -2, -2, -1, 0]. You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array a and obtain the array b then the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i will be maximum possible. Note that you can choose the empty set. If there are multiple answers, you can print any. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and m (1 ≀ n ≀ 10^5, 0 ≀ m ≀ 300) β€” the length of the array a and the number of segments, respectively. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^6 ≀ a_i ≀ 10^6), where a_i is the value of the i-th element of the array a. The next m lines are contain two integers each. The j-th of them contains two integers l_j and r_j (1 ≀ l_j ≀ r_j ≀ n), where l_j and r_j are the ends of the j-th segment. Output In the first line of the output print one integer d β€” the maximum possible value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i if b is the array obtained by applying some subset of the given segments to the array a. In the second line of the output print one integer q (0 ≀ q ≀ m) β€” the number of segments you apply. In the third line print q distinct integers c_1, c_2, ..., c_q in any order (1 ≀ c_k ≀ m) β€” indices of segments you apply to the array a in such a way that the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i of the obtained array b is maximum possible. If there are multiple answers, you can print any. Examples Input 5 4 2 -2 3 1 2 1 3 4 5 2 5 1 3 Output 6 2 4 1 Input 5 4 2 -2 3 1 4 3 5 3 4 2 4 2 5 Output 7 2 3 2 Input 1 0 1000000 Output 0 0 Note In the first example the obtained array b will be [0, -4, 1, 1, 2] so the answer is 6. In the second example the obtained array b will be [2, -3, 1, -1, 4] so the answer is 7. In the third example you cannot do anything so the answer is 0.
instruction
0
90,158
12
180,316
Tags: data structures, implementation Correct Solution: ``` from sys import stdin input=stdin.readline def f(a,b): # if max(a)<0 and min(a)<0: b=sorted(b,key=lambda s:s[1]-s[0]) t={} for i in range(len(a)): l=[] for j in b: if i in range(j[0],j[1]+1): l.append(j) t[i]=l t=dict(sorted(t.items(),key=lambda s:a[s[0]])) t=dict(sorted(t.items(),key=lambda s:len(s[1])-a[s[0]],reverse=True)) mn=list(t.items())[0] curr=max(a)-min(a) # print(mn) bigans=0 bigd=[] for mn in t.items(): s = a.copy() ans = [] a2 = [] for i in mn[1]: l=i[0] r=i[1] for j in range(l,r+1): s[j]-=1 # print(s) tempans=max(s)-min(s) # print("tempans",i[2],tempans,curr,s) # print(s,max(s),min(s),max(s)-min(s),i[2]+1) if tempans>=curr: a2.append(i[2]+1) ans+=a2 a2=[] else: a2.append(i[2]+1) curr=max(curr,tempans) if bigans<curr: bigans=curr bigd=ans else: break return bigd,bigans a,b=map(int,input().strip().split()) blacnk=[] lst=list(map(int,input().strip().split())) for i in range(b): l,r = map(int, input().strip().split()) blacnk.append([l-1,r-1,i]) x=f(lst,blacnk) print(x[1]) print(len(x[0])) print(*x[0]) ```
output
1
90,158
12
180,317
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions is a number of elements in the array. You are given an array a consisting of n integers. The value of the i-th element of the array is a_i. You are also given a set of m segments. The j-th segment is [l_j; r_j], where 1 ≀ l_j ≀ r_j ≀ n. You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array a = [0, 0, 0, 0, 0] and the given segments are [1; 3] and [2; 4] then you can choose both of them and the array will become b = [-1, -2, -2, -1, 0]. You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array a and obtain the array b then the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i will be maximum possible. Note that you can choose the empty set. If there are multiple answers, you can print any. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and m (1 ≀ n ≀ 10^5, 0 ≀ m ≀ 300) β€” the length of the array a and the number of segments, respectively. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^6 ≀ a_i ≀ 10^6), where a_i is the value of the i-th element of the array a. The next m lines are contain two integers each. The j-th of them contains two integers l_j and r_j (1 ≀ l_j ≀ r_j ≀ n), where l_j and r_j are the ends of the j-th segment. Output In the first line of the output print one integer d β€” the maximum possible value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i if b is the array obtained by applying some subset of the given segments to the array a. In the second line of the output print one integer q (0 ≀ q ≀ m) β€” the number of segments you apply. In the third line print q distinct integers c_1, c_2, ..., c_q in any order (1 ≀ c_k ≀ m) β€” indices of segments you apply to the array a in such a way that the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i of the obtained array b is maximum possible. If there are multiple answers, you can print any. Examples Input 5 4 2 -2 3 1 2 1 3 4 5 2 5 1 3 Output 6 2 4 1 Input 5 4 2 -2 3 1 4 3 5 3 4 2 4 2 5 Output 7 2 3 2 Input 1 0 1000000 Output 0 0 Note In the first example the obtained array b will be [0, -4, 1, 1, 2] so the answer is 6. In the second example the obtained array b will be [2, -3, 1, -1, 4] so the answer is 7. In the third example you cannot do anything so the answer is 0.
instruction
0
90,159
12
180,318
Tags: data structures, implementation Correct Solution: ``` from __future__ import division, print_function def main(): def f(a, b): # if max(a)<0 and min(a)<0: b = sorted(b, key=lambda s: s[1] - s[0]) t = {} for i in range(len(a)): l = [] for j in b: if i in range(j[0], j[1] + 1): l.append(j) t[i] = l t = dict(sorted(t.items(), key=lambda s: a[s[0]])) t = dict(sorted(t.items(), key=lambda s: len(s[1]) - a[s[0]], reverse=True)) mn = list(t.items())[0] curr = max(a) - min(a) # print(mn) bigans = 0 bigd = [] for mn in t.items(): s = a.copy() ans = [] a2 = [] for i in mn[1]: l = i[0] r = i[1] for j in range(l, r + 1): s[j] -= 1 # print(s) tempans = max(s) - min(s) # print("tempans",i[2],tempans,curr,s) # print(s,max(s),min(s),max(s)-min(s),i[2]+1) if tempans >= curr: a2.append(i[2] + 1) ans += a2 a2 = [] else: a2.append(i[2] + 1) curr = max(curr, tempans) if bigans < curr: bigans = curr bigd = ans else: break return bigd, bigans a, b = map(int, input().strip().split()) blacnk = [] lst = list(map(int, input().strip().split())) for i in range(b): l, r = map(int, input().strip().split()) blacnk.append([l - 1, r - 1, i]) x = f(lst, blacnk) print(x[1]) print(len(x[0])) print(*x[0]) ######## Python 2 and 3 footer by Pajenegod and c1729 # Note because cf runs old PyPy3 version which doesn't have the sped up # unicode strings, PyPy3 strings will many times be slower than pypy2. # There is a way to get around this by using binary strings in PyPy3 # but its syntax is different which makes it kind of a mess to use. # So on cf, use PyPy2 for best string performance. py2 = round(0.5) if py2: from future_builtins import ascii, filter, hex, map, oct, zip range = xrange import os, sys from io import IOBase, BytesIO BUFSIZE = 8192 class FastIO(BytesIO): newlines = 0 def __init__(self, file): self._file = file self._fd = file.fileno() self.writable = "x" in file.mode or "w" in file.mode self.write = super(FastIO, self).write if self.writable else None def _fill(self): s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0]) return s def read(self): while self._fill(): pass return super(FastIO,self).read() def readline(self): while self.newlines == 0: s = self._fill(); self.newlines = s.count(b"\n") + (not s) self.newlines -= 1 return super(FastIO, self).readline() def flush(self): if self.writable: os.write(self._fd, self.getvalue()) self.truncate(0), self.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable if py2: self.write = self.buffer.write self.read = self.buffer.read self.readline = self.buffer.readline else: self.write = lambda s:self.buffer.write(s.encode('ascii')) self.read = lambda:self.buffer.read().decode('ascii') self.readline = lambda:self.buffer.readline().decode('ascii') sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip('\r\n') # Cout implemented in Python import sys class ostream: def __lshift__(self,a): sys.stdout.write(str(a)) return self cout = ostream() endl = '\n' # Read all remaining integers in stdin, type is given by optional argument, this is fast def readnumbers(zero = 0): conv = ord if py2 else lambda x:x A = []; numb = zero; sign = 1; i = 0; s = sys.stdin.buffer.read() try: while True: if s[i] >= b'0' [0]: numb = 10 * numb + conv(s[i]) - 48 elif s[i] == b'-' [0]: sign = -1 elif s[i] != b'\r' [0]: A.append(sign*numb) numb = zero; sign = 1 i += 1 except:pass if s and s[-1] >= b'0' [0]: A.append(sign*numb) return A if __name__== "__main__": main() ```
output
1
90,159
12
180,319
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions is a number of elements in the array. You are given an array a consisting of n integers. The value of the i-th element of the array is a_i. You are also given a set of m segments. The j-th segment is [l_j; r_j], where 1 ≀ l_j ≀ r_j ≀ n. You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array a = [0, 0, 0, 0, 0] and the given segments are [1; 3] and [2; 4] then you can choose both of them and the array will become b = [-1, -2, -2, -1, 0]. You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array a and obtain the array b then the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i will be maximum possible. Note that you can choose the empty set. If there are multiple answers, you can print any. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and m (1 ≀ n ≀ 10^5, 0 ≀ m ≀ 300) β€” the length of the array a and the number of segments, respectively. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^6 ≀ a_i ≀ 10^6), where a_i is the value of the i-th element of the array a. The next m lines are contain two integers each. The j-th of them contains two integers l_j and r_j (1 ≀ l_j ≀ r_j ≀ n), where l_j and r_j are the ends of the j-th segment. Output In the first line of the output print one integer d β€” the maximum possible value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i if b is the array obtained by applying some subset of the given segments to the array a. In the second line of the output print one integer q (0 ≀ q ≀ m) β€” the number of segments you apply. In the third line print q distinct integers c_1, c_2, ..., c_q in any order (1 ≀ c_k ≀ m) β€” indices of segments you apply to the array a in such a way that the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i of the obtained array b is maximum possible. If there are multiple answers, you can print any. Examples Input 5 4 2 -2 3 1 2 1 3 4 5 2 5 1 3 Output 6 2 4 1 Input 5 4 2 -2 3 1 4 3 5 3 4 2 4 2 5 Output 7 2 3 2 Input 1 0 1000000 Output 0 0 Note In the first example the obtained array b will be [0, -4, 1, 1, 2] so the answer is 6. In the second example the obtained array b will be [2, -3, 1, -1, 4] so the answer is 7. In the third example you cannot do anything so the answer is 0.
instruction
0
90,160
12
180,320
Tags: data structures, implementation Correct Solution: ``` # ---------------------------iye ha aam zindegi--------------------------------------------- import math import random import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys #import threading from collections import defaultdict #threading.stack_size(10**8) mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase #sys.setrecursionlimit(300000) BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # -------------------game starts now----------------------------------------------------import math class TreeNode: def __init__(self, k, v): self.key = k self.value = v self.left = None self.right = None self.parent = None self.height = 1 self.num_left = 1 self.num_total = 1 class AvlTree: def __init__(self): self._tree = None def add(self, k, v): if not self._tree: self._tree = TreeNode(k, v) return node = self._add(k, v) if node: self._rebalance(node) def _add(self, k, v): node = self._tree while node: if k < node.key: if node.left: node = node.left else: node.left = TreeNode(k, v) node.left.parent = node return node.left elif node.key < k: if node.right: node = node.right else: node.right = TreeNode(k, v) node.right.parent = node return node.right else: node.value = v return @staticmethod def get_height(x): return x.height if x else 0 @staticmethod def get_num_total(x): return x.num_total if x else 0 def _rebalance(self, node): n = node while n: lh = self.get_height(n.left) rh = self.get_height(n.right) n.height = max(lh, rh) + 1 balance_factor = lh - rh n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right) n.num_left = 1 + self.get_num_total(n.left) if balance_factor > 1: if self.get_height(n.left.left) < self.get_height(n.left.right): self._rotate_left(n.left) self._rotate_right(n) elif balance_factor < -1: if self.get_height(n.right.right) < self.get_height(n.right.left): self._rotate_right(n.right) self._rotate_left(n) else: n = n.parent def _remove_one(self, node): """ Side effect!!! Changes node. Node should have exactly one child """ replacement = node.left or node.right if node.parent: if AvlTree._is_left(node): node.parent.left = replacement else: node.parent.right = replacement replacement.parent = node.parent node.parent = None else: self._tree = replacement replacement.parent = None node.left = None node.right = None node.parent = None self._rebalance(replacement) def _remove_leaf(self, node): if node.parent: if AvlTree._is_left(node): node.parent.left = None else: node.parent.right = None self._rebalance(node.parent) else: self._tree = None node.parent = None node.left = None node.right = None def remove(self, k): node = self._get_node(k) if not node: return if AvlTree._is_leaf(node): self._remove_leaf(node) return if node.left and node.right: nxt = AvlTree._get_next(node) node.key = nxt.key node.value = nxt.value if self._is_leaf(nxt): self._remove_leaf(nxt) else: self._remove_one(nxt) self._rebalance(node) else: self._remove_one(node) def get(self, k): node = self._get_node(k) return node.value if node else -1 def _get_node(self, k): if not self._tree: return None node = self._tree while node: if k < node.key: node = node.left elif node.key < k: node = node.right else: return node return None def get_at(self, pos): x = pos + 1 node = self._tree while node: if x < node.num_left: node = node.left elif node.num_left < x: x -= node.num_left node = node.right else: return (node.key, node.value) raise IndexError("Out of ranges") @staticmethod def _is_left(node): return node.parent.left and node.parent.left == node @staticmethod def _is_leaf(node): return node.left is None and node.right is None def _rotate_right(self, node): if not node.parent: self._tree = node.left node.left.parent = None elif AvlTree._is_left(node): node.parent.left = node.left node.left.parent = node.parent else: node.parent.right = node.left node.left.parent = node.parent bk = node.left.right node.left.right = node node.parent = node.left node.left = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) def _rotate_left(self, node): if not node.parent: self._tree = node.right node.right.parent = None elif AvlTree._is_left(node): node.parent.left = node.right node.right.parent = node.parent else: node.parent.right = node.right node.right.parent = node.parent bk = node.right.left node.right.left = node node.parent = node.right node.right = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) @staticmethod def _get_next(node): if not node.right: return node.parent n = node.right while n.left: n = n.left return n class SegmentTree2: def __init__(self, data, default=3000006, func=lambda a, b: min(a,b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default=10**10, func=lambda a, b: min(a , b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------game starts now----------------------------------------------------import math class SegmentTree: def __init__(self, data, default=0, func=lambda a, b:a + b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------------------iye ha chutiya zindegi------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD # --------------------------------------iye ha combinations ka zindegi--------------------------------- def powm(a, n, m): if a == 1 or n == 0: return 1 if n % 2 == 0: s = powm(a, n // 2, m) return s * s % m else: return a * powm(a, n - 1, m) % m # --------------------------------------iye ha power ka zindegi--------------------------------- def sort_list(list1, list2): zipped_pairs = zip(list2, list1) z = [x for _, x in sorted(zipped_pairs)] return z # --------------------------------------------------product---------------------------------------- def product(l): por = 1 for i in range(len(l)): por *= l[i] return por # --------------------------------------------------binary---------------------------------------- def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left) / 2) # Check if middle element is # less than or equal to key if (arr[mid] <key): count = mid + 1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # --------------------------------------------------binary---------------------------------------- def countdig(n): c = 0 while (n > 0): n //= 10 c += 1 return c def binary(x, length): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y def countGreater(arr, n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) if (arr[m] > k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) # --------------------------------------------------binary------------------------------------ class TrieNode: def __init__(self): self.children = [None] * 26 self.isEndOfWord = False class Trie: def __init__(self): self.root = self.getNode() def getNode(self): return TrieNode() def _charToIndex(self, ch): return ord(ch) - ord('a') def insert(self, key): pCrawl = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) if not pCrawl.children[index]: pCrawl.children[index] = self.getNode() pCrawl = pCrawl.children[index] pCrawl.isEndOfWord = True def search(self, key): pCrawl = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) if not pCrawl.children[index]: return False pCrawl = pCrawl.children[index] return pCrawl != None and pCrawl.isEndOfWord #-----------------------------------------trie--------------------------------- class Node: def __init__(self, data): self.data = data self.count=0 self.left = None # left node for 0 self.right = None # right node for 1 class BinaryTrie: def __init__(self): self.root = Node(0) def insert(self, pre_xor,t): self.temp = self.root for i in range(31, -1, -1): val = pre_xor & (1 << i) if val: if not self.temp.right: self.temp.right = Node(0) self.temp = self.temp.right self.temp.count+=t if not val: if not self.temp.left: self.temp.left = Node(0) self.temp = self.temp.left self.temp.count += t self.temp.data = pre_xor def query(self, p,l): ans=0 self.temp = self.root for i in range(31, -1, -1): val = p & (1 << i) val1= l & (1<<i) if val1==0: if val==0: if self.temp.left and self.temp.left.count>0: self.temp = self.temp.left else: return ans else: if self.temp.right and self.temp.right.count>0: self.temp = self.temp.right else: return ans else: if val !=0 : if self.temp.right: ans+=self.temp.right.count if self.temp.left and self.temp.left.count > 0: self.temp = self.temp.left else: return ans else: if self.temp.left: ans += self.temp.left.count if self.temp.right and self.temp.right.count > 0: self.temp = self.temp.right else: return ans return ans #-------------------------bin trie------------------------------------------- n,m=map(int,input().split()) l=list(map(int,input().split())) ma=max(l) d=defaultdict(list) d1=defaultdict(list) ans=[ma+m]*n ans1=[ma+m]*n we=[] for i in range(m): a,b=map(int,input().split()) we.append((a-1,b-1)) d[b-1].append(a-1) d1[a-1].append(b-1) e=l+[] for i in range(n): mi=e[i] ans[i]=mi if i>0: for j in d[i-1]: for k in range(j,i): e[k]-=1 mi=min(mi,e[k]) ans[i]=min(ans[i-1],mi) e=l+[] for i in range(n-1,-1,-1): mi=e[i] ans1[i]=mi if i<n-1: for j in d1[i+1]: for k in range(i+1,j+1): e[k]-=1 mi=min(mi,e[k]) ans1[i]=min(ans1[i+1],mi) fi=0 ind=-1 for i in range(n): if fi<l[i]-min(ans[i],ans1[i]): fi=l[i]-min(ans[i],ans1[i]) ind=i print(fi) awe=[] for i in range(m): if we[i][1]<ind or we[i][0]>ind: awe.append(i+1) print(len(awe)) print(*awe) ```
output
1
90,160
12
180,321
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions is a number of elements in the array. You are given an array a consisting of n integers. The value of the i-th element of the array is a_i. You are also given a set of m segments. The j-th segment is [l_j; r_j], where 1 ≀ l_j ≀ r_j ≀ n. You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array a = [0, 0, 0, 0, 0] and the given segments are [1; 3] and [2; 4] then you can choose both of them and the array will become b = [-1, -2, -2, -1, 0]. You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array a and obtain the array b then the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i will be maximum possible. Note that you can choose the empty set. If there are multiple answers, you can print any. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and m (1 ≀ n ≀ 10^5, 0 ≀ m ≀ 300) β€” the length of the array a and the number of segments, respectively. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^6 ≀ a_i ≀ 10^6), where a_i is the value of the i-th element of the array a. The next m lines are contain two integers each. The j-th of them contains two integers l_j and r_j (1 ≀ l_j ≀ r_j ≀ n), where l_j and r_j are the ends of the j-th segment. Output In the first line of the output print one integer d β€” the maximum possible value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i if b is the array obtained by applying some subset of the given segments to the array a. In the second line of the output print one integer q (0 ≀ q ≀ m) β€” the number of segments you apply. In the third line print q distinct integers c_1, c_2, ..., c_q in any order (1 ≀ c_k ≀ m) β€” indices of segments you apply to the array a in such a way that the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i of the obtained array b is maximum possible. If there are multiple answers, you can print any. Examples Input 5 4 2 -2 3 1 2 1 3 4 5 2 5 1 3 Output 6 2 4 1 Input 5 4 2 -2 3 1 4 3 5 3 4 2 4 2 5 Output 7 2 3 2 Input 1 0 1000000 Output 0 0 Note In the first example the obtained array b will be [0, -4, 1, 1, 2] so the answer is 6. In the second example the obtained array b will be [2, -3, 1, -1, 4] so the answer is 7. In the third example you cannot do anything so the answer is 0.
instruction
0
90,161
12
180,322
Tags: data structures, implementation Correct Solution: ``` # after solving E1 it was quite easy to come up with the idea of lazy segtree import sys # a very nice implementation of a minimum segment tree with # some inspiration taken from https://codeforces.com/blog/entry/18051 # this implementation should be able to be modified to do pretty # much anything one would want to do with segment trees apart from # persistance. # note that especially in python this implementation is much much better # than most other approches because how slow python can be with function # calls. /pajenegod # currently it allows for two operations, both running in o(log n), # 'add(l,r,value)' adds value to [l,r) # 'find_min(l,r)' finds the index with the smallest value big = 10**9 class super_seg: def __init__(self,data): n = len(data) m = 1 while m<n: m *= 2 self.n = n self.m = m self.data = [big]*(2*m) for i in range(n): self.data[i+m] = data[i] for i in reversed(range(m)): self.data[i] = min(self.data[2*i], self.data[2*i+1]) self.query = [0]*(2*m) # push the query on seg_ind to its children def push(self,seg_ind): # let the children know of the queries q = self.query[seg_ind] self.query[2*seg_ind] += q self.query[2*seg_ind+1] += q self.data[2*seg_ind] += q self.data[2*seg_ind+1] += q # remove queries from seg_ind self.data[seg_ind] = min(self.data[2*seg_ind],self.data[2*seg_ind+1]) self.query[seg_ind] = 0 # updates the node seg_ind to know of all queries # applied to it via its ancestors def update(self,seg_ind): # find all indecies to be updated seg_ind //= 2 inds = [] while seg_ind>0: inds.append(seg_ind) seg_ind//=2 # push the queries down the segment tree for ind in reversed(inds): self.push(ind) # make the changes to seg_ind be known to its ancestors def build(self,seg_ind): seg_ind//=2 while seg_ind>0: self.data[seg_ind] = min(self.data[2*seg_ind], self.data[2*seg_ind+1]) + self.query[seg_ind] seg_ind //= 2 # lazily add value to [l,r) def add(self,l,r,value): l += self.m r += self.m l0 = l r0 = r while l<r: if l%2==1: self.query[l]+= value self.data[l] += value l+=1 if r%2==1: r-=1 self.query[r]+= value self.data[r] += value l//=2 r//=2 # tell all nodes above of the updated # area of the updates self.build(l0) self.build(r0-1) # min of data[l,r) def min(self,l,r): l += self.m r += self.m # apply all the lazily stored queries self.update(l) self.update(r-1) segs = [] while l<r: if l%2==1: segs.append(l) l+=1 if r%2==1: r-=1 segs.append(r) l//=2 r//=2 return min(self.data[ind] for ind in segs) # find index of smallest value in data[l,r) def find_min(self,l,r): l += self.m r += self.m # apply all the lazily stored queries self.update(l) self.update(r-1) segs = [] while l<r: if l%2==1: segs.append(l) l+=1 if r%2==1: r-=1 segs.append(r) l//=2 r//=2 ind = min(segs, key=lambda i:self.data[i]) mini = self.data[ind] # dig down in search of mini while ind<self.m: self.push(ind) if self.data[2*ind]==mini: ind *= 2 else: ind = 2*ind+1 return ind-self.m,mini n,m = [int(x) for x in input().split()] A = [int(x) for x in input().split()] inter = [] update = [[] for _ in range(n+1)] for _ in range(m): l,r = [int(x) for x in input().split()] l -= 1 inter.append((l,r)) update[l].append((l,r)) update[r].append((l,r)) Aneg = super_seg([-a for a in A]) besta = -1 besta_ind = -1 active_intervals = 0 for i in range(n): for l,r in update[i]: Aneg.add(l,r,1 if l==i else -1) active_intervals += 1 if l==i else -1 Amax = -Aneg.data[1] Ai = A[i] - active_intervals if Amax-Ai>besta: besta = Amax-Ai besta_ind = i ints = [i for i in range(m) if inter[i][0]<=besta_ind<inter[i][1]] print(besta) print(len(ints)) print(*[x+1 for x in ints]) ```
output
1
90,161
12
180,323
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between easy and hard versions is a number of elements in the array. You are given an array a consisting of n integers. The value of the i-th element of the array is a_i. You are also given a set of m segments. The j-th segment is [l_j; r_j], where 1 ≀ l_j ≀ r_j ≀ n. You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array a = [0, 0, 0, 0, 0] and the given segments are [1; 3] and [2; 4] then you can choose both of them and the array will become b = [-1, -2, -2, -1, 0]. You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array a and obtain the array b then the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i will be maximum possible. Note that you can choose the empty set. If there are multiple answers, you can print any. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and m (1 ≀ n ≀ 10^5, 0 ≀ m ≀ 300) β€” the length of the array a and the number of segments, respectively. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^6 ≀ a_i ≀ 10^6), where a_i is the value of the i-th element of the array a. The next m lines are contain two integers each. The j-th of them contains two integers l_j and r_j (1 ≀ l_j ≀ r_j ≀ n), where l_j and r_j are the ends of the j-th segment. Output In the first line of the output print one integer d β€” the maximum possible value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i if b is the array obtained by applying some subset of the given segments to the array a. In the second line of the output print one integer q (0 ≀ q ≀ m) β€” the number of segments you apply. In the third line print q distinct integers c_1, c_2, ..., c_q in any order (1 ≀ c_k ≀ m) β€” indices of segments you apply to the array a in such a way that the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i of the obtained array b is maximum possible. If there are multiple answers, you can print any. Examples Input 5 4 2 -2 3 1 2 1 3 4 5 2 5 1 3 Output 6 2 4 1 Input 5 4 2 -2 3 1 4 3 5 3 4 2 4 2 5 Output 7 2 3 2 Input 1 0 1000000 Output 0 0 Note In the first example the obtained array b will be [0, -4, 1, 1, 2] so the answer is 6. In the second example the obtained array b will be [2, -3, 1, -1, 4] so the answer is 7. In the third example you cannot do anything so the answer is 0. Submitted Solution: ``` n, m = map(int, input().split()) mass = list(map(int, input().split())) lr = [] for t in range(m): l, r = map(int, input().split()) lr.append([l, r]) mq = 0 mdel = [] mitog = 0 m300 = [[-1, -10**6]] for i in range(max(0, m-1)): m300.append([-1, -10**6]) for u in range(len(mass)): if mass[u] > min(m300)[0]: m300[m300.index(min(m300))] = [u, mass[u]] for a, ma in m300: for b in range(len(mass)): mb = mass[b] q = 0 delete = [] itog = 0 for x in range(len(lr)): l, r = lr[x][0], lr[x][1] if l <= b+1 <= r and (a+1 < l or a+1 > r): q += 1 delete.append(x+1) itog = ma + q - mb if mitog < itog: mitog = itog mq = q mdel = delete print(mitog) print(mq) if len(mdel): print(' '.join(list(map(str, mdel)))) else: print('') ```
instruction
0
90,162
12
180,324
No
output
1
90,162
12
180,325
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between easy and hard versions is a number of elements in the array. You are given an array a consisting of n integers. The value of the i-th element of the array is a_i. You are also given a set of m segments. The j-th segment is [l_j; r_j], where 1 ≀ l_j ≀ r_j ≀ n. You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array a = [0, 0, 0, 0, 0] and the given segments are [1; 3] and [2; 4] then you can choose both of them and the array will become b = [-1, -2, -2, -1, 0]. You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array a and obtain the array b then the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i will be maximum possible. Note that you can choose the empty set. If there are multiple answers, you can print any. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and m (1 ≀ n ≀ 10^5, 0 ≀ m ≀ 300) β€” the length of the array a and the number of segments, respectively. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^6 ≀ a_i ≀ 10^6), where a_i is the value of the i-th element of the array a. The next m lines are contain two integers each. The j-th of them contains two integers l_j and r_j (1 ≀ l_j ≀ r_j ≀ n), where l_j and r_j are the ends of the j-th segment. Output In the first line of the output print one integer d β€” the maximum possible value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i if b is the array obtained by applying some subset of the given segments to the array a. In the second line of the output print one integer q (0 ≀ q ≀ m) β€” the number of segments you apply. In the third line print q distinct integers c_1, c_2, ..., c_q in any order (1 ≀ c_k ≀ m) β€” indices of segments you apply to the array a in such a way that the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i of the obtained array b is maximum possible. If there are multiple answers, you can print any. Examples Input 5 4 2 -2 3 1 2 1 3 4 5 2 5 1 3 Output 6 2 4 1 Input 5 4 2 -2 3 1 4 3 5 3 4 2 4 2 5 Output 7 2 3 2 Input 1 0 1000000 Output 0 0 Note In the first example the obtained array b will be [0, -4, 1, 1, 2] so the answer is 6. In the second example the obtained array b will be [2, -3, 1, -1, 4] so the answer is 7. In the third example you cannot do anything so the answer is 0. Submitted Solution: ``` n, m = map(int, input().split()) mass = list(map(int, input().split())) if n > 300: lr = [] for t in range(m): l, r = map(int, input().split()) lr.append([l, r]) mq = 0 mdel = [] mitog = 0 m300 = [[-1, -10**6]] for i in range(max(0, m)): m300.append([-1, -10**6]) for u in range(n): if mass[u] > min(m300)[0]: m300[m300.index(min(m300))] = [u, mass[u]] for a, ma in m300: for b in range(len(mass)): mb = mass[b] q = 0 delete = [] itog = 0 for x in range(len(lr)): l, r = lr[x][0], lr[x][1] if l <= b+1 <= r and (a+1 < l or a+1 > r): q += 1 delete.append(x+1) itog = ma + q - mb if mitog < itog: mitog = itog mq = q mdel = delete print(mitog) print(mq) if len(mdel): print(' '.join(list(map(str, mdel)))) else: print('') else: lr = [] for t in range(m): l, r = map(int, input().split()) lr.append([l, r]) mq = 0 mdel = [] mitog = 0 for a in range(len(mass)): ma = mass[a] for b in range(len(mass)): mb = mass[b] q = 0 delete = [] itog = 0 for x in range(len(lr)): l, r = lr[x][0], lr[x][1] if l <= b + 1 <= r and (a + 1 < l or a + 1 > r): q += 1 delete.append(x + 1) itog = ma + q - mb if mitog < itog: mitog = itog mq = q mdel = delete print(mitog) print(mq) if len(mdel): print(' '.join(list(map(str, mdel)))) else: print('') ```
instruction
0
90,163
12
180,326
No
output
1
90,163
12
180,327
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between easy and hard versions is a number of elements in the array. You are given an array a consisting of n integers. The value of the i-th element of the array is a_i. You are also given a set of m segments. The j-th segment is [l_j; r_j], where 1 ≀ l_j ≀ r_j ≀ n. You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array a = [0, 0, 0, 0, 0] and the given segments are [1; 3] and [2; 4] then you can choose both of them and the array will become b = [-1, -2, -2, -1, 0]. You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array a and obtain the array b then the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i will be maximum possible. Note that you can choose the empty set. If there are multiple answers, you can print any. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and m (1 ≀ n ≀ 10^5, 0 ≀ m ≀ 300) β€” the length of the array a and the number of segments, respectively. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^6 ≀ a_i ≀ 10^6), where a_i is the value of the i-th element of the array a. The next m lines are contain two integers each. The j-th of them contains two integers l_j and r_j (1 ≀ l_j ≀ r_j ≀ n), where l_j and r_j are the ends of the j-th segment. Output In the first line of the output print one integer d β€” the maximum possible value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i if b is the array obtained by applying some subset of the given segments to the array a. In the second line of the output print one integer q (0 ≀ q ≀ m) β€” the number of segments you apply. In the third line print q distinct integers c_1, c_2, ..., c_q in any order (1 ≀ c_k ≀ m) β€” indices of segments you apply to the array a in such a way that the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i of the obtained array b is maximum possible. If there are multiple answers, you can print any. Examples Input 5 4 2 -2 3 1 2 1 3 4 5 2 5 1 3 Output 6 2 4 1 Input 5 4 2 -2 3 1 4 3 5 3 4 2 4 2 5 Output 7 2 3 2 Input 1 0 1000000 Output 0 0 Note In the first example the obtained array b will be [0, -4, 1, 1, 2] so the answer is 6. In the second example the obtained array b will be [2, -3, 1, -1, 4] so the answer is 7. In the third example you cannot do anything so the answer is 0. Submitted Solution: ``` n, m = list(map(int, input().split())) A = list(map(int, input().split())) if n > 300: lst = [] for i in range(m): a, b = list(map(int, input().split())) lst.append([a, b]) answer = 0 answer_1 = [] m300 = [[-1, -10**6]] for i in range(max(0, m-1)): m300.append([-1, -10**6]) for u in range(n): if A[u] > min(m300)[1]: m300[m300.index(min(m300))] = [u, A[u]] for i, mi in m300: B = A.copy() kek = [] for j in range(m): a, b = lst[j][0], lst[j][1] if a <= i + 1 <= b: kek.append(j + 1) for q in range(a - 1, b): B[q] -= 1 elem = max(B) if answer < elem - mi: answer = elem - mi answer_1 = kek.copy() print(answer) print(len(answer_1)) print(' '.join(map(str, answer_1))) else: lst = [] for i in range(m): a, b = list(map(int, input().split())) lst.append([a, b]) answer = 0 answer_1 = [] for i in range(n): B = A.copy() kek = [] for j in range(m): a, b = lst[j][0], lst[j][1] if a <= i + 1 <= b: kek.append(j + 1) for q in range(a - 1, b): B[q] -= 1 elem = max(B) if answer < elem - B[i]: answer = elem - B[i] answer_1 = kek.copy() print(answer) print(len(answer_1)) print(' '.join(map(str, answer_1))) ```
instruction
0
90,164
12
180,328
No
output
1
90,164
12
180,329
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between easy and hard versions is a number of elements in the array. You are given an array a consisting of n integers. The value of the i-th element of the array is a_i. You are also given a set of m segments. The j-th segment is [l_j; r_j], where 1 ≀ l_j ≀ r_j ≀ n. You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array a = [0, 0, 0, 0, 0] and the given segments are [1; 3] and [2; 4] then you can choose both of them and the array will become b = [-1, -2, -2, -1, 0]. You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array a and obtain the array b then the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i will be maximum possible. Note that you can choose the empty set. If there are multiple answers, you can print any. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and m (1 ≀ n ≀ 10^5, 0 ≀ m ≀ 300) β€” the length of the array a and the number of segments, respectively. The second line of the input contains n integers a_1, a_2, ..., a_n (-10^6 ≀ a_i ≀ 10^6), where a_i is the value of the i-th element of the array a. The next m lines are contain two integers each. The j-th of them contains two integers l_j and r_j (1 ≀ l_j ≀ r_j ≀ n), where l_j and r_j are the ends of the j-th segment. Output In the first line of the output print one integer d β€” the maximum possible value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i if b is the array obtained by applying some subset of the given segments to the array a. In the second line of the output print one integer q (0 ≀ q ≀ m) β€” the number of segments you apply. In the third line print q distinct integers c_1, c_2, ..., c_q in any order (1 ≀ c_k ≀ m) β€” indices of segments you apply to the array a in such a way that the value max_{i=1}^{n}b_i - min_{i=1}^{n}b_i of the obtained array b is maximum possible. If there are multiple answers, you can print any. Examples Input 5 4 2 -2 3 1 2 1 3 4 5 2 5 1 3 Output 6 2 4 1 Input 5 4 2 -2 3 1 4 3 5 3 4 2 4 2 5 Output 7 2 3 2 Input 1 0 1000000 Output 0 0 Note In the first example the obtained array b will be [0, -4, 1, 1, 2] so the answer is 6. In the second example the obtained array b will be [2, -3, 1, -1, 4] so the answer is 7. In the third example you cannot do anything so the answer is 0. Submitted Solution: ``` # ---------------------------iye ha aam zindegi--------------------------------------------- import math import random import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys #import threading from collections import defaultdict #threading.stack_size(10**8) mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase #sys.setrecursionlimit(300000) BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # -------------------game starts now----------------------------------------------------import math class TreeNode: def __init__(self, k, v): self.key = k self.value = v self.left = None self.right = None self.parent = None self.height = 1 self.num_left = 1 self.num_total = 1 class AvlTree: def __init__(self): self._tree = None def add(self, k, v): if not self._tree: self._tree = TreeNode(k, v) return node = self._add(k, v) if node: self._rebalance(node) def _add(self, k, v): node = self._tree while node: if k < node.key: if node.left: node = node.left else: node.left = TreeNode(k, v) node.left.parent = node return node.left elif node.key < k: if node.right: node = node.right else: node.right = TreeNode(k, v) node.right.parent = node return node.right else: node.value = v return @staticmethod def get_height(x): return x.height if x else 0 @staticmethod def get_num_total(x): return x.num_total if x else 0 def _rebalance(self, node): n = node while n: lh = self.get_height(n.left) rh = self.get_height(n.right) n.height = max(lh, rh) + 1 balance_factor = lh - rh n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right) n.num_left = 1 + self.get_num_total(n.left) if balance_factor > 1: if self.get_height(n.left.left) < self.get_height(n.left.right): self._rotate_left(n.left) self._rotate_right(n) elif balance_factor < -1: if self.get_height(n.right.right) < self.get_height(n.right.left): self._rotate_right(n.right) self._rotate_left(n) else: n = n.parent def _remove_one(self, node): """ Side effect!!! Changes node. Node should have exactly one child """ replacement = node.left or node.right if node.parent: if AvlTree._is_left(node): node.parent.left = replacement else: node.parent.right = replacement replacement.parent = node.parent node.parent = None else: self._tree = replacement replacement.parent = None node.left = None node.right = None node.parent = None self._rebalance(replacement) def _remove_leaf(self, node): if node.parent: if AvlTree._is_left(node): node.parent.left = None else: node.parent.right = None self._rebalance(node.parent) else: self._tree = None node.parent = None node.left = None node.right = None def remove(self, k): node = self._get_node(k) if not node: return if AvlTree._is_leaf(node): self._remove_leaf(node) return if node.left and node.right: nxt = AvlTree._get_next(node) node.key = nxt.key node.value = nxt.value if self._is_leaf(nxt): self._remove_leaf(nxt) else: self._remove_one(nxt) self._rebalance(node) else: self._remove_one(node) def get(self, k): node = self._get_node(k) return node.value if node else -1 def _get_node(self, k): if not self._tree: return None node = self._tree while node: if k < node.key: node = node.left elif node.key < k: node = node.right else: return node return None def get_at(self, pos): x = pos + 1 node = self._tree while node: if x < node.num_left: node = node.left elif node.num_left < x: x -= node.num_left node = node.right else: return (node.key, node.value) raise IndexError("Out of ranges") @staticmethod def _is_left(node): return node.parent.left and node.parent.left == node @staticmethod def _is_leaf(node): return node.left is None and node.right is None def _rotate_right(self, node): if not node.parent: self._tree = node.left node.left.parent = None elif AvlTree._is_left(node): node.parent.left = node.left node.left.parent = node.parent else: node.parent.right = node.left node.left.parent = node.parent bk = node.left.right node.left.right = node node.parent = node.left node.left = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) def _rotate_left(self, node): if not node.parent: self._tree = node.right node.right.parent = None elif AvlTree._is_left(node): node.parent.left = node.right node.right.parent = node.parent else: node.parent.right = node.right node.right.parent = node.parent bk = node.right.left node.right.left = node node.parent = node.right node.right = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) @staticmethod def _get_next(node): if not node.right: return node.parent n = node.right while n.left: n = n.left return n # -----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default=300006, func=lambda a, b: min(a , b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------game starts now----------------------------------------------------import math class SegmentTree: def __init__(self, data, default=0, func=lambda a, b:a + b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------------------iye ha chutiya zindegi------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD # --------------------------------------iye ha combinations ka zindegi--------------------------------- def powm(a, n, m): if a == 1 or n == 0: return 1 if n % 2 == 0: s = powm(a, n // 2, m) return s * s % m else: return a * powm(a, n - 1, m) % m # --------------------------------------iye ha power ka zindegi--------------------------------- def sort_list(list1, list2): zipped_pairs = zip(list2, list1) z = [x for _, x in sorted(zipped_pairs)] return z # --------------------------------------------------product---------------------------------------- def product(l): por = 1 for i in range(len(l)): por *= l[i] return por # --------------------------------------------------binary---------------------------------------- def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left) / 2) # Check if middle element is # less than or equal to key if (arr[mid] <=key): count = mid + 1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # --------------------------------------------------binary---------------------------------------- def countdig(n): c = 0 while (n > 0): n //= 10 c += 1 return c def binary(x, length): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y def countGreater(arr, n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) if (arr[m] >= k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) # --------------------------------------------------binary------------------------------------ class TrieNode: def __init__(self): self.children = [None] * 26 self.isEndOfWord = False class Trie: def __init__(self): self.root = self.getNode() def getNode(self): return TrieNode() def _charToIndex(self, ch): return ord(ch) - ord('a') def insert(self, key): pCrawl = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) if not pCrawl.children[index]: pCrawl.children[index] = self.getNode() pCrawl = pCrawl.children[index] pCrawl.isEndOfWord = True def search(self, key): pCrawl = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) if not pCrawl.children[index]: return False pCrawl = pCrawl.children[index] return pCrawl != None and pCrawl.isEndOfWord #-----------------------------------------trie--------------------------------- class Node: def __init__(self, data): self.data = data self.height=0 self.left = None # left node for 0 self.right = None # right node for 1 class BinaryTrie: def __init__(self): self.root = Node(0) def insert(self, pre_xor): self.temp = self.root for i in range(31, -1, -1): val = pre_xor & (1 << i) if val==0: if not self.temp.right: self.temp.right = Node(0) self.temp = self.temp.right elif val>=1: if not self.temp.left: self.temp.left = Node(0) self.temp = self.temp.left def do(self,temp): if not temp: return 0 ter=temp temp.height=self.do(ter.left)+self.do(ter.right) if temp.height==0: temp.height+=1 return temp.height def query(self, xor): self.temp = self.root cur=0 i=31 while(i>-1): val = xor & (1 << i) if not self.temp: return cur if val>=1: self.opp = self.temp.right if self.temp.left: self.temp = self.temp.left else: return cur else: self.opp=self.temp.left if self.temp.right: self.temp = self.temp.right else: return cur if self.temp.height==pow(2,i): cur+=1<<(i) self.temp=self.opp i-=1 return cur #-------------------------bin trie------------------------------------------- n,m=map(int,input().split()) l=list(map(int,input().split())) mi=min(l) ans=0 fi=[] for i1 in range(m): a,b=map(int,input().split()) f=0 for i in range(a,b+1): if l[i-1]==mi: mi-=1 f=1 break if f==1: for i in range(a,b+1): l[i-1]-=1 ans+=1 fi.append(i1+1) print(max(l)-mi) print(ans) print(*fi) ```
instruction
0
90,165
12
180,330
No
output
1
90,165
12
180,331
Provide tags and a correct Python 3 solution for this coding contest problem. Bob is an avid fan of the video game "League of Leesins", and today he celebrates as the League of Leesins World Championship comes to an end! The tournament consisted of n (n β‰₯ 5) teams around the world. Before the tournament starts, Bob has made a prediction of the rankings of each team, from 1-st to n-th. After the final, he compared the prediction with the actual result and found out that the i-th team according to his prediction ended up at the p_i-th position (1 ≀ p_i ≀ n, all p_i are unique). In other words, p is a permutation of 1, 2, ..., n. As Bob's favorite League player is the famous "3ga", he decided to write down every 3 consecutive elements of the permutation p. Formally, Bob created an array q of n-2 triples, where q_i = (p_i, p_{i+1}, p_{i+2}) for each 1 ≀ i ≀ n-2. Bob was very proud of his array, so he showed it to his friend Alice. After learning of Bob's array, Alice declared that she could retrieve the permutation p even if Bob rearranges the elements of q and the elements within each triple. Of course, Bob did not believe in such magic, so he did just the same as above to see Alice's respond. For example, if n = 5 and p = [1, 4, 2, 3, 5], then the original array q will be [(1, 4, 2), (4, 2, 3), (2, 3, 5)]. Bob can then rearrange the numbers within each triple and the positions of the triples to get [(4, 3, 2), (2, 3, 5), (4, 1, 2)]. Note that [(1, 4, 2), (4, 2, 2), (3, 3, 5)] is not a valid rearrangement of q, as Bob is not allowed to swap numbers belong to different triples. As Alice's friend, you know for sure that Alice was just trying to show off, so you decided to save her some face by giving her any permutation p that is consistent with the array q she was given. Input The first line contains a single integer n (5 ≀ n ≀ 10^5) β€” the size of permutation p. The i-th of the next n-2 lines contains 3 integers q_{i, 1}, q_{i, 2}, q_{i, 3} (1 ≀ q_{i, j} ≀ n) β€” the elements of the i-th triple of the rearranged (shuffled) array q_i, in random order. Remember, that the numbers within each triple can be rearranged and also the positions of the triples can be rearranged. It is guaranteed that there is at least one permutation p that is consistent with the input. Output Print n distinct integers p_1, p_2, …, p_n (1 ≀ p_i ≀ n) such that p is consistent with array q. If there are multiple answers, print any. Example Input 5 4 3 2 2 3 5 4 1 2 Output 1 4 2 3 5
instruction
0
90,242
12
180,484
Tags: constructive algorithms, implementation Correct Solution: ``` from collections import defaultdict def Fir3(): global final,d,ones for i in d[ones]: x,y= i if len(d[i[0]])==2 else i[::-1] final.extend([x,y]) if (ones,y) in d[x]:d[x].remove((ones,y)) else:d[x].remove((y,ones)) if (ones,x) in d[y]:d[y].remove((ones,x)) else:d[y].remove((x,ones)) n = int(input()) l=[] d = defaultdict(list) items=[] for i in range(n-2): v1,v2,v3=map(int,input().split()) l.append((v1,v2,v3)) d[v1].append((v2, v3)) d[v2].append((v1, v3)) d[v3].append((v2, v1)) ones=0 for i in range(1,n+1): if len(d[i])==1: ones=i break final = [ones] Fir3() for i in range(1,n-2): x,y = final[i],final[i+1] for j in d[x]: z = j[0] if j[1]==y else j[1] final.append(z) if (x,y) in d[z]:d[z].remove((x,y)) else:d[z].remove((y,x)) if (x,z) in d[y]:d[y].remove((x,z)) else:d[y].remove((z,x)) print(*final) ```
output
1
90,242
12
180,485
Provide tags and a correct Python 3 solution for this coding contest problem. Bob is an avid fan of the video game "League of Leesins", and today he celebrates as the League of Leesins World Championship comes to an end! The tournament consisted of n (n β‰₯ 5) teams around the world. Before the tournament starts, Bob has made a prediction of the rankings of each team, from 1-st to n-th. After the final, he compared the prediction with the actual result and found out that the i-th team according to his prediction ended up at the p_i-th position (1 ≀ p_i ≀ n, all p_i are unique). In other words, p is a permutation of 1, 2, ..., n. As Bob's favorite League player is the famous "3ga", he decided to write down every 3 consecutive elements of the permutation p. Formally, Bob created an array q of n-2 triples, where q_i = (p_i, p_{i+1}, p_{i+2}) for each 1 ≀ i ≀ n-2. Bob was very proud of his array, so he showed it to his friend Alice. After learning of Bob's array, Alice declared that she could retrieve the permutation p even if Bob rearranges the elements of q and the elements within each triple. Of course, Bob did not believe in such magic, so he did just the same as above to see Alice's respond. For example, if n = 5 and p = [1, 4, 2, 3, 5], then the original array q will be [(1, 4, 2), (4, 2, 3), (2, 3, 5)]. Bob can then rearrange the numbers within each triple and the positions of the triples to get [(4, 3, 2), (2, 3, 5), (4, 1, 2)]. Note that [(1, 4, 2), (4, 2, 2), (3, 3, 5)] is not a valid rearrangement of q, as Bob is not allowed to swap numbers belong to different triples. As Alice's friend, you know for sure that Alice was just trying to show off, so you decided to save her some face by giving her any permutation p that is consistent with the array q she was given. Input The first line contains a single integer n (5 ≀ n ≀ 10^5) β€” the size of permutation p. The i-th of the next n-2 lines contains 3 integers q_{i, 1}, q_{i, 2}, q_{i, 3} (1 ≀ q_{i, j} ≀ n) β€” the elements of the i-th triple of the rearranged (shuffled) array q_i, in random order. Remember, that the numbers within each triple can be rearranged and also the positions of the triples can be rearranged. It is guaranteed that there is at least one permutation p that is consistent with the input. Output Print n distinct integers p_1, p_2, …, p_n (1 ≀ p_i ≀ n) such that p is consistent with array q. If there are multiple answers, print any. Example Input 5 4 3 2 2 3 5 4 1 2 Output 1 4 2 3 5
instruction
0
90,243
12
180,486
Tags: constructive algorithms, implementation Correct Solution: ``` n = int(input()) trip = {} cnt = [0] * (n + 1) for i in range(n - 2): p1, p2, p3 = sorted(map(int, input().split())) if (p1, p2) in trip: trip[(p1, p2)].append(p3) else: trip[(p1, p2)] = [p3] if (p1, p3) in trip: trip[(p1, p3)].append(p2) else: trip[(p1, p3)] = [p2] if (p2, p3) in trip: trip[(p2, p3)].append(p1) else: trip[(p2, p3)] = [p1] cnt[p1] += 1 cnt[p2] += 1 cnt[p3] += 1 start = min(range(1, n + 1), key=lambda x: cnt[x]) answer = [start] for pr in trip: pr = (pr, trip[pr]) if start in pr[1]: if cnt[pr[0][1]] == 2: answer.append(pr[0][1]) answer.append(pr[0][0]) else: answer.append(pr[0][0]) answer.append(pr[0][1]) was = [False] * (n + 1) was[answer[0]] = was[answer[1]] = was[answer[2]] = True cur = answer[1:] #print(trip) for i in range(n - 3): mp = tuple(cur) if mp not in trip: mp = tuple(reversed(mp)) val = trip[mp] if not was[val[0]]: answer.append(val[0]) was[val[0]] = True cur = [cur[1], val[0]] elif len(val) > 1: answer.append(val[1]) was[val[1]] = True cur = [cur[1], val[1]] print(' '.join(map(str, answer))) ```
output
1
90,243
12
180,487
Provide tags and a correct Python 3 solution for this coding contest problem. Bob is an avid fan of the video game "League of Leesins", and today he celebrates as the League of Leesins World Championship comes to an end! The tournament consisted of n (n β‰₯ 5) teams around the world. Before the tournament starts, Bob has made a prediction of the rankings of each team, from 1-st to n-th. After the final, he compared the prediction with the actual result and found out that the i-th team according to his prediction ended up at the p_i-th position (1 ≀ p_i ≀ n, all p_i are unique). In other words, p is a permutation of 1, 2, ..., n. As Bob's favorite League player is the famous "3ga", he decided to write down every 3 consecutive elements of the permutation p. Formally, Bob created an array q of n-2 triples, where q_i = (p_i, p_{i+1}, p_{i+2}) for each 1 ≀ i ≀ n-2. Bob was very proud of his array, so he showed it to his friend Alice. After learning of Bob's array, Alice declared that she could retrieve the permutation p even if Bob rearranges the elements of q and the elements within each triple. Of course, Bob did not believe in such magic, so he did just the same as above to see Alice's respond. For example, if n = 5 and p = [1, 4, 2, 3, 5], then the original array q will be [(1, 4, 2), (4, 2, 3), (2, 3, 5)]. Bob can then rearrange the numbers within each triple and the positions of the triples to get [(4, 3, 2), (2, 3, 5), (4, 1, 2)]. Note that [(1, 4, 2), (4, 2, 2), (3, 3, 5)] is not a valid rearrangement of q, as Bob is not allowed to swap numbers belong to different triples. As Alice's friend, you know for sure that Alice was just trying to show off, so you decided to save her some face by giving her any permutation p that is consistent with the array q she was given. Input The first line contains a single integer n (5 ≀ n ≀ 10^5) β€” the size of permutation p. The i-th of the next n-2 lines contains 3 integers q_{i, 1}, q_{i, 2}, q_{i, 3} (1 ≀ q_{i, j} ≀ n) β€” the elements of the i-th triple of the rearranged (shuffled) array q_i, in random order. Remember, that the numbers within each triple can be rearranged and also the positions of the triples can be rearranged. It is guaranteed that there is at least one permutation p that is consistent with the input. Output Print n distinct integers p_1, p_2, …, p_n (1 ≀ p_i ≀ n) such that p is consistent with array q. If there are multiple answers, print any. Example Input 5 4 3 2 2 3 5 4 1 2 Output 1 4 2 3 5
instruction
0
90,244
12
180,488
Tags: constructive algorithms, implementation Correct Solution: ``` import sys from functools import lru_cache, cmp_to_key from heapq import merge, heapify, heappop, heappush from math import * from collections import defaultdict as dd, deque, Counter as C from itertools import combinations as comb, permutations as perm from bisect import bisect_left as bl, bisect_right as br, bisect from time import perf_counter from fractions import Fraction # sys.setrecursionlimit(int(pow(10, 2))) # sys.stdin = open("input.txt", "r") # sys.stdout = open("output.txt", "w") mod = int(pow(10, 9) + 7) mod2 = 998244353 def data(): return sys.stdin.readline().strip() def out(*var, end="\n"): sys.stdout.write(' '.join(map(str, var))+end) def l(): return list(sp()) def sl(): return list(ssp()) def sp(): return map(int, data().split()) def ssp(): return map(str, data().split()) def l1d(n, val=0): return [val for i in range(n)] def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)] # @lru_cache(None) for _ in range(1): n=l()[0] A=[l() for i in range(n-2)] d={} for i in range(n-2): for k in A[i]: if(k not in d): d[k]=[] d[k].append(A[i]) for i in range(n): if(len(d[i+1])==1): start=i+1 break for i in range(n): if(len(d[i+1])==2 and (start in d[i+1][0] or start in d[i+1][1])): mid=i+1 ans=[start,mid] for x in d[start][0]: if(x not in ans): ans.append(x) break curr=x for i in range(n-3): # print(curr) # print(d[curr]) for ele in d[curr]: if(ans[-1] in ele and ans[-2] in ele and ans[-3] not in ele): # print(ele) ans.append(sum(ele)-ans[-1]-ans[-2]) curr=ans[-1] # print("Update",curr) break print(*ans) ```
output
1
90,244
12
180,489
Provide tags and a correct Python 3 solution for this coding contest problem. Bob is an avid fan of the video game "League of Leesins", and today he celebrates as the League of Leesins World Championship comes to an end! The tournament consisted of n (n β‰₯ 5) teams around the world. Before the tournament starts, Bob has made a prediction of the rankings of each team, from 1-st to n-th. After the final, he compared the prediction with the actual result and found out that the i-th team according to his prediction ended up at the p_i-th position (1 ≀ p_i ≀ n, all p_i are unique). In other words, p is a permutation of 1, 2, ..., n. As Bob's favorite League player is the famous "3ga", he decided to write down every 3 consecutive elements of the permutation p. Formally, Bob created an array q of n-2 triples, where q_i = (p_i, p_{i+1}, p_{i+2}) for each 1 ≀ i ≀ n-2. Bob was very proud of his array, so he showed it to his friend Alice. After learning of Bob's array, Alice declared that she could retrieve the permutation p even if Bob rearranges the elements of q and the elements within each triple. Of course, Bob did not believe in such magic, so he did just the same as above to see Alice's respond. For example, if n = 5 and p = [1, 4, 2, 3, 5], then the original array q will be [(1, 4, 2), (4, 2, 3), (2, 3, 5)]. Bob can then rearrange the numbers within each triple and the positions of the triples to get [(4, 3, 2), (2, 3, 5), (4, 1, 2)]. Note that [(1, 4, 2), (4, 2, 2), (3, 3, 5)] is not a valid rearrangement of q, as Bob is not allowed to swap numbers belong to different triples. As Alice's friend, you know for sure that Alice was just trying to show off, so you decided to save her some face by giving her any permutation p that is consistent with the array q she was given. Input The first line contains a single integer n (5 ≀ n ≀ 10^5) β€” the size of permutation p. The i-th of the next n-2 lines contains 3 integers q_{i, 1}, q_{i, 2}, q_{i, 3} (1 ≀ q_{i, j} ≀ n) β€” the elements of the i-th triple of the rearranged (shuffled) array q_i, in random order. Remember, that the numbers within each triple can be rearranged and also the positions of the triples can be rearranged. It is guaranteed that there is at least one permutation p that is consistent with the input. Output Print n distinct integers p_1, p_2, …, p_n (1 ≀ p_i ≀ n) such that p is consistent with array q. If there are multiple answers, print any. Example Input 5 4 3 2 2 3 5 4 1 2 Output 1 4 2 3 5
instruction
0
90,245
12
180,490
Tags: constructive algorithms, implementation Correct Solution: ``` import sys input = sys.stdin.readline n = int(input()) adj_list = [[] for _ in range(n)] for _ in range(n-2): q1, q2, q3 = map(int, input().split()) adj_list[q1-1].append(q2-1) adj_list[q1-1].append(q3-1) adj_list[q2-1].append(q3-1) adj_list[q2-1].append(q1-1) adj_list[q3-1].append(q1-1) adj_list[q3-1].append(q2-1) for i in range(n): adj_list[i] = list(set(adj_list[i])) for i in range(n): if len(adj_list[i])==2: start = i break ans = [start] n1 = adj_list[start][0] n2 = adj_list[start][1] if len(adj_list[n1])==3: ans.append(n1) else: ans.append(n2) for i in range(2, n): n1 = ans[i-2] n2 = ans[i-1] s1 = set(adj_list[n1]) s2 = set(adj_list[n2]) s3 = s1&s2 #print(i, n1, n2) if i>=3: s3.remove(ans[i-3]) #print(n1, adj_list[n1], n2, adj_list[n2], s3) ans.append(list(s3)[0]) #print(ans) ans2 = [ai+1 for ai in ans] print(*ans2) ```
output
1
90,245
12
180,491
Provide tags and a correct Python 3 solution for this coding contest problem. Bob is an avid fan of the video game "League of Leesins", and today he celebrates as the League of Leesins World Championship comes to an end! The tournament consisted of n (n β‰₯ 5) teams around the world. Before the tournament starts, Bob has made a prediction of the rankings of each team, from 1-st to n-th. After the final, he compared the prediction with the actual result and found out that the i-th team according to his prediction ended up at the p_i-th position (1 ≀ p_i ≀ n, all p_i are unique). In other words, p is a permutation of 1, 2, ..., n. As Bob's favorite League player is the famous "3ga", he decided to write down every 3 consecutive elements of the permutation p. Formally, Bob created an array q of n-2 triples, where q_i = (p_i, p_{i+1}, p_{i+2}) for each 1 ≀ i ≀ n-2. Bob was very proud of his array, so he showed it to his friend Alice. After learning of Bob's array, Alice declared that she could retrieve the permutation p even if Bob rearranges the elements of q and the elements within each triple. Of course, Bob did not believe in such magic, so he did just the same as above to see Alice's respond. For example, if n = 5 and p = [1, 4, 2, 3, 5], then the original array q will be [(1, 4, 2), (4, 2, 3), (2, 3, 5)]. Bob can then rearrange the numbers within each triple and the positions of the triples to get [(4, 3, 2), (2, 3, 5), (4, 1, 2)]. Note that [(1, 4, 2), (4, 2, 2), (3, 3, 5)] is not a valid rearrangement of q, as Bob is not allowed to swap numbers belong to different triples. As Alice's friend, you know for sure that Alice was just trying to show off, so you decided to save her some face by giving her any permutation p that is consistent with the array q she was given. Input The first line contains a single integer n (5 ≀ n ≀ 10^5) β€” the size of permutation p. The i-th of the next n-2 lines contains 3 integers q_{i, 1}, q_{i, 2}, q_{i, 3} (1 ≀ q_{i, j} ≀ n) β€” the elements of the i-th triple of the rearranged (shuffled) array q_i, in random order. Remember, that the numbers within each triple can be rearranged and also the positions of the triples can be rearranged. It is guaranteed that there is at least one permutation p that is consistent with the input. Output Print n distinct integers p_1, p_2, …, p_n (1 ≀ p_i ≀ n) such that p is consistent with array q. If there are multiple answers, print any. Example Input 5 4 3 2 2 3 5 4 1 2 Output 1 4 2 3 5
instruction
0
90,246
12
180,492
Tags: constructive algorithms, implementation Correct Solution: ``` """ Satwik_Tiwari ;) . 12th Sept , 2020 - Saturday """ #=============================================================================================== #importing some useful libraries. from __future__ import division, print_function from fractions import Fraction import sys import os from io import BytesIO, IOBase from itertools import * import bisect from heapq import * from math import * from copy import * from collections import deque from collections import Counter as counter # Counter(list) return a dict with {key: count} from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)] from itertools import permutations as permutate from bisect import bisect_left as bl #If the element is already present in the list, # the left most position where element has to be inserted is returned. from bisect import bisect_right as br from bisect import bisect #If the element is already present in the list, # the right most position where element has to be inserted is returned #============================================================================================== #fast I/O region BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) # inp = lambda: sys.stdin.readline().rstrip("\r\n") #=============================================================================================== ### START ITERATE RECURSION ### from types import GeneratorType def iterative(f, stack=[]): def wrapped_func(*args, **kwargs): if stack: return f(*args, **kwargs) to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) continue stack.pop() if not stack: break to = stack[-1].send(to) return to return wrapped_func #### END ITERATE RECURSION #### #=============================================================================================== #some shortcuts mod = 1000000007 def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input def out(var): sys.stdout.write(str(var)) #for fast output, always take string def lis(): return list(map(int, inp().split())) def stringlis(): return list(map(str, inp().split())) def sep(): return map(int, inp().split()) def strsep(): return map(str, inp().split()) # def graph(vertex): return [[] for i in range(0,vertex+1)] def zerolist(n): return [0]*n def nextline(): out("\n") #as stdout.write always print sring. def testcase(t): for pp in range(t): solve(pp) def printlist(a) : for p in range(0,len(a)): out(str(a[p]) + ' ') def google(p): print('Case #'+str(p)+': ',end='') def lcm(a,b): return (a*b)//gcd(a,b) def power(x, y, p) : res = 1 # Initialize result x = x % p # Update x if it is more , than or equal to p if (x == 0) : return 0 while (y > 0) : if ((y & 1) == 1) : # If y is odd, multiply, x with result res = (res * x) % p y = y >> 1 # y = y/2 x = (x * x) % p return res def ncr(n,r): return factorial(n)//(factorial(r)*factorial(max(n-r,1))) def isPrime(n) : if (n <= 1) : return False if (n <= 3) : return True if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while(i * i <= n) : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True #=============================================================================================== # code here ;)) def solve(case): n = int(inp()) q = [] hash = {} for i in range(n-2): temp = lis() for j in range(3): if(temp[j] not in hash): hash[temp[j]] = [temp] else: hash[temp[j]].append(temp) # print(hash) ind = 0 ans = [0]*n for val in range(1,n+1): if(len(hash[val]) == 1): ans[ind] = val ind+=1 curr = hash[val][0] break # print(hash) for val in range(1,n+1): if(len(hash[val]) == 2 and val in curr): ans[ind] = val ind+=1 break while(ind<n): temp = hash[ans[ind-2]] for j in range(len(temp)): if(ans[ind-1] in temp[j]): for i in range(3): if(temp[j][i] != ans[ind-1] and temp[j][i] != ans[ind-2]): ans[ind] = temp[j][i] hash[ans[ind]].remove(temp[j]) hash[ans[ind-1]].remove(temp[j]) hash[ans[ind-2]].remove(temp[j]) ind+=1 break break print(' '.join(str(ans[i]) for i in range(n))) testcase(1) # testcase(int(inp())) ```
output
1
90,246
12
180,493
Provide tags and a correct Python 3 solution for this coding contest problem. Bob is an avid fan of the video game "League of Leesins", and today he celebrates as the League of Leesins World Championship comes to an end! The tournament consisted of n (n β‰₯ 5) teams around the world. Before the tournament starts, Bob has made a prediction of the rankings of each team, from 1-st to n-th. After the final, he compared the prediction with the actual result and found out that the i-th team according to his prediction ended up at the p_i-th position (1 ≀ p_i ≀ n, all p_i are unique). In other words, p is a permutation of 1, 2, ..., n. As Bob's favorite League player is the famous "3ga", he decided to write down every 3 consecutive elements of the permutation p. Formally, Bob created an array q of n-2 triples, where q_i = (p_i, p_{i+1}, p_{i+2}) for each 1 ≀ i ≀ n-2. Bob was very proud of his array, so he showed it to his friend Alice. After learning of Bob's array, Alice declared that she could retrieve the permutation p even if Bob rearranges the elements of q and the elements within each triple. Of course, Bob did not believe in such magic, so he did just the same as above to see Alice's respond. For example, if n = 5 and p = [1, 4, 2, 3, 5], then the original array q will be [(1, 4, 2), (4, 2, 3), (2, 3, 5)]. Bob can then rearrange the numbers within each triple and the positions of the triples to get [(4, 3, 2), (2, 3, 5), (4, 1, 2)]. Note that [(1, 4, 2), (4, 2, 2), (3, 3, 5)] is not a valid rearrangement of q, as Bob is not allowed to swap numbers belong to different triples. As Alice's friend, you know for sure that Alice was just trying to show off, so you decided to save her some face by giving her any permutation p that is consistent with the array q she was given. Input The first line contains a single integer n (5 ≀ n ≀ 10^5) β€” the size of permutation p. The i-th of the next n-2 lines contains 3 integers q_{i, 1}, q_{i, 2}, q_{i, 3} (1 ≀ q_{i, j} ≀ n) β€” the elements of the i-th triple of the rearranged (shuffled) array q_i, in random order. Remember, that the numbers within each triple can be rearranged and also the positions of the triples can be rearranged. It is guaranteed that there is at least one permutation p that is consistent with the input. Output Print n distinct integers p_1, p_2, …, p_n (1 ≀ p_i ≀ n) such that p is consistent with array q. If there are multiple answers, print any. Example Input 5 4 3 2 2 3 5 4 1 2 Output 1 4 2 3 5
instruction
0
90,247
12
180,494
Tags: constructive algorithms, implementation Correct Solution: ``` import math #------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #-------------------game starts now---------------------------------------------------- n=int(input()) d=dict() d1=dict() for i in range(n-2): a,b,c=map(int,input().split()) if (min(a,b),max(a,b)) in d: d[(min(a,b),max(a,b))].append(c) else: d.update({(min(a,b),max(a,b)):[c]}) if (min(c,b),max(c,b)) in d: d[(min(c,b),max(c,b))].append(a) else: d.update({(min(c,b),max(c,b)):[a]}) if (min(a,c),max(a,c)) in d: d[(min(a,c),max(a,c))].append(b) else: d.update({(min(a,c),max(a,c)):[b]}) if a in d1: d1[a]+=1 else: d1.update({a:1}) if b in d1: d1[b]+=1 else: d1.update({b:1}) if c in d1: d1[c]+=1 else: d1.update({c:1}) ans=[] for i in range(1,n+1): if d1[i]==1: ans.append(i) st=i break for i in range(1,n+1): if d1[i]==2 and (min(i,st),max(i,st)) in d: ans.append(i) #print(ans) s=set(ans) for i in range(2,n): for j in d[(min(ans[i-2],ans[i-1]),max(ans[i-2],ans[i-1]))]: if j in s: continue ans.append(j) s.add(j) print(*ans,sep=" ") ```
output
1
90,247
12
180,495
Provide tags and a correct Python 3 solution for this coding contest problem. Bob is an avid fan of the video game "League of Leesins", and today he celebrates as the League of Leesins World Championship comes to an end! The tournament consisted of n (n β‰₯ 5) teams around the world. Before the tournament starts, Bob has made a prediction of the rankings of each team, from 1-st to n-th. After the final, he compared the prediction with the actual result and found out that the i-th team according to his prediction ended up at the p_i-th position (1 ≀ p_i ≀ n, all p_i are unique). In other words, p is a permutation of 1, 2, ..., n. As Bob's favorite League player is the famous "3ga", he decided to write down every 3 consecutive elements of the permutation p. Formally, Bob created an array q of n-2 triples, where q_i = (p_i, p_{i+1}, p_{i+2}) for each 1 ≀ i ≀ n-2. Bob was very proud of his array, so he showed it to his friend Alice. After learning of Bob's array, Alice declared that she could retrieve the permutation p even if Bob rearranges the elements of q and the elements within each triple. Of course, Bob did not believe in such magic, so he did just the same as above to see Alice's respond. For example, if n = 5 and p = [1, 4, 2, 3, 5], then the original array q will be [(1, 4, 2), (4, 2, 3), (2, 3, 5)]. Bob can then rearrange the numbers within each triple and the positions of the triples to get [(4, 3, 2), (2, 3, 5), (4, 1, 2)]. Note that [(1, 4, 2), (4, 2, 2), (3, 3, 5)] is not a valid rearrangement of q, as Bob is not allowed to swap numbers belong to different triples. As Alice's friend, you know for sure that Alice was just trying to show off, so you decided to save her some face by giving her any permutation p that is consistent with the array q she was given. Input The first line contains a single integer n (5 ≀ n ≀ 10^5) β€” the size of permutation p. The i-th of the next n-2 lines contains 3 integers q_{i, 1}, q_{i, 2}, q_{i, 3} (1 ≀ q_{i, j} ≀ n) β€” the elements of the i-th triple of the rearranged (shuffled) array q_i, in random order. Remember, that the numbers within each triple can be rearranged and also the positions of the triples can be rearranged. It is guaranteed that there is at least one permutation p that is consistent with the input. Output Print n distinct integers p_1, p_2, …, p_n (1 ≀ p_i ≀ n) such that p is consistent with array q. If there are multiple answers, print any. Example Input 5 4 3 2 2 3 5 4 1 2 Output 1 4 2 3 5
instruction
0
90,248
12
180,496
Tags: constructive algorithms, implementation Correct Solution: ``` n=int(input()) l=[] d={} count={} for i in range(n-2): l.append(list(map(int,input().split()))) temp=l[-1] if temp[0] in count: count[temp[0]][0]+=1 else: count[temp[0]]=[1,temp] if temp[1] in count: count[temp[1]][0]+=1 else: count[temp[1]]=[1,temp] if temp[2] in count: count[temp[2]][0]+=1 else: count[temp[2]]=[1,temp] if (temp[0],temp[1]) in d: d[(temp[0],temp[1])].append(temp[2]) else: d[(temp[0],temp[1])]=[temp[2]] if (temp[1],temp[0]) in d: d[(temp[1],temp[0])].append(temp[2]) else: d[(temp[1],temp[0])]=[temp[2]] if (temp[0],temp[2]) in d: d[(temp[0],temp[2])].append(temp[1]) else: d[(temp[0],temp[2])]=[temp[1]] if (temp[2],temp[1]) in d: d[(temp[2],temp[1])].append(temp[0]) else: d[(temp[2],temp[1])]=[temp[0]] if (temp[2],temp[0]) in d: d[(temp[2],temp[0])].append(temp[1]) else: d[(temp[2],temp[0])]=[temp[1]] if (temp[1],temp[2]) in d: d[(temp[1],temp[2])].append(temp[0]) else: d[(temp[1],temp[2])]=[temp[0]] start=-1 second=-1 for i in count: if count[i][0]==1: if start==-1: start = count[i][1] sn = i else: end = count[i][1] en = i break elif count[i][0]==2: if second==-1: second = count[i][1] secn = i else: second2 = count[i][1] secn2 = i ans=[] ans.append(sn) print (sn,end=" ") if (sn,secn) in d: thirdn = d[(sn,secn)][0] print (secn,thirdn,end=" ") ans.append(secn) else: thirdn = d[(sn,secn2)][0] print (secn2,thirdn,end=" ") ans.append(secn2) ans.append(thirdn) for i in range(n-3): temp = d[(ans[-2],ans[-1])] if temp[0]!=ans[-3]: ans.append(temp[0]) print (temp[0],end=" ") else: ans.append(temp[1]) print (temp[1],end=" ") ```
output
1
90,248
12
180,497
Provide tags and a correct Python 3 solution for this coding contest problem. Bob is an avid fan of the video game "League of Leesins", and today he celebrates as the League of Leesins World Championship comes to an end! The tournament consisted of n (n β‰₯ 5) teams around the world. Before the tournament starts, Bob has made a prediction of the rankings of each team, from 1-st to n-th. After the final, he compared the prediction with the actual result and found out that the i-th team according to his prediction ended up at the p_i-th position (1 ≀ p_i ≀ n, all p_i are unique). In other words, p is a permutation of 1, 2, ..., n. As Bob's favorite League player is the famous "3ga", he decided to write down every 3 consecutive elements of the permutation p. Formally, Bob created an array q of n-2 triples, where q_i = (p_i, p_{i+1}, p_{i+2}) for each 1 ≀ i ≀ n-2. Bob was very proud of his array, so he showed it to his friend Alice. After learning of Bob's array, Alice declared that she could retrieve the permutation p even if Bob rearranges the elements of q and the elements within each triple. Of course, Bob did not believe in such magic, so he did just the same as above to see Alice's respond. For example, if n = 5 and p = [1, 4, 2, 3, 5], then the original array q will be [(1, 4, 2), (4, 2, 3), (2, 3, 5)]. Bob can then rearrange the numbers within each triple and the positions of the triples to get [(4, 3, 2), (2, 3, 5), (4, 1, 2)]. Note that [(1, 4, 2), (4, 2, 2), (3, 3, 5)] is not a valid rearrangement of q, as Bob is not allowed to swap numbers belong to different triples. As Alice's friend, you know for sure that Alice was just trying to show off, so you decided to save her some face by giving her any permutation p that is consistent with the array q she was given. Input The first line contains a single integer n (5 ≀ n ≀ 10^5) β€” the size of permutation p. The i-th of the next n-2 lines contains 3 integers q_{i, 1}, q_{i, 2}, q_{i, 3} (1 ≀ q_{i, j} ≀ n) β€” the elements of the i-th triple of the rearranged (shuffled) array q_i, in random order. Remember, that the numbers within each triple can be rearranged and also the positions of the triples can be rearranged. It is guaranteed that there is at least one permutation p that is consistent with the input. Output Print n distinct integers p_1, p_2, …, p_n (1 ≀ p_i ≀ n) such that p is consistent with array q. If there are multiple answers, print any. Example Input 5 4 3 2 2 3 5 4 1 2 Output 1 4 2 3 5
instruction
0
90,249
12
180,498
Tags: constructive algorithms, implementation Correct Solution: ``` def ii(): return int(input()) def li(): return list(map(int,input().split())) def mp(): return map(int,input().split()) def i(): return input() #Code starts here n=ii() a=[] for i in range(n+1): a.append(set()) for i in range(n-2): x,y,z=mp() a[x].add(y),a[x].add(z),a[y].add(x),a[y].add(z),a[z].add(y),a[z].add(x) ans=[] for i in range(n): if len(a[i])==2: ans.append(i) break for i in a[ans[0]]: if len(a[i])==3: ans.append(i) a[i].remove(ans[0]) break for i in range(1,n-1): x=(a[ans[i]]&a[ans[i-1]]) ans.append(x.pop()) a[ans[i+1]].remove(ans[i]) print(*ans) ```
output
1
90,249
12
180,499
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Bob is an avid fan of the video game "League of Leesins", and today he celebrates as the League of Leesins World Championship comes to an end! The tournament consisted of n (n β‰₯ 5) teams around the world. Before the tournament starts, Bob has made a prediction of the rankings of each team, from 1-st to n-th. After the final, he compared the prediction with the actual result and found out that the i-th team according to his prediction ended up at the p_i-th position (1 ≀ p_i ≀ n, all p_i are unique). In other words, p is a permutation of 1, 2, ..., n. As Bob's favorite League player is the famous "3ga", he decided to write down every 3 consecutive elements of the permutation p. Formally, Bob created an array q of n-2 triples, where q_i = (p_i, p_{i+1}, p_{i+2}) for each 1 ≀ i ≀ n-2. Bob was very proud of his array, so he showed it to his friend Alice. After learning of Bob's array, Alice declared that she could retrieve the permutation p even if Bob rearranges the elements of q and the elements within each triple. Of course, Bob did not believe in such magic, so he did just the same as above to see Alice's respond. For example, if n = 5 and p = [1, 4, 2, 3, 5], then the original array q will be [(1, 4, 2), (4, 2, 3), (2, 3, 5)]. Bob can then rearrange the numbers within each triple and the positions of the triples to get [(4, 3, 2), (2, 3, 5), (4, 1, 2)]. Note that [(1, 4, 2), (4, 2, 2), (3, 3, 5)] is not a valid rearrangement of q, as Bob is not allowed to swap numbers belong to different triples. As Alice's friend, you know for sure that Alice was just trying to show off, so you decided to save her some face by giving her any permutation p that is consistent with the array q she was given. Input The first line contains a single integer n (5 ≀ n ≀ 10^5) β€” the size of permutation p. The i-th of the next n-2 lines contains 3 integers q_{i, 1}, q_{i, 2}, q_{i, 3} (1 ≀ q_{i, j} ≀ n) β€” the elements of the i-th triple of the rearranged (shuffled) array q_i, in random order. Remember, that the numbers within each triple can be rearranged and also the positions of the triples can be rearranged. It is guaranteed that there is at least one permutation p that is consistent with the input. Output Print n distinct integers p_1, p_2, …, p_n (1 ≀ p_i ≀ n) such that p is consistent with array q. If there are multiple answers, print any. Example Input 5 4 3 2 2 3 5 4 1 2 Output 1 4 2 3 5 Submitted Solution: ``` n = int(input()) triple = list() fre = dict() for i in range(1, n+1): fre[i] = 0 for j in range(n-2): c = list(map(int, input().split())) c.sort() triple.append(c) fre[c[0]] += 1 fre[c[1]] += 1 fre[c[2]] += 1 fre_num = list() for i in range(1, n+1): fre_num.append([fre[i], i]) all_duplet = dict() for i in triple: a1 = min(i[0], i[1]) a2 = max(i[0], i[1]) if (a1, a2) in all_duplet: all_duplet[(a1, a2)].append(i[2]) else: all_duplet[(a1, a2)] = list() all_duplet[(a1, a2)].append(i[2]) a1 = min(i[2], i[1]) a2 = max(i[2], i[1]) if (a1, a2) in all_duplet: all_duplet[(a1, a2)].append(i[0]) else: all_duplet[(a1, a2)] = list() all_duplet[(a1, a2)].append(i[0]) a1 = min(i[0], i[2]) a2 = max(i[0], i[2]) if (a1, a2) in all_duplet: all_duplet[(a1, a2)].append(i[1]) else: all_duplet[(a1, a2)] = list() all_duplet[(a1, a2)].append(i[1]) ans = list() ans_set = set() for i in fre_num: if i[0] == 1: ans.append(i[1]) break #ans.append(fre_num[0][1]) #add first num #found first triple for i in range(len(triple)): if ans[-1] in triple[i]: first_triple = triple[i] first_triple.remove(ans[-1]) break if fre[first_triple[0]] < fre[first_triple[1]]: ans.append(first_triple[0]) ans.append(first_triple[1]) else: ans.append(first_triple[1]) ans.append(first_triple[0]) for i in ans: ans_set.add(i) while len(ans) < n: a1 = min(ans[-1], ans[-2]) a2 = max(ans[-1], ans[-2]) for j in all_duplet[(a1, a2)]: if j not in ans_set: ans_set.add(j) ans.append(j) break print(*ans) ```
instruction
0
90,250
12
180,500
Yes
output
1
90,250
12
180,501
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Bob is an avid fan of the video game "League of Leesins", and today he celebrates as the League of Leesins World Championship comes to an end! The tournament consisted of n (n β‰₯ 5) teams around the world. Before the tournament starts, Bob has made a prediction of the rankings of each team, from 1-st to n-th. After the final, he compared the prediction with the actual result and found out that the i-th team according to his prediction ended up at the p_i-th position (1 ≀ p_i ≀ n, all p_i are unique). In other words, p is a permutation of 1, 2, ..., n. As Bob's favorite League player is the famous "3ga", he decided to write down every 3 consecutive elements of the permutation p. Formally, Bob created an array q of n-2 triples, where q_i = (p_i, p_{i+1}, p_{i+2}) for each 1 ≀ i ≀ n-2. Bob was very proud of his array, so he showed it to his friend Alice. After learning of Bob's array, Alice declared that she could retrieve the permutation p even if Bob rearranges the elements of q and the elements within each triple. Of course, Bob did not believe in such magic, so he did just the same as above to see Alice's respond. For example, if n = 5 and p = [1, 4, 2, 3, 5], then the original array q will be [(1, 4, 2), (4, 2, 3), (2, 3, 5)]. Bob can then rearrange the numbers within each triple and the positions of the triples to get [(4, 3, 2), (2, 3, 5), (4, 1, 2)]. Note that [(1, 4, 2), (4, 2, 2), (3, 3, 5)] is not a valid rearrangement of q, as Bob is not allowed to swap numbers belong to different triples. As Alice's friend, you know for sure that Alice was just trying to show off, so you decided to save her some face by giving her any permutation p that is consistent with the array q she was given. Input The first line contains a single integer n (5 ≀ n ≀ 10^5) β€” the size of permutation p. The i-th of the next n-2 lines contains 3 integers q_{i, 1}, q_{i, 2}, q_{i, 3} (1 ≀ q_{i, j} ≀ n) β€” the elements of the i-th triple of the rearranged (shuffled) array q_i, in random order. Remember, that the numbers within each triple can be rearranged and also the positions of the triples can be rearranged. It is guaranteed that there is at least one permutation p that is consistent with the input. Output Print n distinct integers p_1, p_2, …, p_n (1 ≀ p_i ≀ n) such that p is consistent with array q. If there are multiple answers, print any. Example Input 5 4 3 2 2 3 5 4 1 2 Output 1 4 2 3 5 Submitted Solution: ``` import math import sys from collections import defaultdict, Counter from functools import lru_cache n = int(input()) q = [] arr = [] Dict = defaultdict(list) for _ in range(n - 2): a, b, c = [int(i) for i in input().split()] arr.append(a) arr.append(b) arr.append(c) q.append([a, b, c]) count = Counter(arr) val = -1 for i in range(1, n + 1): if count[i] == 1: val = i break for i in range(len(q)): Dict[q[i][0]].append(i) Dict[q[i][1]].append(i) Dict[q[i][2]].append(i) ans = [] temp = q[Dict[val][0]] first = [0] * 3 cur_ind = Dict[val][0] for i in range(3): first[count[temp[i]] - 1] = temp[i] ans = [] ans += first #print(ans, val) while len(set(Dict[ans[-1]]).intersection(set(Dict[ans[-2]]))) > 1: a1 = list(set(Dict[ans[-1]]).intersection(set(Dict[ans[-2]]))) for i in a1: if i != cur_ind: temp = q[i] ind = i cur = -1 for i in range(3): if temp[i] != ans[-2] and temp[i] != ans[-1]: cur = temp[i] break ans += [cur] cur_ind = ind print(*ans) ```
instruction
0
90,251
12
180,502
Yes
output
1
90,251
12
180,503
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Bob is an avid fan of the video game "League of Leesins", and today he celebrates as the League of Leesins World Championship comes to an end! The tournament consisted of n (n β‰₯ 5) teams around the world. Before the tournament starts, Bob has made a prediction of the rankings of each team, from 1-st to n-th. After the final, he compared the prediction with the actual result and found out that the i-th team according to his prediction ended up at the p_i-th position (1 ≀ p_i ≀ n, all p_i are unique). In other words, p is a permutation of 1, 2, ..., n. As Bob's favorite League player is the famous "3ga", he decided to write down every 3 consecutive elements of the permutation p. Formally, Bob created an array q of n-2 triples, where q_i = (p_i, p_{i+1}, p_{i+2}) for each 1 ≀ i ≀ n-2. Bob was very proud of his array, so he showed it to his friend Alice. After learning of Bob's array, Alice declared that she could retrieve the permutation p even if Bob rearranges the elements of q and the elements within each triple. Of course, Bob did not believe in such magic, so he did just the same as above to see Alice's respond. For example, if n = 5 and p = [1, 4, 2, 3, 5], then the original array q will be [(1, 4, 2), (4, 2, 3), (2, 3, 5)]. Bob can then rearrange the numbers within each triple and the positions of the triples to get [(4, 3, 2), (2, 3, 5), (4, 1, 2)]. Note that [(1, 4, 2), (4, 2, 2), (3, 3, 5)] is not a valid rearrangement of q, as Bob is not allowed to swap numbers belong to different triples. As Alice's friend, you know for sure that Alice was just trying to show off, so you decided to save her some face by giving her any permutation p that is consistent with the array q she was given. Input The first line contains a single integer n (5 ≀ n ≀ 10^5) β€” the size of permutation p. The i-th of the next n-2 lines contains 3 integers q_{i, 1}, q_{i, 2}, q_{i, 3} (1 ≀ q_{i, j} ≀ n) β€” the elements of the i-th triple of the rearranged (shuffled) array q_i, in random order. Remember, that the numbers within each triple can be rearranged and also the positions of the triples can be rearranged. It is guaranteed that there is at least one permutation p that is consistent with the input. Output Print n distinct integers p_1, p_2, …, p_n (1 ≀ p_i ≀ n) such that p is consistent with array q. If there are multiple answers, print any. Example Input 5 4 3 2 2 3 5 4 1 2 Output 1 4 2 3 5 Submitted Solution: ``` n = int(input()) lst = [] nums = [] ans = [] looking_for = [] looking_for1 = [] looking_for2 = [] last_triple_index = -1 triple_index = [False] * (n+10) triple_indexxx = [] for i in range(n+1): nums.append([]) for i in range(n-2): lst.append(list(map(int, input().split()))) for j in range(3): nums[lst[i][j]].append(i) for i in range(1, n+1): if len(nums[i]) == 1: ans.append(i) looking_for = [] for j in range(3): if lst[nums[i][0]][j] != i: looking_for.append(lst[nums[i][0]][j]) triple_index[nums[i][0]] = True triple_indexxx.append(nums[i][0]) done = i break # print(nums) # print(lst) while len(ans) < n-3: # print(looking_for) # print(looking_for1) # print(looking_for2) # print() looking_for1 = [] looking_for2 = [] for j in range(len(nums[looking_for[0]])): triple_i = nums[looking_for[0]][j] if triple_i in nums[looking_for[1]] and not triple_index[triple_i]: triple_index[triple_i] = True triple_indexxx.append(triple_i) for k in range(3): if lst[triple_i][k] not in looking_for: looking_for1.append(lst[triple_i][k]) looking_for2.append(lst[triple_i][k]) yeah = lst[triple_i][k] for k in range(3): if lst[triple_i][k] not in looking_for1 and len(looking_for1) < 2 and lst[triple_i][k] != yeah: looking_for1.append(lst[triple_i][k]) elif lst[triple_i][k] != yeah: looking_for2.append(lst[triple_i][k]) found = False # print(looking_for) # print(looking_for1) # print(looking_for2) for j in range(len(nums[looking_for1[0]])): triple_i = nums[looking_for1[0]][j] if triple_i in nums[looking_for1[1]] and not triple_index[triple_i]: # print("yes") for i in range(2): if looking_for2[i] not in looking_for1: ans.append(looking_for2[i]) break looking_for = looking_for1 found = True # print() # print(looking_for) # print(looking_for1) # print(looking_for2) # print() if not found: for j in range(len(nums[looking_for2[0]])): triple_i = nums[looking_for2[0]][j] if triple_i in nums[looking_for2[1]] and not triple_index[triple_i]: # print("yes") for i in range(2): if looking_for1[i] not in looking_for2: ans.append(looking_for1[i]) break looking_for = looking_for2 found = True # print(ans) current = triple_indexxx[-2] # print(triple_i) for i in range(2): if looking_for[i] in lst[current]: ans.append(looking_for[i]) looking_for[i] = None for i in range(2): if looking_for[i] is not None: ans.append(looking_for[i]) for i in range(1, n+1): if len(nums[i]) == 1 and i not in ans: ans.append(i) looking_for = [] for j in range(3): if lst[nums[i][0]][j] != i: looking_for.append(lst[nums[i][0]][j]) triple_index.append(nums[i][0]) done = i break # print(triple_index) # print(triple_i) # print(looking_for) # print(looking_for1) # print(looking_for2) # print(ans) for i in range(len(ans)): print(ans[i], end=' ') ```
instruction
0
90,252
12
180,504
Yes
output
1
90,252
12
180,505
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Bob is an avid fan of the video game "League of Leesins", and today he celebrates as the League of Leesins World Championship comes to an end! The tournament consisted of n (n β‰₯ 5) teams around the world. Before the tournament starts, Bob has made a prediction of the rankings of each team, from 1-st to n-th. After the final, he compared the prediction with the actual result and found out that the i-th team according to his prediction ended up at the p_i-th position (1 ≀ p_i ≀ n, all p_i are unique). In other words, p is a permutation of 1, 2, ..., n. As Bob's favorite League player is the famous "3ga", he decided to write down every 3 consecutive elements of the permutation p. Formally, Bob created an array q of n-2 triples, where q_i = (p_i, p_{i+1}, p_{i+2}) for each 1 ≀ i ≀ n-2. Bob was very proud of his array, so he showed it to his friend Alice. After learning of Bob's array, Alice declared that she could retrieve the permutation p even if Bob rearranges the elements of q and the elements within each triple. Of course, Bob did not believe in such magic, so he did just the same as above to see Alice's respond. For example, if n = 5 and p = [1, 4, 2, 3, 5], then the original array q will be [(1, 4, 2), (4, 2, 3), (2, 3, 5)]. Bob can then rearrange the numbers within each triple and the positions of the triples to get [(4, 3, 2), (2, 3, 5), (4, 1, 2)]. Note that [(1, 4, 2), (4, 2, 2), (3, 3, 5)] is not a valid rearrangement of q, as Bob is not allowed to swap numbers belong to different triples. As Alice's friend, you know for sure that Alice was just trying to show off, so you decided to save her some face by giving her any permutation p that is consistent with the array q she was given. Input The first line contains a single integer n (5 ≀ n ≀ 10^5) β€” the size of permutation p. The i-th of the next n-2 lines contains 3 integers q_{i, 1}, q_{i, 2}, q_{i, 3} (1 ≀ q_{i, j} ≀ n) β€” the elements of the i-th triple of the rearranged (shuffled) array q_i, in random order. Remember, that the numbers within each triple can be rearranged and also the positions of the triples can be rearranged. It is guaranteed that there is at least one permutation p that is consistent with the input. Output Print n distinct integers p_1, p_2, …, p_n (1 ≀ p_i ≀ n) such that p is consistent with array q. If there are multiple answers, print any. Example Input 5 4 3 2 2 3 5 4 1 2 Output 1 4 2 3 5 Submitted Solution: ``` import sys import math from collections import defaultdict,Counter,deque # input=sys.stdin.readline # def print(x): # sys.stdout.write(str(x)+"\n") import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # sys.stdout=open("CP1/output.txt",'w') # sys.stdin=open("CP1/input.txt",'r') # mod=pow(10,9)+7 t=int(input()) d=[0]*(t+1) l=defaultdict(list) for i in range(t-2): q=list(map(int,input().split())) q.sort() d[q[0]]+=1 d[q[1]]+=1 d[q[2]]+=1 l[(q[0],q[1])].append(q[2]) l[(q[1],q[2])].append(q[0]) l[(q[0],q[2])].append(q[1]) l[(q[1],q[0])].append(q[2]) l[(q[2],q[1])].append(q[0]) l[(q[2],q[0])].append(q[1]) # print(l) start1=[] for j in range(1,t+1): if d[j]==1: start=j elif d[j]==2: start1.append(j) d=[0]*(t+1) d[start]=1 ans=[start] if l.get((start,start1[0]))!=None: ans.append(start1[0]) d[start1[0]]=1 else: ans.append(start1[1]) d[start1[1]]=1 for j in range(t-2): for k in l[(ans[-1],ans[-2])]: if d[k]==0: d[k]=1 ans.append(k) print(*ans) ```
instruction
0
90,253
12
180,506
Yes
output
1
90,253
12
180,507
Evaluate the correctness of the submitted Python 2 solution to the coding contest problem. Provide a "Yes" or "No" response. Bob is an avid fan of the video game "League of Leesins", and today he celebrates as the League of Leesins World Championship comes to an end! The tournament consisted of n (n β‰₯ 5) teams around the world. Before the tournament starts, Bob has made a prediction of the rankings of each team, from 1-st to n-th. After the final, he compared the prediction with the actual result and found out that the i-th team according to his prediction ended up at the p_i-th position (1 ≀ p_i ≀ n, all p_i are unique). In other words, p is a permutation of 1, 2, ..., n. As Bob's favorite League player is the famous "3ga", he decided to write down every 3 consecutive elements of the permutation p. Formally, Bob created an array q of n-2 triples, where q_i = (p_i, p_{i+1}, p_{i+2}) for each 1 ≀ i ≀ n-2. Bob was very proud of his array, so he showed it to his friend Alice. After learning of Bob's array, Alice declared that she could retrieve the permutation p even if Bob rearranges the elements of q and the elements within each triple. Of course, Bob did not believe in such magic, so he did just the same as above to see Alice's respond. For example, if n = 5 and p = [1, 4, 2, 3, 5], then the original array q will be [(1, 4, 2), (4, 2, 3), (2, 3, 5)]. Bob can then rearrange the numbers within each triple and the positions of the triples to get [(4, 3, 2), (2, 3, 5), (4, 1, 2)]. Note that [(1, 4, 2), (4, 2, 2), (3, 3, 5)] is not a valid rearrangement of q, as Bob is not allowed to swap numbers belong to different triples. As Alice's friend, you know for sure that Alice was just trying to show off, so you decided to save her some face by giving her any permutation p that is consistent with the array q she was given. Input The first line contains a single integer n (5 ≀ n ≀ 10^5) β€” the size of permutation p. The i-th of the next n-2 lines contains 3 integers q_{i, 1}, q_{i, 2}, q_{i, 3} (1 ≀ q_{i, j} ≀ n) β€” the elements of the i-th triple of the rearranged (shuffled) array q_i, in random order. Remember, that the numbers within each triple can be rearranged and also the positions of the triples can be rearranged. It is guaranteed that there is at least one permutation p that is consistent with the input. Output Print n distinct integers p_1, p_2, …, p_n (1 ≀ p_i ≀ n) such that p is consistent with array q. If there are multiple answers, print any. Example Input 5 4 3 2 2 3 5 4 1 2 Output 1 4 2 3 5 Submitted Solution: ``` from sys import stdin, stdout from collections import Counter, defaultdict pr=stdout.write raw_input = stdin.readline def ni(): return int(raw_input()) def li(): return list(map(int,raw_input().split())) def pn(n): stdout.write(str(n)+'\n') def pa(arr): pr(' '.join(map(str,arr))+'\n') # fast read function for total integer input def inp(): # this function returns whole input of # space/line seperated integers # Use Ctrl+D to flush stdin. return (map(int,stdin.read().split())) range = xrange # not for python 3.0+ # main code n=ni() d=Counter() d1=defaultdict(list) arr=[] for i in range(n-2): x,y,z=li() d1[x].append([y,z]) d1[y].append([x,z]) d1[z].append([x,y]) d[x]+=1 d[y]+=1 d[z]+=1 for i in range(1,n+1): if d[i]==1: p=i break px=p for i in d1[p][0]: if d[i]==2: py=i break print px, print py, vis=Counter() vis[px]=1 vis[py]=1 for i in range(n-2): #print px,py for j in d1[px]: if py in j: for k in j: if k!=py: #print i,'asdf' temp=k break if not vis[temp]: vis[temp]=1 print temp, px,py=py,temp break ```
instruction
0
90,254
12
180,508
Yes
output
1
90,254
12
180,509
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Bob is an avid fan of the video game "League of Leesins", and today he celebrates as the League of Leesins World Championship comes to an end! The tournament consisted of n (n β‰₯ 5) teams around the world. Before the tournament starts, Bob has made a prediction of the rankings of each team, from 1-st to n-th. After the final, he compared the prediction with the actual result and found out that the i-th team according to his prediction ended up at the p_i-th position (1 ≀ p_i ≀ n, all p_i are unique). In other words, p is a permutation of 1, 2, ..., n. As Bob's favorite League player is the famous "3ga", he decided to write down every 3 consecutive elements of the permutation p. Formally, Bob created an array q of n-2 triples, where q_i = (p_i, p_{i+1}, p_{i+2}) for each 1 ≀ i ≀ n-2. Bob was very proud of his array, so he showed it to his friend Alice. After learning of Bob's array, Alice declared that she could retrieve the permutation p even if Bob rearranges the elements of q and the elements within each triple. Of course, Bob did not believe in such magic, so he did just the same as above to see Alice's respond. For example, if n = 5 and p = [1, 4, 2, 3, 5], then the original array q will be [(1, 4, 2), (4, 2, 3), (2, 3, 5)]. Bob can then rearrange the numbers within each triple and the positions of the triples to get [(4, 3, 2), (2, 3, 5), (4, 1, 2)]. Note that [(1, 4, 2), (4, 2, 2), (3, 3, 5)] is not a valid rearrangement of q, as Bob is not allowed to swap numbers belong to different triples. As Alice's friend, you know for sure that Alice was just trying to show off, so you decided to save her some face by giving her any permutation p that is consistent with the array q she was given. Input The first line contains a single integer n (5 ≀ n ≀ 10^5) β€” the size of permutation p. The i-th of the next n-2 lines contains 3 integers q_{i, 1}, q_{i, 2}, q_{i, 3} (1 ≀ q_{i, j} ≀ n) β€” the elements of the i-th triple of the rearranged (shuffled) array q_i, in random order. Remember, that the numbers within each triple can be rearranged and also the positions of the triples can be rearranged. It is guaranteed that there is at least one permutation p that is consistent with the input. Output Print n distinct integers p_1, p_2, …, p_n (1 ≀ p_i ≀ n) such that p is consistent with array q. If there are multiple answers, print any. Example Input 5 4 3 2 2 3 5 4 1 2 Output 1 4 2 3 5 Submitted Solution: ``` n=int(input()) arr=[None]*(n-2) d=dict() nearby=dict() for i in range(n-2): arr[i]=list(map(int,input().split())) nearby[arr[i][0]]=set([arr[i][1],arr[i][2]]) nearby[arr[i][1]]=set([arr[i][0],arr[i][2]]) nearby[arr[i][2]]=set([arr[i][1],arr[i][0]]) for j in arr[i]: if j in d: d[j]+=1 else: d[j]=1 d1=dict() for i in d: try: d1[d[i]].add(i) except: d1[d[i]]=set([i]) ans=[] last=[] aagye=set() j=0 for i in d1[1]: if (j%2)==0: ans.append(i) else: last.append(i) j+=1 for i in d1[2]: if i in nearby[ans[0]]: ans.append(i) else: last.append(i) for i in range(n-4): lol=(nearby[ans[-1]]&nearby[ans[-2]]) for k in lol: ans.append(k) print(*ans,*last[::-1]) ```
instruction
0
90,255
12
180,510
No
output
1
90,255
12
180,511
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Bob is an avid fan of the video game "League of Leesins", and today he celebrates as the League of Leesins World Championship comes to an end! The tournament consisted of n (n β‰₯ 5) teams around the world. Before the tournament starts, Bob has made a prediction of the rankings of each team, from 1-st to n-th. After the final, he compared the prediction with the actual result and found out that the i-th team according to his prediction ended up at the p_i-th position (1 ≀ p_i ≀ n, all p_i are unique). In other words, p is a permutation of 1, 2, ..., n. As Bob's favorite League player is the famous "3ga", he decided to write down every 3 consecutive elements of the permutation p. Formally, Bob created an array q of n-2 triples, where q_i = (p_i, p_{i+1}, p_{i+2}) for each 1 ≀ i ≀ n-2. Bob was very proud of his array, so he showed it to his friend Alice. After learning of Bob's array, Alice declared that she could retrieve the permutation p even if Bob rearranges the elements of q and the elements within each triple. Of course, Bob did not believe in such magic, so he did just the same as above to see Alice's respond. For example, if n = 5 and p = [1, 4, 2, 3, 5], then the original array q will be [(1, 4, 2), (4, 2, 3), (2, 3, 5)]. Bob can then rearrange the numbers within each triple and the positions of the triples to get [(4, 3, 2), (2, 3, 5), (4, 1, 2)]. Note that [(1, 4, 2), (4, 2, 2), (3, 3, 5)] is not a valid rearrangement of q, as Bob is not allowed to swap numbers belong to different triples. As Alice's friend, you know for sure that Alice was just trying to show off, so you decided to save her some face by giving her any permutation p that is consistent with the array q she was given. Input The first line contains a single integer n (5 ≀ n ≀ 10^5) β€” the size of permutation p. The i-th of the next n-2 lines contains 3 integers q_{i, 1}, q_{i, 2}, q_{i, 3} (1 ≀ q_{i, j} ≀ n) β€” the elements of the i-th triple of the rearranged (shuffled) array q_i, in random order. Remember, that the numbers within each triple can be rearranged and also the positions of the triples can be rearranged. It is guaranteed that there is at least one permutation p that is consistent with the input. Output Print n distinct integers p_1, p_2, …, p_n (1 ≀ p_i ≀ n) such that p is consistent with array q. If there are multiple answers, print any. Example Input 5 4 3 2 2 3 5 4 1 2 Output 1 4 2 3 5 Submitted Solution: ``` from collections import defaultdict n = int(input()) soups = list() d = defaultdict(set) c = defaultdict(lambda: 0) first = None first_t = None second = None for ti in range(n-2): soup = list(map(int, input().split())) soups.append(soup) d[tuple(sorted([soup[0], soup[1]]))].add(soup[2]) d[tuple(sorted([soup[0], soup[2]]))].add(soup[1]) d[tuple(sorted([soup[2], soup[1]]))].add(soup[0]) for i in soup: c[i] += 1 if c[i] == 1: first = i first_t = set(soup) - set([first]) ans = list() ans.append(first) second = first_t.pop() if c[second] != 2: second = first_t.pop() ans.append(second) for _ in range(n-2): other = d[tuple(sorted(ans[-2:]))] # print('other', other) if len(ans) > 2 and len(other) >=2: other -= set([ans[-3]]) ans.append(other.pop()) else: ans.append(other.pop()) print(' '.join(map(str, ans))) ```
instruction
0
90,256
12
180,512
No
output
1
90,256
12
180,513
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Bob is an avid fan of the video game "League of Leesins", and today he celebrates as the League of Leesins World Championship comes to an end! The tournament consisted of n (n β‰₯ 5) teams around the world. Before the tournament starts, Bob has made a prediction of the rankings of each team, from 1-st to n-th. After the final, he compared the prediction with the actual result and found out that the i-th team according to his prediction ended up at the p_i-th position (1 ≀ p_i ≀ n, all p_i are unique). In other words, p is a permutation of 1, 2, ..., n. As Bob's favorite League player is the famous "3ga", he decided to write down every 3 consecutive elements of the permutation p. Formally, Bob created an array q of n-2 triples, where q_i = (p_i, p_{i+1}, p_{i+2}) for each 1 ≀ i ≀ n-2. Bob was very proud of his array, so he showed it to his friend Alice. After learning of Bob's array, Alice declared that she could retrieve the permutation p even if Bob rearranges the elements of q and the elements within each triple. Of course, Bob did not believe in such magic, so he did just the same as above to see Alice's respond. For example, if n = 5 and p = [1, 4, 2, 3, 5], then the original array q will be [(1, 4, 2), (4, 2, 3), (2, 3, 5)]. Bob can then rearrange the numbers within each triple and the positions of the triples to get [(4, 3, 2), (2, 3, 5), (4, 1, 2)]. Note that [(1, 4, 2), (4, 2, 2), (3, 3, 5)] is not a valid rearrangement of q, as Bob is not allowed to swap numbers belong to different triples. As Alice's friend, you know for sure that Alice was just trying to show off, so you decided to save her some face by giving her any permutation p that is consistent with the array q she was given. Input The first line contains a single integer n (5 ≀ n ≀ 10^5) β€” the size of permutation p. The i-th of the next n-2 lines contains 3 integers q_{i, 1}, q_{i, 2}, q_{i, 3} (1 ≀ q_{i, j} ≀ n) β€” the elements of the i-th triple of the rearranged (shuffled) array q_i, in random order. Remember, that the numbers within each triple can be rearranged and also the positions of the triples can be rearranged. It is guaranteed that there is at least one permutation p that is consistent with the input. Output Print n distinct integers p_1, p_2, …, p_n (1 ≀ p_i ≀ n) such that p is consistent with array q. If there are multiple answers, print any. Example Input 5 4 3 2 2 3 5 4 1 2 Output 1 4 2 3 5 Submitted Solution: ``` n = int(input()) z = [] d = dict() ans = [] # anss = [] for _ in range(n - 2): z.append([int(x) for x in input().split()]) z[0], z[-1] = z[-1], z[0] for _ in z: for i in _: if i not in d: d[i] = 1 ans.append(i) print(*ans) ```
instruction
0
90,257
12
180,514
No
output
1
90,257
12
180,515
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Bob is an avid fan of the video game "League of Leesins", and today he celebrates as the League of Leesins World Championship comes to an end! The tournament consisted of n (n β‰₯ 5) teams around the world. Before the tournament starts, Bob has made a prediction of the rankings of each team, from 1-st to n-th. After the final, he compared the prediction with the actual result and found out that the i-th team according to his prediction ended up at the p_i-th position (1 ≀ p_i ≀ n, all p_i are unique). In other words, p is a permutation of 1, 2, ..., n. As Bob's favorite League player is the famous "3ga", he decided to write down every 3 consecutive elements of the permutation p. Formally, Bob created an array q of n-2 triples, where q_i = (p_i, p_{i+1}, p_{i+2}) for each 1 ≀ i ≀ n-2. Bob was very proud of his array, so he showed it to his friend Alice. After learning of Bob's array, Alice declared that she could retrieve the permutation p even if Bob rearranges the elements of q and the elements within each triple. Of course, Bob did not believe in such magic, so he did just the same as above to see Alice's respond. For example, if n = 5 and p = [1, 4, 2, 3, 5], then the original array q will be [(1, 4, 2), (4, 2, 3), (2, 3, 5)]. Bob can then rearrange the numbers within each triple and the positions of the triples to get [(4, 3, 2), (2, 3, 5), (4, 1, 2)]. Note that [(1, 4, 2), (4, 2, 2), (3, 3, 5)] is not a valid rearrangement of q, as Bob is not allowed to swap numbers belong to different triples. As Alice's friend, you know for sure that Alice was just trying to show off, so you decided to save her some face by giving her any permutation p that is consistent with the array q she was given. Input The first line contains a single integer n (5 ≀ n ≀ 10^5) β€” the size of permutation p. The i-th of the next n-2 lines contains 3 integers q_{i, 1}, q_{i, 2}, q_{i, 3} (1 ≀ q_{i, j} ≀ n) β€” the elements of the i-th triple of the rearranged (shuffled) array q_i, in random order. Remember, that the numbers within each triple can be rearranged and also the positions of the triples can be rearranged. It is guaranteed that there is at least one permutation p that is consistent with the input. Output Print n distinct integers p_1, p_2, …, p_n (1 ≀ p_i ≀ n) such that p is consistent with array q. If there are multiple answers, print any. Example Input 5 4 3 2 2 3 5 4 1 2 Output 1 4 2 3 5 Submitted Solution: ``` import math,string,itertools,fractions,heapq,collections,re,array,bisect,copy,sys from sys import stdin, stdout # sys.setrecursionlimit(10**6) def modinv(n,p): return pow(n,p-2,p) def nc(): return map(int,ns().split()) def narr(): return list(map(int,ns().split())) def ns(): return input() def ni(): return int(input()) n = ni() P = collections.defaultdict(list) I = [[] for i in range(n + 1)] tuples = [] for i in range(n-2): q = sorted(narr()) tuples.append(q) P[(q[0], q[1])].append(i) P[(q[1], q[2])].append(i) P[(q[0], q[2])].append(i) I[q[0]].append(i) I[q[1]].append(i) I[q[2]].append(i) current_element = 0 current_tuple_index = -1 for i in range(n): if len(I[i]) == 1: current_element = i current_tuple_index = I[i][0] break def sort_tuple_given_first(p, x, y): p1 = (min(p, x), max(p, x)) p2 = (min(p, y), max(p, y)) if len(P[p1]) == 2: return [p, x, y] else: return [p, y, x] return t def sort_tuple_given_third(a, b, c): return list(reversed(sort_tuple_given_first(c, b, a))) def setdiff(x, y): return sorted(list(set(x).difference(set(y)))) first_pair = setdiff(tuples[current_tuple_index], [current_element]) current_tuple = sort_tuple_given_first(current_element, first_pair[0], first_pair[1]) answer = current_tuple.copy() for t in range(n-3): pair = setdiff(current_tuple, [current_element]) possible_tuple_indexes = I[pair[0]] for i in possible_tuple_indexes: if pair[1] in tuples[i] and current_element not in tuples[i]: current_tuple_index = i break next_tuple = tuples[current_tuple_index] third_element = setdiff(next_tuple, current_tuple)[0] first_two_elements = setdiff(next_tuple, [third_element]) next_tuple = sort_tuple_given_third(first_two_elements[0], first_two_elements[1], third_element) current_tuple = next_tuple current_element = current_tuple[0] answer.append(current_tuple[2]) print(' '.join(map(str, answer))) ```
instruction
0
90,258
12
180,516
No
output
1
90,258
12
180,517
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This problem is interactive. We have hidden a permutation p_1, p_2, ..., p_n of numbers from 1 to n from you, where n is even. You can try to guess it using the following queries: ? k a_1 a_2 ... a_k. In response, you will learn if the average of elements with indexes a_1, a_2, ..., a_k is an integer. In other words, you will receive 1 if \frac{p_{a_1} + p_{a_2} + ... + p_{a_k}}{k} is integer, and 0 otherwise. You have to guess the permutation. You can ask not more than 18n queries. Note that permutations [p_1, p_2, ..., p_k] and [n + 1 - p_1, n + 1 - p_2, ..., n + 1 - p_k] are indistinguishable. Therefore, you are guaranteed that p_1 ≀ n/2. Note that the permutation p is fixed before the start of the interaction and doesn't depend on your queries. In other words, interactor is not adaptive. Note that you don't have to minimize the number of queries. Input The first line contains a single integer n (2 ≀ n ≀ 800, n is even). Interaction You begin the interaction by reading n. To ask a question about elements on positions a_1, a_2, ..., a_k, in a separate line output ? k a_1 a_2 ... a_k Numbers in the query have to satisfy 1 ≀ a_i ≀ n, and all a_i have to be different. Don't forget to 'flush', to get the answer. In response, you will receive 1 if \frac{p_{a_1} + p_{a_2} + ... + p_{a_k}}{k} is integer, and 0 otherwise. In case your query is invalid or you asked more than 18n queries, the program will print -1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts. When you determine permutation, output ! p_1 p_2 ... p_n After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see documentation for other languages. Hack format For the hacks use the following format: The first line has to contain a single integer n (2 ≀ n ≀ 800, n is even). In the next line output n integers p_1, p_2, ..., p_n β€” the valid permutation of numbers from 1 to n. p_1 ≀ n/2 must hold. Example Input 2 1 2 Output ? 1 2 ? 1 1 ! 1 2 Submitted Solution: ``` T = 1 # T = int(input()) for t in range(1, T + 1): low = set([]) high = set([]) # k_1_group = set([]) n, k = map(int, input().split()) print("? ", end = "") print(*list(range(1, k + 1))) x, a_x = map(int, input().split()) k_1 = 0 # k_1 = 1 means low, k_1 = 2 means high for i in range(1, k + 1): if i == x: continue print("? ", end = "") for j in range(1, k + 2): if j != i: print(j, end = " ") print("") y, a_y = map(int, input().split()) if y == x and k_1 == 0: print("? ", end = "") for j in range(1, k + 2): if j != x: print(j, end = " ") print("") y, a_y = map(int, input().split()) if a_y < a_x: k_1 = 1 low.add(i) else: k_1 = 2 high.add(i) elif a_y < a_x: high.add(i) k_1 = 1 else: low.add(i) k_1 = 2 # print(high, low) print(len(low) + 1) ```
instruction
0
90,275
12
180,550
No
output
1
90,275
12
180,551
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This problem is interactive. We have hidden a permutation p_1, p_2, ..., p_n of numbers from 1 to n from you, where n is even. You can try to guess it using the following queries: ? k a_1 a_2 ... a_k. In response, you will learn if the average of elements with indexes a_1, a_2, ..., a_k is an integer. In other words, you will receive 1 if \frac{p_{a_1} + p_{a_2} + ... + p_{a_k}}{k} is integer, and 0 otherwise. You have to guess the permutation. You can ask not more than 18n queries. Note that permutations [p_1, p_2, ..., p_k] and [n + 1 - p_1, n + 1 - p_2, ..., n + 1 - p_k] are indistinguishable. Therefore, you are guaranteed that p_1 ≀ n/2. Note that the permutation p is fixed before the start of the interaction and doesn't depend on your queries. In other words, interactor is not adaptive. Note that you don't have to minimize the number of queries. Input The first line contains a single integer n (2 ≀ n ≀ 800, n is even). Interaction You begin the interaction by reading n. To ask a question about elements on positions a_1, a_2, ..., a_k, in a separate line output ? k a_1 a_2 ... a_k Numbers in the query have to satisfy 1 ≀ a_i ≀ n, and all a_i have to be different. Don't forget to 'flush', to get the answer. In response, you will receive 1 if \frac{p_{a_1} + p_{a_2} + ... + p_{a_k}}{k} is integer, and 0 otherwise. In case your query is invalid or you asked more than 18n queries, the program will print -1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts. When you determine permutation, output ! p_1 p_2 ... p_n After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see documentation for other languages. Hack format For the hacks use the following format: The first line has to contain a single integer n (2 ≀ n ≀ 800, n is even). In the next line output n integers p_1, p_2, ..., p_n β€” the valid permutation of numbers from 1 to n. p_1 ≀ n/2 must hold. Example Input 2 1 2 Output ? 1 2 ? 1 1 ! 1 2 Submitted Solution: ``` # -*- coding: utf-8 -*- """ Created on Wed Sep 23 05:53:26 2020 @author: Dark Soul """ [n,k]=list(map(int,input().split())) def query(a,n): prnt=['?'] for i in range(1,n+1): if i!=a: prnt.append(i) print(*prnt) [x,y]=list(map(int,input().split())) return (y,x) dic={} n=k+1 cnt=0 for i in range(1,n+1): a=query(i,n) try: dic[a]+=1 except: dic[a]=1 for keys in dic: cnt+=1 if cnt==len(dic)-1: ans=keys break print('!',ans[1]-1) ```
instruction
0
90,276
12
180,552
No
output
1
90,276
12
180,553
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This problem is interactive. We have hidden a permutation p_1, p_2, ..., p_n of numbers from 1 to n from you, where n is even. You can try to guess it using the following queries: ? k a_1 a_2 ... a_k. In response, you will learn if the average of elements with indexes a_1, a_2, ..., a_k is an integer. In other words, you will receive 1 if \frac{p_{a_1} + p_{a_2} + ... + p_{a_k}}{k} is integer, and 0 otherwise. You have to guess the permutation. You can ask not more than 18n queries. Note that permutations [p_1, p_2, ..., p_k] and [n + 1 - p_1, n + 1 - p_2, ..., n + 1 - p_k] are indistinguishable. Therefore, you are guaranteed that p_1 ≀ n/2. Note that the permutation p is fixed before the start of the interaction and doesn't depend on your queries. In other words, interactor is not adaptive. Note that you don't have to minimize the number of queries. Input The first line contains a single integer n (2 ≀ n ≀ 800, n is even). Interaction You begin the interaction by reading n. To ask a question about elements on positions a_1, a_2, ..., a_k, in a separate line output ? k a_1 a_2 ... a_k Numbers in the query have to satisfy 1 ≀ a_i ≀ n, and all a_i have to be different. Don't forget to 'flush', to get the answer. In response, you will receive 1 if \frac{p_{a_1} + p_{a_2} + ... + p_{a_k}}{k} is integer, and 0 otherwise. In case your query is invalid or you asked more than 18n queries, the program will print -1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts. When you determine permutation, output ! p_1 p_2 ... p_n After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see documentation for other languages. Hack format For the hacks use the following format: The first line has to contain a single integer n (2 ≀ n ≀ 800, n is even). In the next line output n integers p_1, p_2, ..., p_n β€” the valid permutation of numbers from 1 to n. p_1 ≀ n/2 must hold. Example Input 2 1 2 Output ? 1 2 ? 1 1 ! 1 2 Submitted Solution: ``` import sys n, k = map(int, input().split()) print("! 1") ```
instruction
0
90,277
12
180,554
No
output
1
90,277
12
180,555
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This problem is interactive. We have hidden a permutation p_1, p_2, ..., p_n of numbers from 1 to n from you, where n is even. You can try to guess it using the following queries: ? k a_1 a_2 ... a_k. In response, you will learn if the average of elements with indexes a_1, a_2, ..., a_k is an integer. In other words, you will receive 1 if \frac{p_{a_1} + p_{a_2} + ... + p_{a_k}}{k} is integer, and 0 otherwise. You have to guess the permutation. You can ask not more than 18n queries. Note that permutations [p_1, p_2, ..., p_k] and [n + 1 - p_1, n + 1 - p_2, ..., n + 1 - p_k] are indistinguishable. Therefore, you are guaranteed that p_1 ≀ n/2. Note that the permutation p is fixed before the start of the interaction and doesn't depend on your queries. In other words, interactor is not adaptive. Note that you don't have to minimize the number of queries. Input The first line contains a single integer n (2 ≀ n ≀ 800, n is even). Interaction You begin the interaction by reading n. To ask a question about elements on positions a_1, a_2, ..., a_k, in a separate line output ? k a_1 a_2 ... a_k Numbers in the query have to satisfy 1 ≀ a_i ≀ n, and all a_i have to be different. Don't forget to 'flush', to get the answer. In response, you will receive 1 if \frac{p_{a_1} + p_{a_2} + ... + p_{a_k}}{k} is integer, and 0 otherwise. In case your query is invalid or you asked more than 18n queries, the program will print -1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts. When you determine permutation, output ! p_1 p_2 ... p_n After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see documentation for other languages. Hack format For the hacks use the following format: The first line has to contain a single integer n (2 ≀ n ≀ 800, n is even). In the next line output n integers p_1, p_2, ..., p_n β€” the valid permutation of numbers from 1 to n. p_1 ≀ n/2 must hold. Example Input 2 1 2 Output ? 1 2 ? 1 1 ! 1 2 Submitted Solution: ``` import sys def minp(): return sys.stdin.readline().strip() def mint(): return int(minp()) def mints(): return map(int,minp().split()) def emit(x): print('?',' '.join(map(str,x))) sys.stdout.flush() s = minp().split() if len(s) == 1: s.append('-1') return tuple(map(int,s)) def emit1(x): z = [] for j in x: z.append((a[j-1],j)) z.sort() s = z[m-1] return tuple(map(int,s)) def solve(): n,k = mints() #global n,k #w = dict() w = [] for i in range(k+1): x = [] for j in range(k+1): if i != j: x.append(j+1) y = emit(x) if y[0] == -1: return w.append(y) w.sort(reverse=True) i = 0 while w[i] == w[0]: i += 1 #print('!',w[max(w.keys())]) print('!',i) sys.stdout.flush() #return w[max(w.keys())] #for i in range(mint()): solve() '''from random import randint while True: n = randint(2,500) was = [False]*(1001) a = [0]*n for i in range(n): while True: x = randint(0,1000) if not was[x]: was[x] = True break a[i] = x a = list(range(n,0,-1)) k = randint(1,n-1) m = randint(1,k) if m != solve(): print('k',k,'m', m,solve(),'a',a) break ''' ```
instruction
0
90,278
12
180,556
No
output
1
90,278
12
180,557
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Koa the Koala has a matrix A of n rows and m columns. Elements of this matrix are distinct integers from 1 to n β‹… m (each number from 1 to n β‹… m appears exactly once in the matrix). For any matrix M of n rows and m columns let's define the following: * The i-th row of M is defined as R_i(M) = [ M_{i1}, M_{i2}, …, M_{im} ] for all i (1 ≀ i ≀ n). * The j-th column of M is defined as C_j(M) = [ M_{1j}, M_{2j}, …, M_{nj} ] for all j (1 ≀ j ≀ m). Koa defines S(A) = (X, Y) as the spectrum of A, where X is the set of the maximum values in rows of A and Y is the set of the maximum values in columns of A. More formally: * X = \{ max(R_1(A)), max(R_2(A)), …, max(R_n(A)) \} * Y = \{ max(C_1(A)), max(C_2(A)), …, max(C_m(A)) \} Koa asks you to find some matrix A' of n rows and m columns, such that each number from 1 to n β‹… m appears exactly once in the matrix, and the following conditions hold: * S(A') = S(A) * R_i(A') is bitonic for all i (1 ≀ i ≀ n) * C_j(A') is bitonic for all j (1 ≀ j ≀ m) An array t (t_1, t_2, …, t_k) is called bitonic if it first increases and then decreases. More formally: t is bitonic if there exists some position p (1 ≀ p ≀ k) such that: t_1 < t_2 < … < t_p > t_{p+1} > … > t_k. Help Koa to find such matrix or to determine that it doesn't exist. Input The first line of the input contains two integers n and m (1 ≀ n, m ≀ 250) β€” the number of rows and columns of A. Each of the ollowing n lines contains m integers. The j-th integer in the i-th line denotes element A_{ij} (1 ≀ A_{ij} ≀ n β‹… m) of matrix A. It is guaranteed that every number from 1 to n β‹… m appears exactly once among elements of the matrix. Output If such matrix doesn't exist, print -1 on a single line. Otherwise, the output must consist of n lines, each one consisting of m space separated integers β€” a description of A'. The j-th number in the i-th line represents the element A'_{ij}. Every integer from 1 to n β‹… m should appear exactly once in A', every row and column in A' must be bitonic and S(A) = S(A') must hold. If there are many answers print any. Examples Input 3 3 3 5 6 1 7 9 4 8 2 Output 9 5 1 7 8 2 3 6 4 Input 2 2 4 1 3 2 Output 4 1 3 2 Input 3 4 12 10 8 6 3 4 5 7 2 11 9 1 Output 12 8 6 1 10 11 9 2 3 4 5 7 Note Let's analyze the first sample: For matrix A we have: * Rows: * R_1(A) = [3, 5, 6]; max(R_1(A)) = 6 * R_2(A) = [1, 7, 9]; max(R_2(A)) = 9 * R_3(A) = [4, 8, 2]; max(R_3(A)) = 8 * Columns: * C_1(A) = [3, 1, 4]; max(C_1(A)) = 4 * C_2(A) = [5, 7, 8]; max(C_2(A)) = 8 * C_3(A) = [6, 9, 2]; max(C_3(A)) = 9 * X = \{ max(R_1(A)), max(R_2(A)), max(R_3(A)) \} = \{ 6, 9, 8 \} * Y = \{ max(C_1(A)), max(C_2(A)), max(C_3(A)) \} = \{ 4, 8, 9 \} * So S(A) = (X, Y) = (\{ 6, 9, 8 \}, \{ 4, 8, 9 \}) For matrix A' we have: * Rows: * R_1(A') = [9, 5, 1]; max(R_1(A')) = 9 * R_2(A') = [7, 8, 2]; max(R_2(A')) = 8 * R_3(A') = [3, 6, 4]; max(R_3(A')) = 6 * Columns: * C_1(A') = [9, 7, 3]; max(C_1(A')) = 9 * C_2(A') = [5, 8, 6]; max(C_2(A')) = 8 * C_3(A') = [1, 2, 4]; max(C_3(A')) = 4 * Note that each of this arrays are bitonic. * X = \{ max(R_1(A')), max(R_2(A')), max(R_3(A')) \} = \{ 9, 8, 6 \} * Y = \{ max(C_1(A')), max(C_2(A')), max(C_3(A')) \} = \{ 9, 8, 4 \} * So S(A') = (X, Y) = (\{ 9, 8, 6 \}, \{ 9, 8, 4 \}) Submitted Solution: ``` s=input() n=input() print(s.count(n)) ```
instruction
0
90,322
12
180,644
No
output
1
90,322
12
180,645
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Koa the Koala has a matrix A of n rows and m columns. Elements of this matrix are distinct integers from 1 to n β‹… m (each number from 1 to n β‹… m appears exactly once in the matrix). For any matrix M of n rows and m columns let's define the following: * The i-th row of M is defined as R_i(M) = [ M_{i1}, M_{i2}, …, M_{im} ] for all i (1 ≀ i ≀ n). * The j-th column of M is defined as C_j(M) = [ M_{1j}, M_{2j}, …, M_{nj} ] for all j (1 ≀ j ≀ m). Koa defines S(A) = (X, Y) as the spectrum of A, where X is the set of the maximum values in rows of A and Y is the set of the maximum values in columns of A. More formally: * X = \{ max(R_1(A)), max(R_2(A)), …, max(R_n(A)) \} * Y = \{ max(C_1(A)), max(C_2(A)), …, max(C_m(A)) \} Koa asks you to find some matrix A' of n rows and m columns, such that each number from 1 to n β‹… m appears exactly once in the matrix, and the following conditions hold: * S(A') = S(A) * R_i(A') is bitonic for all i (1 ≀ i ≀ n) * C_j(A') is bitonic for all j (1 ≀ j ≀ m) An array t (t_1, t_2, …, t_k) is called bitonic if it first increases and then decreases. More formally: t is bitonic if there exists some position p (1 ≀ p ≀ k) such that: t_1 < t_2 < … < t_p > t_{p+1} > … > t_k. Help Koa to find such matrix or to determine that it doesn't exist. Input The first line of the input contains two integers n and m (1 ≀ n, m ≀ 250) β€” the number of rows and columns of A. Each of the ollowing n lines contains m integers. The j-th integer in the i-th line denotes element A_{ij} (1 ≀ A_{ij} ≀ n β‹… m) of matrix A. It is guaranteed that every number from 1 to n β‹… m appears exactly once among elements of the matrix. Output If such matrix doesn't exist, print -1 on a single line. Otherwise, the output must consist of n lines, each one consisting of m space separated integers β€” a description of A'. The j-th number in the i-th line represents the element A'_{ij}. Every integer from 1 to n β‹… m should appear exactly once in A', every row and column in A' must be bitonic and S(A) = S(A') must hold. If there are many answers print any. Examples Input 3 3 3 5 6 1 7 9 4 8 2 Output 9 5 1 7 8 2 3 6 4 Input 2 2 4 1 3 2 Output 4 1 3 2 Input 3 4 12 10 8 6 3 4 5 7 2 11 9 1 Output 12 8 6 1 10 11 9 2 3 4 5 7 Note Let's analyze the first sample: For matrix A we have: * Rows: * R_1(A) = [3, 5, 6]; max(R_1(A)) = 6 * R_2(A) = [1, 7, 9]; max(R_2(A)) = 9 * R_3(A) = [4, 8, 2]; max(R_3(A)) = 8 * Columns: * C_1(A) = [3, 1, 4]; max(C_1(A)) = 4 * C_2(A) = [5, 7, 8]; max(C_2(A)) = 8 * C_3(A) = [6, 9, 2]; max(C_3(A)) = 9 * X = \{ max(R_1(A)), max(R_2(A)), max(R_3(A)) \} = \{ 6, 9, 8 \} * Y = \{ max(C_1(A)), max(C_2(A)), max(C_3(A)) \} = \{ 4, 8, 9 \} * So S(A) = (X, Y) = (\{ 6, 9, 8 \}, \{ 4, 8, 9 \}) For matrix A' we have: * Rows: * R_1(A') = [9, 5, 1]; max(R_1(A')) = 9 * R_2(A') = [7, 8, 2]; max(R_2(A')) = 8 * R_3(A') = [3, 6, 4]; max(R_3(A')) = 6 * Columns: * C_1(A') = [9, 7, 3]; max(C_1(A')) = 9 * C_2(A') = [5, 8, 6]; max(C_2(A')) = 8 * C_3(A') = [1, 2, 4]; max(C_3(A')) = 4 * Note that each of this arrays are bitonic. * X = \{ max(R_1(A')), max(R_2(A')), max(R_3(A')) \} = \{ 9, 8, 6 \} * Y = \{ max(C_1(A')), max(C_2(A')), max(C_3(A')) \} = \{ 9, 8, 4 \} * So S(A') = (X, Y) = (\{ 9, 8, 6 \}, \{ 9, 8, 4 \}) Submitted Solution: ``` import sys input = sys.stdin.readline from operator import itemgetter n,m=map(int,input().split()) A=[list(map(int,input().split())) for i in range(n)] R=[] for i in range(n): R.append((max(A[i]),i)) R.sort(key=itemgetter(0)) A2=[] for x,i in R: A2.append(A[i]) C=[] for i in range(m): C.append((max([A2[j][i] for j in range(n)]),i)) C.sort(key=itemgetter(0)) A3=[[0]*m for i in range(n)] for i in range(m): x=C[i][1] for j in range(n): A3[j][i]=A2[j][x] #print(A3) for a in A3: print(*a) ```
instruction
0
90,323
12
180,646
No
output
1
90,323
12
180,647
Provide tags and a correct Python 3 solution for this coding contest problem. The Little Elephant has got a problem β€” somebody has been touching his sorted by non-decreasing array a of length n and possibly swapped some elements of the array. The Little Elephant doesn't want to call the police until he understands if he could have accidentally changed the array himself. He thinks that he could have accidentally changed array a, only if array a can be sorted in no more than one operation of swapping elements (not necessarily adjacent). That is, the Little Elephant could have accidentally swapped some two elements. Help the Little Elephant, determine if he could have accidentally changed the array a, sorted by non-decreasing, himself. Input The first line contains a single integer n (2 ≀ n ≀ 105) β€” the size of array a. The next line contains n positive integers, separated by single spaces and not exceeding 109, β€” array a. Note that the elements of the array are not necessarily distinct numbers. Output In a single line print "YES" (without the quotes) if the Little Elephant could have accidentally changed the array himself, and "NO" (without the quotes) otherwise. Examples Input 2 1 2 Output YES Input 3 3 2 1 Output YES Input 4 4 3 2 1 Output NO Note In the first sample the array has already been sorted, so to sort it, we need 0 swap operations, that is not more than 1. Thus, the answer is "YES". In the second sample we can sort the array if we swap elements 1 and 3, so we need 1 swap operation to sort the array. Thus, the answer is "YES". In the third sample we can't sort the array in more than one swap operation, so the answer is "NO".
instruction
0
90,403
12
180,806
Tags: implementation, sortings Correct Solution: ``` n=int(input()) arr1=list(map(int,input().split())) count=0 j=0 arr2=sorted(arr1) for i in range(n): if(arr1[i]!=arr2[i]): count+=1 if(count<=2): print('YES') else: print('NO') ```
output
1
90,403
12
180,807