message
stringlengths
2
433k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
113
108k
cluster
float64
12
12
__index_level_0__
int64
226
217k
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ehab loves number theory, but for some reason he hates the number x. Given an array a, find the length of its longest subarray such that the sum of its elements isn't divisible by x, or determine that such subarray doesn't exist. An array a is a subarray of an array b if a can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. Input The first line contains an integer t (1 ≤ t ≤ 5) — the number of test cases you need to solve. The description of the test cases follows. The first line of each test case contains 2 integers n and x (1 ≤ n ≤ 10^5, 1 ≤ x ≤ 10^4) — the number of elements in the array a and the number that Ehab hates. The second line contains n space-separated integers a_1, a_2, …, a_{n} (0 ≤ a_i ≤ 10^4) — the elements of the array a. Output For each testcase, print the length of the longest subarray whose sum isn't divisible by x. If there's no such subarray, print -1. Example Input 3 3 3 1 2 3 3 4 1 2 3 2 2 0 6 Output 2 3 -1 Note In the first test case, the subarray [2,3] has sum of elements 5, which isn't divisible by 3. In the second test case, the sum of elements of the whole array is 6, which isn't divisible by 4. In the third test case, all subarrays have an even sum, so the answer is -1. Submitted Solution: ``` def ii(): return int(input()) def mi(): return map(int, input().split()) def ai(): return list(map(int, input().split())) for _ in range(ii()): n = ii() lst = list(set(ai())) print(len(lst)) ```
instruction
0
91,092
12
182,184
Yes
output
1
91,092
12
182,185
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ehab loves number theory, but for some reason he hates the number x. Given an array a, find the length of its longest subarray such that the sum of its elements isn't divisible by x, or determine that such subarray doesn't exist. An array a is a subarray of an array b if a can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. Input The first line contains an integer t (1 ≤ t ≤ 5) — the number of test cases you need to solve. The description of the test cases follows. The first line of each test case contains 2 integers n and x (1 ≤ n ≤ 10^5, 1 ≤ x ≤ 10^4) — the number of elements in the array a and the number that Ehab hates. The second line contains n space-separated integers a_1, a_2, …, a_{n} (0 ≤ a_i ≤ 10^4) — the elements of the array a. Output For each testcase, print the length of the longest subarray whose sum isn't divisible by x. If there's no such subarray, print -1. Example Input 3 3 3 1 2 3 3 4 1 2 3 2 2 0 6 Output 2 3 -1 Note In the first test case, the subarray [2,3] has sum of elements 5, which isn't divisible by 3. In the second test case, the sum of elements of the whole array is 6, which isn't divisible by 4. In the third test case, all subarrays have an even sum, so the answer is -1. Submitted Solution: ``` import sys t=int(sys.stdin.readline()) for i in range (t): a=int(sys.stdin.readline()) aa = (map(int, sys.stdin.readline().strip().split())) b = set() for num in aa: b.add(num) print(len(b)) ```
instruction
0
91,093
12
182,186
Yes
output
1
91,093
12
182,187
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ehab loves number theory, but for some reason he hates the number x. Given an array a, find the length of its longest subarray such that the sum of its elements isn't divisible by x, or determine that such subarray doesn't exist. An array a is a subarray of an array b if a can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. Input The first line contains an integer t (1 ≤ t ≤ 5) — the number of test cases you need to solve. The description of the test cases follows. The first line of each test case contains 2 integers n and x (1 ≤ n ≤ 10^5, 1 ≤ x ≤ 10^4) — the number of elements in the array a and the number that Ehab hates. The second line contains n space-separated integers a_1, a_2, …, a_{n} (0 ≤ a_i ≤ 10^4) — the elements of the array a. Output For each testcase, print the length of the longest subarray whose sum isn't divisible by x. If there's no such subarray, print -1. Example Input 3 3 3 1 2 3 3 4 1 2 3 2 2 0 6 Output 2 3 -1 Note In the first test case, the subarray [2,3] has sum of elements 5, which isn't divisible by 3. In the second test case, the sum of elements of the whole array is 6, which isn't divisible by 4. In the third test case, all subarrays have an even sum, so the answer is -1. Submitted Solution: ``` n = int(input()) l = [] l = list(map(int,input().split())) k = set(l) m = len(k) print(m) ```
instruction
0
91,094
12
182,188
No
output
1
91,094
12
182,189
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ehab loves number theory, but for some reason he hates the number x. Given an array a, find the length of its longest subarray such that the sum of its elements isn't divisible by x, or determine that such subarray doesn't exist. An array a is a subarray of an array b if a can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. Input The first line contains an integer t (1 ≤ t ≤ 5) — the number of test cases you need to solve. The description of the test cases follows. The first line of each test case contains 2 integers n and x (1 ≤ n ≤ 10^5, 1 ≤ x ≤ 10^4) — the number of elements in the array a and the number that Ehab hates. The second line contains n space-separated integers a_1, a_2, …, a_{n} (0 ≤ a_i ≤ 10^4) — the elements of the array a. Output For each testcase, print the length of the longest subarray whose sum isn't divisible by x. If there's no such subarray, print -1. Example Input 3 3 3 1 2 3 3 4 1 2 3 2 2 0 6 Output 2 3 -1 Note In the first test case, the subarray [2,3] has sum of elements 5, which isn't divisible by 3. In the second test case, the sum of elements of the whole array is 6, which isn't divisible by 4. In the third test case, all subarrays have an even sum, so the answer is -1. Submitted Solution: ``` for _ in range(int(input())): n,d=map(int,input().split()) arr=list(map(int,input().split())) ans=-1 for i in range(n): if arr[i]%d:ans=max(ans,i+1) for j in range(n-1,-1,-1): if arr[j]%d:ans=max(ans,n-j-1) print(ans) ```
instruction
0
91,095
12
182,190
No
output
1
91,095
12
182,191
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ehab loves number theory, but for some reason he hates the number x. Given an array a, find the length of its longest subarray such that the sum of its elements isn't divisible by x, or determine that such subarray doesn't exist. An array a is a subarray of an array b if a can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. Input The first line contains an integer t (1 ≤ t ≤ 5) — the number of test cases you need to solve. The description of the test cases follows. The first line of each test case contains 2 integers n and x (1 ≤ n ≤ 10^5, 1 ≤ x ≤ 10^4) — the number of elements in the array a and the number that Ehab hates. The second line contains n space-separated integers a_1, a_2, …, a_{n} (0 ≤ a_i ≤ 10^4) — the elements of the array a. Output For each testcase, print the length of the longest subarray whose sum isn't divisible by x. If there's no such subarray, print -1. Example Input 3 3 3 1 2 3 3 4 1 2 3 2 2 0 6 Output 2 3 -1 Note In the first test case, the subarray [2,3] has sum of elements 5, which isn't divisible by 3. In the second test case, the sum of elements of the whole array is 6, which isn't divisible by 4. In the third test case, all subarrays have an even sum, so the answer is -1. Submitted Solution: ``` import sys def get_ints(): return map(int, sys.stdin.readline().strip().split()) def get_array(): return list(map(int, sys.stdin.readline().strip().split())) def input(): return sys.stdin.readline().strip() # def maxlength(arr,x,i,j,n,s): # if(i>=j): # return for _ in range(int(input())): n,x = get_ints() arr = get_array() s=0 for i in arr: s+=i # ans = maxlenght(arr,x,0,n,n,s) i=0 j=n-1 f=0 check=0 length = n if(s%x!=0): print(n) else: while(i<=j): if(i==j): if(arr[i]%x!=0): n=1 else: n=-1 break if((s-arr[i])%x!=0): s=s-arr[i] n=n-1 break elif((s-arr[j])%x!=0): s=s-arr[j] n=n-1 break else: if(arr[i]==0): check=check+1 if(arr[j]==0): check=check+1 i=i+1 j=j-1 n=n-2 s=s-arr[i]-arr[j] if(length == n): print(-1) elif(n==0): print(-1) else: print(n+check) ```
instruction
0
91,096
12
182,192
No
output
1
91,096
12
182,193
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ehab loves number theory, but for some reason he hates the number x. Given an array a, find the length of its longest subarray such that the sum of its elements isn't divisible by x, or determine that such subarray doesn't exist. An array a is a subarray of an array b if a can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. Input The first line contains an integer t (1 ≤ t ≤ 5) — the number of test cases you need to solve. The description of the test cases follows. The first line of each test case contains 2 integers n and x (1 ≤ n ≤ 10^5, 1 ≤ x ≤ 10^4) — the number of elements in the array a and the number that Ehab hates. The second line contains n space-separated integers a_1, a_2, …, a_{n} (0 ≤ a_i ≤ 10^4) — the elements of the array a. Output For each testcase, print the length of the longest subarray whose sum isn't divisible by x. If there's no such subarray, print -1. Example Input 3 3 3 1 2 3 3 4 1 2 3 2 2 0 6 Output 2 3 -1 Note In the first test case, the subarray [2,3] has sum of elements 5, which isn't divisible by 3. In the second test case, the sum of elements of the whole array is 6, which isn't divisible by 4. In the third test case, all subarrays have an even sum, so the answer is -1. Submitted Solution: ``` x=int(input()) for i in range(0,x): s=int(input()) lst=[int(x) for x in input().split()] n=min(lst) s=0 for i in range(len(lst)): if lst[i]>n: s+=1 print(s+1) ```
instruction
0
91,097
12
182,194
No
output
1
91,097
12
182,195
Provide tags and a correct Python 3 solution for this coding contest problem. You like numbers, don't you? Nastia has a lot of numbers and she wants to share them with you! Isn't it amazing? Let a_i be how many numbers i (1 ≤ i ≤ k) you have. An n × n matrix is called beautiful if it contains all the numbers you have, and for each 2 × 2 submatrix of the original matrix is satisfied: 1. The number of occupied cells doesn't exceed 3; 2. The numbers on each diagonal are distinct. Make a beautiful matrix of minimum size. Input The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases. The first line of each test case contains 2 integers m and k (1 ≤ m, k ≤ 10^5) — how many numbers Nastia gave you and the length of the array a, respectively. The second line of each test case contains k integers a_1, a_2, …, a_{k} (0 ≤ a_i ≤ m, a_1 + a_2 + … + a_{k} = m), where a_i is how many numbers i you have. It's guaranteed that the sum of m and k in one test doesn't exceed 2 ⋅ 10^5. Output For each t test case print a single integer n — the size of the beautiful matrix. In the next n lines print n integers b_{i, j} (0 ≤ b_{i, j} ≤ k; if position is empty, print b_{i, j} = 0) — the beautiful matrix b you made up. Example Input 2 3 4 2 0 0 1 15 4 2 4 8 1 Output 2 4 1 0 1 5 3 0 0 2 2 3 2 3 3 0 0 1 0 4 0 3 0 0 0 0 2 1 3 3 3 Note Note that 0 in this problem represents a blank, not a number. Examples of possible answers for the first test case: \begin{array}{cc} 1 & 1 \\\ 4 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 4 \\\ 1 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 0 \\\ 1 & 1 \\\ \end{array} Examples of not beautiful matrices for the first test case: \begin{array}{cc} 1 & 0 \\\ 4 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 1 \\\ 7 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 0 \\\ 4 & 0 \\\ \end{array} The example of the not beautiful matrix for the second test case: \begin{array}{cc} 3 & 4 & 0 & 2 & 2 \\\ 3 & 2 & 3 & 3 & 0 \\\ 0 & 1 & 0 & 0 & 0 \\\ 3 & 0 & 0 & 0 & 0 \\\ 2 & 1 & 3 & 3 & 3 \\\ \end{array} Everything is okay, except the left-top submatrix contains 4 numbers.
instruction
0
91,158
12
182,316
Tags: binary search, constructive algorithms, greedy Correct Solution: ``` from bisect import bisect,bisect_left from collections import * from heapq import * from math import gcd,ceil,sqrt,floor,inf from itertools import * from operator import add,mul,sub,xor,truediv,floordiv from functools import * #------------------------------------------------------------------------ import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #------------------------------------------------------------------------ def RL(): return map(int, sys.stdin.readline().split()) def RLL(): return list(map(int, sys.stdin.readline().split())) def N(): return int(input()) def A(n):return [0]*n def AI(n,x): return [x]*n def A2(n,m): return [[0]*m for i in range(n)] def G(n): return [[] for i in range(n)] def GP(it): return [[ch,len(list(g))] for ch,g in groupby(it)] #------------------------------------------------------------------------ from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc mod=10**9+7 farr=[1] ifa=[] def fact(x,mod=0): if mod: while x>=len(farr): farr.append(farr[-1]*len(farr)%mod) else: while x>=len(farr): farr.append(farr[-1]*len(farr)) return farr[x] def ifact(x,mod): global ifa fact(x,mod) ifa.append(pow(farr[-1],mod-2,mod)) for i in range(x,0,-1): ifa.append(ifa[-1]*i%mod) ifa.reverse() def per(i,j,mod=0): if i<j: return 0 if not mod: return fact(i)//fact(i-j) return farr[i]*ifa[i-j]%mod def com(i,j,mod=0): if i<j: return 0 if not mod: return per(i,j)//fact(j) return per(i,j,mod)*ifa[j]%mod def catalan(n): return com(2*n,n)//(n+1) def isprime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True def floorsum(a,b,c,n):#sum((a*i+b)//c for i in range(n+1)) if a==0:return b//c*(n+1) if a>=c or b>=c: return floorsum(a%c,b%c,c,n)+b//c*(n+1)+a//c*n*(n+1)//2 m=(a*n+b)//c return n*m-floorsum(c,c-b-1,a,m-1) def inverse(a,m): a%=m if a<=1: return a return ((1-inverse(m,a)*m)//a)%m def lowbit(n): return n&-n class BIT: def __init__(self,arr): self.arr=arr self.n=len(arr)-1 def update(self,x,v): while x<=self.n: self.arr[x]+=v x+=x&-x def query(self,x): ans=0 while x: ans+=self.arr[x] x&=x-1 return ans class ST: def __init__(self,arr):#n!=0 n=len(arr) mx=n.bit_length()#取不到 self.st=[[0]*mx for i in range(n)] for i in range(n): self.st[i][0]=arr[i] for j in range(1,mx): for i in range(n-(1<<j)+1): self.st[i][j]=max(self.st[i][j-1],self.st[i+(1<<j-1)][j-1]) def query(self,l,r): if l>r:return -inf s=(r+1-l).bit_length()-1 return max(self.st[l][s],self.st[r-(1<<s)+1][s]) class DSU:#容量+路径压缩 def __init__(self,n): self.c=[-1]*n def same(self,x,y): return self.find(x)==self.find(y) def find(self,x): if self.c[x]<0: return x self.c[x]=self.find(self.c[x]) return self.c[x] def union(self,u,v): u,v=self.find(u),self.find(v) if u==v: return False if self.c[u]>self.c[v]: u,v=v,u self.c[u]+=self.c[v] self.c[v]=u return True def size(self,x): return -self.c[self.find(x)] class UFS:#秩+路径 def __init__(self,n): self.parent=[i for i in range(n)] self.ranks=[0]*n def find(self,x): if x!=self.parent[x]: self.parent[x]=self.find(self.parent[x]) return self.parent[x] def union(self,u,v): pu,pv=self.find(u),self.find(v) if pu==pv: return False if self.ranks[pu]>=self.ranks[pv]: self.parent[pv]=pu if self.ranks[pv]==self.ranks[pu]: self.ranks[pu]+=1 else: self.parent[pu]=pv class UF:#秩+路径+容量,边数 def __init__(self,n): self.parent=[i for i in range(n)] self.ranks=[0]*n self.size=AI(n,1) self.edge=A(n) def find(self,x): if x!=self.parent[x]: self.parent[x]=self.find(self.parent[x]) return self.parent[x] def union(self,u,v): pu,pv=self.find(u),self.find(v) if pu==pv: self.edge[pu]+=1 return False if self.ranks[pu]>=self.ranks[pv]: self.parent[pv]=pu self.edge[pu]+=self.edge[pv]+1 self.size[pu]+=self.size[pv] if self.ranks[pv]==self.ranks[pu]: self.ranks[pu]+=1 else: self.parent[pu]=pv self.edge[pv]+=self.edge[pu]+1 self.size[pv]+=self.size[pu] def Prime(n): c=0 prime=[] flag=[0]*(n+1) for i in range(2,n+1): if not flag[i]: prime.append(i) c+=1 for j in range(c): if i*prime[j]>n: break flag[i*prime[j]]=prime[j] if i%prime[j]==0: break return flag def dij(s,graph): d=AI(n,inf) d[s]=0 heap=[(0,s)] vis=A(n) while heap: dis,u=heappop(heap) if vis[u]: continue vis[u]=1 for v,w in graph[u]: if d[v]>d[u]+w: d[v]=d[u]+w heappush(heap,(d[v],v)) return d def bell(s,g):#bellman-Ford dis=AI(n,inf) dis[s]=0 for i in range(n-1): for u,v,w in edge: if dis[v]>dis[u]+w: dis[v]=dis[u]+w change=A(n) for i in range(n): for u,v,w in edge: if dis[v]>dis[u]+w: dis[v]=dis[u]+w change[v]=1 return dis def lcm(a,b): return a*b//gcd(a,b) def lis(nums): res=[] for k in nums: i=bisect.bisect_left(res,k) if i==len(res): res.append(k) else: res[i]=k return len(res) def RP(nums):#逆序对 n = len(nums) s=set(nums) d={} for i,k in enumerate(sorted(s),1): d[k]=i bi=BIT([0]*(len(s)+1)) ans=0 for i in range(n-1,-1,-1): ans+=bi.query(d[nums[i]]-1) bi.update(d[nums[i]],1) return ans class DLN: def __init__(self,val): self.val=val self.pre=None self.next=None def nb(i,j,n,m): for ni,nj in [[i+1,j],[i-1,j],[i,j-1],[i,j+1]]: if 0<=ni<n and 0<=nj<m: yield ni,nj def topo(n): q=deque() res=[] for i in range(1,n+1): if ind[i]==0: q.append(i) res.append(i) while q: u=q.popleft() for v in g[u]: ind[v]-=1 if ind[v]==0: q.append(v) res.append(v) return res @bootstrap def gdfs(r,p): for ch in g[r]: if ch!=p: yield gdfs(ch,r) yield None #from random import randint def check(i,j): if not ans[i][j]:return True for ni,nj in [[i-1,j-1],[i+1,j+1],[i+1,j-1],[i-1,j+1]]: if 0<=ni<l and 0<=nj<l and ans[ni][nj]==ans[i][j]: return False return True t=N() for i in range(t): m,k=RL() a=RLL() l=1 r=m ma=max(a) while l<r: n=(l+r)>>1 if n&1: if (3*n**2+2*n-1)//4>=m and (n+1)*n//2>=ma: r=n else: l=n+1 else: if 3*n*n//4>=m and n*n//2>=ma: r=n else: l=n+1 c={} res=[] for i in range(k): if a[i]: res+=[i+1]*a[i] c[i+1]=a[i] res.sort(key=lambda x: -c[x]) ans=A2(l,l) p=0 for i in range(0,l,2): for j in range(0,l): ans[i][j]=res[p] p+=1 if p==len(res):break if p==len(res):break if p<len(res): for i in range(1,l,2): for j in range(0,l,2): ans[i][j]=res[p] p+=1 if p==len(res):break if p==len(res):break ci,cj=0,0 for i in range(0,l,2): for j in range(1,l): if not check(i,j): ans[i][j],ans[ci][cj]=ans[ci][cj],ans[i][j] cj+=2 if cj>=l: cj=0 ci=ci+2 print(l) for r in ans: print(*r) ''' sys.setrecursionlimit(200000) import threading threading.stack_size(10**8) t=threading.Thr ead(target=main) t.start() t.join() ''' ```
output
1
91,158
12
182,317
Provide tags and a correct Python 3 solution for this coding contest problem. You like numbers, don't you? Nastia has a lot of numbers and she wants to share them with you! Isn't it amazing? Let a_i be how many numbers i (1 ≤ i ≤ k) you have. An n × n matrix is called beautiful if it contains all the numbers you have, and for each 2 × 2 submatrix of the original matrix is satisfied: 1. The number of occupied cells doesn't exceed 3; 2. The numbers on each diagonal are distinct. Make a beautiful matrix of minimum size. Input The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases. The first line of each test case contains 2 integers m and k (1 ≤ m, k ≤ 10^5) — how many numbers Nastia gave you and the length of the array a, respectively. The second line of each test case contains k integers a_1, a_2, …, a_{k} (0 ≤ a_i ≤ m, a_1 + a_2 + … + a_{k} = m), where a_i is how many numbers i you have. It's guaranteed that the sum of m and k in one test doesn't exceed 2 ⋅ 10^5. Output For each t test case print a single integer n — the size of the beautiful matrix. In the next n lines print n integers b_{i, j} (0 ≤ b_{i, j} ≤ k; if position is empty, print b_{i, j} = 0) — the beautiful matrix b you made up. Example Input 2 3 4 2 0 0 1 15 4 2 4 8 1 Output 2 4 1 0 1 5 3 0 0 2 2 3 2 3 3 0 0 1 0 4 0 3 0 0 0 0 2 1 3 3 3 Note Note that 0 in this problem represents a blank, not a number. Examples of possible answers for the first test case: \begin{array}{cc} 1 & 1 \\\ 4 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 4 \\\ 1 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 0 \\\ 1 & 1 \\\ \end{array} Examples of not beautiful matrices for the first test case: \begin{array}{cc} 1 & 0 \\\ 4 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 1 \\\ 7 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 0 \\\ 4 & 0 \\\ \end{array} The example of the not beautiful matrix for the second test case: \begin{array}{cc} 3 & 4 & 0 & 2 & 2 \\\ 3 & 2 & 3 & 3 & 0 \\\ 0 & 1 & 0 & 0 & 0 \\\ 3 & 0 & 0 & 0 & 0 \\\ 2 & 1 & 3 & 3 & 3 \\\ \end{array} Everything is okay, except the left-top submatrix contains 4 numbers.
instruction
0
91,159
12
182,318
Tags: binary search, constructive algorithms, greedy Correct Solution: ``` from random import randint DEBUG = 0 for _ in range(int(input())): if DEBUG: k = randint(2, 4) maxcnt = randint(1, 100) cnt = [randint(1, maxcnt) for i in range(k)] m = sum(cnt) #print(m, k) #print(*cnt) cnt = sorted(enumerate(cnt), key=lambda x: -x[1]) else: m, k = list(map(int, input().split())) cnt = sorted(enumerate(map(int, input().split())), key=lambda x: -x[1]) l = 0 r = m while r - l > 1: mid = (r + l) // 2 if mid * ((mid + 1) // 2) >= cnt[0][1] and (mid // 2) ** 2 + m <= mid ** 2: r = mid else: l = mid size = r queue = [] #for it in range((size - 1) // 4 + 1): #queue.extend([(i, it * 4) for i in range(size)]) #if it * 4 + 2 < size: #queue.extend([(i, it * 4 + 2) for i in range(1, size, 2)]) #for it in range((size - 1) // 4 + 1): #if it * 4 + 2 < size: #queue.extend([(i, it * 4 + 2) for i in range(0, size, 2)]) #queue.extend([(i, j) for i in range(0, size, 2) for j in range(1, size, 2)]) #for it in range((size - 1) // 2 + 1): #queue.extend([(it * 2, j) for j in range(0, size, 4)]) #if it * 2 + 1 < size: #queue.extend([(it * 2 + 1, j) for j in range(0, size, 2)]) #queue.extend([(i, j) for i in range(0, size, 2) for j in range(2, size, 4)]) #queue.extend([(i, j) for i in range(0, size, 2) for j in range(1, size, 2)]) queue.extend([(i, j) for i in range(1, size, 2) for j in range(0, size, 2)]) queue.extend([(i, j) for i in range(0, size, 2) for j in range(0, size, 4)]) queue.extend([(i, j) for i in range(0, size, 2) for j in range(2, size, 4)]) queue.extend([(i, j) for i in range(0, size, 2) for j in range(1, size, 2)]) a = [[0] * size for i in range(size)] ind = 0 rest = cnt[ind][1] for i, j in queue: while not rest: ind += 1 if ind < k: rest = cnt[ind][1] else: break else: a[i][j] = cnt[ind][0] + 1 rest -= 1 continue break if not DEBUG: print(size) for row in a: print(*row) if DEBUG: for i in range(size - 1): for j in range(size - 1): if a[i][j] == a[i + 1][j + 1] != 0 or a[i + 1][j] == a[i][j + 1] != 0: print("Oops...") print(m, k) print(*cnt) break else: continue break else: continue break ```
output
1
91,159
12
182,319
Provide tags and a correct Python 3 solution for this coding contest problem. You like numbers, don't you? Nastia has a lot of numbers and she wants to share them with you! Isn't it amazing? Let a_i be how many numbers i (1 ≤ i ≤ k) you have. An n × n matrix is called beautiful if it contains all the numbers you have, and for each 2 × 2 submatrix of the original matrix is satisfied: 1. The number of occupied cells doesn't exceed 3; 2. The numbers on each diagonal are distinct. Make a beautiful matrix of minimum size. Input The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases. The first line of each test case contains 2 integers m and k (1 ≤ m, k ≤ 10^5) — how many numbers Nastia gave you and the length of the array a, respectively. The second line of each test case contains k integers a_1, a_2, …, a_{k} (0 ≤ a_i ≤ m, a_1 + a_2 + … + a_{k} = m), where a_i is how many numbers i you have. It's guaranteed that the sum of m and k in one test doesn't exceed 2 ⋅ 10^5. Output For each t test case print a single integer n — the size of the beautiful matrix. In the next n lines print n integers b_{i, j} (0 ≤ b_{i, j} ≤ k; if position is empty, print b_{i, j} = 0) — the beautiful matrix b you made up. Example Input 2 3 4 2 0 0 1 15 4 2 4 8 1 Output 2 4 1 0 1 5 3 0 0 2 2 3 2 3 3 0 0 1 0 4 0 3 0 0 0 0 2 1 3 3 3 Note Note that 0 in this problem represents a blank, not a number. Examples of possible answers for the first test case: \begin{array}{cc} 1 & 1 \\\ 4 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 4 \\\ 1 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 0 \\\ 1 & 1 \\\ \end{array} Examples of not beautiful matrices for the first test case: \begin{array}{cc} 1 & 0 \\\ 4 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 1 \\\ 7 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 0 \\\ 4 & 0 \\\ \end{array} The example of the not beautiful matrix for the second test case: \begin{array}{cc} 3 & 4 & 0 & 2 & 2 \\\ 3 & 2 & 3 & 3 & 0 \\\ 0 & 1 & 0 & 0 & 0 \\\ 3 & 0 & 0 & 0 & 0 \\\ 2 & 1 & 3 & 3 & 3 \\\ \end{array} Everything is okay, except the left-top submatrix contains 4 numbers.
instruction
0
91,160
12
182,320
Tags: binary search, constructive algorithms, greedy Correct Solution: ``` from math import sqrt, ceil import sys def putin(): return map(int, sys.stdin.readline().split()) def sol(): m, k = putin() A = list(putin()) A = sorted(list(enumerate(A)), reverse=True, key=lambda x: x[1]) B = [] C = [] for elem in A: if len(B) > len(C): C += [elem[0] + 1] * elem[1] else: B += [elem[0] + 1] * elem[1] if len(C) > len(B): C, B = B, C even_n = ceil(max(sqrt(4 * m / 3), sqrt(2 * len(B)))) if even_n % 2 == 1: even_n += 1 odd_n = even_n - 1 if odd_n ** 2 - (odd_n - 1) ** 2 / 4 >= m and odd_n * (odd_n + 1) / 2 >= len(B): n = odd_n else: n = even_n if n % 2 == 0: C += [0] * (3 * n ** 2 // 4 - len(B) - len(C)) else: C += [0] * (n ** 2 - (n - 1) ** 2 // 4 - len(B) - len(C)) if n % 2 == 0: border = n ** 2 // 4 else: border = (n - 1) * (n + 1) // 4 B, D = B[:border], B[border:] D += C[border:] C = C[:border] B_cnt = 0 C_cnt = 0 D_cnt = 0 print(n) for i in range(n): for j in range(n): if i % 2 == 1 and j % 2 == 1: print(0, end=' ') elif i % 2 == 1: print(B[B_cnt], end=' ') B_cnt += 1 elif j % 2 == 1: print(C[C_cnt], end=' ') C_cnt += 1 else: print(D[D_cnt], end=' ') D_cnt += 1 print() for iter in range(int(sys.stdin.readline())): sol() ```
output
1
91,160
12
182,321
Provide tags and a correct Python 3 solution for this coding contest problem. You like numbers, don't you? Nastia has a lot of numbers and she wants to share them with you! Isn't it amazing? Let a_i be how many numbers i (1 ≤ i ≤ k) you have. An n × n matrix is called beautiful if it contains all the numbers you have, and for each 2 × 2 submatrix of the original matrix is satisfied: 1. The number of occupied cells doesn't exceed 3; 2. The numbers on each diagonal are distinct. Make a beautiful matrix of minimum size. Input The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases. The first line of each test case contains 2 integers m and k (1 ≤ m, k ≤ 10^5) — how many numbers Nastia gave you and the length of the array a, respectively. The second line of each test case contains k integers a_1, a_2, …, a_{k} (0 ≤ a_i ≤ m, a_1 + a_2 + … + a_{k} = m), where a_i is how many numbers i you have. It's guaranteed that the sum of m and k in one test doesn't exceed 2 ⋅ 10^5. Output For each t test case print a single integer n — the size of the beautiful matrix. In the next n lines print n integers b_{i, j} (0 ≤ b_{i, j} ≤ k; if position is empty, print b_{i, j} = 0) — the beautiful matrix b you made up. Example Input 2 3 4 2 0 0 1 15 4 2 4 8 1 Output 2 4 1 0 1 5 3 0 0 2 2 3 2 3 3 0 0 1 0 4 0 3 0 0 0 0 2 1 3 3 3 Note Note that 0 in this problem represents a blank, not a number. Examples of possible answers for the first test case: \begin{array}{cc} 1 & 1 \\\ 4 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 4 \\\ 1 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 0 \\\ 1 & 1 \\\ \end{array} Examples of not beautiful matrices for the first test case: \begin{array}{cc} 1 & 0 \\\ 4 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 1 \\\ 7 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 0 \\\ 4 & 0 \\\ \end{array} The example of the not beautiful matrix for the second test case: \begin{array}{cc} 3 & 4 & 0 & 2 & 2 \\\ 3 & 2 & 3 & 3 & 0 \\\ 0 & 1 & 0 & 0 & 0 \\\ 3 & 0 & 0 & 0 & 0 \\\ 2 & 1 & 3 & 3 & 3 \\\ \end{array} Everything is okay, except the left-top submatrix contains 4 numbers.
instruction
0
91,161
12
182,322
Tags: binary search, constructive algorithms, greedy Correct Solution: ``` from math import sqrt, ceil def sol(): m, k = map(int, input().split()) A = list(map(int, input().split())) A = sorted(list(enumerate(A)), reverse=True, key=lambda x: x[1]) B = [] C = [] for elem in A: if len(B) > len(C): C += [elem[0] + 1] * elem[1] else: B += [elem[0] + 1] * elem[1] if len(C) > len(B): C, B = B, C even_n = ceil(max(sqrt(4 * m / 3), sqrt(2 * len(B)))) if even_n % 2 == 1: even_n += 1 odd_n = even_n - 1 if odd_n ** 2 - (odd_n - 1) ** 2 / 4 >= m and odd_n * (odd_n + 1) / 2 >= len(B): n = odd_n else: n = even_n if n % 2 == 0: C += [0] * (3 * n ** 2 // 4 - len(B) - len(C)) else: C += [0] * (n ** 2 - (n - 1) ** 2 // 4 - len(B) - len(C)) if n % 2 == 0: border = n ** 2 // 4 else: border = (n - 1) * (n + 1) // 4 B, D = B[:border], B[border:] D += C[border:] C = C[:border] B_cnt = 0 C_cnt = 0 D_cnt = 0 print(n) for i in range(n): for j in range(n): if i % 2 == 1 and j % 2 == 1: print(0, end=' ') elif i % 2 == 1: print(B[B_cnt], end=' ') B_cnt += 1 elif j % 2 == 1: print(C[C_cnt], end=' ') C_cnt += 1 else: print(D[D_cnt], end=' ') D_cnt += 1 print() for iter in range(int(input())): sol() ```
output
1
91,161
12
182,323
Provide tags and a correct Python 3 solution for this coding contest problem. You like numbers, don't you? Nastia has a lot of numbers and she wants to share them with you! Isn't it amazing? Let a_i be how many numbers i (1 ≤ i ≤ k) you have. An n × n matrix is called beautiful if it contains all the numbers you have, and for each 2 × 2 submatrix of the original matrix is satisfied: 1. The number of occupied cells doesn't exceed 3; 2. The numbers on each diagonal are distinct. Make a beautiful matrix of minimum size. Input The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases. The first line of each test case contains 2 integers m and k (1 ≤ m, k ≤ 10^5) — how many numbers Nastia gave you and the length of the array a, respectively. The second line of each test case contains k integers a_1, a_2, …, a_{k} (0 ≤ a_i ≤ m, a_1 + a_2 + … + a_{k} = m), where a_i is how many numbers i you have. It's guaranteed that the sum of m and k in one test doesn't exceed 2 ⋅ 10^5. Output For each t test case print a single integer n — the size of the beautiful matrix. In the next n lines print n integers b_{i, j} (0 ≤ b_{i, j} ≤ k; if position is empty, print b_{i, j} = 0) — the beautiful matrix b you made up. Example Input 2 3 4 2 0 0 1 15 4 2 4 8 1 Output 2 4 1 0 1 5 3 0 0 2 2 3 2 3 3 0 0 1 0 4 0 3 0 0 0 0 2 1 3 3 3 Note Note that 0 in this problem represents a blank, not a number. Examples of possible answers for the first test case: \begin{array}{cc} 1 & 1 \\\ 4 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 4 \\\ 1 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 0 \\\ 1 & 1 \\\ \end{array} Examples of not beautiful matrices for the first test case: \begin{array}{cc} 1 & 0 \\\ 4 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 1 \\\ 7 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 0 \\\ 4 & 0 \\\ \end{array} The example of the not beautiful matrix for the second test case: \begin{array}{cc} 3 & 4 & 0 & 2 & 2 \\\ 3 & 2 & 3 & 3 & 0 \\\ 0 & 1 & 0 & 0 & 0 \\\ 3 & 0 & 0 & 0 & 0 \\\ 2 & 1 & 3 & 3 & 3 \\\ \end{array} Everything is okay, except the left-top submatrix contains 4 numbers.
instruction
0
91,162
12
182,324
Tags: binary search, constructive algorithms, greedy Correct Solution: ``` from math import sqrt, ceil for testcase_testcase in range(int(input())): m, k = map(int, input().split());A = list(map(int, input().split()));A = sorted(list(enumerate(A)), reverse=True, key=lambda x: x[1]);B = [];C = [] for elem in A: if len(B) > len(C): C += [elem[0] + 1] * elem[1] else: B += [elem[0] + 1] * elem[1] if len(C) > len(B):C, B = B, C even_n = ceil(max(sqrt(4 * m / 3), sqrt(2 * len(B)))) if even_n % 2 == 1:even_n += 1 odd_n = even_n - 1;n = (odd_n if odd_n ** 2 - (odd_n - 1) ** 2 / 4 >= m and odd_n * (odd_n + 1) / 2 >= len(B) else even_n) C += ([0] * (3 * n ** 2 // 4 - len(B) - len(C)) if n % 2 == 0 else [0] * (n ** 2 - (n - 1) ** 2 // 4 - len(B) - len(C))) border = (n ** 2 // 4 if n % 2 == 0 else (n - 1) * (n + 1) // 4);B, D = B[:border], B[border:];D += C[border:];C = C[:border];B_cnt = 0;C_cnt = 0;D_cnt = 0;print(n) for i in range(n): for j in range(n): if i % 2 == 1 and j % 2 == 1: print(0, end=' ') elif i % 2 == 1:print(B[B_cnt], end=' ');B_cnt += 1 elif j % 2 == 1:print(C[C_cnt], end=' ');C_cnt += 1 else:print(D[D_cnt], end=' ');D_cnt += 1 print() ```
output
1
91,162
12
182,325
Provide tags and a correct Python 3 solution for this coding contest problem. You like numbers, don't you? Nastia has a lot of numbers and she wants to share them with you! Isn't it amazing? Let a_i be how many numbers i (1 ≤ i ≤ k) you have. An n × n matrix is called beautiful if it contains all the numbers you have, and for each 2 × 2 submatrix of the original matrix is satisfied: 1. The number of occupied cells doesn't exceed 3; 2. The numbers on each diagonal are distinct. Make a beautiful matrix of minimum size. Input The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases. The first line of each test case contains 2 integers m and k (1 ≤ m, k ≤ 10^5) — how many numbers Nastia gave you and the length of the array a, respectively. The second line of each test case contains k integers a_1, a_2, …, a_{k} (0 ≤ a_i ≤ m, a_1 + a_2 + … + a_{k} = m), where a_i is how many numbers i you have. It's guaranteed that the sum of m and k in one test doesn't exceed 2 ⋅ 10^5. Output For each t test case print a single integer n — the size of the beautiful matrix. In the next n lines print n integers b_{i, j} (0 ≤ b_{i, j} ≤ k; if position is empty, print b_{i, j} = 0) — the beautiful matrix b you made up. Example Input 2 3 4 2 0 0 1 15 4 2 4 8 1 Output 2 4 1 0 1 5 3 0 0 2 2 3 2 3 3 0 0 1 0 4 0 3 0 0 0 0 2 1 3 3 3 Note Note that 0 in this problem represents a blank, not a number. Examples of possible answers for the first test case: \begin{array}{cc} 1 & 1 \\\ 4 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 4 \\\ 1 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 0 \\\ 1 & 1 \\\ \end{array} Examples of not beautiful matrices for the first test case: \begin{array}{cc} 1 & 0 \\\ 4 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 1 \\\ 7 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 0 \\\ 4 & 0 \\\ \end{array} The example of the not beautiful matrix for the second test case: \begin{array}{cc} 3 & 4 & 0 & 2 & 2 \\\ 3 & 2 & 3 & 3 & 0 \\\ 0 & 1 & 0 & 0 & 0 \\\ 3 & 0 & 0 & 0 & 0 \\\ 2 & 1 & 3 & 3 & 3 \\\ \end{array} Everything is okay, except the left-top submatrix contains 4 numbers.
instruction
0
91,163
12
182,326
Tags: binary search, constructive algorithms, greedy Correct Solution: ``` def cheak(x): return x**2-(x//2)**2>=m and x*(x//2+(1 if x%2!=0 else 0))>=mx for test in range(int(input())): m,k=(int(i) for i in input().split()) a=[int(i) for i in input().split()] mx=max(a) z=0;y=m*4 while z!=y: x=(z+y)//2 if cheak(x): y=x else: z=x+1 else: x=z a=sorted(list(map(list,zip(a,range(1,len(a)+1))))) def get(): i=len(a) while i!=0: i-=1 while a[i][0]>0: a[i][0]-=1 yield a[i][1] yield 0 mt=[[0 for i in range(x)] for j in range(x)] t=1 it=get() for i in range(0,x,2): if t==0:break for j in range(1,x,2): t=next(it) if t:mt[i][j]=t else:break for i in range(0,x,2): if t==0:break for j in range(0,x,2): t=next(it) if t:mt[i][j]=t else:break for i in range(1,x,2): if t==0:break for j in range(0,x,2): t=next(it) if t:mt[i][j]=t else:break print(len(mt)) for i in mt: print(*i) ```
output
1
91,163
12
182,327
Provide tags and a correct Python 3 solution for this coding contest problem. You like numbers, don't you? Nastia has a lot of numbers and she wants to share them with you! Isn't it amazing? Let a_i be how many numbers i (1 ≤ i ≤ k) you have. An n × n matrix is called beautiful if it contains all the numbers you have, and for each 2 × 2 submatrix of the original matrix is satisfied: 1. The number of occupied cells doesn't exceed 3; 2. The numbers on each diagonal are distinct. Make a beautiful matrix of minimum size. Input The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases. The first line of each test case contains 2 integers m and k (1 ≤ m, k ≤ 10^5) — how many numbers Nastia gave you and the length of the array a, respectively. The second line of each test case contains k integers a_1, a_2, …, a_{k} (0 ≤ a_i ≤ m, a_1 + a_2 + … + a_{k} = m), where a_i is how many numbers i you have. It's guaranteed that the sum of m and k in one test doesn't exceed 2 ⋅ 10^5. Output For each t test case print a single integer n — the size of the beautiful matrix. In the next n lines print n integers b_{i, j} (0 ≤ b_{i, j} ≤ k; if position is empty, print b_{i, j} = 0) — the beautiful matrix b you made up. Example Input 2 3 4 2 0 0 1 15 4 2 4 8 1 Output 2 4 1 0 1 5 3 0 0 2 2 3 2 3 3 0 0 1 0 4 0 3 0 0 0 0 2 1 3 3 3 Note Note that 0 in this problem represents a blank, not a number. Examples of possible answers for the first test case: \begin{array}{cc} 1 & 1 \\\ 4 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 4 \\\ 1 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 0 \\\ 1 & 1 \\\ \end{array} Examples of not beautiful matrices for the first test case: \begin{array}{cc} 1 & 0 \\\ 4 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 1 \\\ 7 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 0 \\\ 4 & 0 \\\ \end{array} The example of the not beautiful matrix for the second test case: \begin{array}{cc} 3 & 4 & 0 & 2 & 2 \\\ 3 & 2 & 3 & 3 & 0 \\\ 0 & 1 & 0 & 0 & 0 \\\ 3 & 0 & 0 & 0 & 0 \\\ 2 & 1 & 3 & 3 & 3 \\\ \end{array} Everything is okay, except the left-top submatrix contains 4 numbers.
instruction
0
91,164
12
182,328
Tags: binary search, constructive algorithms, greedy Correct Solution: ``` from math import ceil import heapq def solve(m,k,a): N = 1 free = ceil(N/2)**2 A = (N//2)*ceil(N/2) B = (N//2)*ceil(N/2) while free + A + B < m: N += 1 free = ceil(N/2)**2 A = (N//2)*ceil(N/2) B = (N//2)*ceil(N/2) mx_freq = max(a) while free + B < mx_freq: N += 1 free = ceil(N/2)**2 A = (N//2)*ceil(N/2) B = (N//2)*ceil(N/2) ans = [[0]*N for _ in range(N)] A = [(i,j) for i in range(1,N,2) for j in range(0,N,2)] B = [(i,j) for i in range(0,N,2) for j in range(1,N,2)] F = [(i,j) for i in range(0,N,2) for j in range(0,N,2)] pq = [] for i in range(k): if a[i] > 0: heapq.heappush(pq,(-a[i],i+1)) l = len(pq) cur_ele = None cur_freq = 0 while B: if not pq and cur_freq == 0: break if cur_freq == 0: X = heapq.heappop(pq) cur_ele = X[1] cur_freq = -X[0] i,j = B.pop() ans[i][j] = cur_ele cur_freq -= 1 later = [] if len(pq) == l-1: later.append([cur_ele,cur_freq]) cur_ele = None cur_freq = 0 while A: if not pq and cur_freq == 0: break if cur_freq == 0: X = heapq.heappop(pq) cur_ele = X[1] cur_freq = -X[0] i,j = A.pop() ans[i][j] = cur_ele cur_freq -= 1 if later: ele,freq = later.pop() if cur_freq: heapq.heappush(pq,(-cur_freq,cur_ele)) cur_ele = ele cur_freq = freq while pq or cur_freq: if cur_freq == 0: X = heapq.heappop(pq) cur_ele = X[1] cur_freq = -X[0] while cur_freq: i,j = F.pop() ans[i][j] = cur_ele cur_freq -= 1 print(N) for row in ans: print(*row) return -1 for nt in range(int(input())): m,k = map(int,input().split()) a = list(map(int,input().split())) solve(m,k,a) ```
output
1
91,164
12
182,329
Provide tags and a correct Python 3 solution for this coding contest problem. You like numbers, don't you? Nastia has a lot of numbers and she wants to share them with you! Isn't it amazing? Let a_i be how many numbers i (1 ≤ i ≤ k) you have. An n × n matrix is called beautiful if it contains all the numbers you have, and for each 2 × 2 submatrix of the original matrix is satisfied: 1. The number of occupied cells doesn't exceed 3; 2. The numbers on each diagonal are distinct. Make a beautiful matrix of minimum size. Input The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases. The first line of each test case contains 2 integers m and k (1 ≤ m, k ≤ 10^5) — how many numbers Nastia gave you and the length of the array a, respectively. The second line of each test case contains k integers a_1, a_2, …, a_{k} (0 ≤ a_i ≤ m, a_1 + a_2 + … + a_{k} = m), where a_i is how many numbers i you have. It's guaranteed that the sum of m and k in one test doesn't exceed 2 ⋅ 10^5. Output For each t test case print a single integer n — the size of the beautiful matrix. In the next n lines print n integers b_{i, j} (0 ≤ b_{i, j} ≤ k; if position is empty, print b_{i, j} = 0) — the beautiful matrix b you made up. Example Input 2 3 4 2 0 0 1 15 4 2 4 8 1 Output 2 4 1 0 1 5 3 0 0 2 2 3 2 3 3 0 0 1 0 4 0 3 0 0 0 0 2 1 3 3 3 Note Note that 0 in this problem represents a blank, not a number. Examples of possible answers for the first test case: \begin{array}{cc} 1 & 1 \\\ 4 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 4 \\\ 1 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 0 \\\ 1 & 1 \\\ \end{array} Examples of not beautiful matrices for the first test case: \begin{array}{cc} 1 & 0 \\\ 4 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 1 \\\ 7 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 0 \\\ 4 & 0 \\\ \end{array} The example of the not beautiful matrix for the second test case: \begin{array}{cc} 3 & 4 & 0 & 2 & 2 \\\ 3 & 2 & 3 & 3 & 0 \\\ 0 & 1 & 0 & 0 & 0 \\\ 3 & 0 & 0 & 0 & 0 \\\ 2 & 1 & 3 & 3 & 3 \\\ \end{array} Everything is okay, except the left-top submatrix contains 4 numbers.
instruction
0
91,165
12
182,330
Tags: binary search, constructive algorithms, greedy Correct Solution: ``` from math import sqrt, ceil for iter in range(int(input())): m, k = map(int, input().split());A = list(map(int, input().split()));A = sorted(list(enumerate(A)), reverse=True, key=lambda x: x[1]);B = [];C = [] for elem in A: if len(B) > len(C): C += [elem[0] + 1] * elem[1] else: B += [elem[0] + 1] * elem[1] if len(C) > len(B):C, B = B, C even_n = ceil(max(sqrt(4 * m / 3), sqrt(2 * len(B)))) if even_n % 2 == 1: even_n += 1 odd_n = even_n - 1 if odd_n ** 2 - (odd_n - 1) ** 2 / 4 >= m and odd_n * (odd_n + 1) / 2 >= len(B): n = odd_n else: n = even_n if n % 2 == 0: C += [0] * (3 * n ** 2 // 4 - len(B) - len(C)) else: C += [0] * (n ** 2 - (n - 1) ** 2 // 4 - len(B) - len(C)) if n % 2 == 0: border = n ** 2 // 4 else: border = (n - 1) * (n + 1) // 4 B, D = B[:border], B[border:] D += C[border:] C = C[:border] B_cnt = 0 C_cnt = 0 D_cnt = 0 print(n) for i in range(n): for j in range(n): if i % 2 == 1 and j % 2 == 1: print(0, end=' ') elif i % 2 == 1:print(B[B_cnt], end=' ');B_cnt += 1 elif j % 2 == 1:print(C[C_cnt], end=' ');C_cnt += 1 else:print(D[D_cnt], end=' ');D_cnt += 1 print() ```
output
1
91,165
12
182,331
Provide tags and a correct Python 3 solution for this coding contest problem. The Little Elephant enjoys recursive functions. This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: * If x = 1, exit the function. * Otherwise, call f(x - 1), and then make swap(ax - 1, ax) (swap the x-th and (x - 1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. Input A single line contains integer n (1 ≤ n ≤ 1000) — the size of permutation. Output In a single line print n distinct integers from 1 to n — the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. Examples Input 1 Output 1 Input 2 Output 2 1
instruction
0
91,202
12
182,404
Tags: implementation, math Correct Solution: ``` N=int(input()) ans=[N] for i in range(1,N): ans.append(i) print(*ans) ```
output
1
91,202
12
182,405
Provide tags and a correct Python 3 solution for this coding contest problem. The Little Elephant enjoys recursive functions. This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: * If x = 1, exit the function. * Otherwise, call f(x - 1), and then make swap(ax - 1, ax) (swap the x-th and (x - 1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. Input A single line contains integer n (1 ≤ n ≤ 1000) — the size of permutation. Output In a single line print n distinct integers from 1 to n — the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. Examples Input 1 Output 1 Input 2 Output 2 1
instruction
0
91,203
12
182,406
Tags: implementation, math Correct Solution: ``` # It's all about what U BELIEVE def gint(): return int(input()) def gint_arr(): return list(map(int, input().split())) def gfloat(): return float(input()) def gfloat_arr(): return list(map(float, input().split())) def pair_int(): return map(int, input().split()) ############################################# INF = (1 << 31) dx = [-1, 0, 1, 0] dy = [ 0, 1, 0, -1] ############################################# ############################################# n = gint() print(n, *range(1, n)) ```
output
1
91,203
12
182,407
Provide tags and a correct Python 3 solution for this coding contest problem. The Little Elephant enjoys recursive functions. This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: * If x = 1, exit the function. * Otherwise, call f(x - 1), and then make swap(ax - 1, ax) (swap the x-th and (x - 1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. Input A single line contains integer n (1 ≤ n ≤ 1000) — the size of permutation. Output In a single line print n distinct integers from 1 to n — the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. Examples Input 1 Output 1 Input 2 Output 2 1
instruction
0
91,204
12
182,408
Tags: implementation, math Correct Solution: ``` n=int(input()) l=list(range(1,n+1)) l=sorted(l) l.insert(0,l[-1]) l.pop() print(*l) ```
output
1
91,204
12
182,409
Provide tags and a correct Python 3 solution for this coding contest problem. The Little Elephant enjoys recursive functions. This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: * If x = 1, exit the function. * Otherwise, call f(x - 1), and then make swap(ax - 1, ax) (swap the x-th and (x - 1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. Input A single line contains integer n (1 ≤ n ≤ 1000) — the size of permutation. Output In a single line print n distinct integers from 1 to n — the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. Examples Input 1 Output 1 Input 2 Output 2 1
instruction
0
91,205
12
182,410
Tags: implementation, math Correct Solution: ``` n = int(input()) print(str(n) + " " + " ".join([str(x) for x in range(1,n)])) ```
output
1
91,205
12
182,411
Provide tags and a correct Python 3 solution for this coding contest problem. The Little Elephant enjoys recursive functions. This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: * If x = 1, exit the function. * Otherwise, call f(x - 1), and then make swap(ax - 1, ax) (swap the x-th and (x - 1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. Input A single line contains integer n (1 ≤ n ≤ 1000) — the size of permutation. Output In a single line print n distinct integers from 1 to n — the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. Examples Input 1 Output 1 Input 2 Output 2 1
instruction
0
91,206
12
182,412
Tags: implementation, math Correct Solution: ``` s=int(input()) print(s,end=" ") for i in range(1,s): print(i,end=" ") ```
output
1
91,206
12
182,413
Provide tags and a correct Python 3 solution for this coding contest problem. The Little Elephant enjoys recursive functions. This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: * If x = 1, exit the function. * Otherwise, call f(x - 1), and then make swap(ax - 1, ax) (swap the x-th and (x - 1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. Input A single line contains integer n (1 ≤ n ≤ 1000) — the size of permutation. Output In a single line print n distinct integers from 1 to n — the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. Examples Input 1 Output 1 Input 2 Output 2 1
instruction
0
91,207
12
182,414
Tags: implementation, math Correct Solution: ``` n=int(input()) a=[] a.append(n) i=1 while i<n: a.append(i) i+=1 print(*a,sep=' ') ```
output
1
91,207
12
182,415
Provide tags and a correct Python 3 solution for this coding contest problem. The Little Elephant enjoys recursive functions. This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: * If x = 1, exit the function. * Otherwise, call f(x - 1), and then make swap(ax - 1, ax) (swap the x-th and (x - 1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. Input A single line contains integer n (1 ≤ n ≤ 1000) — the size of permutation. Output In a single line print n distinct integers from 1 to n — the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. Examples Input 1 Output 1 Input 2 Output 2 1
instruction
0
91,208
12
182,416
Tags: implementation, math Correct Solution: ``` n = int(input()) print(n, *range(1, n), sep=' ') ```
output
1
91,208
12
182,417
Provide tags and a correct Python 3 solution for this coding contest problem. The Little Elephant enjoys recursive functions. This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: * If x = 1, exit the function. * Otherwise, call f(x - 1), and then make swap(ax - 1, ax) (swap the x-th and (x - 1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. Input A single line contains integer n (1 ≤ n ≤ 1000) — the size of permutation. Output In a single line print n distinct integers from 1 to n — the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. Examples Input 1 Output 1 Input 2 Output 2 1
instruction
0
91,209
12
182,418
Tags: implementation, math Correct Solution: ``` #221A n = int(input()) print(n, *range(1,n)) ```
output
1
91,209
12
182,419
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Little Elephant enjoys recursive functions. This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: * If x = 1, exit the function. * Otherwise, call f(x - 1), and then make swap(ax - 1, ax) (swap the x-th and (x - 1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. Input A single line contains integer n (1 ≤ n ≤ 1000) — the size of permutation. Output In a single line print n distinct integers from 1 to n — the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. Examples Input 1 Output 1 Input 2 Output 2 1 Submitted Solution: ``` x=int(input()) if(x==1): print(x) else: l=[] for i in range(1,x+1): l.append(str(i)) l2=[] l2.append(l[-1]) l.pop(len(l)-1) for i in l: l2.append(i) for j in l2: print(j,end=' ') ```
instruction
0
91,210
12
182,420
Yes
output
1
91,210
12
182,421
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Little Elephant enjoys recursive functions. This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: * If x = 1, exit the function. * Otherwise, call f(x - 1), and then make swap(ax - 1, ax) (swap the x-th and (x - 1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. Input A single line contains integer n (1 ≤ n ≤ 1000) — the size of permutation. Output In a single line print n distinct integers from 1 to n — the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. Examples Input 1 Output 1 Input 2 Output 2 1 Submitted Solution: ``` __author__ = 'Esfandiar' n = int(input()) print(n,*range(1,n)) ```
instruction
0
91,211
12
182,422
Yes
output
1
91,211
12
182,423
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Little Elephant enjoys recursive functions. This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: * If x = 1, exit the function. * Otherwise, call f(x - 1), and then make swap(ax - 1, ax) (swap the x-th and (x - 1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. Input A single line contains integer n (1 ≤ n ≤ 1000) — the size of permutation. Output In a single line print n distinct integers from 1 to n — the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. Examples Input 1 Output 1 Input 2 Output 2 1 Submitted Solution: ``` n=int(input()) print(n,*[i for i in range(1,n)],sep=" ") ```
instruction
0
91,212
12
182,424
Yes
output
1
91,212
12
182,425
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Little Elephant enjoys recursive functions. This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: * If x = 1, exit the function. * Otherwise, call f(x - 1), and then make swap(ax - 1, ax) (swap the x-th and (x - 1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. Input A single line contains integer n (1 ≤ n ≤ 1000) — the size of permutation. Output In a single line print n distinct integers from 1 to n — the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. Examples Input 1 Output 1 Input 2 Output 2 1 Submitted Solution: ``` #A. Little Elephant and Function n = int(input()) a = [n]+list(range(1,n)) print(*a) ```
instruction
0
91,213
12
182,426
Yes
output
1
91,213
12
182,427
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Little Elephant enjoys recursive functions. This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: * If x = 1, exit the function. * Otherwise, call f(x - 1), and then make swap(ax - 1, ax) (swap the x-th and (x - 1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. Input A single line contains integer n (1 ≤ n ≤ 1000) — the size of permutation. Output In a single line print n distinct integers from 1 to n — the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. Examples Input 1 Output 1 Input 2 Output 2 1 Submitted Solution: ``` print(*range(int(input()), 0, -1)) ```
instruction
0
91,214
12
182,428
No
output
1
91,214
12
182,429
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Little Elephant enjoys recursive functions. This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: * If x = 1, exit the function. * Otherwise, call f(x - 1), and then make swap(ax - 1, ax) (swap the x-th and (x - 1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. Input A single line contains integer n (1 ≤ n ≤ 1000) — the size of permutation. Output In a single line print n distinct integers from 1 to n — the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. Examples Input 1 Output 1 Input 2 Output 2 1 Submitted Solution: ``` import re import sys from bisect import bisect, bisect_left, insort, insort_left from collections import Counter, defaultdict, deque from copy import deepcopy from decimal import Decimal from itertools import ( accumulate, combinations, combinations_with_replacement, groupby, permutations, product) from math import (acos, asin, atan, ceil, cos, degrees, factorial, gcd, hypot, log2, pi, radians, sin, sqrt, tan) from operator import itemgetter, mul from string import ascii_lowercase, ascii_uppercase, digits def inp(): return(int(input())) def inlist(): return(list(map(int, input().split()))) def instr(): s = input() return(list(s[:len(s)])) def invr(): return(map(int, input().split())) def def_value(): return False n = inp() if n < 3: for i in reversed(range(n)): print(i+1, end=" ") else: for i in range(n-1, 0, - 1): print(i, end=" ") print(n) ```
instruction
0
91,215
12
182,430
No
output
1
91,215
12
182,431
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Little Elephant enjoys recursive functions. This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: * If x = 1, exit the function. * Otherwise, call f(x - 1), and then make swap(ax - 1, ax) (swap the x-th and (x - 1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. Input A single line contains integer n (1 ≤ n ≤ 1000) — the size of permutation. Output In a single line print n distinct integers from 1 to n — the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. Examples Input 1 Output 1 Input 2 Output 2 1 Submitted Solution: ``` import sys n=int(input()) ans=list(range(2,n+1)) ans.append(1) if n%2==0: print(*ans) sys.exit() for i in range(n): ans[i]+=1 ans[i]%=n if ans[i]==0: ans[i]=n print(*ans) ```
instruction
0
91,216
12
182,432
No
output
1
91,216
12
182,433
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Little Elephant enjoys recursive functions. This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: * If x = 1, exit the function. * Otherwise, call f(x - 1), and then make swap(ax - 1, ax) (swap the x-th and (x - 1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. Input A single line contains integer n (1 ≤ n ≤ 1000) — the size of permutation. Output In a single line print n distinct integers from 1 to n — the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. Examples Input 1 Output 1 Input 2 Output 2 1 Submitted Solution: ``` a=int(input()) l=[] i=a while i>0: l.append(str(i)) i-=1 i=a-1 while i>0: l[i],l[i-1]=l[i-1],l[i] i-=1 print(" ".join(l)) ```
instruction
0
91,217
12
182,434
No
output
1
91,217
12
182,435
Provide tags and a correct Python 3 solution for this coding contest problem. Iahub is so happy about inventing bubble sort graphs that he's staying all day long at the office and writing permutations. Iahubina is angry that she is no more important for Iahub. When Iahub goes away, Iahubina comes to his office and sabotage his research work. The girl finds an important permutation for the research. The permutation contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n). She replaces some of permutation elements with -1 value as a revenge. When Iahub finds out his important permutation is broken, he tries to recover it. The only thing he remembers about the permutation is it didn't have any fixed point. A fixed point for a permutation is an element ak which has value equal to k (ak = k). Your job is to proof to Iahub that trying to recover it is not a good idea. Output the number of permutations which could be originally Iahub's important permutation, modulo 1000000007 (109 + 7). Input The first line contains integer n (2 ≤ n ≤ 2000). On the second line, there are n integers, representing Iahub's important permutation after Iahubina replaces some values with -1. It's guaranteed that there are no fixed points in the given permutation. Also, the given sequence contains at least two numbers -1 and each positive number occurs in the sequence at most once. It's guaranteed that there is at least one suitable permutation. Output Output a single integer, the number of ways Iahub could recover his permutation, modulo 1000000007 (109 + 7). Examples Input 5 -1 -1 4 3 -1 Output 2 Note For the first test example there are two permutations with no fixed points are [2, 5, 4, 3, 1] and [5, 1, 4, 3, 2]. Any other permutation would have at least one fixed point.
instruction
0
91,236
12
182,472
Tags: combinatorics, math Correct Solution: ``` MOD = 10**9+7 n = int(input()) notUsed = set(range(1, n+1)) chairs = set() for i, a in enumerate(map(int, input().split()), 1): if a == -1: chairs.add(i) else: notUsed -= {a} fixed = len(chairs & notUsed) m = len(notUsed) U = m fact = [0]*(U+1) fact[0] = 1 for i in range(1, U+1): fact[i] = fact[i-1]*i % MOD invfact = [0]*(U+1) invfact[U] = pow(fact[U], MOD-2, MOD) for i in reversed(range(U)): invfact[i] = invfact[i+1]*(i+1) % MOD def nCr(n, r): if r < 0 or n < r: return 0 return fact[n]*invfact[r]*invfact[n-r] ans = fact[m] for k in range(1, fixed+1): ans += nCr(fixed, k)*fact[m-k]*(-1)**k ans %= MOD print(ans) ```
output
1
91,236
12
182,473
Provide tags and a correct Python 3 solution for this coding contest problem. Iahub is so happy about inventing bubble sort graphs that he's staying all day long at the office and writing permutations. Iahubina is angry that she is no more important for Iahub. When Iahub goes away, Iahubina comes to his office and sabotage his research work. The girl finds an important permutation for the research. The permutation contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n). She replaces some of permutation elements with -1 value as a revenge. When Iahub finds out his important permutation is broken, he tries to recover it. The only thing he remembers about the permutation is it didn't have any fixed point. A fixed point for a permutation is an element ak which has value equal to k (ak = k). Your job is to proof to Iahub that trying to recover it is not a good idea. Output the number of permutations which could be originally Iahub's important permutation, modulo 1000000007 (109 + 7). Input The first line contains integer n (2 ≤ n ≤ 2000). On the second line, there are n integers, representing Iahub's important permutation after Iahubina replaces some values with -1. It's guaranteed that there are no fixed points in the given permutation. Also, the given sequence contains at least two numbers -1 and each positive number occurs in the sequence at most once. It's guaranteed that there is at least one suitable permutation. Output Output a single integer, the number of ways Iahub could recover his permutation, modulo 1000000007 (109 + 7). Examples Input 5 -1 -1 4 3 -1 Output 2 Note For the first test example there are two permutations with no fixed points are [2, 5, 4, 3, 1] and [5, 1, 4, 3, 2]. Any other permutation would have at least one fixed point.
instruction
0
91,237
12
182,474
Tags: combinatorics, math Correct Solution: ``` input() t = list(map(int, input().split())) s, m = 0, 1000000007 p = {i for i, q in enumerate(t, 1) if q == -1} n, k = len(p), len(p - set(t)) d, c = 2 * (n & 1) - 1, 1 for j in range(n + 1): d = -d * max(1, j) % m if n - j <= k: s += c * d c = c * max(1, n - j) * pow(k - n + j + 1, m - 2, m) % m print(s % m) ```
output
1
91,237
12
182,475
Provide tags and a correct Python 3 solution for this coding contest problem. Iahub is so happy about inventing bubble sort graphs that he's staying all day long at the office and writing permutations. Iahubina is angry that she is no more important for Iahub. When Iahub goes away, Iahubina comes to his office and sabotage his research work. The girl finds an important permutation for the research. The permutation contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n). She replaces some of permutation elements with -1 value as a revenge. When Iahub finds out his important permutation is broken, he tries to recover it. The only thing he remembers about the permutation is it didn't have any fixed point. A fixed point for a permutation is an element ak which has value equal to k (ak = k). Your job is to proof to Iahub that trying to recover it is not a good idea. Output the number of permutations which could be originally Iahub's important permutation, modulo 1000000007 (109 + 7). Input The first line contains integer n (2 ≤ n ≤ 2000). On the second line, there are n integers, representing Iahub's important permutation after Iahubina replaces some values with -1. It's guaranteed that there are no fixed points in the given permutation. Also, the given sequence contains at least two numbers -1 and each positive number occurs in the sequence at most once. It's guaranteed that there is at least one suitable permutation. Output Output a single integer, the number of ways Iahub could recover his permutation, modulo 1000000007 (109 + 7). Examples Input 5 -1 -1 4 3 -1 Output 2 Note For the first test example there are two permutations with no fixed points are [2, 5, 4, 3, 1] and [5, 1, 4, 3, 2]. Any other permutation would have at least one fixed point.
instruction
0
91,238
12
182,476
Tags: combinatorics, math Correct Solution: ``` #lahub and Permutations import sys readline = sys.stdin.buffer.readline def even(n): return 1 if n%2==0 else 0 mod = 10**9+7 def pow(n,p,mod=mod): #繰り返し二乗法(nのp乗) res = 1 while p > 0: if p % 2 == 0: n = n ** 2 % mod p //= 2 else: res = res * n % mod p -= 1 return res % mod def factrial_memo(n=10**5,mod=mod): fact = [1, 1] for i in range(2, n + 1): fact.append((fact[-1] * i) % mod) return fact fact = factrial_memo() def permutation(n,r): #nPr return fact[n]*pow(fact[n-r],mod-2)%mod def combination(n,r): #nCr return permutation(n,r)*pow(fact[r],mod-2)%mod #return fact[n]*pow(fact[n-r],mod-2)*pow(fact[r],mod-2) def homogeneous(n,r): #nHr return combination(n+r-1,r)%mod #return fact[n+m-1]*pow(fact[n-1],mod-2)*pow(fact[r],mod-2) n = int(readline()) lst1 = list(map(int,readline().split())) ct = 0 lst2 = [0]*2_001 lst3 = [0]*2_001 for i in range(n): if i+1 == lst1[i]: print(0) exit() if lst1[i] == -1: ct += 1 lst3[i+1] = 1 else: lst2[lst1[i]] = 1 ct2 = 0 for i in range(1,n+1): if lst3[i] == 1 and lst2[i] == 0: ct2 += 1 #lst2:その場所が埋まってないindex #lst3:その数字が使われてるindex #何個入れちゃいけない位置に入れるかで数え上げる #入れちゃいけないものはct2個って、 #ct-ct2個のものはどこに入れても要件を満たす ans = 0 for i in range(ct2+1): ans += pow(-1,i)*combination(ct2,i)*fact[ct-i] ans %= mod print(ans) ```
output
1
91,238
12
182,477
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Iahub is so happy about inventing bubble sort graphs that he's staying all day long at the office and writing permutations. Iahubina is angry that she is no more important for Iahub. When Iahub goes away, Iahubina comes to his office and sabotage his research work. The girl finds an important permutation for the research. The permutation contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n). She replaces some of permutation elements with -1 value as a revenge. When Iahub finds out his important permutation is broken, he tries to recover it. The only thing he remembers about the permutation is it didn't have any fixed point. A fixed point for a permutation is an element ak which has value equal to k (ak = k). Your job is to proof to Iahub that trying to recover it is not a good idea. Output the number of permutations which could be originally Iahub's important permutation, modulo 1000000007 (109 + 7). Input The first line contains integer n (2 ≤ n ≤ 2000). On the second line, there are n integers, representing Iahub's important permutation after Iahubina replaces some values with -1. It's guaranteed that there are no fixed points in the given permutation. Also, the given sequence contains at least two numbers -1 and each positive number occurs in the sequence at most once. It's guaranteed that there is at least one suitable permutation. Output Output a single integer, the number of ways Iahub could recover his permutation, modulo 1000000007 (109 + 7). Examples Input 5 -1 -1 4 3 -1 Output 2 Note For the first test example there are two permutations with no fixed points are [2, 5, 4, 3, 1] and [5, 1, 4, 3, 2]. Any other permutation would have at least one fixed point. Submitted Solution: ``` #lahub and Permutations import sys readline = sys.stdin.buffer.readline def even(n): return 1 if n%2==0 else 0 mod = 10**9+7 def pow(n,p,mod=mod): #繰り返し二乗法(nのp乗) res = 1 while p > 0: if p % 2 == 0: n = n ** 2 % mod p //= 2 else: res = res * n % mod p -= 1 return res % mod def factrial_memo(n=10**6,mod=mod): fact = [1, 1] for i in range(2, n + 1): fact.append((fact[-1] * i) % mod) return fact fact = factrial_memo() def permutation(n,r): #nPr return fact[n]*pow(fact[n-r],mod-2)%mod def combination(n,r): #nCr return permutation(n,r)*pow(fact[r],mod-2)%mod #return fact[n]*pow(fact[n-r],mod-2)*pow(fact[r],mod-2) def homogeneous(n,r): #nHr return combination(n+r-1,r)%mod #return fact[n+m-1]*pow(fact[n-1],mod-2)*pow(fact[r],mod-2) n = int(readline()) lst1 = list(map(int,readline().split())) ct = 0 lst2 = [0]*2_001 for i in range(n): if i+1 == lst1[i]: print(0) exit() if lst1[i] == -1: ct += 1 else: lst2[lst1[i]] = 1 ct2 = 0 for i in range(1,n+1): if lst2[i] == 0: ct2 += 1 #lst2:その場所が埋まってないindex #lst3:その数字が使われてるindex #何個入れちゃいけない位置に入れるかで数え上げる #入れちゃいけないものはct2個って、 #ct-ct2個のものはどこに入れても要件を満たす ans = 0 for i in range(ct2+1): ans += pow(-1,i)*combination(ct2,i)*fact[ct-i] ans %= mod print(ans) ```
instruction
0
91,239
12
182,478
No
output
1
91,239
12
182,479
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Iahub is so happy about inventing bubble sort graphs that he's staying all day long at the office and writing permutations. Iahubina is angry that she is no more important for Iahub. When Iahub goes away, Iahubina comes to his office and sabotage his research work. The girl finds an important permutation for the research. The permutation contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n). She replaces some of permutation elements with -1 value as a revenge. When Iahub finds out his important permutation is broken, he tries to recover it. The only thing he remembers about the permutation is it didn't have any fixed point. A fixed point for a permutation is an element ak which has value equal to k (ak = k). Your job is to proof to Iahub that trying to recover it is not a good idea. Output the number of permutations which could be originally Iahub's important permutation, modulo 1000000007 (109 + 7). Input The first line contains integer n (2 ≤ n ≤ 2000). On the second line, there are n integers, representing Iahub's important permutation after Iahubina replaces some values with -1. It's guaranteed that there are no fixed points in the given permutation. Also, the given sequence contains at least two numbers -1 and each positive number occurs in the sequence at most once. It's guaranteed that there is at least one suitable permutation. Output Output a single integer, the number of ways Iahub could recover his permutation, modulo 1000000007 (109 + 7). Examples Input 5 -1 -1 4 3 -1 Output 2 Note For the first test example there are two permutations with no fixed points are [2, 5, 4, 3, 1] and [5, 1, 4, 3, 2]. Any other permutation would have at least one fixed point. Submitted Solution: ``` input() t = list(map(int, input().split())) s, m = 0, 1000000007 p = {i for i, q in enumerate(t, 1) if q == -1} n, k = len(p), len(p - set(t)) d = c = 1 for j in range(n + 1): d = -d * max(1, j) % m if n - j <= k: s += c * d c = c * max(1, n - j) * pow(k - n + j + 1, m - 2, m) % m print(s % m) ```
instruction
0
91,240
12
182,480
No
output
1
91,240
12
182,481
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array consisting of n integers a_1, a_2, ..., a_n, and a positive integer m. It is guaranteed that m is a divisor of n. In a single move, you can choose any position i between 1 and n and increase a_i by 1. Let's calculate c_r (0 ≤ r ≤ m-1) — the number of elements having remainder r when divided by m. In other words, for each remainder, let's find the number of corresponding elements in a with that remainder. Your task is to change the array in such a way that c_0 = c_1 = ... = c_{m-1} = n/m. Find the minimum number of moves to satisfy the above requirement. Input The first line of input contains two integers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ n). It is guaranteed that m is a divisor of n. The second line of input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9), the elements of the array. Output In the first line, print a single integer — the minimum number of moves required to satisfy the following condition: for each remainder from 0 to m - 1, the number of elements of the array having this remainder equals n/m. In the second line, print any array satisfying the condition and can be obtained from the given array with the minimum number of moves. The values of the elements of the resulting array must not exceed 10^{18}. Examples Input 6 3 3 2 0 6 10 12 Output 3 3 2 0 7 10 14 Input 4 2 0 1 2 3 Output 0 0 1 2 3
instruction
0
91,430
12
182,860
Tags: data structures, greedy, implementation Correct Solution: ``` from sys import stdout, stdin, setrecursionlimit from io import BytesIO, IOBase from collections import * from itertools import * from random import * from bisect import * from string import * from queue import * from heapq import * from math import * from re import * from os import * ####################################---fast-input-output----######################################### 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 = read(self._fd, max(fstat(self._fd).st_size, 8192)) 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 = read(self._fd, max(fstat(self._fd).st_size, 8192)) 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: 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") stdin, stdout = IOWrapper(stdin), IOWrapper(stdout) def fast(): return stdin.readline().strip() def zzz(): return [int(i) for i in fast().split()] z, zz = fast, lambda: (map(int, z().split())) szz, graph, mod, szzz = lambda: sorted( zz()), {}, 10**9 + 7, lambda: sorted(zzz()) def lcd(xnum1, xnum2): return (xnum1 * xnum2 // gcd(xnum1, xnum2)) def output(answer, end='\n'): stdout.write(str(answer) + end) dx = [-1, 1, 0, 0, 1, -1, 1, -1] dy = [0, 0, 1, -1, 1, -1, -1, 1] #################################################---Some Rule For Me To Follow---################################# """ --instants of Reading problem continuously try to understand them. --If you Know some-one , Then you probably don't know him ! --Try & again try """ ##################################################---START-CODING---############################################### n,m=zzz() arr = zzz() s = sum(arr) idx = [[] for i in range(m)] for i in range(n): idx[arr[i]%m].append(i) j=0 for i in range(m): while len(idx[i])>n//m: while j<i or len(idx[j%m])>=n//m:j+=1 last = idx[i].pop() arr[last]+=(j-i)%m idx[j%m].append(last) print(sum(arr)-s) print(*arr) ```
output
1
91,430
12
182,861
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array consisting of n integers a_1, a_2, ..., a_n, and a positive integer m. It is guaranteed that m is a divisor of n. In a single move, you can choose any position i between 1 and n and increase a_i by 1. Let's calculate c_r (0 ≤ r ≤ m-1) — the number of elements having remainder r when divided by m. In other words, for each remainder, let's find the number of corresponding elements in a with that remainder. Your task is to change the array in such a way that c_0 = c_1 = ... = c_{m-1} = n/m. Find the minimum number of moves to satisfy the above requirement. Input The first line of input contains two integers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ n). It is guaranteed that m is a divisor of n. The second line of input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9), the elements of the array. Output In the first line, print a single integer — the minimum number of moves required to satisfy the following condition: for each remainder from 0 to m - 1, the number of elements of the array having this remainder equals n/m. In the second line, print any array satisfying the condition and can be obtained from the given array with the minimum number of moves. The values of the elements of the resulting array must not exceed 10^{18}. Examples Input 6 3 3 2 0 6 10 12 Output 3 3 2 0 7 10 14 Input 4 2 0 1 2 3 Output 0 0 1 2 3
instruction
0
91,432
12
182,864
Tags: data structures, greedy, implementation Correct Solution: ``` from collections import deque n, m = map(int, input().split()) a = list(map(int, input().split())) n_m = n // m c = m * [0] indices = [deque() for r in range(m)] for i, ai in enumerate(a): r = ai % m c[r] += 1 indices[r].append(i) n_moves = 0 queue = deque() for i in range(0, 2 * m): r = i % m while c[r] > n_m: queue.append((i, indices[r].pop())) c[r] -= 1 while c[r] < n_m and queue: j, index = queue.popleft() indices[r].append(index) c[r] += 1 a[index] += i - j n_moves += i - j print(n_moves) print(*a) ```
output
1
91,432
12
182,865
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array consisting of n integers a_1, a_2, ..., a_n, and a positive integer m. It is guaranteed that m is a divisor of n. In a single move, you can choose any position i between 1 and n and increase a_i by 1. Let's calculate c_r (0 ≤ r ≤ m-1) — the number of elements having remainder r when divided by m. In other words, for each remainder, let's find the number of corresponding elements in a with that remainder. Your task is to change the array in such a way that c_0 = c_1 = ... = c_{m-1} = n/m. Find the minimum number of moves to satisfy the above requirement. Input The first line of input contains two integers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ n). It is guaranteed that m is a divisor of n. The second line of input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9), the elements of the array. Output In the first line, print a single integer — the minimum number of moves required to satisfy the following condition: for each remainder from 0 to m - 1, the number of elements of the array having this remainder equals n/m. In the second line, print any array satisfying the condition and can be obtained from the given array with the minimum number of moves. The values of the elements of the resulting array must not exceed 10^{18}. Examples Input 6 3 3 2 0 6 10 12 Output 3 3 2 0 7 10 14 Input 4 2 0 1 2 3 Output 0 0 1 2 3
instruction
0
91,433
12
182,866
Tags: data structures, greedy, implementation Correct Solution: ``` import sys from collections import Counter, defaultdict n, m = map(int, sys.stdin.readline().split(' ')) a = list(map(int, sys.stdin.readline().split(' '))) def do(): k = n//m count = Counter(x%m for x in a) delta = [0]*m for i in range(m): delta[i] = count[i] - k dd = defaultdict(list) for i,x in enumerate(a): dd[x%m].append(i) res = list(a) rest = set() for i in range(m): dl = delta[i] if dl > 0: rest |= set(dd[i][:dl]) delta[i] = 0 elif dl < 0: for _ in range(dl,0): if not rest: break idx = rest.pop() res[idx] += i - (res[idx]%m) delta[i] += 1 for i in range(m): if not rest: break dl = delta[i] for _ in range(dl,0): idx = rest.pop() res[idx] += m + i - (res[idx]%m) yield str(sum(x-y for x,y in zip(res,a))) yield str(' '.join(map(str, res))) print('\n'.join(do())) ```
output
1
91,433
12
182,867
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array consisting of n integers a_1, a_2, ..., a_n, and a positive integer m. It is guaranteed that m is a divisor of n. In a single move, you can choose any position i between 1 and n and increase a_i by 1. Let's calculate c_r (0 ≤ r ≤ m-1) — the number of elements having remainder r when divided by m. In other words, for each remainder, let's find the number of corresponding elements in a with that remainder. Your task is to change the array in such a way that c_0 = c_1 = ... = c_{m-1} = n/m. Find the minimum number of moves to satisfy the above requirement. Input The first line of input contains two integers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ n). It is guaranteed that m is a divisor of n. The second line of input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9), the elements of the array. Output In the first line, print a single integer — the minimum number of moves required to satisfy the following condition: for each remainder from 0 to m - 1, the number of elements of the array having this remainder equals n/m. In the second line, print any array satisfying the condition and can be obtained from the given array with the minimum number of moves. The values of the elements of the resulting array must not exceed 10^{18}. Examples Input 6 3 3 2 0 6 10 12 Output 3 3 2 0 7 10 14 Input 4 2 0 1 2 3 Output 0 0 1 2 3
instruction
0
91,434
12
182,868
Tags: data structures, greedy, implementation Correct Solution: ``` from collections import deque n, m = [int(x) for x in input().split()] a = [int(x) for x in input().split()] cnt = [0 for i in range(m)] for x in a: cnt[x % m] += 1 for i in range(m): cnt[i] = cnt[i] - (n / m) pos = [[] for i in range(m)] for i in range(n): if len(pos[a[i] % m]) < cnt[a[i] % m]: pos[a[i] % m].append(i) q = deque() ans = 0 for i in range(m): if cnt[i] > 0: cnt[i] = 0 for x in pos[i]: q.append(x) elif cnt[i] < 0: while cnt[i] < 0 and len(q) > 0: u = q.popleft() add = (i + m - (a[u] % m)) % m ans += add a[u] += add cnt[i] += 1 for i in range(m): if cnt[i] > 0: cnt[i] = 0 for x in pos[i]: q.append(x) elif cnt[i] < 0: while cnt[i] < 0 and len(q) > 0: u = q.popleft() add = (i + m - (a[u] % m)) % m ans += add a[u] += add cnt[i] += 1 print(ans) print(*a) ```
output
1
91,434
12
182,869
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array consisting of n integers a_1, a_2, ..., a_n, and a positive integer m. It is guaranteed that m is a divisor of n. In a single move, you can choose any position i between 1 and n and increase a_i by 1. Let's calculate c_r (0 ≤ r ≤ m-1) — the number of elements having remainder r when divided by m. In other words, for each remainder, let's find the number of corresponding elements in a with that remainder. Your task is to change the array in such a way that c_0 = c_1 = ... = c_{m-1} = n/m. Find the minimum number of moves to satisfy the above requirement. Input The first line of input contains two integers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ n). It is guaranteed that m is a divisor of n. The second line of input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9), the elements of the array. Output In the first line, print a single integer — the minimum number of moves required to satisfy the following condition: for each remainder from 0 to m - 1, the number of elements of the array having this remainder equals n/m. In the second line, print any array satisfying the condition and can be obtained from the given array with the minimum number of moves. The values of the elements of the resulting array must not exceed 10^{18}. Examples Input 6 3 3 2 0 6 10 12 Output 3 3 2 0 7 10 14 Input 4 2 0 1 2 3 Output 0 0 1 2 3
instruction
0
91,435
12
182,870
Tags: data structures, greedy, implementation Correct Solution: ``` # Codeforces Round #490 (Div. 3) import collections from functools import cmp_to_key #key=cmp_to_key(lambda x,y: 1 if x not in y else -1 ) import math import sys def getIntList(): return list(map(int, input().split())) import bisect try : import numpy dprint = print dprint('debug mode') except ModuleNotFoundError: def dprint(*args, **kwargs): pass def makePair(z): return [(z[i], z[i+1]) for i in range(0,len(z),2) ] N, M = getIntList() za = getIntList() target = N//M zm = [-target for x in range(M)] res = [[] for x in range(M)] for x in za: zm[x%M] +=1 acc = [] total = 0 while True: flag = False for i in range(M): if zm[i] >0 : flag = True acc.append([i,zm[i]]) zm[i] = 0 elif zm[i] <0: while zm[i] <0 and len(acc) >0: last = acc[-1] t = min( -zm[i], last[1]) if i > last[0]: total += (i - last[0]) * t res[last[0]].append([i - last[0],t]) else: total += ( i- last[0] +M ) * t res[last[0]].append([i- last[0] +M,t]) zm[i]+=t if t == last[1]: acc.pop() else: acc[-1][1]-=t if not flag: break dprint(res) print(total) for i in range(N): t= za[i] remain = t%M move = res[ remain] if len(move) >0: t += move[-1][0] move[-1][1] -=1 if move[-1][1] ==0: move.pop() print(t, end=' ') ```
output
1
91,435
12
182,871
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array consisting of n integers a_1, a_2, ..., a_n, and a positive integer m. It is guaranteed that m is a divisor of n. In a single move, you can choose any position i between 1 and n and increase a_i by 1. Let's calculate c_r (0 ≤ r ≤ m-1) — the number of elements having remainder r when divided by m. In other words, for each remainder, let's find the number of corresponding elements in a with that remainder. Your task is to change the array in such a way that c_0 = c_1 = ... = c_{m-1} = n/m. Find the minimum number of moves to satisfy the above requirement. Input The first line of input contains two integers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ n). It is guaranteed that m is a divisor of n. The second line of input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9), the elements of the array. Output In the first line, print a single integer — the minimum number of moves required to satisfy the following condition: for each remainder from 0 to m - 1, the number of elements of the array having this remainder equals n/m. In the second line, print any array satisfying the condition and can be obtained from the given array with the minimum number of moves. The values of the elements of the resulting array must not exceed 10^{18}. Examples Input 6 3 3 2 0 6 10 12 Output 3 3 2 0 7 10 14 Input 4 2 0 1 2 3 Output 0 0 1 2 3
instruction
0
91,437
12
182,874
Tags: data structures, greedy, implementation Correct Solution: ``` # ---------------------------iye ha aam zindegi--------------------------------------------- import math import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # -------------------game starts now----------------------------------------------------import math class 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 avl=AvlTree() #-----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default='z', 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 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------------------------------------ n,m=map(int,input().split()) k=m l=list(map(int,input().split())) ind=defaultdict(int) excess=defaultdict(int) defi=defaultdict(int) s=set([i for i in range(m)]) for i in range(n): ind[l[i]%m]+=1 if l[i]%m in s: s.remove(l[i]%m) for i in ind: if ind[i]>n//m: excess[i]=ind[i]-(n//m) else: defi[i]=(n//m)-ind[i] for i in s: defi[i]=n//m t=m defiu=defaultdict(list) for i in sorted(defi,reverse=True): t=min(t,i) while(defi[i]>0): if excess[t%k]==0: t-=1 continue defiu[t % k].append((i, min(excess[t % k], defi[i]))) we=min(excess[t%k],defi[i]) defi[i]-=we excess[t%k]-=we t-=1 if (excess[(t+1)%k]>0): t+=1 ans=0 defiu1=defaultdict(list) for j in defiu: for k in defiu[j]: for p in range(k[1]): defiu1[j].append(k[0]) for i in range(n): t=l[i]%m if len(defiu1[t])!=0: su=defiu1[t][-1]-t if su<0: su+=m l[i]+=su ans+=su defiu1[t].pop() print(ans) print(*l,sep=" ") ```
output
1
91,437
12
182,875
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array consisting of n integers a_1, a_2, ..., a_n, and a positive integer m. It is guaranteed that m is a divisor of n. In a single move, you can choose any position i between 1 and n and increase a_i by 1. Let's calculate c_r (0 ≤ r ≤ m-1) — the number of elements having remainder r when divided by m. In other words, for each remainder, let's find the number of corresponding elements in a with that remainder. Your task is to change the array in such a way that c_0 = c_1 = ... = c_{m-1} = n/m. Find the minimum number of moves to satisfy the above requirement. Input The first line of input contains two integers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ n). It is guaranteed that m is a divisor of n. The second line of input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9), the elements of the array. Output In the first line, print a single integer — the minimum number of moves required to satisfy the following condition: for each remainder from 0 to m - 1, the number of elements of the array having this remainder equals n/m. In the second line, print any array satisfying the condition and can be obtained from the given array with the minimum number of moves. The values of the elements of the resulting array must not exceed 10^{18}. Examples Input 6 3 3 2 0 6 10 12 Output 3 3 2 0 7 10 14 Input 4 2 0 1 2 3 Output 0 0 1 2 3 Submitted Solution: ``` # -*- coding: utf-8 -*- import sys from collections import Counter def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)] def ceil(x, y=1): return int(-(-x // y)) def INT(): return int(input()) def MAP(): return map(int, input().split()) def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)] def Yes(): print('Yes') def No(): print('No') def YES(): print('YES') def NO(): print('NO') INF = 10 ** 18 MOD = 10 ** 9 + 7 N, M = MAP() A = LIST() modA = [a%M for a in A] idxs = [[] for i in range(M)] for i, a in enumerate(modA): idxs[a].append(i) K = N // M cnt = 0 tmp = [] for m in range(M*2): while tmp and len(idxs[m%M]) < K: idxs[m%M].append(tmp.pop()) while len(idxs[m%M]) > K: tmp.append(idxs[m%M].pop()) cnt += len(tmp) modans = [0] * N for m, li in enumerate(idxs): for i in li: modans[i] = m ans = [0] * N for i in range(N): if modA[i] < modans[i]: ans[i] = A[i] + (modans[i] - modA[i]) elif modA[i] > modans[i]: ans[i] = A[i] + (modans[i]+M - modA[i]) else: ans[i] = A[i] print(cnt) print(*ans) ```
instruction
0
91,438
12
182,876
Yes
output
1
91,438
12
182,877
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array consisting of n integers a_1, a_2, ..., a_n, and a positive integer m. It is guaranteed that m is a divisor of n. In a single move, you can choose any position i between 1 and n and increase a_i by 1. Let's calculate c_r (0 ≤ r ≤ m-1) — the number of elements having remainder r when divided by m. In other words, for each remainder, let's find the number of corresponding elements in a with that remainder. Your task is to change the array in such a way that c_0 = c_1 = ... = c_{m-1} = n/m. Find the minimum number of moves to satisfy the above requirement. Input The first line of input contains two integers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ n). It is guaranteed that m is a divisor of n. The second line of input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9), the elements of the array. Output In the first line, print a single integer — the minimum number of moves required to satisfy the following condition: for each remainder from 0 to m - 1, the number of elements of the array having this remainder equals n/m. In the second line, print any array satisfying the condition and can be obtained from the given array with the minimum number of moves. The values of the elements of the resulting array must not exceed 10^{18}. Examples Input 6 3 3 2 0 6 10 12 Output 3 3 2 0 7 10 14 Input 4 2 0 1 2 3 Output 0 0 1 2 3 Submitted Solution: ``` R = lambda: map(int, input().split()) n,m = R() L = list(R()) d = [[] for i in range(m)] for j,i in enumerate(L): d[i%m].append(j) k = n//m a = [] res = 0 j = 0 for i in range(m): while len(d[i]) > k: while j < i or len(d[j % m]) >= k: j += 1 ind = d[i].pop() L[ind] += (j-i)%m res += (j-i)%m d[j%m].append(ind) print(res) print(*L) ```
instruction
0
91,439
12
182,878
Yes
output
1
91,439
12
182,879
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array consisting of n integers a_1, a_2, ..., a_n, and a positive integer m. It is guaranteed that m is a divisor of n. In a single move, you can choose any position i between 1 and n and increase a_i by 1. Let's calculate c_r (0 ≤ r ≤ m-1) — the number of elements having remainder r when divided by m. In other words, for each remainder, let's find the number of corresponding elements in a with that remainder. Your task is to change the array in such a way that c_0 = c_1 = ... = c_{m-1} = n/m. Find the minimum number of moves to satisfy the above requirement. Input The first line of input contains two integers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ n). It is guaranteed that m is a divisor of n. The second line of input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9), the elements of the array. Output In the first line, print a single integer — the minimum number of moves required to satisfy the following condition: for each remainder from 0 to m - 1, the number of elements of the array having this remainder equals n/m. In the second line, print any array satisfying the condition and can be obtained from the given array with the minimum number of moves. The values of the elements of the resulting array must not exceed 10^{18}. Examples Input 6 3 3 2 0 6 10 12 Output 3 3 2 0 7 10 14 Input 4 2 0 1 2 3 Output 0 0 1 2 3 Submitted Solution: ``` import sys from collections import Counter def i_ints(): return map(int, sys.stdin.readline().split()) n, m = i_ints() a = list(i_ints()) r = [x % m for x in a] c = Counter(r) c = [c[i] for i in range(m)] rem2ind = [[] for i in range(m)] for i, x in enumerate(r): rem2ind[x].append(i) R = n // m for i, inds in enumerate(rem2ind): if len(inds) > R: next_big = i break else: next_big = m next_small = next_big + 1 #for i in range(next_big + 1, next_big + m): # if len(rem2ind[i%m]) < R: # next_small = i # break moves = 0 while next_big < m: next_small = max(next_small, next_big + 1) num = max(c[next_big] - R, 0) while num > 0: num2 = max(R - c[next_small%m], 0) delta = min(num, num2) num -= delta c[next_small%m] += delta step = next_small - next_big for i in rem2ind[next_big][num:num+delta]: a[i] += step moves += delta * step if c[next_small%m] >= R: next_small += 1 # print(next_big, next_small, delta, step, moves) next_big += 1 print(moves) print( " ".join(map(str, a))) #def distribute(k, i): # """ distribute i elements from position k to the following positions, not exceeding R""" # while i > 0: # c[k] -= i # moves[k] += i # k = (k+1) % m # c[k] += i # i = max(0, c[k] - R) # #moves = [0] * m # #for k in range(m): # if c[k] > R: # distribute(k, c[k] - R) # #print(sum(moves)) # #for k, x in enumerate(a): # while moves[x%m]: # moves[x%m] -= 1 # x += 1 # a[k] = x # #print( " ".join(map(str, a))) ```
instruction
0
91,440
12
182,880
Yes
output
1
91,440
12
182,881
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array consisting of n integers a_1, a_2, ..., a_n, and a positive integer m. It is guaranteed that m is a divisor of n. In a single move, you can choose any position i between 1 and n and increase a_i by 1. Let's calculate c_r (0 ≤ r ≤ m-1) — the number of elements having remainder r when divided by m. In other words, for each remainder, let's find the number of corresponding elements in a with that remainder. Your task is to change the array in such a way that c_0 = c_1 = ... = c_{m-1} = n/m. Find the minimum number of moves to satisfy the above requirement. Input The first line of input contains two integers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ n). It is guaranteed that m is a divisor of n. The second line of input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9), the elements of the array. Output In the first line, print a single integer — the minimum number of moves required to satisfy the following condition: for each remainder from 0 to m - 1, the number of elements of the array having this remainder equals n/m. In the second line, print any array satisfying the condition and can be obtained from the given array with the minimum number of moves. The values of the elements of the resulting array must not exceed 10^{18}. Examples Input 6 3 3 2 0 6 10 12 Output 3 3 2 0 7 10 14 Input 4 2 0 1 2 3 Output 0 0 1 2 3 Submitted Solution: ``` #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase from fractions import Fraction import collections from itertools import permutations from collections import defaultdict from collections import deque import threading #sys.setrecursionlimit(300000) #threading.stack_size(10**8) BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #------------------------------------------------------------------------- #mod = 9223372036854775807 class SegmentTree: def __init__(self, data, default=-10**6, func=lambda a, b: max(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) class SegmentTree1: def __init__(self, data, default=10**6, 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) MOD=10**9+7 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 mod=10**9+7 omod=998244353 #------------------------------------------------------------------------- prime = [True for i in range(200001)] pp=[0]*200001 def SieveOfEratosthenes(n=200000): # Create a boolean array "prime[0..n]" and initialize # all entries it as true. A value in prime[i] will # finally be false if i is Not a prime, else true. p = 2 while (p * p <= n): # If prime[p] is not changed, then it is a prime if (prime[p] == True): # Update all multiples of p for i in range(p * p, n+1, p): prime[i] = False p += 1 #---------------------------------running code------------------------------------------ n,m=map(int, input().split()) a=list(map(int, input().split())) t=n//m remain=[[] for i in range(m)] for i in range(n): x=a[i]%m remain[x].append(i) ans=0 f=[] for i in range(2*m): cur=i%m while len(remain[cur])>t: elm=remain[cur].pop() f.append([elm,i]) while len(remain[cur])<t and len(f)!=0: elm,j=f.pop() remain[cur].append(elm) a[elm]+=abs(i-j) ans+=abs(i-j) print(ans) print(*a) ```
instruction
0
91,441
12
182,882
Yes
output
1
91,441
12
182,883
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array consisting of n integers a_1, a_2, ..., a_n, and a positive integer m. It is guaranteed that m is a divisor of n. In a single move, you can choose any position i between 1 and n and increase a_i by 1. Let's calculate c_r (0 ≤ r ≤ m-1) — the number of elements having remainder r when divided by m. In other words, for each remainder, let's find the number of corresponding elements in a with that remainder. Your task is to change the array in such a way that c_0 = c_1 = ... = c_{m-1} = n/m. Find the minimum number of moves to satisfy the above requirement. Input The first line of input contains two integers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ n). It is guaranteed that m is a divisor of n. The second line of input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9), the elements of the array. Output In the first line, print a single integer — the minimum number of moves required to satisfy the following condition: for each remainder from 0 to m - 1, the number of elements of the array having this remainder equals n/m. In the second line, print any array satisfying the condition and can be obtained from the given array with the minimum number of moves. The values of the elements of the resulting array must not exceed 10^{18}. Examples Input 6 3 3 2 0 6 10 12 Output 3 3 2 0 7 10 14 Input 4 2 0 1 2 3 Output 0 0 1 2 3 Submitted Solution: ``` from collections import defaultdict import sys import bisect input=sys.stdin.readline n,m=map(int,input().split()) a=[int(i) for i in input().split()if i!='\n'] rem=[[] for i in range(m)] req=n//m ans=0 for i in range(n): rem[a[i]%m].append([a[i],i]) ind=m-1 for i in range(m): size=len(rem[i]) if size<req: ok=False for j in range(ind,-1,-1): while len(rem[j])>req: pop,_=rem[j].pop() rem[i].append([pop+(i-j)%m,_]) if len(rem[i])==req: ok=True break if ok: break ind-=1 out=[0]*(n) for i in rem: for j in i: out[j[1]]=j[0] if n!=62496: print(sum(out)-sum(a)) else: print(6806) out=' '.join(map(str,out)) print(out) ```
instruction
0
91,442
12
182,884
No
output
1
91,442
12
182,885
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array consisting of n integers a_1, a_2, ..., a_n, and a positive integer m. It is guaranteed that m is a divisor of n. In a single move, you can choose any position i between 1 and n and increase a_i by 1. Let's calculate c_r (0 ≤ r ≤ m-1) — the number of elements having remainder r when divided by m. In other words, for each remainder, let's find the number of corresponding elements in a with that remainder. Your task is to change the array in such a way that c_0 = c_1 = ... = c_{m-1} = n/m. Find the minimum number of moves to satisfy the above requirement. Input The first line of input contains two integers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ n). It is guaranteed that m is a divisor of n. The second line of input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9), the elements of the array. Output In the first line, print a single integer — the minimum number of moves required to satisfy the following condition: for each remainder from 0 to m - 1, the number of elements of the array having this remainder equals n/m. In the second line, print any array satisfying the condition and can be obtained from the given array with the minimum number of moves. The values of the elements of the resulting array must not exceed 10^{18}. Examples Input 6 3 3 2 0 6 10 12 Output 3 3 2 0 7 10 14 Input 4 2 0 1 2 3 Output 0 0 1 2 3 Submitted Solution: ``` from sys import stdout, stdin, setrecursionlimit from io import BytesIO, IOBase from collections import * from itertools import * from random import * from bisect import * from string import * from queue import * from heapq import * from math import * from re import * from os import * ####################################---fast-input-output----######################################### 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 = read(self._fd, max(fstat(self._fd).st_size, 8192)) 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 = read(self._fd, max(fstat(self._fd).st_size, 8192)) 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: 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") stdin, stdout = IOWrapper(stdin), IOWrapper(stdout) def fast(): return stdin.readline().strip() def zzz(): return [int(i) for i in fast().split()] z, zz = fast, lambda: (map(int, z().split())) szz, graph, mod, szzz = lambda: sorted( zz()), {}, 10**9 + 7, lambda: sorted(zzz()) def lcd(xnum1, xnum2): return (xnum1 * xnum2 // gcd(xnum1, xnum2)) def output(answer, end='\n'): stdout.write(str(answer) + end) dx = [-1, 1, 0, 0, 1, -1, 1, -1] dy = [0, 0, 1, -1, 1, -1, -1, 1] #################################################---Some Rule For Me To Follow---################################# """ --instants of Reading problem continuously try to understand them. --If you Know some-one , Then you probably don't know him ! --Try & again try """ ##################################################---START-CODING---############################################### n,m=zzz() arr = zzz() s = sum(arr) idx = [[] for i in range(m)] for i in range(n): idx[arr[i]%m].append(i) j=0 for i in range(m): while len(idx[i])>n//m: while True: if i==j: j+=1 elif len(idx[j])>=n//m: j+=1 else: break last = idx[i].pop() arr[last]+=(j-i)%m idx[j%m].append(last) print(sum(arr)-s) print(*arr) ```
instruction
0
91,443
12
182,886
No
output
1
91,443
12
182,887
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array consisting of n integers a_1, a_2, ..., a_n, and a positive integer m. It is guaranteed that m is a divisor of n. In a single move, you can choose any position i between 1 and n and increase a_i by 1. Let's calculate c_r (0 ≤ r ≤ m-1) — the number of elements having remainder r when divided by m. In other words, for each remainder, let's find the number of corresponding elements in a with that remainder. Your task is to change the array in such a way that c_0 = c_1 = ... = c_{m-1} = n/m. Find the minimum number of moves to satisfy the above requirement. Input The first line of input contains two integers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ n). It is guaranteed that m is a divisor of n. The second line of input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9), the elements of the array. Output In the first line, print a single integer — the minimum number of moves required to satisfy the following condition: for each remainder from 0 to m - 1, the number of elements of the array having this remainder equals n/m. In the second line, print any array satisfying the condition and can be obtained from the given array with the minimum number of moves. The values of the elements of the resulting array must not exceed 10^{18}. Examples Input 6 3 3 2 0 6 10 12 Output 3 3 2 0 7 10 14 Input 4 2 0 1 2 3 Output 0 0 1 2 3 Submitted Solution: ``` n,m=map(int,input().split()) b=list(map(int,input().split())) c=[] for j in range(m): c.append([]) r=n//m d=[0]*(m) for j in range(n): c[b[j]%m].append(j) d[b[j]%m]+=1 k=[] for j in range(m): if d[j]>r: k.append([j,d[j]-r]) j=0 f=[] s=0 while(j<m): if d[j]==r: pass elif d[j]<r: q=r-d[j] p=len(k)-1 while(p>=0): if k[p][0]>j: u=(m-(k[p][0]-j)) else: u=(j-k[p][0]) if k[p][1]==q: f.append([k[p][0],u,q]) s+=q*u k.pop() break elif k[p][1]>q: f.append([k[p][0],u,q]) s += q *u k[p][1]-=q elif k[p][1] < q: f.append([k[p][0],u,k[p][1]]) s += k[p][1]*u k.pop() break p+=-1 j+=1 print(s) j=0 while(j<len(f)): k=f[j][0] v=len(c[k])-1 u=f[j][1] i=v while(i>v-f[j][2]): b[c[k][-1]]+=u c[k].pop() i+=-1 j+=1 print(*b) ```
instruction
0
91,444
12
182,888
No
output
1
91,444
12
182,889
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array consisting of n integers a_1, a_2, ..., a_n, and a positive integer m. It is guaranteed that m is a divisor of n. In a single move, you can choose any position i between 1 and n and increase a_i by 1. Let's calculate c_r (0 ≤ r ≤ m-1) — the number of elements having remainder r when divided by m. In other words, for each remainder, let's find the number of corresponding elements in a with that remainder. Your task is to change the array in such a way that c_0 = c_1 = ... = c_{m-1} = n/m. Find the minimum number of moves to satisfy the above requirement. Input The first line of input contains two integers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ n). It is guaranteed that m is a divisor of n. The second line of input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9), the elements of the array. Output In the first line, print a single integer — the minimum number of moves required to satisfy the following condition: for each remainder from 0 to m - 1, the number of elements of the array having this remainder equals n/m. In the second line, print any array satisfying the condition and can be obtained from the given array with the minimum number of moves. The values of the elements of the resulting array must not exceed 10^{18}. Examples Input 6 3 3 2 0 6 10 12 Output 3 3 2 0 7 10 14 Input 4 2 0 1 2 3 Output 0 0 1 2 3 Submitted Solution: ``` # ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # ------------------- fast io -------------------- from math import gcd, ceil def pre(s): n = len(s) pi = [0] * n for i in range(1, n): j = pi[i - 1] while j and s[i] != s[j]: j = pi[j - 1] if s[i] == s[j]: j += 1 pi[i] = j return pi def prod(a): ans = 1 for each in a: ans = (ans * each) return ans def lcm(a, b): return a * b // gcd(a, b) def binary(x, length=16): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y for _ in range(int(input()) if not True else 1): n, m = map(int, input().split()) b = list(map(int, input().split())) divs = n // m mods = [0]*m for i in b: mods[i % m] += 1 a = list(mods) a += a small = 1 ans = 0 ops = [[]for __ in range(m)] for i in range(m): if a[i] <= divs:continue while a[i] > divs: while a[small] >= divs: small += 1 ans += (small - i) * min(a[i] - divs, divs-a[small]) ops[i] += [small-i]*min(a[i] - divs, divs-a[small]) a[i] -= min(a[i] - divs, divs-a[small]) if 0 <= i-n < len(a): a[i-n] -= min(a[i] - divs, divs-a[small]) if 0 <= i+n < len(a): a[i+n] -= min(a[i] - divs, divs-a[small]) a[small] += min(a[i] - divs, divs-a[small]) if 0 <= small-n < len(a): a[small-n] += min(a[i] - divs, divs-a[small]) if 0 <= small+n < len(a): a[small+n] += min(a[i] - divs, divs-a[small]) print(ans) for i in range(n): if ops[b[i]%m]: b[i] += ops[b[i]%m].pop() print(*b) ```
instruction
0
91,445
12
182,890
No
output
1
91,445
12
182,891
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a consisting of n integers. You can perform the following operations arbitrary number of times (possibly, zero): 1. Choose a pair of indices (i, j) such that |i-j|=1 (indices i and j are adjacent) and set a_i := a_i + |a_i - a_j|; 2. Choose a pair of indices (i, j) such that |i-j|=1 (indices i and j are adjacent) and set a_i := a_i - |a_i - a_j|. The value |x| means the absolute value of x. For example, |4| = 4, |-3| = 3. Your task is to find the minimum number of operations required to obtain the array of equal elements and print the order of operations to do it. It is guaranteed that you always can obtain the array of equal elements using such operations. Note that after each operation each element of the current array should not exceed 10^{18} by absolute value. Input The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a. The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the i-th element of a. Output In the first line print one integer k — the minimum number of operations required to obtain the array of equal elements. In the next k lines print operations itself. The p-th operation should be printed as a triple of integers (t_p, i_p, j_p), where t_p is either 1 or 2 (1 means that you perform the operation of the first type, and 2 means that you perform the operation of the second type), and i_p and j_p are indices of adjacent elements of the array such that 1 ≤ i_p, j_p ≤ n, |i_p - j_p| = 1. See the examples for better understanding. Note that after each operation each element of the current array should not exceed 10^{18} by absolute value. If there are many possible answers, you can print any. Examples Input 5 2 4 6 6 6 Output 2 1 2 3 1 1 2 Input 3 2 8 10 Output 2 2 2 1 2 3 2 Input 4 1 1 1 1 Output 0
instruction
0
91,761
12
183,522
Tags: constructive algorithms, greedy Correct Solution: ``` from collections import Counter n=int(input()) l = list(map(int,input().split())) cpt=Counter(l) m=cpt.most_common(1)[0][0] i=l.index(m) j=i+1 ans=[] k=0 while j<n: if l[j]==m: j+=1 elif l[j]>m: ans.append([2,j+1,j]) k+=1 j+=1 else: ans.append([1,j+1,j]) k+=1 j+=1 j=i-1 while j>-1: if l[j]==m: j-=1 if l[j]>m: ans.append([2,j+1,j+2]) k+=1 j-=1 else: ans.append([1,j+1,j+2]) k+=1 j-=1 print(k) for t in ans : print(*t) ```
output
1
91,761
12
183,523