message
stringlengths
2
433k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
113
108k
cluster
float64
12
12
__index_level_0__
int64
226
217k
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a consisting of n non-negative integers. You have to choose a non-negative integer x and form a new array b of size n according to the following rule: for all i from 1 to n, b_i = a_i ⊕ x (⊕ denotes the operation [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)). An inversion in the b array is a pair of integers i and j such that 1 ≤ i < j ≤ n and b_i > b_j. You should choose x in such a way that the number of inversions in b is minimized. If there are several options for x — output the smallest one. Input First line contains a single integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the number of elements in a. Second line contains n space-separated integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9), where a_i is the i-th element of a. Output Output two integers: the minimum possible number of inversions in b, and the minimum possible value of x, which achieves those number of inversions. Examples Input 4 0 1 3 2 Output 1 0 Input 9 10 7 9 10 7 5 5 3 5 Output 4 14 Input 3 8 10 3 Output 0 8 Note In the first sample it is optimal to leave the array as it is by choosing x = 0. In the second sample the selection of x = 14 results in b: [4, 9, 7, 4, 9, 11, 11, 13, 11]. It has 4 inversions: * i = 2, j = 3; * i = 2, j = 4; * i = 3, j = 4; * i = 8, j = 9. In the third sample the selection of x = 8 results in b: [0, 2, 11]. It has no inversions. Submitted Solution: ``` n = int(input()) a = list(map(int, input().split())) m = max(a) b = 0 while (1<<b)<m: b+=1 now = [a] x = 0 inv = 0 for i in reversed(range(b)): nxt = [] zrs = ons = 0 for arr in now: zeroes = [] ones = [] zr = 0 on = 0 for j in arr: if (1<<i)&j!=0: on+=len(zeroes) ones.append(j) else: zr+=len(ones) zeroes.append(j) if len(zeroes)>0: nxt.append(zeroes) if len(zeroes)>0: nxt.append(ones) zrs+=zr ons+=on inv+=min(zrs, ons) if ons<zrs: x+=1<<i now = nxt.copy() #print(now) print(inv, x) ```
instruction
0
38,852
12
77,704
No
output
1
38,852
12
77,705
Provide tags and a correct Python 3 solution for this coding contest problem. Seiji Maki doesn't only like to observe relationships being unfolded, he also likes to observe sequences of numbers, especially permutations. Today, he has his eyes on almost sorted permutations. A permutation a_1, a_2, ..., a_n of 1, 2, ..., n is said to be almost sorted if the condition a_{i + 1} ≥ a_i - 1 holds for all i between 1 and n - 1 inclusive. Maki is considering the list of all almost sorted permutations of 1, 2, ..., n, given in lexicographical order, and he wants to find the k-th permutation in this list. Can you help him to find such permutation? Permutation p is lexicographically smaller than a permutation q if and only if the following holds: * in the first position where p and q differ, the permutation p has a smaller element than the corresponding element in q. Input The first line contains a single integer t (1≤ t≤ 1000) — the number of test cases. Each test case consists of a single line containing two integers n and k (1 ≤ n ≤ 10^5, 1 ≤ k ≤ 10^{18}). It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print a single line containing the k-th almost sorted permutation of length n in lexicographical order, or -1 if it doesn't exist. Example Input 5 1 1 1 2 3 3 6 5 3 4 Output 1 -1 2 1 3 1 2 4 3 5 6 3 2 1 Note For the first and second test, the list of almost sorted permutations with n = 1 is \{[1]\}. For the third and fifth test, the list of almost sorted permutations with n = 3 is \{[1, 2, 3], [1, 3, 2], [2, 1, 3], [3, 2, 1]\}.
instruction
0
38,901
12
77,802
Tags: binary search, combinatorics, constructive algorithms, implementation Correct Solution: ``` import sys input = sys.stdin.readline t = int(input()) for _ in range(t): n, k = map(int, input().split()) k -= 1 p = [i + 1 for i in range(n)] x = 1 sw = [] for i in range(n - 2, -1, -1): if k < x: break if k & x == x: k -= x sw.append(i) x *= 2 f = 0 for i in sw: if not f: r, l = i + 1, i + 1 f = 1 if l - i == 1: l = i else: for j in range(r - l + 1): p[l + j] = r - j + 1 r, l = i + 1, i if sw: for j in range(r - l + 1): p[l + j] = r - j + 1 if k: p = [-1] print(*p) ```
output
1
38,901
12
77,803
Provide tags and a correct Python 3 solution for this coding contest problem. Seiji Maki doesn't only like to observe relationships being unfolded, he also likes to observe sequences of numbers, especially permutations. Today, he has his eyes on almost sorted permutations. A permutation a_1, a_2, ..., a_n of 1, 2, ..., n is said to be almost sorted if the condition a_{i + 1} ≥ a_i - 1 holds for all i between 1 and n - 1 inclusive. Maki is considering the list of all almost sorted permutations of 1, 2, ..., n, given in lexicographical order, and he wants to find the k-th permutation in this list. Can you help him to find such permutation? Permutation p is lexicographically smaller than a permutation q if and only if the following holds: * in the first position where p and q differ, the permutation p has a smaller element than the corresponding element in q. Input The first line contains a single integer t (1≤ t≤ 1000) — the number of test cases. Each test case consists of a single line containing two integers n and k (1 ≤ n ≤ 10^5, 1 ≤ k ≤ 10^{18}). It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print a single line containing the k-th almost sorted permutation of length n in lexicographical order, or -1 if it doesn't exist. Example Input 5 1 1 1 2 3 3 6 5 3 4 Output 1 -1 2 1 3 1 2 4 3 5 6 3 2 1 Note For the first and second test, the list of almost sorted permutations with n = 1 is \{[1]\}. For the third and fifth test, the list of almost sorted permutations with n = 3 is \{[1, 2, 3], [1, 3, 2], [2, 1, 3], [3, 2, 1]\}.
instruction
0
38,902
12
77,804
Tags: binary search, combinatorics, constructive algorithms, implementation Correct Solution: ``` t = int(input()) for _ in range(t): n, k = [int(x) for x in input().split()] if (k > 1 << (n-1)): print(-1) continue ans = [] i = 1 while (i <= n): l = 0 while i < n and 1 << (n-i-1) < k: k -= 1 << (n-i-1) l += 1 i += 1 for j in range(i, i-l-1, -1): ans.append(j) i += 1 for i in ans: print(i, end=" ") print() ```
output
1
38,902
12
77,805
Provide tags and a correct Python 3 solution for this coding contest problem. Seiji Maki doesn't only like to observe relationships being unfolded, he also likes to observe sequences of numbers, especially permutations. Today, he has his eyes on almost sorted permutations. A permutation a_1, a_2, ..., a_n of 1, 2, ..., n is said to be almost sorted if the condition a_{i + 1} ≥ a_i - 1 holds for all i between 1 and n - 1 inclusive. Maki is considering the list of all almost sorted permutations of 1, 2, ..., n, given in lexicographical order, and he wants to find the k-th permutation in this list. Can you help him to find such permutation? Permutation p is lexicographically smaller than a permutation q if and only if the following holds: * in the first position where p and q differ, the permutation p has a smaller element than the corresponding element in q. Input The first line contains a single integer t (1≤ t≤ 1000) — the number of test cases. Each test case consists of a single line containing two integers n and k (1 ≤ n ≤ 10^5, 1 ≤ k ≤ 10^{18}). It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print a single line containing the k-th almost sorted permutation of length n in lexicographical order, or -1 if it doesn't exist. Example Input 5 1 1 1 2 3 3 6 5 3 4 Output 1 -1 2 1 3 1 2 4 3 5 6 3 2 1 Note For the first and second test, the list of almost sorted permutations with n = 1 is \{[1]\}. For the third and fifth test, the list of almost sorted permutations with n = 3 is \{[1, 2, 3], [1, 3, 2], [2, 1, 3], [3, 2, 1]\}.
instruction
0
38,903
12
77,806
Tags: binary search, combinatorics, constructive algorithms, implementation Correct Solution: ``` import sys,io,os try:Z=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline except:Z=lambda:sys.stdin.readline().encode() O=[] for _ in range(int(Z())): n,k=map(int,Z().split());k-=1 if k.bit_length()>=n:O.append('-1');continue if n<2:O.append('1');continue r=[] low=0 c=1 s=bin(k)[2:].rjust(n-1,'0') for i in s: if i=='1':c+=1 else: for j in range(low+c,low,-1):r.append(j) low+=c c=1 for j in range(low+c,low,-1):r.append(j) O.append(' '.join(map(str,r))) print('\n'.join(O)) ```
output
1
38,903
12
77,807
Provide tags and a correct Python 3 solution for this coding contest problem. Seiji Maki doesn't only like to observe relationships being unfolded, he also likes to observe sequences of numbers, especially permutations. Today, he has his eyes on almost sorted permutations. A permutation a_1, a_2, ..., a_n of 1, 2, ..., n is said to be almost sorted if the condition a_{i + 1} ≥ a_i - 1 holds for all i between 1 and n - 1 inclusive. Maki is considering the list of all almost sorted permutations of 1, 2, ..., n, given in lexicographical order, and he wants to find the k-th permutation in this list. Can you help him to find such permutation? Permutation p is lexicographically smaller than a permutation q if and only if the following holds: * in the first position where p and q differ, the permutation p has a smaller element than the corresponding element in q. Input The first line contains a single integer t (1≤ t≤ 1000) — the number of test cases. Each test case consists of a single line containing two integers n and k (1 ≤ n ≤ 10^5, 1 ≤ k ≤ 10^{18}). It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print a single line containing the k-th almost sorted permutation of length n in lexicographical order, or -1 if it doesn't exist. Example Input 5 1 1 1 2 3 3 6 5 3 4 Output 1 -1 2 1 3 1 2 4 3 5 6 3 2 1 Note For the first and second test, the list of almost sorted permutations with n = 1 is \{[1]\}. For the third and fifth test, the list of almost sorted permutations with n = 3 is \{[1, 2, 3], [1, 3, 2], [2, 1, 3], [3, 2, 1]\}.
instruction
0
38,904
12
77,808
Tags: binary search, combinatorics, constructive algorithms, implementation Correct Solution: ``` import sys input = sys.stdin.readline t = int(input()) for _ in range(t): n, k = map(int, input().split()) k -= 1 out = [] curr = [1] todo = [] for i in range(n - 1): todo.append(k % 2) k//=2 todo.reverse() for i in range(n - 1): if todo[i]: curr.append(i + 2) else: while curr: out.append(curr.pop()) curr.append(i + 2) while curr: out.append(curr.pop()) if k == 0: print(' '.join(map(str,out))) else: print(-1) ```
output
1
38,904
12
77,809
Provide tags and a correct Python 3 solution for this coding contest problem. Seiji Maki doesn't only like to observe relationships being unfolded, he also likes to observe sequences of numbers, especially permutations. Today, he has his eyes on almost sorted permutations. A permutation a_1, a_2, ..., a_n of 1, 2, ..., n is said to be almost sorted if the condition a_{i + 1} ≥ a_i - 1 holds for all i between 1 and n - 1 inclusive. Maki is considering the list of all almost sorted permutations of 1, 2, ..., n, given in lexicographical order, and he wants to find the k-th permutation in this list. Can you help him to find such permutation? Permutation p is lexicographically smaller than a permutation q if and only if the following holds: * in the first position where p and q differ, the permutation p has a smaller element than the corresponding element in q. Input The first line contains a single integer t (1≤ t≤ 1000) — the number of test cases. Each test case consists of a single line containing two integers n and k (1 ≤ n ≤ 10^5, 1 ≤ k ≤ 10^{18}). It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print a single line containing the k-th almost sorted permutation of length n in lexicographical order, or -1 if it doesn't exist. Example Input 5 1 1 1 2 3 3 6 5 3 4 Output 1 -1 2 1 3 1 2 4 3 5 6 3 2 1 Note For the first and second test, the list of almost sorted permutations with n = 1 is \{[1]\}. For the third and fifth test, the list of almost sorted permutations with n = 3 is \{[1, 2, 3], [1, 3, 2], [2, 1, 3], [3, 2, 1]\}.
instruction
0
38,905
12
77,810
Tags: binary search, combinatorics, constructive algorithms, implementation Correct Solution: ``` from bisect import * from collections import * from math import gcd,ceil,sqrt,floor,inf from heapq import * from itertools import * from operator import add,mul,sub,xor,truediv,floordiv from functools import * #------------------------------------------------------------------------ import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #------------------------------------------------------------------------ def RL(): return map(int, sys.stdin.readline().rstrip().split()) def RLL(): return list(map(int, sys.stdin.readline().rstrip().split())) def N(): return int(input()) def A(n):return [0]*n def AI(n,x): return [x]*n def A2(n,m): return [[0]*m for i in range(n)] def G(n): return [[] for i in range(n)] def GP(it): return [[ch,len(list(g))] for ch,g in groupby(it)] #------------------------------------------------------------------------ from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc mod=10**9+7 farr=[1] ifa=[] def fact(x,mod=0): if mod: while x>=len(farr): farr.append(farr[-1]*len(farr)%mod) else: while x>=len(farr): farr.append(farr[-1]*len(farr)) return farr[x] def ifact(x,mod): global ifa fact(x,mod) ifa.append(pow(farr[-1],mod-2,mod)) for i in range(x,0,-1): ifa.append(ifa[-1]*i%mod) ifa.reverse() def per(i,j,mod=0): if i<j: return 0 if not mod: return fact(i)//fact(i-j) return farr[i]*ifa[i-j]%mod def com(i,j,mod=0): if i<j: return 0 if not mod: return per(i,j)//fact(j) return per(i,j,mod)*ifa[j]%mod def catalan(n): return com(2*n,n)//(n+1) def isprime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True def floorsum(a,b,c,n):#sum((a*i+b)//c for i in range(n+1)) if a==0:return b//c*(n+1) if a>=c or b>=c: return floorsum(a%c,b%c,c,n)+b//c*(n+1)+a//c*n*(n+1)//2 m=(a*n+b)//c return n*m-floorsum(c,c-b-1,a,m-1) def inverse(a,m): a%=m if a<=1: return a return ((1-inverse(m,a)*m)//a)%m def lowbit(n): return n&-n class BIT: def __init__(self,arr): self.arr=arr self.n=len(arr)-1 def update(self,x,v): while x<=self.n: self.arr[x]+=v x+=x&-x def query(self,x): ans=0 while x: ans+=self.arr[x] x&=x-1 return ans class ST: def __init__(self,arr):#n!=0 n=len(arr) mx=n.bit_length()#取不到 self.st=[[0]*mx for i in range(n)] for i in range(n): self.st[i][0]=arr[i] for j in range(1,mx): for i in range(n-(1<<j)+1): self.st[i][j]=max(self.st[i][j-1],self.st[i+(1<<j-1)][j-1]) def query(self,l,r): if l>r:return -inf s=(r+1-l).bit_length()-1 return max(self.st[l][s],self.st[r-(1<<s)+1][s]) ''' class DSU:#容量+路径压缩 def __init__(self,n): self.c=[-1]*n def same(self,x,y): return self.find(x)==self.find(y) def find(self,x): if self.c[x]<0: return x self.c[x]=self.find(self.c[x]) return self.c[x] def union(self,u,v): u,v=self.find(u),self.find(v) if u==v: return False if self.c[u]>self.c[v]: u,v=v,u self.c[u]+=self.c[v] self.c[v]=u return True def size(self,x): return -self.c[self.find(x)]''' class UFS:#秩+路径 def __init__(self,n): self.parent=[i for i in range(n)] self.ranks=[0]*n def find(self,x): if x!=self.parent[x]: self.parent[x]=self.find(self.parent[x]) return self.parent[x] def union(self,u,v): pu,pv=self.find(u),self.find(v) if pu==pv: return False if self.ranks[pu]>=self.ranks[pv]: self.parent[pv]=pu if self.ranks[pv]==self.ranks[pu]: self.ranks[pu]+=1 else: self.parent[pu]=pv def Prime(n): c=0 prime=[] flag=[0]*(n+1) for i in range(2,n+1): if not flag[i]: prime.append(i) c+=1 for j in range(c): if i*prime[j]>n: break flag[i*prime[j]]=prime[j] if i%prime[j]==0: break return prime def dij(s,graph): d={} d[s]=0 heap=[(0,s)] seen=set() while heap: dis,u=heappop(heap) if u in seen: continue seen.add(u) for v,w in graph[u]: if v not in d or d[v]>d[u]+w: d[v]=d[u]+w heappush(heap,(d[v],v)) return d def bell(s,g):#bellman-Ford dis=AI(n,inf) dis[s]=0 for i in range(n-1): for u,v,w in edge: if dis[v]>dis[u]+w: dis[v]=dis[u]+w change=A(n) for i in range(n): for u,v,w in edge: if dis[v]>dis[u]+w: dis[v]=dis[u]+w change[v]=1 return dis def lcm(a,b): return a*b//gcd(a,b) def lis(nums): res=[] for k in nums: i=bisect.bisect_left(res,k) if i==len(res): res.append(k) else: res[i]=k return len(res) def RP(nums):#逆序对 n = len(nums) s=set(nums) d={} for i,k in enumerate(sorted(s),1): d[k]=i bi=BIT([0]*(len(s)+1)) ans=0 for i in range(n-1,-1,-1): ans+=bi.query(d[nums[i]]-1) bi.update(d[nums[i]],1) return ans class DLN: def __init__(self,val): self.val=val self.pre=None self.next=None def nb(i,j,n,m): for ni,nj in [[i+1,j],[i-1,j],[i,j-1],[i,j+1]]: if 0<=ni<n and 0<=nj<m: yield ni,nj def topo(n): q=deque() res=[] for i in range(1,n+1): if ind[i]==0: q.append(i) res.append(i) while q: u=q.popleft() for v in g[u]: ind[v]-=1 if ind[v]==0: q.append(v) res.append(v) return res @bootstrap def gdfs(r,p): for ch in g[r]: if ch!=p: yield gdfs(ch,r) yield None t=N() for i in range(t): n,k=RL() if n<=61 and pow(2,n-1)<k: print(-1) continue ans=[] l=0 r=n cnt=0 s=1 while k: for i in range(s,n+1): #print(i,cnt,k,ans) if i==n: ans+=list(range(n,s-1,-1)) k=0 break tmp=pow(2,n-1-i) cnt+=tmp if cnt==k: k=0 ans+=list(range(i,s-1,-1)) ans+=list(range(n,i,-1)) break elif cnt>k: cnt-=tmp ans+=list(range(i,s-1,-1)) k-=cnt cnt=0 s=i+1 break print(*ans) ''' sys.setrecursionlimit(200000) import threading threading.stack_size(10**8) t=threading.Thr ead(target=main) t.start() t.join() ''' ```
output
1
38,905
12
77,811
Provide tags and a correct Python 3 solution for this coding contest problem. Seiji Maki doesn't only like to observe relationships being unfolded, he also likes to observe sequences of numbers, especially permutations. Today, he has his eyes on almost sorted permutations. A permutation a_1, a_2, ..., a_n of 1, 2, ..., n is said to be almost sorted if the condition a_{i + 1} ≥ a_i - 1 holds for all i between 1 and n - 1 inclusive. Maki is considering the list of all almost sorted permutations of 1, 2, ..., n, given in lexicographical order, and he wants to find the k-th permutation in this list. Can you help him to find such permutation? Permutation p is lexicographically smaller than a permutation q if and only if the following holds: * in the first position where p and q differ, the permutation p has a smaller element than the corresponding element in q. Input The first line contains a single integer t (1≤ t≤ 1000) — the number of test cases. Each test case consists of a single line containing two integers n and k (1 ≤ n ≤ 10^5, 1 ≤ k ≤ 10^{18}). It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print a single line containing the k-th almost sorted permutation of length n in lexicographical order, or -1 if it doesn't exist. Example Input 5 1 1 1 2 3 3 6 5 3 4 Output 1 -1 2 1 3 1 2 4 3 5 6 3 2 1 Note For the first and second test, the list of almost sorted permutations with n = 1 is \{[1]\}. For the third and fifth test, the list of almost sorted permutations with n = 3 is \{[1, 2, 3], [1, 3, 2], [2, 1, 3], [3, 2, 1]\}.
instruction
0
38,906
12
77,812
Tags: binary search, combinatorics, constructive algorithms, implementation Correct Solution: ``` import sys input = sys.stdin.readline for f in range(int(input())): n,k=map(int,input().split()) b=bin(k-1)[2:] if k-1: b+="0" if len(b)>n: print(-1) else: b="0"*(n-len(b))+b a=[] t=[] for i in range(n): t+=[str(i+1)] if b[i]=="0": a+=t[::-1] t=[] print(*a) ```
output
1
38,906
12
77,813
Provide tags and a correct Python 3 solution for this coding contest problem. Seiji Maki doesn't only like to observe relationships being unfolded, he also likes to observe sequences of numbers, especially permutations. Today, he has his eyes on almost sorted permutations. A permutation a_1, a_2, ..., a_n of 1, 2, ..., n is said to be almost sorted if the condition a_{i + 1} ≥ a_i - 1 holds for all i between 1 and n - 1 inclusive. Maki is considering the list of all almost sorted permutations of 1, 2, ..., n, given in lexicographical order, and he wants to find the k-th permutation in this list. Can you help him to find such permutation? Permutation p is lexicographically smaller than a permutation q if and only if the following holds: * in the first position where p and q differ, the permutation p has a smaller element than the corresponding element in q. Input The first line contains a single integer t (1≤ t≤ 1000) — the number of test cases. Each test case consists of a single line containing two integers n and k (1 ≤ n ≤ 10^5, 1 ≤ k ≤ 10^{18}). It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print a single line containing the k-th almost sorted permutation of length n in lexicographical order, or -1 if it doesn't exist. Example Input 5 1 1 1 2 3 3 6 5 3 4 Output 1 -1 2 1 3 1 2 4 3 5 6 3 2 1 Note For the first and second test, the list of almost sorted permutations with n = 1 is \{[1]\}. For the third and fifth test, the list of almost sorted permutations with n = 3 is \{[1, 2, 3], [1, 3, 2], [2, 1, 3], [3, 2, 1]\}.
instruction
0
38,907
12
77,814
Tags: binary search, combinatorics, constructive algorithms, implementation Correct Solution: ``` it = int(input()) for _ in range(it): n, k = map(int, input().split()) if n < 64 and 2 ** (n-1) < k: print(-1) else: l = n c = 1 ans = [] while l > 0: z = 1 while k>1 and k > 2 ** (l - z - 1): k -= 2 ** (l - z - 1) z += 1 ans += list(range(c + z - 1, c - 1, -1)) c += z l -= z z = 1 ans = [str(x) for x in ans] print(' '.join(ans)) ```
output
1
38,907
12
77,815
Provide tags and a correct Python 3 solution for this coding contest problem. Seiji Maki doesn't only like to observe relationships being unfolded, he also likes to observe sequences of numbers, especially permutations. Today, he has his eyes on almost sorted permutations. A permutation a_1, a_2, ..., a_n of 1, 2, ..., n is said to be almost sorted if the condition a_{i + 1} ≥ a_i - 1 holds for all i between 1 and n - 1 inclusive. Maki is considering the list of all almost sorted permutations of 1, 2, ..., n, given in lexicographical order, and he wants to find the k-th permutation in this list. Can you help him to find such permutation? Permutation p is lexicographically smaller than a permutation q if and only if the following holds: * in the first position where p and q differ, the permutation p has a smaller element than the corresponding element in q. Input The first line contains a single integer t (1≤ t≤ 1000) — the number of test cases. Each test case consists of a single line containing two integers n and k (1 ≤ n ≤ 10^5, 1 ≤ k ≤ 10^{18}). It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print a single line containing the k-th almost sorted permutation of length n in lexicographical order, or -1 if it doesn't exist. Example Input 5 1 1 1 2 3 3 6 5 3 4 Output 1 -1 2 1 3 1 2 4 3 5 6 3 2 1 Note For the first and second test, the list of almost sorted permutations with n = 1 is \{[1]\}. For the third and fifth test, the list of almost sorted permutations with n = 3 is \{[1, 2, 3], [1, 3, 2], [2, 1, 3], [3, 2, 1]\}.
instruction
0
38,908
12
77,816
Tags: binary search, combinatorics, constructive algorithms, implementation Correct Solution: ``` def divisors(M): d=[] i=1 while M>=i**2: if M%i==0: d.append(i) if i**2!=M: d.append(M//i) i=i+1 return d def popcount(x): x = x - ((x >> 1) & 0x55555555) x = (x & 0x33333333) + ((x >> 2) & 0x33333333) x = (x + (x >> 4)) & 0x0f0f0f0f x = x + (x >> 8) x = x + (x >> 16) return x & 0x0000007f def eratosthenes(n): res=[0 for i in range(n+1)] prime=set([]) for i in range(2,n+1): if not res[i]: prime.add(i) for j in range(1,n//i+1): res[i*j]=1 return prime def factorization(n): res=[] for p in prime: if n%p==0: while n%p==0: n//=p res.append(p) if n!=1: res.append(n) return res def euler_phi(n): res = n for x in range(2,n+1): if x ** 2 > n: break if n%x==0: res = res//x * (x-1) while n%x==0: n //= x if n!=1: res = res//n * (n-1) return res def ind(b,n): res=0 while n%b==0: res+=1 n//=b return res def isPrimeMR(n): if n==1: return 0 d = n - 1 d = d // (d & -d) L = [2, 3, 5, 7, 11, 13, 17] for a in L: t = d y = pow(a, t, n) if y == 1: continue while y != n - 1: y = (y * y) % n if y == 1 or t == n - 1: return 0 t <<= 1 return 1 def findFactorRho(n): from math import gcd m = 1 << n.bit_length() // 8 for c in range(1, 99): f = lambda x: (x * x + c) % n y, r, q, g = 2, 1, 1, 1 while g == 1: x = y for i in range(r): y = f(y) k = 0 while k < r and g == 1: ys = y for i in range(min(m, r - k)): y = f(y) q = q * abs(x - y) % n g = gcd(q, n) k += m r <<= 1 if g == n: g = 1 while g == 1: ys = f(ys) g = gcd(abs(x - ys), n) if g < n: if isPrimeMR(g): return g elif isPrimeMR(n // g): return n // g return findFactorRho(g) def primeFactor(n): i = 2 ret = {} rhoFlg = 0 while i*i <= n: k = 0 while n % i == 0: n //= i k += 1 if k: ret[i] = k i += 1 + i % 2 if i == 101 and n >= 2 ** 20: while n > 1: if isPrimeMR(n): ret[n], n = 1, 1 else: rhoFlg = 1 j = findFactorRho(n) k = 0 while n % j == 0: n //= j k += 1 ret[j] = k if n > 1: ret[n] = 1 if rhoFlg: ret = {x: ret[x] for x in sorted(ret)} return ret def divisors(n): res = [1] prime = primeFactor(n) for p in prime: newres = [] for d in res: for j in range(prime[p]+1): newres.append(d*p**j) res = newres res.sort() return res def xorfactorial(num):#排他的論理和の階乗 if num==0: return 0 elif num==1: return 1 elif num==2: return 3 elif num==3: return 0 else: x=baseorder(num) return (2**x)*((num-2**x+1)%2)+function(num-2**x) def xorconv(n,X,Y): if n==0: res=[(X[0]*Y[0])%mod] return res x=[digit[i]+X[i+2**(n-1)] for i in range(2**(n-1))] y=[Y[i]+Y[i+2**(n-1)] for i in range(2**(n-1))] z=[digit[i]-X[i+2**(n-1)] for i in range(2**(n-1))] w=[Y[i]-Y[i+2**(n-1)] for i in range(2**(n-1))] res1=xorconv(n-1,x,y) res2=xorconv(n-1,z,w) former=[(res1[i]+res2[i])*inv for i in range(2**(n-1))] latter=[(res1[i]-res2[i])*inv for i in range(2**(n-1))] former=list(map(lambda x:x%mod,former)) latter=list(map(lambda x:x%mod,latter)) return former+latter def merge_sort(A,B): pos_A,pos_B = 0,0 n,m = len(A),len(B) res = [] while pos_A < n and pos_B < m: a,b = A[pos_A],B[pos_B] if a < b: res.append(a) pos_A += 1 else: res.append(b) pos_B += 1 res += A[pos_A:] res += B[pos_B:] return res class UnionFindVerSize(): def __init__(self, N): self._parent = [n for n in range(0, N)] self._size = [1] * N self.group = N def find_root(self, x): if self._parent[x] == x: return x self._parent[x] = self.find_root(self._parent[x]) stack = [x] while self._parent[stack[-1]]!=stack[-1]: stack.append(self._parent[stack[-1]]) for v in stack: self._parent[v] = stack[-1] return self._parent[x] def unite(self, x, y): gx = self.find_root(x) gy = self.find_root(y) if gx == gy: return self.group -= 1 if self._size[gx] < self._size[gy]: self._parent[gx] = gy self._size[gy] += self._size[gx] else: self._parent[gy] = gx self._size[gx] += self._size[gy] def get_size(self, x): return self._size[self.find_root(x)] def is_same_group(self, x, y): return self.find_root(x) == self.find_root(y) class WeightedUnionFind(): def __init__(self,N): self.parent = [i for i in range(N)] self.size = [1 for i in range(N)] self.val = [0 for i in range(N)] self.flag = True self.edge = [[] for i in range(N)] def dfs(self,v,pv): stack = [(v,pv)] new_parent = self.parent[pv] while stack: v,pv = stack.pop() self.parent[v] = new_parent for nv,w in self.edge[v]: if nv!=pv: self.val[nv] = self.val[v] + w stack.append((nv,v)) def unite(self,x,y,w): if not self.flag: return if self.parent[x]==self.parent[y]: self.flag = (self.val[x] - self.val[y] == w) return if self.size[self.parent[x]]>self.size[self.parent[y]]: self.edge[x].append((y,-w)) self.edge[y].append((x,w)) self.size[x] += self.size[y] self.val[y] = self.val[x] - w self.dfs(y,x) else: self.edge[x].append((y,-w)) self.edge[y].append((x,w)) self.size[y] += self.size[x] self.val[x] = self.val[y] + w self.dfs(x,y) class Dijkstra(): class Edge(): def __init__(self, _to, _cost): self.to = _to self.cost = _cost def __init__(self, V): self.G = [[] for i in range(V)] self._E = 0 self._V = V @property def E(self): return self._E @property def V(self): return self._V def add_edge(self, _from, _to, _cost): self.G[_from].append(self.Edge(_to, _cost)) self._E += 1 def shortest_path(self, s): import heapq que = [] d = [10**15] * self.V d[s] = 0 heapq.heappush(que, (0, s)) while len(que) != 0: cost, v = heapq.heappop(que) if d[v] < cost: continue for i in range(len(self.G[v])): e = self.G[v][i] if d[e.to] > d[v] + e.cost: d[e.to] = d[v] + e.cost heapq.heappush(que, (d[e.to], e.to)) return d #Z[i]:length of the longest list starting from S[i] which is also a prefix of S #O(|S|) def Z_algorithm(s): N = len(s) Z_alg = [0]*N Z_alg[0] = N i = 1 j = 0 while i < N: while i+j < N and s[j] == s[i+j]: j += 1 Z_alg[i] = j if j == 0: i += 1 continue k = 1 while i+k < N and k + Z_alg[k]<j: Z_alg[i+k] = Z_alg[k] k += 1 i += k j -= k return Z_alg class BIT(): def __init__(self,n,mod=0): self.BIT = [0]*(n+1) self.num = n self.mod = mod def query(self,idx): res_sum = 0 mod = self.mod while idx > 0: res_sum += self.BIT[idx] if mod: res_sum %= mod idx -= idx&(-idx) return res_sum #Ai += x O(logN) def update(self,idx,x): mod = self.mod while idx <= self.num: self.BIT[idx] += x if mod: self.BIT[idx] %= mod idx += idx&(-idx) return class dancinglink(): def __init__(self,n,debug=False): self.n = n self.debug = debug self._left = [i-1 for i in range(n)] self._right = [i+1 for i in range(n)] self.exist = [True for i in range(n)] def pop(self,k): if self.debug: assert self.exist[k] L = self._left[k] R = self._right[k] if L!=-1: if R!=self.n: self._right[L],self._left[R] = R,L else: self._right[L] = self.n elif R!=self.n: self._left[R] = -1 self.exist[k] = False def left(self,idx,k=1): if self.debug: assert self.exist[idx] res = idx while k: res = self._left[res] if res==-1: break k -= 1 return res def right(self,idx,k=1): if self.debug: assert self.exist[idx] res = idx while k: res = self._right[res] if res==self.n: break k -= 1 return res class SparseTable(): def __init__(self,A,merge_func,ide_ele): N=len(A) n=N.bit_length() self.table=[[ide_ele for i in range(n)] for i in range(N)] self.merge_func=merge_func for i in range(N): self.table[i][0]=A[i] for j in range(1,n): for i in range(0,N-2**j+1): f=self.table[i][j-1] s=self.table[i+2**(j-1)][j-1] self.table[i][j]=self.merge_func(f,s) def query(self,s,t): b=t-s+1 m=b.bit_length()-1 return self.merge_func(self.table[s][m],self.table[t-2**m+1][m]) class BinaryTrie: class node: def __init__(self,val): self.left = None self.right = None self.max = val def __init__(self): self.root = self.node(-10**15) def append(self,key,val): pos = self.root for i in range(29,-1,-1): pos.max = max(pos.max,val) if key>>i & 1: if pos.right is None: pos.right = self.node(val) pos = pos.right else: pos = pos.right else: if pos.left is None: pos.left = self.node(val) pos = pos.left else: pos = pos.left pos.max = max(pos.max,val) def search(self,M,xor): res = -10**15 pos = self.root for i in range(29,-1,-1): if pos is None: break if M>>i & 1: if xor>>i & 1: if pos.right: res = max(res,pos.right.max) pos = pos.left else: if pos.left: res = max(res,pos.left.max) pos = pos.right else: if xor>>i & 1: pos = pos.right else: pos = pos.left if pos: res = max(res,pos.max) return res def solveequation(edge,ans,n,m): #edge=[[to,dire,id]...] x=[0]*m used=[False]*n for v in range(n): if used[v]: continue y = dfs(v) if y!=0: return False return x def dfs(v): used[v]=True r=ans[v] for to,dire,id in edge[v]: if used[to]: continue y=dfs(to) if dire==-1: x[id]=y else: x[id]=-y r+=y return r class Matrix(): mod=10**9+7 def set_mod(m): Matrix.mod=m def __init__(self,L): self.row=len(L) self.column=len(L[0]) self._matrix=L for i in range(self.row): for j in range(self.column): self._matridigit[i][j]%=Matrix.mod def __getitem__(self,item): if type(item)==int: raise IndexError("you must specific row and column") elif len(item)!=2: raise IndexError("you must specific row and column") i,j=item return self._matridigit[i][j] def __setitem__(self,item,val): if type(item)==int: raise IndexError("you must specific row and column") elif len(item)!=2: raise IndexError("you must specific row and column") i,j=item self._matridigit[i][j]=val def __add__(self,other): if (self.row,self.column)!=(other.row,other.column): raise SizeError("sizes of matrixes are different") res=[[0 for j in range(self.column)] for i in range(self.row)] for i in range(self.row): for j in range(self.column): res[i][j]=self._matridigit[i][j]+other._matridigit[i][j] res[i][j]%=Matrix.mod return Matrix(res) def __sub__(self,other): if (self.row,self.column)!=(other.row,other.column): raise SizeError("sizes of matrixes are different") res=[[0 for j in range(self.column)] for i in range(self.row)] for i in range(self.row): for j in range(self.column): res[i][j]=self._matridigit[i][j]-other._matridigit[i][j] res[i][j]%=Matrix.mod return Matrix(res) def __mul__(self,other): if type(other)!=int: if self.column!=other.row: raise SizeError("sizes of matrixes are different") res=[[0 for j in range(other.column)] for i in range(self.row)] for i in range(self.row): for j in range(other.column): temp=0 for k in range(self.column): temp+=self._matridigit[i][k]*other._matrix[k][j] res[i][j]=temp%Matrix.mod return Matrix(res) else: n=other res=[[(n*self._matridigit[i][j])%Matrix.mod for j in range(self.column)] for i in range(self.row)] return Matrix(res) def __pow__(self,m): if self.column!=self.row: raise MatrixPowError("the size of row must be the same as that of column") n=self.row res=Matrix([[int(i==j) for i in range(n)] for j in range(n)]) while m: if m%2==1: res=res*self self=self*self m//=2 return res def __str__(self): res=[] for i in range(self.row): for j in range(self.column): res.append(str(self._matridigit[i][j])) res.append(" ") res.append("\n") res=res[:len(res)-1] return "".join(res) import sys,random,bisect from collections import deque,defaultdict from heapq import heapify,heappop,heappush from itertools import permutations from math import gcd,log input = lambda :sys.stdin.readline().rstrip() mi = lambda :map(int,input().split()) li = lambda :list(mi()) def pow2(n): if n>=70: return 10**18 else: return pow(2,n) def solve(n,k): if n < 70 and k > 2**(n-1): return [-1] res = [] skip = 0 for i in range(n-1): if skip + pow2(n-2-i) < k: skip += pow2(n-2-i) continue else: res = [j+1 for j in range(i,-1,-1)] tmp = solve(n-i-1,k-skip) res += [j+i+1 for j in tmp] return res return [n-i for i in range(n)] def solve_no_recurse(n,k): if n < 70 and k > 2**(n-1): return [-1] res = [] plus = 0 while n: tmp = [] skip = 0 for i in range(n-1): if skip + pow2(n-2-i) < k: skip += pow2(n-2-i) continue else: tmp = [j+1+plus for j in range(i,-1,-1)] res += tmp n,k,plus = n-i-1,k-skip,len(res) break else: tmp = [n-i+plus for i in range(n)] res += tmp n = 0 res = [val for val in res] return res for _ in range(int(input())): n,k = mi() print(*solve_no_recurse(n,k)) ```
output
1
38,908
12
77,817
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Seiji Maki doesn't only like to observe relationships being unfolded, he also likes to observe sequences of numbers, especially permutations. Today, he has his eyes on almost sorted permutations. A permutation a_1, a_2, ..., a_n of 1, 2, ..., n is said to be almost sorted if the condition a_{i + 1} ≥ a_i - 1 holds for all i between 1 and n - 1 inclusive. Maki is considering the list of all almost sorted permutations of 1, 2, ..., n, given in lexicographical order, and he wants to find the k-th permutation in this list. Can you help him to find such permutation? Permutation p is lexicographically smaller than a permutation q if and only if the following holds: * in the first position where p and q differ, the permutation p has a smaller element than the corresponding element in q. Input The first line contains a single integer t (1≤ t≤ 1000) — the number of test cases. Each test case consists of a single line containing two integers n and k (1 ≤ n ≤ 10^5, 1 ≤ k ≤ 10^{18}). It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print a single line containing the k-th almost sorted permutation of length n in lexicographical order, or -1 if it doesn't exist. Example Input 5 1 1 1 2 3 3 6 5 3 4 Output 1 -1 2 1 3 1 2 4 3 5 6 3 2 1 Note For the first and second test, the list of almost sorted permutations with n = 1 is \{[1]\}. For the third and fifth test, the list of almost sorted permutations with n = 3 is \{[1, 2, 3], [1, 3, 2], [2, 1, 3], [3, 2, 1]\}. Submitted Solution: ``` import sys import itertools input = sys.stdin.readline # dp = [0] * (10**5+1) # cumsum = [0] * (10**5+1) # def init(): # # using up to ith # dp[0] = 1 # dp[1] = 2 # cumsum[0] = 1 # cumsum[1] = 3 # for i in range(2, 10**5+1): # dp[i] = 1 + cumsum[i-2] + dp[i-1] # cumsum[i] = cumsum[i-1] + dp[i] # init() # for k in range(1, 7): # count = 0 # for aa in itertools.permutations(range(1, k+1)): # if all(a2 >= a1 - 1 for a1, a2 in zip(aa, aa[1:])): # print(aa) # count += all(a2 >= a1 - 1 for a1, a2 in zip(aa, aa[1:])) # print(k, count) def solve(N, K): # print('nk', N, K) if K > 1 << (N-1): return [-1] left = 1 right = N + 1 ret = [] # print('lr', left, right, ret) while right > left: r = right - left block = 1 # print('klr', K, left, right) while 1 << max(0, r - 1 - block) < K: # print(block, 1 << max(0, r - 1 - block), K) K -= 1 << max(0, r - 1 - block) block += 1 # print('K', K, 'block', block, 'r', r,) ret.extend(range(left,left+block)[::-1]) # print(left, right, block, K, ret) left += block return ret def main(): T, = map(int, input().split()) for _ in range(T): N, K = map(int, input().split()) print(' '.join(map(str, solve(N, K)))) main() ```
instruction
0
38,909
12
77,818
Yes
output
1
38,909
12
77,819
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Seiji Maki doesn't only like to observe relationships being unfolded, he also likes to observe sequences of numbers, especially permutations. Today, he has his eyes on almost sorted permutations. A permutation a_1, a_2, ..., a_n of 1, 2, ..., n is said to be almost sorted if the condition a_{i + 1} ≥ a_i - 1 holds for all i between 1 and n - 1 inclusive. Maki is considering the list of all almost sorted permutations of 1, 2, ..., n, given in lexicographical order, and he wants to find the k-th permutation in this list. Can you help him to find such permutation? Permutation p is lexicographically smaller than a permutation q if and only if the following holds: * in the first position where p and q differ, the permutation p has a smaller element than the corresponding element in q. Input The first line contains a single integer t (1≤ t≤ 1000) — the number of test cases. Each test case consists of a single line containing two integers n and k (1 ≤ n ≤ 10^5, 1 ≤ k ≤ 10^{18}). It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print a single line containing the k-th almost sorted permutation of length n in lexicographical order, or -1 if it doesn't exist. Example Input 5 1 1 1 2 3 3 6 5 3 4 Output 1 -1 2 1 3 1 2 4 3 5 6 3 2 1 Note For the first and second test, the list of almost sorted permutations with n = 1 is \{[1]\}. For the third and fifth test, the list of almost sorted permutations with n = 3 is \{[1, 2, 3], [1, 3, 2], [2, 1, 3], [3, 2, 1]\}. Submitted Solution: ``` import sys, os if os.environ['USERNAME']=='kissz': inp=open('in.txt','r').readline def debug(*args): print(*args,file=sys.stderr) else: inp=sys.stdin.readline def debug(*args): pass # SCRIPT STARTS HERE for _ in range(int(inp())): n,k=map(int,inp().split()) if k>2**(n-1): print(-1) else: b=(bin(k-1)[2:]).zfill(n) L=[] for i in range(n): if b[i]=='1': L+=[L[-1]-1] elif i<n-1 and b[i+1]=='1': j=i+1 cnt=0 while j<n and b[j]=='1': cnt+=1 j+=1 L+=[i+1+cnt] else: L+=[i+1] print(*L) ```
instruction
0
38,910
12
77,820
Yes
output
1
38,910
12
77,821
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Seiji Maki doesn't only like to observe relationships being unfolded, he also likes to observe sequences of numbers, especially permutations. Today, he has his eyes on almost sorted permutations. A permutation a_1, a_2, ..., a_n of 1, 2, ..., n is said to be almost sorted if the condition a_{i + 1} ≥ a_i - 1 holds for all i between 1 and n - 1 inclusive. Maki is considering the list of all almost sorted permutations of 1, 2, ..., n, given in lexicographical order, and he wants to find the k-th permutation in this list. Can you help him to find such permutation? Permutation p is lexicographically smaller than a permutation q if and only if the following holds: * in the first position where p and q differ, the permutation p has a smaller element than the corresponding element in q. Input The first line contains a single integer t (1≤ t≤ 1000) — the number of test cases. Each test case consists of a single line containing two integers n and k (1 ≤ n ≤ 10^5, 1 ≤ k ≤ 10^{18}). It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print a single line containing the k-th almost sorted permutation of length n in lexicographical order, or -1 if it doesn't exist. Example Input 5 1 1 1 2 3 3 6 5 3 4 Output 1 -1 2 1 3 1 2 4 3 5 6 3 2 1 Note For the first and second test, the list of almost sorted permutations with n = 1 is \{[1]\}. For the third and fifth test, the list of almost sorted permutations with n = 3 is \{[1, 2, 3], [1, 3, 2], [2, 1, 3], [3, 2, 1]\}. Submitted Solution: ``` from sys import stdin,stdout from math import gcd,sqrt,factorial,pi,inf from collections import deque,defaultdict from bisect import bisect,bisect_left from time import time from itertools import permutations as per input=stdin.readline R=lambda:map(int,input().split()) I=lambda:int(input()) S=lambda:input().rstrip('\r\n') L=lambda:list(R()) P=lambda x:stdout.write(str(x)+'\n') lcm=lambda x,y:(x*y)//gcd(x,y) nCr=lambda x,y:(f[x]*inv((f[y]*f[x-y])%N))%N inv=lambda x:pow(x,N-2,N) sm=lambda x:(x**2+x)//2 N=10**9+7 for _ in range(I()): n,k=R() f=bin(k-1)[2:] if k-1: f+='0' if len(f)>n: print(-1) continue f='0'*(n-len(f))+f arr=[] ans=[] for i in range(n): arr+=i+1, if f[i]=='0': ans+=arr[::-1] arr=[] print(*ans) ```
instruction
0
38,911
12
77,822
Yes
output
1
38,911
12
77,823
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Seiji Maki doesn't only like to observe relationships being unfolded, he also likes to observe sequences of numbers, especially permutations. Today, he has his eyes on almost sorted permutations. A permutation a_1, a_2, ..., a_n of 1, 2, ..., n is said to be almost sorted if the condition a_{i + 1} ≥ a_i - 1 holds for all i between 1 and n - 1 inclusive. Maki is considering the list of all almost sorted permutations of 1, 2, ..., n, given in lexicographical order, and he wants to find the k-th permutation in this list. Can you help him to find such permutation? Permutation p is lexicographically smaller than a permutation q if and only if the following holds: * in the first position where p and q differ, the permutation p has a smaller element than the corresponding element in q. Input The first line contains a single integer t (1≤ t≤ 1000) — the number of test cases. Each test case consists of a single line containing two integers n and k (1 ≤ n ≤ 10^5, 1 ≤ k ≤ 10^{18}). It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print a single line containing the k-th almost sorted permutation of length n in lexicographical order, or -1 if it doesn't exist. Example Input 5 1 1 1 2 3 3 6 5 3 4 Output 1 -1 2 1 3 1 2 4 3 5 6 3 2 1 Note For the first and second test, the list of almost sorted permutations with n = 1 is \{[1]\}. For the third and fifth test, the list of almost sorted permutations with n = 3 is \{[1, 2, 3], [1, 3, 2], [2, 1, 3], [3, 2, 1]\}. Submitted Solution: ``` for _ in range(int(input())): n, k = map(int, input().split()) b = bin(k - 1)[2:] if k - 1 > 0: b += '0' if len(b) > n: print(-1) else: b = '0'*(n-len(b)) + b p, temp = [], [] for i in range(n): temp += [str(i+1)] if b[i] == '0': p += temp[::-1] temp = [] print(*p) ```
instruction
0
38,912
12
77,824
Yes
output
1
38,912
12
77,825
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Seiji Maki doesn't only like to observe relationships being unfolded, he also likes to observe sequences of numbers, especially permutations. Today, he has his eyes on almost sorted permutations. A permutation a_1, a_2, ..., a_n of 1, 2, ..., n is said to be almost sorted if the condition a_{i + 1} ≥ a_i - 1 holds for all i between 1 and n - 1 inclusive. Maki is considering the list of all almost sorted permutations of 1, 2, ..., n, given in lexicographical order, and he wants to find the k-th permutation in this list. Can you help him to find such permutation? Permutation p is lexicographically smaller than a permutation q if and only if the following holds: * in the first position where p and q differ, the permutation p has a smaller element than the corresponding element in q. Input The first line contains a single integer t (1≤ t≤ 1000) — the number of test cases. Each test case consists of a single line containing two integers n and k (1 ≤ n ≤ 10^5, 1 ≤ k ≤ 10^{18}). It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print a single line containing the k-th almost sorted permutation of length n in lexicographical order, or -1 if it doesn't exist. Example Input 5 1 1 1 2 3 3 6 5 3 4 Output 1 -1 2 1 3 1 2 4 3 5 6 3 2 1 Note For the first and second test, the list of almost sorted permutations with n = 1 is \{[1]\}. For the third and fifth test, the list of almost sorted permutations with n = 3 is \{[1, 2, 3], [1, 3, 2], [2, 1, 3], [3, 2, 1]\}. Submitted Solution: ``` from sys import stdin, stdout input = stdin.readline def im(): return map(int,input().split()) def ii(): return int(input()) def il(): return list(map(int,input().split())) for _ in range(ii()): n,k = im() if k > ((n*(n-1))//2)+1: print(-1) else: lis = [i for i in range(1,n+1)] if k==1: print(*lis) continue # print(lis) k-=1 j=1 while j<k: #2 1 k-=j j+=1 i = n-1-j j = i+k # print(i,j) if j==n-1: ans = lis[:i] + lis[i:j+1][::-1] else: # print(lis[:i],lis[i:j+1][::-1],lis[j+1:]) ans = lis[:i] + lis[i:j+1][::-1] + lis[j+1:] print(*ans) ```
instruction
0
38,913
12
77,826
No
output
1
38,913
12
77,827
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Seiji Maki doesn't only like to observe relationships being unfolded, he also likes to observe sequences of numbers, especially permutations. Today, he has his eyes on almost sorted permutations. A permutation a_1, a_2, ..., a_n of 1, 2, ..., n is said to be almost sorted if the condition a_{i + 1} ≥ a_i - 1 holds for all i between 1 and n - 1 inclusive. Maki is considering the list of all almost sorted permutations of 1, 2, ..., n, given in lexicographical order, and he wants to find the k-th permutation in this list. Can you help him to find such permutation? Permutation p is lexicographically smaller than a permutation q if and only if the following holds: * in the first position where p and q differ, the permutation p has a smaller element than the corresponding element in q. Input The first line contains a single integer t (1≤ t≤ 1000) — the number of test cases. Each test case consists of a single line containing two integers n and k (1 ≤ n ≤ 10^5, 1 ≤ k ≤ 10^{18}). It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print a single line containing the k-th almost sorted permutation of length n in lexicographical order, or -1 if it doesn't exist. Example Input 5 1 1 1 2 3 3 6 5 3 4 Output 1 -1 2 1 3 1 2 4 3 5 6 3 2 1 Note For the first and second test, the list of almost sorted permutations with n = 1 is \{[1]\}. For the third and fifth test, the list of almost sorted permutations with n = 3 is \{[1, 2, 3], [1, 3, 2], [2, 1, 3], [3, 2, 1]\}. Submitted Solution: ``` #Code by Sounak, IIESTS #------------------------------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=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) 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(10)] pp=[0]*10 def SieveOfEratosthenes(n=10): p = 2 c=0 while (p * p <= n): if (prime[p] == True): c+=1 for i in range(p, n+1, p): pp[i]+=1 prime[i] = False p += 1 #---------------------------------Binary Search------------------------------------------ def binarySearch(arr, n, key): left = 0 right = n-1 mid = 0 res=arr[n-1] while (left <= right): mid = (right + left)//2 if (arr[mid] >= key): res=arr[mid] right = mid-1 else: left = mid + 1 return res def binarySearch1(arr, n, key): left = 0 right = n-1 mid = 0 res=arr[0] while (left <= right): mid = (right + left)//2 if (arr[mid] > key): right = mid-1 else: res=arr[mid] left = mid + 1 return res #---------------------------------running code------------------------------------------ for i in range (int(input())): n,k=map(int,input().split()) if k>=2**n-1: print(-1) continue a=[] copy=k k-=1 while k: a.append(k%2) k//=2 a=a[::-1] d=max(0,n-len(a)-1) a=[0]*d+a+[0] #print(a) curr=1 res=[0]*n for i in range (n): if a[i]==0: j=i while j>=0 and res[j]==0: res[j]=curr curr+=1 j-=1 print(*res) ```
instruction
0
38,914
12
77,828
No
output
1
38,914
12
77,829
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Seiji Maki doesn't only like to observe relationships being unfolded, he also likes to observe sequences of numbers, especially permutations. Today, he has his eyes on almost sorted permutations. A permutation a_1, a_2, ..., a_n of 1, 2, ..., n is said to be almost sorted if the condition a_{i + 1} ≥ a_i - 1 holds for all i between 1 and n - 1 inclusive. Maki is considering the list of all almost sorted permutations of 1, 2, ..., n, given in lexicographical order, and he wants to find the k-th permutation in this list. Can you help him to find such permutation? Permutation p is lexicographically smaller than a permutation q if and only if the following holds: * in the first position where p and q differ, the permutation p has a smaller element than the corresponding element in q. Input The first line contains a single integer t (1≤ t≤ 1000) — the number of test cases. Each test case consists of a single line containing two integers n and k (1 ≤ n ≤ 10^5, 1 ≤ k ≤ 10^{18}). It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print a single line containing the k-th almost sorted permutation of length n in lexicographical order, or -1 if it doesn't exist. Example Input 5 1 1 1 2 3 3 6 5 3 4 Output 1 -1 2 1 3 1 2 4 3 5 6 3 2 1 Note For the first and second test, the list of almost sorted permutations with n = 1 is \{[1]\}. For the third and fifth test, the list of almost sorted permutations with n = 3 is \{[1, 2, 3], [1, 3, 2], [2, 1, 3], [3, 2, 1]\}. Submitted Solution: ``` class SortedList: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" values = sorted(iterable) self._len = _len = len(values) self._load = _load self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)] self._list_lens = [len(_list) for _list in _lists] self._mins = [_list[0] for _list in _lists] self._fen_tree = [] self._rebuild = True def _fen_build(self): """Build a fenwick tree instance.""" self._fen_tree[:] = self._list_lens _fen_tree = self._fen_tree for i in range(len(_fen_tree)): if i | i + 1 < len(_fen_tree): _fen_tree[i | i + 1] += _fen_tree[i] self._rebuild = False def _fen_update(self, index, value): """Update `fen_tree[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree while index < len(_fen_tree): _fen_tree[index] += value index |= index + 1 def _fen_query(self, end): """Return `sum(_fen_tree[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree x = 0 while end: x += _fen_tree[end - 1] end &= end - 1 return x def _fen_findkth(self, k): """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).""" _list_lens = self._list_lens if k < _list_lens[0]: return 0, k if k >= self._len - _list_lens[-1]: return len(_list_lens) - 1, k + _list_lens[-1] - self._len if self._rebuild: self._fen_build() _fen_tree = self._fen_tree idx = -1 for d in reversed(range(len(_fen_tree).bit_length())): right_idx = idx + (1 << d) if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]: idx = right_idx k -= _fen_tree[idx] return idx + 1, k def _delete(self, pos, idx): """Delete value at the given `(pos, idx)`.""" _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len -= 1 self._fen_update(pos, -1) del _lists[pos][idx] _list_lens[pos] -= 1 if _list_lens[pos]: _mins[pos] = _lists[pos][0] else: del _lists[pos] del _list_lens[pos] del _mins[pos] self._rebuild = True def _loc_left(self, value): """Return an index pair that corresponds to the first position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins lo, pos = -1, len(_lists) - 1 while lo + 1 < pos: mi = (lo + pos) >> 1 if value <= _mins[mi]: pos = mi else: lo = mi if pos and value <= _lists[pos - 1][-1]: pos -= 1 _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value <= _list[mi]: idx = mi else: lo = mi return pos, idx def _loc_right(self, value): """Return an index pair that corresponds to the last position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins pos, hi = 0, len(_lists) while pos + 1 < hi: mi = (pos + hi) >> 1 if value < _mins[mi]: hi = mi else: pos = mi _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value < _list[mi]: idx = mi else: lo = mi return pos, idx def add(self, value): """Add `value` to sorted list.""" _load = self._load _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len += 1 if _lists: pos, idx = self._loc_right(value) self._fen_update(pos, 1) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 _mins[pos] = _list[0] if _load + _load < len(_list): _lists.insert(pos + 1, _list[_load:]) _list_lens.insert(pos + 1, len(_list) - _load) _mins.insert(pos + 1, _list[_load]) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _mins.append(value) _list_lens.append(1) self._rebuild = True def discard(self, value): """Remove `value` from sorted list if it is a member.""" _lists = self._lists if _lists: pos, idx = self._loc_right(value) if idx and _lists[pos][idx - 1] == value: self._delete(pos, idx - 1) def remove(self, value): """Remove `value` from sorted list; `value` must be a member.""" _len = self._len self.discard(value) if _len == self._len: raise ValueError('{0!r} not in list'.format(value)) def pop(self, index=-1): """Remove and return value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) value = self._lists[pos][idx] self._delete(pos, idx) return value def bisect_left(self, value): """Return the first index to insert `value` in the sorted list.""" pos, idx = self._loc_left(value) return self._fen_query(pos) + idx def bisect_right(self, value): """Return the last index to insert `value` in the sorted list.""" pos, idx = self._loc_right(value) return self._fen_query(pos) + idx def count(self, value): """Return number of occurrences of `value` in the sorted list.""" return self.bisect_right(value) - self.bisect_left(value) def __len__(self): """Return the size of the sorted list.""" return self._len def __getitem__(self, index): """Lookup value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) return self._lists[pos][idx] def __delitem__(self, index): """Remove value at `index` from sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._delete(pos, idx) def __contains__(self, value): """Return true if `value` is an element of the sorted list.""" _lists = self._lists if _lists: pos, idx = self._loc_left(value) return idx < len(_lists[pos]) and _lists[pos][idx] == value return False def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return 'SortedList({0})'.format(list(self)) class OrderedList(SortedList): #Codeforces, Ordered Multiset def __init__(self, arg): super().__init__(arg) def rangeCountByValue(self, leftVal, rightVal): #returns number of items in range [leftVal,rightVal] inclusive leftCummulative = self.bisect_left(leftVal) rightCummulative = self.bisect_left(rightVal + 1) return rightCummulative - leftCummulative def isAlmostSorted(arr): # for brute force n=len(arr) for i in range(1,n): if not arr[i]>=arr[i-1]-1: return False return True import math def main(): # n=int(input()) # from itertools import permutations # arr=list(range(1,n+1)) # allP=list(permutations(arr)) # allP.sort() # # for row in allP: # # print(row) # okP=[p for p in allP if isAlmostSorted(p)] # for i,p in enumerate(okP): # print('i:{} p:{}'.format(i,p)) t=int(input()) allans=[] for _ in range(t): n,k=readIntArr() # if k>pow(2,n-1): # impossible # if math.log2(k)>n-1: if n<60 and k>pow(2,n-1): # impossible, and avoiding overflow allans.append([-1]) else: ans=[] ol=OrderedList(list(range(1,n+1))) m=n while len(ans)<n: cnts=0 # broken=False for i in range(len(ol)): if m-2-i>60 or cnts+pow(2,m-2-i)>=k: # 1st inequality is to avoid overflow # broken=True break cnts+=pow(2,m-2-i) # if broken==False: # i+=1 # print('n:{} k:{} ans:{} i:{} ol:{} m:{}'.format(n,k,ans,i,ol,m)) if i==0: ans.append(ol.pop(0)) m-=1 else: ans.append(ol.pop(i)) # must take i and i-1 ans.append(ol.pop(i-1)) m-=2 k-=cnts allans.append(ans) multiLineArrayOfArraysPrint(allans) return import sys input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok) # input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS. def oneLineArrayPrint(arr): print(' '.join([str(x) for x in arr])) def multiLineArrayPrint(arr): print('\n'.join([str(x) for x in arr])) def multiLineArrayOfArraysPrint(arr): print('\n'.join([' '.join([str(x) for x in y]) for y in arr])) def readIntArr(): return [int(x) for x in input().split()] # def readFloatArr(): # return [float(x) for x in input().split()] def makeArr(defaultVal,dimensionArr): # eg. makeArr(0,[n,m]) dv=defaultVal;da=dimensionArr if len(da)==1:return [dv for _ in range(da[0])] else:return [makeArr(dv,da[1:]) for _ in range(da[0])] def queryInteractive(x,y): print('? {} {}'.format(x,y)) sys.stdout.flush() return int(input()) def answerInteractive(ans): print('! {}'.format(ans)) sys.stdout.flush() inf=float('inf') MOD=10**9+7 # MOD=998244353 for _abc in range(1): main() ```
instruction
0
38,915
12
77,830
No
output
1
38,915
12
77,831
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Seiji Maki doesn't only like to observe relationships being unfolded, he also likes to observe sequences of numbers, especially permutations. Today, he has his eyes on almost sorted permutations. A permutation a_1, a_2, ..., a_n of 1, 2, ..., n is said to be almost sorted if the condition a_{i + 1} ≥ a_i - 1 holds for all i between 1 and n - 1 inclusive. Maki is considering the list of all almost sorted permutations of 1, 2, ..., n, given in lexicographical order, and he wants to find the k-th permutation in this list. Can you help him to find such permutation? Permutation p is lexicographically smaller than a permutation q if and only if the following holds: * in the first position where p and q differ, the permutation p has a smaller element than the corresponding element in q. Input The first line contains a single integer t (1≤ t≤ 1000) — the number of test cases. Each test case consists of a single line containing two integers n and k (1 ≤ n ≤ 10^5, 1 ≤ k ≤ 10^{18}). It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case, print a single line containing the k-th almost sorted permutation of length n in lexicographical order, or -1 if it doesn't exist. Example Input 5 1 1 1 2 3 3 6 5 3 4 Output 1 -1 2 1 3 1 2 4 3 5 6 3 2 1 Note For the first and second test, the list of almost sorted permutations with n = 1 is \{[1]\}. For the third and fifth test, the list of almost sorted permutations with n = 3 is \{[1, 2, 3], [1, 3, 2], [2, 1, 3], [3, 2, 1]\}. Submitted Solution: ``` import sys def inp(): return sys.stdin.readline().rstrip("\r\n") def N(): return int(inp()) def lis(): return list(map(int, inp().split())) def stringlis(): return list(map(str, inp().split())) def sep(): return map(int, inp().split()) def strsep(): return map(str, inp().split()) def fsep(): return map(float, inp().split()) def testcase(t): for p in range(t): solve() #### END ITERATE RECURSION #### ########################### # Sorted list class SortedList: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" values = sorted(iterable) self._len = _len = len(values) self._load = _load self._lists = _lists = [values[start:start + _load] for start in range(0, _len, _load)] self._list_lens = [len(_list) for _list in _lists] self._mins = [_list[0] for _list in _lists] self._fen_tree = [] self._rebuild = True def _fen_build(self): """Build a fenwick tree instance.""" self._fen_tree[:] = self._list_lens _fen_tree = self._fen_tree for start in range(len(_fen_tree)): if start | start + 1 < len(_fen_tree): _fen_tree[start | start + 1] += _fen_tree[start] self._rebuild = False def _fen_update(self, index, value): """Update `fen_tree[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree while index < len(_fen_tree): _fen_tree[index] += value index |= index + 1 def _fen_query(self, end): """Return `sum(_fen_tree[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree A = 0 while end: A += _fen_tree[end - 1] end &= end - 1 return A def _fen_findkth(self, k): """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).""" _list_lens = self._list_lens if k < _list_lens[0]: return 0, k if k >= self._len - _list_lens[-1]: return len(_list_lens) - 1, k + _list_lens[-1] - self._len if self._rebuild: self._fen_build() _fen_tree = self._fen_tree idx = -1 for d in reversed(range(len(_fen_tree).bit_length())): right_idx = idx + (1 << d) if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]: idx = right_idx k -= _fen_tree[idx] return idx + 1, k def _delete(self, pos, idx): """Delete value at the given `(pos, idx)`.""" _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len -= 1 self._fen_update(pos, -1) del _lists[pos][idx] _list_lens[pos] -= 1 if _list_lens[pos]: _mins[pos] = _lists[pos][0] else: del _lists[pos] del _list_lens[pos] del _mins[pos] self._rebuild = True def _loc_left(self, value): """Return an index pair that corresponds to the first position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins lo, pos = -1, len(_lists) - 1 while lo + 1 < pos: mi = (lo + pos) >> 1 if value <= _mins[mi]: pos = mi else: lo = mi if pos and value <= _lists[pos - 1][-1]: pos -= 1 _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value <= _list[mi]: idx = mi else: lo = mi return pos, idx def _loc_right(self, value): """Return an index pair that corresponds to the last position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins pos, hi = 0, len(_lists) while pos + 1 < hi: mi = (pos + hi) >> 1 if value < _mins[mi]: hi = mi else: pos = mi _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value < _list[mi]: idx = mi else: lo = mi return pos, idx def add(self, value): """Add `value` to sorted list.""" _load = self._load _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len += 1 if _lists: pos, idx = self._loc_right(value) self._fen_update(pos, 1) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 _mins[pos] = _list[0] if _load + _load < len(_list): _lists.insert(pos + 1, _list[_load:]) _list_lens.insert(pos + 1, len(_list) - _load) _mins.insert(pos + 1, _list[_load]) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _mins.append(value) _list_lens.append(1) self._rebuild = True def discard(self, value): """Remove `value` from sorted list if it is a member.""" _lists = self._lists if _lists: pos, idx = self._loc_right(value) if idx and _lists[pos][idx - 1] == value: self._delete(pos, idx - 1) def remove(self, value): """Remove `value` from sorted list; `value` must be a member.""" _len = self._len self.discard(value) if _len == self._len: raise ValueError('{0!r} not in list'.format(value)) def pop(self, index=-1): """Remove and return value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) value = self._lists[pos][idx] self._delete(pos, idx) return value def bisect_left(self, value): """Return the first index to insert `value` in the sorted list.""" pos, idx = self._loc_left(value) return self._fen_query(pos) + idx def bisect_right(self, value): """Return the last index to insert `value` in the sorted list.""" pos, idx = self._loc_right(value) return self._fen_query(pos) + idx def count(self, value): """Return number of occurrences of `value` in the sorted list.""" return self.bisect_right(value) - self.bisect_left(value) def __len__(self): """Return the size of the sorted list.""" return self._len def __getitem__(self, index): """Lookup value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) return self._lists[pos][idx] def __delitem__(self, index): """Remove value at `index` from sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._delete(pos, idx) def __contains__(self, value): """Return true if `value` is an element of the sorted list.""" _lists = self._lists if _lists: pos, idx = self._loc_left(value) return idx < len(_lists[pos]) and _lists[pos][idx] == value return False def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return 'SortedList({0})'.format(list(self)) pow2=[1] for i in range(36): pow2.append(pow2[-1]*2) def solve(): n,k=sep() ans=[] S=SortedList() if(n>36): for i in range(1,n-36): ans.append(i) for i in range(n-36,n+1): S.add(i) else: for i in range(1,n+1): S.add(i) while(k>0 and S): # # # print(S,k) le=len(S) if (k ==pow2[le-1]): while(S): ans.append(S[-1]) S.remove(S[-1]) k=0 break if(k>pow2[le-1]): print(-1) return for l in range(le,1,-1): t=pow2[l-2] if(k<=t): tor=le-l while(tor>=0): ans.append(S[tor]) S.remove(S[tor]) tor-=1 break else: k-=t if(k>0): print(-1) return print(*ans) # solve() testcase(N()) ```
instruction
0
38,916
12
77,832
No
output
1
38,916
12
77,833
Provide tags and a correct Python 3 solution for this coding contest problem. When he's not training for IOI, Little Alawn enjoys playing with puzzles of various types to stimulate his brain. Today, he's playing with a puzzle that consists of a 2 × n grid where each row is a permutation of the numbers 1,2,3,…,n. The goal of Little Alawn's puzzle is to make sure no numbers on the same column or row are the same (we'll call this state of the puzzle as solved), and to achieve this he is able to swap the numbers in any column. However, after solving the puzzle many times, Little Alawn got bored and began wondering about the number of possible solved configurations of the puzzle he could achieve from an initial solved configuration only by swapping numbers in a column. Unfortunately, Little Alawn got stuck while trying to solve this harder problem, so he was wondering if you could help him with it. Find the answer modulo 10^9+7. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows. The first line of each test case contains a single integer n (2 ≤ n ≤ 4 ⋅ 10^5). The next two lines of each test case describe the initial state of the puzzle grid. Each line will be a permutation of the numbers 1,2,3,…,n and the numbers in each column and row will be pairwise distinct. It is guaranteed that the sum of n over all test cases does not exceed 4 ⋅ 10^5. Output For each test case output a single integer, the number of possible solved configurations of the puzzle Little Alawn can achieve from an initial solved configuration only by swapping numbers in a column. As the answer can be very large, please output it modulo 10^9+7. The answer for each test case should be on a separate line. Example Input 2 4 1 4 2 3 3 2 1 4 8 2 6 5 1 4 3 7 8 3 8 7 5 1 2 4 6 Output 2 8 Note The two possible puzzle configurations for example 1 are: * [1,4,2,3] in the first row and [3,2,1,4] in the second; * [3,2,1,4] in the first row and [1,4,2,3] in the second.
instruction
0
38,917
12
77,834
Tags: combinatorics, dfs and similar, dp, dsu, graphs, math Correct Solution: ``` t=int(input()) mod = 10**9+7 vis=[] for _ in range(t): n=int(input()) a=[] a.append(list(map(int,input().split()))) a.append(list(map(int,input().split()))) vis = [0 for i in range(n+1)] e={} d=0 for i in range(n): e[a[0][i]]=a[1][i] for i in range(1,n+1): if vis[i]: pass else: d+=1 x= i while not vis[x]: vis[x]=1 x = e[x] print(pow(2,d,mod)) ```
output
1
38,917
12
77,835
Provide tags and a correct Python 3 solution for this coding contest problem. When he's not training for IOI, Little Alawn enjoys playing with puzzles of various types to stimulate his brain. Today, he's playing with a puzzle that consists of a 2 × n grid where each row is a permutation of the numbers 1,2,3,…,n. The goal of Little Alawn's puzzle is to make sure no numbers on the same column or row are the same (we'll call this state of the puzzle as solved), and to achieve this he is able to swap the numbers in any column. However, after solving the puzzle many times, Little Alawn got bored and began wondering about the number of possible solved configurations of the puzzle he could achieve from an initial solved configuration only by swapping numbers in a column. Unfortunately, Little Alawn got stuck while trying to solve this harder problem, so he was wondering if you could help him with it. Find the answer modulo 10^9+7. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows. The first line of each test case contains a single integer n (2 ≤ n ≤ 4 ⋅ 10^5). The next two lines of each test case describe the initial state of the puzzle grid. Each line will be a permutation of the numbers 1,2,3,…,n and the numbers in each column and row will be pairwise distinct. It is guaranteed that the sum of n over all test cases does not exceed 4 ⋅ 10^5. Output For each test case output a single integer, the number of possible solved configurations of the puzzle Little Alawn can achieve from an initial solved configuration only by swapping numbers in a column. As the answer can be very large, please output it modulo 10^9+7. The answer for each test case should be on a separate line. Example Input 2 4 1 4 2 3 3 2 1 4 8 2 6 5 1 4 3 7 8 3 8 7 5 1 2 4 6 Output 2 8 Note The two possible puzzle configurations for example 1 are: * [1,4,2,3] in the first row and [3,2,1,4] in the second; * [3,2,1,4] in the first row and [1,4,2,3] in the second.
instruction
0
38,918
12
77,836
Tags: combinatorics, dfs and similar, dp, dsu, graphs, math Correct Solution: ``` from sys import stdin,stdout import math, bisect, heapq from collections import Counter, deque, defaultdict L = lambda: list(map(int, stdin.readline().strip().split())) I = lambda: int(stdin.readline().strip()) S = lambda: stdin.readline().strip() C = lambda: stdin.readline().strip().split() def pr(a): return("".join(list(map(str, a)))) #_________________________________________________# def solve(): n = I() a = L() b = L() d = {} for i in range(n): d[a[i]] = b[i] ans = 0 mod = 10**9+7 c = [0]*n for i in range(1,n+1): if c[i-1]: continue ans+=1 x = d[i] c[i-1] = 1 while i!=x: c[x-1] = 1 x = d[x] print(pow(2,ans,mod)) for _ in range(I()): solve() ```
output
1
38,918
12
77,837
Provide tags and a correct Python 3 solution for this coding contest problem. When he's not training for IOI, Little Alawn enjoys playing with puzzles of various types to stimulate his brain. Today, he's playing with a puzzle that consists of a 2 × n grid where each row is a permutation of the numbers 1,2,3,…,n. The goal of Little Alawn's puzzle is to make sure no numbers on the same column or row are the same (we'll call this state of the puzzle as solved), and to achieve this he is able to swap the numbers in any column. However, after solving the puzzle many times, Little Alawn got bored and began wondering about the number of possible solved configurations of the puzzle he could achieve from an initial solved configuration only by swapping numbers in a column. Unfortunately, Little Alawn got stuck while trying to solve this harder problem, so he was wondering if you could help him with it. Find the answer modulo 10^9+7. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows. The first line of each test case contains a single integer n (2 ≤ n ≤ 4 ⋅ 10^5). The next two lines of each test case describe the initial state of the puzzle grid. Each line will be a permutation of the numbers 1,2,3,…,n and the numbers in each column and row will be pairwise distinct. It is guaranteed that the sum of n over all test cases does not exceed 4 ⋅ 10^5. Output For each test case output a single integer, the number of possible solved configurations of the puzzle Little Alawn can achieve from an initial solved configuration only by swapping numbers in a column. As the answer can be very large, please output it modulo 10^9+7. The answer for each test case should be on a separate line. Example Input 2 4 1 4 2 3 3 2 1 4 8 2 6 5 1 4 3 7 8 3 8 7 5 1 2 4 6 Output 2 8 Note The two possible puzzle configurations for example 1 are: * [1,4,2,3] in the first row and [3,2,1,4] in the second; * [3,2,1,4] in the first row and [1,4,2,3] in the second.
instruction
0
38,919
12
77,838
Tags: combinatorics, dfs and similar, dp, dsu, graphs, math Correct Solution: ``` import math, sys from itertools import permutations from collections import defaultdict, Counter, deque from heapq import heapify, heappush, heappop MOD = int(1e9) + 7 INF = float('inf') def solve(): n = int(input()) a1 = list(map(int, input().split())) a2 = list(map(int, input().split())) g = defaultdict(list) for i in range(n): g[a1[i]].append(a2[i]) p = 0 visited = set() for i in range(1, n + 1): if i in visited: continue p += 1 s = [i] while s: node = s.pop() if node in visited: continue visited.add(node) for child in g[node]: s.append(child) print(pow(2, p, MOD)) def main(): ts = 1 ts = int(input()) for t in range(1, ts + 1): solve() def input(): return sys.stdin.readline().rstrip('\n').strip() def print(*args, sep=' ', end='\n'): first = True for arg in args: if not first: sys.stdout.write(sep) sys.stdout.write(str(arg)) first = False sys.stdout.write(end) main() ```
output
1
38,919
12
77,839
Provide tags and a correct Python 3 solution for this coding contest problem. When he's not training for IOI, Little Alawn enjoys playing with puzzles of various types to stimulate his brain. Today, he's playing with a puzzle that consists of a 2 × n grid where each row is a permutation of the numbers 1,2,3,…,n. The goal of Little Alawn's puzzle is to make sure no numbers on the same column or row are the same (we'll call this state of the puzzle as solved), and to achieve this he is able to swap the numbers in any column. However, after solving the puzzle many times, Little Alawn got bored and began wondering about the number of possible solved configurations of the puzzle he could achieve from an initial solved configuration only by swapping numbers in a column. Unfortunately, Little Alawn got stuck while trying to solve this harder problem, so he was wondering if you could help him with it. Find the answer modulo 10^9+7. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows. The first line of each test case contains a single integer n (2 ≤ n ≤ 4 ⋅ 10^5). The next two lines of each test case describe the initial state of the puzzle grid. Each line will be a permutation of the numbers 1,2,3,…,n and the numbers in each column and row will be pairwise distinct. It is guaranteed that the sum of n over all test cases does not exceed 4 ⋅ 10^5. Output For each test case output a single integer, the number of possible solved configurations of the puzzle Little Alawn can achieve from an initial solved configuration only by swapping numbers in a column. As the answer can be very large, please output it modulo 10^9+7. The answer for each test case should be on a separate line. Example Input 2 4 1 4 2 3 3 2 1 4 8 2 6 5 1 4 3 7 8 3 8 7 5 1 2 4 6 Output 2 8 Note The two possible puzzle configurations for example 1 are: * [1,4,2,3] in the first row and [3,2,1,4] in the second; * [3,2,1,4] in the first row and [1,4,2,3] in the second.
instruction
0
38,920
12
77,840
Tags: combinatorics, dfs and similar, dp, dsu, graphs, math Correct Solution: ``` #from math import * #from bisect import * #from collections import * #from random import * #from decimal import *""" #from heapq import * #from random import * import sys input=sys.stdin.readline sys.setrecursionlimit(3*(10**5)) def inp(): return int(input()) def st(): return input().rstrip('\n') def lis(): return list(map(int,input().split())) def ma(): return map(int,input().split()) t=inp() while(t): t-=1 n=inp() a=lis() co=0 b=lis() vis=[0]*(n+1) d={} for i in range(n): d[a[i]]=b[i] for i in range(n): if(vis[a[i]]==0): co+=1 pa=a[i] vis[a[i]]=1 go=d[a[i]] while(go!=pa): vis[go]=1 go=d[go] print(pow(2,co,1000000007)) ```
output
1
38,920
12
77,841
Provide tags and a correct Python 3 solution for this coding contest problem. When he's not training for IOI, Little Alawn enjoys playing with puzzles of various types to stimulate his brain. Today, he's playing with a puzzle that consists of a 2 × n grid where each row is a permutation of the numbers 1,2,3,…,n. The goal of Little Alawn's puzzle is to make sure no numbers on the same column or row are the same (we'll call this state of the puzzle as solved), and to achieve this he is able to swap the numbers in any column. However, after solving the puzzle many times, Little Alawn got bored and began wondering about the number of possible solved configurations of the puzzle he could achieve from an initial solved configuration only by swapping numbers in a column. Unfortunately, Little Alawn got stuck while trying to solve this harder problem, so he was wondering if you could help him with it. Find the answer modulo 10^9+7. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows. The first line of each test case contains a single integer n (2 ≤ n ≤ 4 ⋅ 10^5). The next two lines of each test case describe the initial state of the puzzle grid. Each line will be a permutation of the numbers 1,2,3,…,n and the numbers in each column and row will be pairwise distinct. It is guaranteed that the sum of n over all test cases does not exceed 4 ⋅ 10^5. Output For each test case output a single integer, the number of possible solved configurations of the puzzle Little Alawn can achieve from an initial solved configuration only by swapping numbers in a column. As the answer can be very large, please output it modulo 10^9+7. The answer for each test case should be on a separate line. Example Input 2 4 1 4 2 3 3 2 1 4 8 2 6 5 1 4 3 7 8 3 8 7 5 1 2 4 6 Output 2 8 Note The two possible puzzle configurations for example 1 are: * [1,4,2,3] in the first row and [3,2,1,4] in the second; * [3,2,1,4] in the first row and [1,4,2,3] in the second.
instruction
0
38,921
12
77,842
Tags: combinatorics, dfs and similar, dp, dsu, graphs, math Correct Solution: ``` import collections import heapq from bisect import bisect_right import math t = int(input()) for w in range(t): n = int(input()) a = [int(x) for x in input().split()] b = [int(x) for x in input().split()] v = [] for i in range(n): arr = [a[i], b[i], 0] v.append(arr) v.sort() count = 0 for i in range(n): pos = i if v[i][2] == 1: continue while True: if v[pos][1] == v[i][0]: count += 1 break else: pos = v[pos][1] - 1 v[pos][2] = 1 print((2**count) % (10**9 + 7)) ```
output
1
38,921
12
77,843
Provide tags and a correct Python 3 solution for this coding contest problem. When he's not training for IOI, Little Alawn enjoys playing with puzzles of various types to stimulate his brain. Today, he's playing with a puzzle that consists of a 2 × n grid where each row is a permutation of the numbers 1,2,3,…,n. The goal of Little Alawn's puzzle is to make sure no numbers on the same column or row are the same (we'll call this state of the puzzle as solved), and to achieve this he is able to swap the numbers in any column. However, after solving the puzzle many times, Little Alawn got bored and began wondering about the number of possible solved configurations of the puzzle he could achieve from an initial solved configuration only by swapping numbers in a column. Unfortunately, Little Alawn got stuck while trying to solve this harder problem, so he was wondering if you could help him with it. Find the answer modulo 10^9+7. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows. The first line of each test case contains a single integer n (2 ≤ n ≤ 4 ⋅ 10^5). The next two lines of each test case describe the initial state of the puzzle grid. Each line will be a permutation of the numbers 1,2,3,…,n and the numbers in each column and row will be pairwise distinct. It is guaranteed that the sum of n over all test cases does not exceed 4 ⋅ 10^5. Output For each test case output a single integer, the number of possible solved configurations of the puzzle Little Alawn can achieve from an initial solved configuration only by swapping numbers in a column. As the answer can be very large, please output it modulo 10^9+7. The answer for each test case should be on a separate line. Example Input 2 4 1 4 2 3 3 2 1 4 8 2 6 5 1 4 3 7 8 3 8 7 5 1 2 4 6 Output 2 8 Note The two possible puzzle configurations for example 1 are: * [1,4,2,3] in the first row and [3,2,1,4] in the second; * [3,2,1,4] in the first row and [1,4,2,3] in the second.
instruction
0
38,922
12
77,844
Tags: combinatorics, dfs and similar, dp, dsu, graphs, math Correct Solution: ``` mod = 10**9+7 import sys input = sys.stdin.readline from collections import deque class Graph(object): """docstring for Graph""" def __init__(self,n,d): # Number of nodes and d is True if directed self.n = n self.graph = [[] for i in range(n)] self.parent = [-1 for i in range(n)] self.child = {} self.directed = d self.total_edges = 0 def addEdge(self,x,y): self.total_edges += 1 self.graph[x].append(y) if not self.directed: self.graph[y].append(x) def bfs(self, root): # NORMAL BFS queue = [root] queue = deque(queue) while len(queue)!=0: element = queue.popleft() vis[element] = 1 for i in self.graph[element]: if vis[i]==0: queue.append(i) self.parent[i] = element vis[i] = 1 # TRY EXPERIMENTING BY REPLACING STACK2 WITH EULER TOUR AND TAKING THE SECOND OCCURRENCE FROM BACK def dfs(self, root): # Iterative DFS ans = [0]*n stack=[root] vis=[0]*self.n stack2=[] while len(stack)!=0: # INITIAL TRAVERSAL element = stack.pop() if vis[element]: continue vis[element] = 1 stack2.append(element) for i in self.graph[element]: if vis[i]==0: self.parent[i] = element stack.append(i) while len(stack2)!=0: # BACKTRACING. Modify the loop according to the question element = stack2.pop() m = 0 for i in self.graph[element]: if i!=self.parent[element]: m += ans[i] ans[element] = m return ans def shortestpath(self, source, dest): # Calculate Shortest Path between two nodes self.bfs(source) path = [dest] while self.parent[path[-1]]!=-1: path.append(parent[path[-1]]) return path[::-1] def detect_cycle(self): indeg = [0]*self.n for i in range(self.n): for j in self.graph[i]: indeg[j] += 1 q = deque() vis = 0 for i in range(self.n): if indeg[i]==0: q.append(i) while len(q)!=0: e = q.popleft() vis += 1 for i in self.graph[e]: indeg[i] -= 1 if indeg[i]==0: q.append(i) if vis!=self.n: return True return False def reroot(self, root, ans): stack = [root] vis = [0]*n while len(stack)!=0: e = stack[-1] if vis[e]: stack.pop() # Reverse_The_Change() continue vis[e] = 1 for i in graph[e]: if not vis[e]: stack.append(i) if self.parent[e]==-1: continue # Change_The_Answers() def eulertour(self, root): # Order in which vertices are visited in DFS stack=[root] t = [] vis = [0]*self.n while len(stack)!=0: element = stack[-1] if vis[element]: t.append(stack.pop()) continue t.append(element) vis[element] = 1 for i in self.graph[element]: if not vis[i]: self.parent[i] = element stack.append(i) c = {} ans = [] for i in t: if i not in c: ans.append(i) c[i] = 1 elif c[i]!=2: ans.append(i) c[i] += 1 return ans def articulation_points(self): # UNTESTED at = [0]*self.n order = self.eulertour(0) done = {} disc = [0]*self.n low = [0]*self.n time = 0 for i in order: if i not in done: done[i] = 1 if self.parent[i] != -1: disc[i] = time+1 time += 1 low[i] = disc[i] after = {} for i in range(self.n): if self.parent[i] not in after: after[self.parent[i]] = [i] else: after[self.parent[i]].append(i) dfs_order = [] done = {} for i in order[::-1]: if i not in done: done[i] = 1 else: dfs_order.append(i) for i in dfs_order: for j in self.graph[i]: if i in after and j in after[i]: low[i] = min(low[i], low[j]) if i==0 and len(after[i])>1: at[i] = 1 if i!=0 and low[j]>=disc[i]: at[i] = 1 elif j!=self.parent[i]: low[i] = min(low[i], disc[j]) return at def eulerian_path(self): # Assumes conditions reqd are satisfied (For directed graph) curr_path = [0] cycle = [] while curr_path: node = curr_path[-1] if self.graph[node]: nxt = self.graph[node].pop() curr_path.append(nxt) else: cycle.append(curr_path.pop()) return cycle[::-1] for nt in range(int(input())): n = int(input()) a = list(map(int,input().split())) b = list(map(int,input().split())) g = Graph(n, False) for i in range(n): g.addEdge(a[i]-1, b[i]-1) ans = 0 vis = [0]*n for i in range(n): if not vis[i]: g.bfs(i) ans += 1 print (pow(2, ans, mod)) ```
output
1
38,922
12
77,845
Provide tags and a correct Python 3 solution for this coding contest problem. When he's not training for IOI, Little Alawn enjoys playing with puzzles of various types to stimulate his brain. Today, he's playing with a puzzle that consists of a 2 × n grid where each row is a permutation of the numbers 1,2,3,…,n. The goal of Little Alawn's puzzle is to make sure no numbers on the same column or row are the same (we'll call this state of the puzzle as solved), and to achieve this he is able to swap the numbers in any column. However, after solving the puzzle many times, Little Alawn got bored and began wondering about the number of possible solved configurations of the puzzle he could achieve from an initial solved configuration only by swapping numbers in a column. Unfortunately, Little Alawn got stuck while trying to solve this harder problem, so he was wondering if you could help him with it. Find the answer modulo 10^9+7. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows. The first line of each test case contains a single integer n (2 ≤ n ≤ 4 ⋅ 10^5). The next two lines of each test case describe the initial state of the puzzle grid. Each line will be a permutation of the numbers 1,2,3,…,n and the numbers in each column and row will be pairwise distinct. It is guaranteed that the sum of n over all test cases does not exceed 4 ⋅ 10^5. Output For each test case output a single integer, the number of possible solved configurations of the puzzle Little Alawn can achieve from an initial solved configuration only by swapping numbers in a column. As the answer can be very large, please output it modulo 10^9+7. The answer for each test case should be on a separate line. Example Input 2 4 1 4 2 3 3 2 1 4 8 2 6 5 1 4 3 7 8 3 8 7 5 1 2 4 6 Output 2 8 Note The two possible puzzle configurations for example 1 are: * [1,4,2,3] in the first row and [3,2,1,4] in the second; * [3,2,1,4] in the first row and [1,4,2,3] in the second.
instruction
0
38,923
12
77,846
Tags: combinatorics, dfs and similar, dp, dsu, graphs, math Correct Solution: ``` from __future__ import division, print_function import math import sys import os from io import BytesIO, IOBase #from collections import deque, Counter, OrderedDict, defaultdict #import heapq #ceil,floor,log,sqrt,factorial,pow,pi,gcd #import bisect #from bisect import bisect_left,bisect_right BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") from sys import maxsize, stdout, stdin,stderr mod = int(1e9 + 7) def Ii(): return (int(input())) def lint(): return list(map(int,input().split())) def S(): return input().strip() def grid(r, c): return [lint() for i in range(r)] from collections import defaultdict, Counter import math import heapq from heapq import heappop , heappush import bisect from itertools import groupby def gcd(a,b): while b: a %= b tmp = a a = b b = tmp return a def lcm(a,b): return a / gcd(a, b) * b def check_prime(n): for i in range(2, int(n ** (1 / 2)) + 1): if not n % i: return False return True def Bs(a, x): i=0 j=0 left = 0 right = len(a) flag=False while left<right: mi = (left+right)//2 #print(smi,a[mi],x) if a[mi]<=x: left = mi+1 i+=1 else: right = mi j+=1 #print(left,right,"----") #print(i-1,j) if left>0 and a[left-1]==x: return i-1, j else: return -1, -1 def nCr(n, r): return (fact(n) / (fact(r) * fact(n - r))) # Returns factorial of n def fact(n): res = 1 for i in range(2, n+1): res = res * i return res def primefactors(n): num=0 while n % 2 == 0: num+=1 n = n / 2 for i in range(3,int(math.sqrt(n))+1,2): while n % i== 0: num+=1 n = n // i if n > 2: num+=1 return num t = Ii() for _ in range(t): n = Ii() s1=lint() s2=lint() d=[] d=[[s1[i],s2[i]] for i in range(n)] d.sort() vis=[0 for i in range(n)] cnt,tmp,num=0,1,0 tot=set() while len(tot)!=n: if vis[tmp-1]: tmp+=1 if num: cnt+=1 num=0 else: vis[tmp-1]=1 tot.add(d[tmp-1][0]) tmp=d[tmp-1][1] num+=1 print(2**(cnt+1)%mod) ```
output
1
38,923
12
77,847
Provide tags and a correct Python 3 solution for this coding contest problem. When he's not training for IOI, Little Alawn enjoys playing with puzzles of various types to stimulate his brain. Today, he's playing with a puzzle that consists of a 2 × n grid where each row is a permutation of the numbers 1,2,3,…,n. The goal of Little Alawn's puzzle is to make sure no numbers on the same column or row are the same (we'll call this state of the puzzle as solved), and to achieve this he is able to swap the numbers in any column. However, after solving the puzzle many times, Little Alawn got bored and began wondering about the number of possible solved configurations of the puzzle he could achieve from an initial solved configuration only by swapping numbers in a column. Unfortunately, Little Alawn got stuck while trying to solve this harder problem, so he was wondering if you could help him with it. Find the answer modulo 10^9+7. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows. The first line of each test case contains a single integer n (2 ≤ n ≤ 4 ⋅ 10^5). The next two lines of each test case describe the initial state of the puzzle grid. Each line will be a permutation of the numbers 1,2,3,…,n and the numbers in each column and row will be pairwise distinct. It is guaranteed that the sum of n over all test cases does not exceed 4 ⋅ 10^5. Output For each test case output a single integer, the number of possible solved configurations of the puzzle Little Alawn can achieve from an initial solved configuration only by swapping numbers in a column. As the answer can be very large, please output it modulo 10^9+7. The answer for each test case should be on a separate line. Example Input 2 4 1 4 2 3 3 2 1 4 8 2 6 5 1 4 3 7 8 3 8 7 5 1 2 4 6 Output 2 8 Note The two possible puzzle configurations for example 1 are: * [1,4,2,3] in the first row and [3,2,1,4] in the second; * [3,2,1,4] in the first row and [1,4,2,3] in the second.
instruction
0
38,924
12
77,848
Tags: combinatorics, dfs and similar, dp, dsu, graphs, math Correct Solution: ``` import collections import functools import math import random import sys import bisect import io, os # input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline # # input = sys.stdin.readline def In(): return map(int, input().split()) def f(): r, c = In() count = [r] * c l = [] for i in range(r): s = input().rstrip() for i1 in range(c): if s[i1] == '#' and count[i1] == r: count[i1] = i l.append(s) ans = 0 for i in range(r): for i1 in range(c): if l[i][i1] == '#': if i1 and count[i1 - 1] <= i: continue if count[i1] != i: continue if i1 < c - 1 and count[i1 + 1] <= i: continue ans += 1 print(ans) # f() def cnum(): mod = int(1e9) + 7 for _ in range(int(input())): n = int(input()) count = [[] for _ in range(n)] l = input().split() l1 = input().split() for i in range(n): count[int(l[i]) - 1].append(int(l1[i]) - 1) his = [False] * n c = 0 for i in range(n): if not his[i]: todo = [i] while todo: s = todo.pop() if his[s]: continue his[s] = True for i in count[s]: todo.append(i) c += 1 res = 1 x = 2 while c: if c % 2 == 1: res = (res * x) % mod x = (x*x)%mod c //= 2 print(res) cnum() ```
output
1
38,924
12
77,849
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. When he's not training for IOI, Little Alawn enjoys playing with puzzles of various types to stimulate his brain. Today, he's playing with a puzzle that consists of a 2 × n grid where each row is a permutation of the numbers 1,2,3,…,n. The goal of Little Alawn's puzzle is to make sure no numbers on the same column or row are the same (we'll call this state of the puzzle as solved), and to achieve this he is able to swap the numbers in any column. However, after solving the puzzle many times, Little Alawn got bored and began wondering about the number of possible solved configurations of the puzzle he could achieve from an initial solved configuration only by swapping numbers in a column. Unfortunately, Little Alawn got stuck while trying to solve this harder problem, so he was wondering if you could help him with it. Find the answer modulo 10^9+7. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows. The first line of each test case contains a single integer n (2 ≤ n ≤ 4 ⋅ 10^5). The next two lines of each test case describe the initial state of the puzzle grid. Each line will be a permutation of the numbers 1,2,3,…,n and the numbers in each column and row will be pairwise distinct. It is guaranteed that the sum of n over all test cases does not exceed 4 ⋅ 10^5. Output For each test case output a single integer, the number of possible solved configurations of the puzzle Little Alawn can achieve from an initial solved configuration only by swapping numbers in a column. As the answer can be very large, please output it modulo 10^9+7. The answer for each test case should be on a separate line. Example Input 2 4 1 4 2 3 3 2 1 4 8 2 6 5 1 4 3 7 8 3 8 7 5 1 2 4 6 Output 2 8 Note The two possible puzzle configurations for example 1 are: * [1,4,2,3] in the first row and [3,2,1,4] in the second; * [3,2,1,4] in the first row and [1,4,2,3] in the second. Submitted Solution: ``` import sys import random import time input = sys.stdin.readline MOD = int(1e9) + 7 ans = [] T = int(input().strip()) # start = time.time() for _ in range(T): N = int(input().strip()) A = list(map(int, input().strip().split())) B = list(map(int, input().strip().split())) mainB = [0] * (N + 1) calc = [0] * (N + 1) for i, b in enumerate(B): mainB[b] = A[i] unique = 0 for i in range(1, N + 1): if calc[i] == 0: unique += 1 j = mainB[i] calc[i] = 1 while j != i: calc[j] = 1 j = mainB[j] ans.append(str(pow(2, unique, MOD))) print('\n'.join(ans)) # print('time elapsed:', time.time() - start) """ 1 3 2 3 1 4 1 2 4 3 """ ```
instruction
0
38,925
12
77,850
Yes
output
1
38,925
12
77,851
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. When he's not training for IOI, Little Alawn enjoys playing with puzzles of various types to stimulate his brain. Today, he's playing with a puzzle that consists of a 2 × n grid where each row is a permutation of the numbers 1,2,3,…,n. The goal of Little Alawn's puzzle is to make sure no numbers on the same column or row are the same (we'll call this state of the puzzle as solved), and to achieve this he is able to swap the numbers in any column. However, after solving the puzzle many times, Little Alawn got bored and began wondering about the number of possible solved configurations of the puzzle he could achieve from an initial solved configuration only by swapping numbers in a column. Unfortunately, Little Alawn got stuck while trying to solve this harder problem, so he was wondering if you could help him with it. Find the answer modulo 10^9+7. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows. The first line of each test case contains a single integer n (2 ≤ n ≤ 4 ⋅ 10^5). The next two lines of each test case describe the initial state of the puzzle grid. Each line will be a permutation of the numbers 1,2,3,…,n and the numbers in each column and row will be pairwise distinct. It is guaranteed that the sum of n over all test cases does not exceed 4 ⋅ 10^5. Output For each test case output a single integer, the number of possible solved configurations of the puzzle Little Alawn can achieve from an initial solved configuration only by swapping numbers in a column. As the answer can be very large, please output it modulo 10^9+7. The answer for each test case should be on a separate line. Example Input 2 4 1 4 2 3 3 2 1 4 8 2 6 5 1 4 3 7 8 3 8 7 5 1 2 4 6 Output 2 8 Note The two possible puzzle configurations for example 1 are: * [1,4,2,3] in the first row and [3,2,1,4] in the second; * [3,2,1,4] in the first row and [1,4,2,3] in the second. Submitted Solution: ``` import math import heapq import sys import bisect from collections import deque import time input = sys.stdin.readline mod=10**9+7 ############ ---- Input Functions ---- ############ def inp(): return(int(input())) def inlt(): return(list(map(int,input().split()))) def insr(): s = input() return(list(s[:len(s) - 1])) def invr(): return(map(int,input().split())) for _ in range(inp()): n=inp() l=inlt() m=inlt() d={} for i in range(n): d[l[i]]=m[i] x=0 v=[0]*n for i in range(n): if not v[i]: x+=1 a=i+1 v[i]=1 while d[a]-1!=i: a=d[a] v[a-1]=1 print(pow(2,x,mod)) ```
instruction
0
38,926
12
77,852
Yes
output
1
38,926
12
77,853
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. When he's not training for IOI, Little Alawn enjoys playing with puzzles of various types to stimulate his brain. Today, he's playing with a puzzle that consists of a 2 × n grid where each row is a permutation of the numbers 1,2,3,…,n. The goal of Little Alawn's puzzle is to make sure no numbers on the same column or row are the same (we'll call this state of the puzzle as solved), and to achieve this he is able to swap the numbers in any column. However, after solving the puzzle many times, Little Alawn got bored and began wondering about the number of possible solved configurations of the puzzle he could achieve from an initial solved configuration only by swapping numbers in a column. Unfortunately, Little Alawn got stuck while trying to solve this harder problem, so he was wondering if you could help him with it. Find the answer modulo 10^9+7. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows. The first line of each test case contains a single integer n (2 ≤ n ≤ 4 ⋅ 10^5). The next two lines of each test case describe the initial state of the puzzle grid. Each line will be a permutation of the numbers 1,2,3,…,n and the numbers in each column and row will be pairwise distinct. It is guaranteed that the sum of n over all test cases does not exceed 4 ⋅ 10^5. Output For each test case output a single integer, the number of possible solved configurations of the puzzle Little Alawn can achieve from an initial solved configuration only by swapping numbers in a column. As the answer can be very large, please output it modulo 10^9+7. The answer for each test case should be on a separate line. Example Input 2 4 1 4 2 3 3 2 1 4 8 2 6 5 1 4 3 7 8 3 8 7 5 1 2 4 6 Output 2 8 Note The two possible puzzle configurations for example 1 are: * [1,4,2,3] in the first row and [3,2,1,4] in the second; * [3,2,1,4] in the first row and [1,4,2,3] in the second. Submitted Solution: ``` for _ in range(int(input())): n = int(input()) a = list(map(int,input().split())) b = list(map(int,input().split())) up = {} visited = set(a) for i in range(n): up[a[i]] = b[i] ans = 1 mod = int(1e9+7) while visited: cr = visited.pop() ky = up[cr] visited.remove(ky) while cr != up[ky]: ky = up[ky] visited.remove(ky) ans *= 2 ans %= mod print(ans) ```
instruction
0
38,927
12
77,854
Yes
output
1
38,927
12
77,855
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. When he's not training for IOI, Little Alawn enjoys playing with puzzles of various types to stimulate his brain. Today, he's playing with a puzzle that consists of a 2 × n grid where each row is a permutation of the numbers 1,2,3,…,n. The goal of Little Alawn's puzzle is to make sure no numbers on the same column or row are the same (we'll call this state of the puzzle as solved), and to achieve this he is able to swap the numbers in any column. However, after solving the puzzle many times, Little Alawn got bored and began wondering about the number of possible solved configurations of the puzzle he could achieve from an initial solved configuration only by swapping numbers in a column. Unfortunately, Little Alawn got stuck while trying to solve this harder problem, so he was wondering if you could help him with it. Find the answer modulo 10^9+7. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows. The first line of each test case contains a single integer n (2 ≤ n ≤ 4 ⋅ 10^5). The next two lines of each test case describe the initial state of the puzzle grid. Each line will be a permutation of the numbers 1,2,3,…,n and the numbers in each column and row will be pairwise distinct. It is guaranteed that the sum of n over all test cases does not exceed 4 ⋅ 10^5. Output For each test case output a single integer, the number of possible solved configurations of the puzzle Little Alawn can achieve from an initial solved configuration only by swapping numbers in a column. As the answer can be very large, please output it modulo 10^9+7. The answer for each test case should be on a separate line. Example Input 2 4 1 4 2 3 3 2 1 4 8 2 6 5 1 4 3 7 8 3 8 7 5 1 2 4 6 Output 2 8 Note The two possible puzzle configurations for example 1 are: * [1,4,2,3] in the first row and [3,2,1,4] in the second; * [3,2,1,4] in the first row and [1,4,2,3] in the second. Submitted Solution: ``` #!/usr/bin/env python3 # from typing import * import sys import io import math import collections import decimal import itertools import bisect import heapq def input(): return sys.stdin.readline()[:-1] # sys.setrecursionlimit(1000000) # _INPUT = """# paste here... # """ # sys.stdin = io.StringIO(_INPUT) MOD = 1000000007 def solve(N, A, B): T = [-1] * N for i in range(N): T[A[i]-1] = B[i]-1 seen = [False] * N n = 0 for i in range(N): if seen[i]: continue j = i while not seen[j]: seen[j] = True j = T[j] n += 1 return pow(2, n, MOD) T0 = int(input()) for _ in range(T0): N = int(input()) A = list(map(int, input().split())) B = list(map(int, input().split())) print(solve(N, A, B)) ```
instruction
0
38,928
12
77,856
Yes
output
1
38,928
12
77,857
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. When he's not training for IOI, Little Alawn enjoys playing with puzzles of various types to stimulate his brain. Today, he's playing with a puzzle that consists of a 2 × n grid where each row is a permutation of the numbers 1,2,3,…,n. The goal of Little Alawn's puzzle is to make sure no numbers on the same column or row are the same (we'll call this state of the puzzle as solved), and to achieve this he is able to swap the numbers in any column. However, after solving the puzzle many times, Little Alawn got bored and began wondering about the number of possible solved configurations of the puzzle he could achieve from an initial solved configuration only by swapping numbers in a column. Unfortunately, Little Alawn got stuck while trying to solve this harder problem, so he was wondering if you could help him with it. Find the answer modulo 10^9+7. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows. The first line of each test case contains a single integer n (2 ≤ n ≤ 4 ⋅ 10^5). The next two lines of each test case describe the initial state of the puzzle grid. Each line will be a permutation of the numbers 1,2,3,…,n and the numbers in each column and row will be pairwise distinct. It is guaranteed that the sum of n over all test cases does not exceed 4 ⋅ 10^5. Output For each test case output a single integer, the number of possible solved configurations of the puzzle Little Alawn can achieve from an initial solved configuration only by swapping numbers in a column. As the answer can be very large, please output it modulo 10^9+7. The answer for each test case should be on a separate line. Example Input 2 4 1 4 2 3 3 2 1 4 8 2 6 5 1 4 3 7 8 3 8 7 5 1 2 4 6 Output 2 8 Note The two possible puzzle configurations for example 1 are: * [1,4,2,3] in the first row and [3,2,1,4] in the second; * [3,2,1,4] in the first row and [1,4,2,3] in the second. Submitted Solution: ``` import time for _ in range(int(input())): n = int(input()) a = [[None] * (n + 1), [None] * (n + 1)] for i, l in enumerate(map(int, input().split()), 1): a[0][l] = i for i, l in enumerate(map(int, input().split()), 1): a[1][l] = i for x, y in zip(*a): if x == y: print(0) else: c = 0 for i in range(1, n + 1): f = True if a[f][i]: c += 1 while i and a[f][i]: j = i i = a[f][i] a[f][j] = None f ^= True print(int((1 << c) % (1e9 + 7))) ```
instruction
0
38,929
12
77,858
No
output
1
38,929
12
77,859
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. When he's not training for IOI, Little Alawn enjoys playing with puzzles of various types to stimulate his brain. Today, he's playing with a puzzle that consists of a 2 × n grid where each row is a permutation of the numbers 1,2,3,…,n. The goal of Little Alawn's puzzle is to make sure no numbers on the same column or row are the same (we'll call this state of the puzzle as solved), and to achieve this he is able to swap the numbers in any column. However, after solving the puzzle many times, Little Alawn got bored and began wondering about the number of possible solved configurations of the puzzle he could achieve from an initial solved configuration only by swapping numbers in a column. Unfortunately, Little Alawn got stuck while trying to solve this harder problem, so he was wondering if you could help him with it. Find the answer modulo 10^9+7. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows. The first line of each test case contains a single integer n (2 ≤ n ≤ 4 ⋅ 10^5). The next two lines of each test case describe the initial state of the puzzle grid. Each line will be a permutation of the numbers 1,2,3,…,n and the numbers in each column and row will be pairwise distinct. It is guaranteed that the sum of n over all test cases does not exceed 4 ⋅ 10^5. Output For each test case output a single integer, the number of possible solved configurations of the puzzle Little Alawn can achieve from an initial solved configuration only by swapping numbers in a column. As the answer can be very large, please output it modulo 10^9+7. The answer for each test case should be on a separate line. Example Input 2 4 1 4 2 3 3 2 1 4 8 2 6 5 1 4 3 7 8 3 8 7 5 1 2 4 6 Output 2 8 Note The two possible puzzle configurations for example 1 are: * [1,4,2,3] in the first row and [3,2,1,4] in the second; * [3,2,1,4] in the first row and [1,4,2,3] in the second. Submitted Solution: ``` t=int(input()) for case in range(t): n=int(input()) a=list(map(int,input().split())) b=list(map(int,input().split())) adj=[[] for x in range(n+1)] for x in range(n): adj[a[x]].append(b[x]) visited=[False]*(n+1) c=0 for x in range(1,n+1): i=x f=False while not visited[i]: f=True visited[i]=True i=adj[i][0] c+=int(f) if c!=1: c+=1 print(2*c) ```
instruction
0
38,930
12
77,860
No
output
1
38,930
12
77,861
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. When he's not training for IOI, Little Alawn enjoys playing with puzzles of various types to stimulate his brain. Today, he's playing with a puzzle that consists of a 2 × n grid where each row is a permutation of the numbers 1,2,3,…,n. The goal of Little Alawn's puzzle is to make sure no numbers on the same column or row are the same (we'll call this state of the puzzle as solved), and to achieve this he is able to swap the numbers in any column. However, after solving the puzzle many times, Little Alawn got bored and began wondering about the number of possible solved configurations of the puzzle he could achieve from an initial solved configuration only by swapping numbers in a column. Unfortunately, Little Alawn got stuck while trying to solve this harder problem, so he was wondering if you could help him with it. Find the answer modulo 10^9+7. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows. The first line of each test case contains a single integer n (2 ≤ n ≤ 4 ⋅ 10^5). The next two lines of each test case describe the initial state of the puzzle grid. Each line will be a permutation of the numbers 1,2,3,…,n and the numbers in each column and row will be pairwise distinct. It is guaranteed that the sum of n over all test cases does not exceed 4 ⋅ 10^5. Output For each test case output a single integer, the number of possible solved configurations of the puzzle Little Alawn can achieve from an initial solved configuration only by swapping numbers in a column. As the answer can be very large, please output it modulo 10^9+7. The answer for each test case should be on a separate line. Example Input 2 4 1 4 2 3 3 2 1 4 8 2 6 5 1 4 3 7 8 3 8 7 5 1 2 4 6 Output 2 8 Note The two possible puzzle configurations for example 1 are: * [1,4,2,3] in the first row and [3,2,1,4] in the second; * [3,2,1,4] in the first row and [1,4,2,3] in the second. Submitted Solution: ``` import math def task(): n = int(input()) grid = [] grid.append(list(map(int, input().split()))) grid.append(list(map(int, input().split()))) pos = [-1] * (n+1) done = set() for i in range(n): e = grid[0][i] pos[e] = i c = 0 for i in range(n): e = grid[1][i] if grid[0][i] == grid[1][ pos[e] ] and min(grid[0][i], grid[1][i]) not in done: c += 1 done.add(min(grid[0][i], grid[1][i])) print(2 * int(math.pow(2,c))) t = int(input()) for _ in range(t): task() ```
instruction
0
38,931
12
77,862
No
output
1
38,931
12
77,863
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. When he's not training for IOI, Little Alawn enjoys playing with puzzles of various types to stimulate his brain. Today, he's playing with a puzzle that consists of a 2 × n grid where each row is a permutation of the numbers 1,2,3,…,n. The goal of Little Alawn's puzzle is to make sure no numbers on the same column or row are the same (we'll call this state of the puzzle as solved), and to achieve this he is able to swap the numbers in any column. However, after solving the puzzle many times, Little Alawn got bored and began wondering about the number of possible solved configurations of the puzzle he could achieve from an initial solved configuration only by swapping numbers in a column. Unfortunately, Little Alawn got stuck while trying to solve this harder problem, so he was wondering if you could help him with it. Find the answer modulo 10^9+7. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows. The first line of each test case contains a single integer n (2 ≤ n ≤ 4 ⋅ 10^5). The next two lines of each test case describe the initial state of the puzzle grid. Each line will be a permutation of the numbers 1,2,3,…,n and the numbers in each column and row will be pairwise distinct. It is guaranteed that the sum of n over all test cases does not exceed 4 ⋅ 10^5. Output For each test case output a single integer, the number of possible solved configurations of the puzzle Little Alawn can achieve from an initial solved configuration only by swapping numbers in a column. As the answer can be very large, please output it modulo 10^9+7. The answer for each test case should be on a separate line. Example Input 2 4 1 4 2 3 3 2 1 4 8 2 6 5 1 4 3 7 8 3 8 7 5 1 2 4 6 Output 2 8 Note The two possible puzzle configurations for example 1 are: * [1,4,2,3] in the first row and [3,2,1,4] in the second; * [3,2,1,4] in the first row and [1,4,2,3] in the second. Submitted Solution: ``` for _ in range(int(input())): n=int(input()) l=list(map(int,input().split())) ll=list(map(int,input().split())) d=dict() for i in range(n): d[l[i]]=ll[i] c=0 while len(d)>0: for i in range(1,n+1): if i in d: x=d[i] d.pop(i) while i!=x: x=d.pop(x) c+=1 print(2**c) ```
instruction
0
38,932
12
77,864
No
output
1
38,932
12
77,865
Provide tags and a correct Python 3 solution for this coding contest problem. In this problem your goal is to sort an array consisting of n integers in at most n swaps. For the given array find the sequence of swaps that makes the array sorted in the non-descending order. Swaps are performed consecutively, one after another. Note that in this problem you do not have to minimize the number of swaps — your task is to find any sequence that is no longer than n. Input The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of array elements. The second line contains elements of array: a0, a1, ..., an - 1 ( - 109 ≤ ai ≤ 109), where ai is the i-th element of the array. The elements are numerated from 0 to n - 1 from left to right. Some integers may appear in the array more than once. Output In the first line print k (0 ≤ k ≤ n) — the number of swaps. Next k lines must contain the descriptions of the k swaps, one per line. Each swap should be printed as a pair of integers i, j (0 ≤ i, j ≤ n - 1), representing the swap of elements ai and aj. You can print indices in the pairs in any order. The swaps are performed in the order they appear in the output, from the first to the last. It is allowed to print i = j and swap the same pair of elements multiple times. If there are multiple answers, print any of them. It is guaranteed that at least one answer exists. Examples Input 5 5 2 5 1 4 Output 2 0 3 4 2 Input 6 10 20 20 40 60 60 Output 0 Input 2 101 100 Output 1 0 1
instruction
0
39,074
12
78,148
Tags: greedy, implementation, sortings Correct Solution: ``` def find_min(i): min = 1000000001 index = 0 for j in range(i, n): if a[j] < min: min = a[j] index = j return index n = int(input()) a = input().split() for i in range(n): a[i] = int(a[i]) k = 0 ans = () for i in range(n): m = find_min(i) if i != m: a[i] = a[i] + a[m] a[m] = a[i] - a[m] a[i] = a[i] - a[m] ans += (i, m) k += 1 print(k) for i in range(0, len(ans), 2): print(ans[i], ans[i+1]) ```
output
1
39,074
12
78,149
Provide tags and a correct Python 3 solution for this coding contest problem. In this problem your goal is to sort an array consisting of n integers in at most n swaps. For the given array find the sequence of swaps that makes the array sorted in the non-descending order. Swaps are performed consecutively, one after another. Note that in this problem you do not have to minimize the number of swaps — your task is to find any sequence that is no longer than n. Input The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of array elements. The second line contains elements of array: a0, a1, ..., an - 1 ( - 109 ≤ ai ≤ 109), where ai is the i-th element of the array. The elements are numerated from 0 to n - 1 from left to right. Some integers may appear in the array more than once. Output In the first line print k (0 ≤ k ≤ n) — the number of swaps. Next k lines must contain the descriptions of the k swaps, one per line. Each swap should be printed as a pair of integers i, j (0 ≤ i, j ≤ n - 1), representing the swap of elements ai and aj. You can print indices in the pairs in any order. The swaps are performed in the order they appear in the output, from the first to the last. It is allowed to print i = j and swap the same pair of elements multiple times. If there are multiple answers, print any of them. It is guaranteed that at least one answer exists. Examples Input 5 5 2 5 1 4 Output 2 0 3 4 2 Input 6 10 20 20 40 60 60 Output 0 Input 2 101 100 Output 1 0 1
instruction
0
39,075
12
78,150
Tags: greedy, implementation, sortings Correct Solution: ``` #maxn = 3100 #num = [0 for i in range(maxn)] #id = [maxn for i in range(maxn)] #cause problem if set to 0 #pp = [[0, 0] for i in range(100000)] #map = [0 for i in range(maxn)] #pos = [0 for i in range(maxn)] def key_function(num): def key(i): return num[i] return key def main(): n = 0 ans = 0 line = input() n = int(line) line = input() line = line.split() num = [int(line[i]) for i in range(n)] id = [i for i in range(n)] id.sort(key=key_function(num)) map = dict() #hash for i in range(n): map[id[i]] = i pp = list() for i in range(n): j = 0 for j in range(n): if map[j] == i: break if(i != j and j < n): pp.append((i, j)) ans = ans + 1 map[i], map[j] = map[j], map[i] print(ans) for i in range(ans): print(pp[i][0], pp[i][1]) main() ```
output
1
39,075
12
78,151
Provide tags and a correct Python 3 solution for this coding contest problem. In this problem your goal is to sort an array consisting of n integers in at most n swaps. For the given array find the sequence of swaps that makes the array sorted in the non-descending order. Swaps are performed consecutively, one after another. Note that in this problem you do not have to minimize the number of swaps — your task is to find any sequence that is no longer than n. Input The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of array elements. The second line contains elements of array: a0, a1, ..., an - 1 ( - 109 ≤ ai ≤ 109), where ai is the i-th element of the array. The elements are numerated from 0 to n - 1 from left to right. Some integers may appear in the array more than once. Output In the first line print k (0 ≤ k ≤ n) — the number of swaps. Next k lines must contain the descriptions of the k swaps, one per line. Each swap should be printed as a pair of integers i, j (0 ≤ i, j ≤ n - 1), representing the swap of elements ai and aj. You can print indices in the pairs in any order. The swaps are performed in the order they appear in the output, from the first to the last. It is allowed to print i = j and swap the same pair of elements multiple times. If there are multiple answers, print any of them. It is guaranteed that at least one answer exists. Examples Input 5 5 2 5 1 4 Output 2 0 3 4 2 Input 6 10 20 20 40 60 60 Output 0 Input 2 101 100 Output 1 0 1
instruction
0
39,076
12
78,152
Tags: greedy, implementation, sortings Correct Solution: ``` n = int(input()) a = list(map(int, input().split())) print(n - 1) for i in range(n - 1): j = a.index(min(a[i:]), i) print(i, j) a[i], a[j] = a[j], a[i] ```
output
1
39,076
12
78,153
Provide tags and a correct Python 3 solution for this coding contest problem. In this problem your goal is to sort an array consisting of n integers in at most n swaps. For the given array find the sequence of swaps that makes the array sorted in the non-descending order. Swaps are performed consecutively, one after another. Note that in this problem you do not have to minimize the number of swaps — your task is to find any sequence that is no longer than n. Input The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of array elements. The second line contains elements of array: a0, a1, ..., an - 1 ( - 109 ≤ ai ≤ 109), where ai is the i-th element of the array. The elements are numerated from 0 to n - 1 from left to right. Some integers may appear in the array more than once. Output In the first line print k (0 ≤ k ≤ n) — the number of swaps. Next k lines must contain the descriptions of the k swaps, one per line. Each swap should be printed as a pair of integers i, j (0 ≤ i, j ≤ n - 1), representing the swap of elements ai and aj. You can print indices in the pairs in any order. The swaps are performed in the order they appear in the output, from the first to the last. It is allowed to print i = j and swap the same pair of elements multiple times. If there are multiple answers, print any of them. It is guaranteed that at least one answer exists. Examples Input 5 5 2 5 1 4 Output 2 0 3 4 2 Input 6 10 20 20 40 60 60 Output 0 Input 2 101 100 Output 1 0 1
instruction
0
39,077
12
78,154
Tags: greedy, implementation, sortings Correct Solution: ``` n=int(input()) s=[int(i) for i in input().split()] j=list(s) j.sort() #print(j,s) if s==j: print(0) else: hh=0 x=[] for i in range(n): a=s[i] b=j[i] if a==b: s[i]=10**9 +1 continue else : if s==j: break h=s.index(b) x.append((h,i)) s[h]=a s[i]=10**9 +1 hh+=1 print(hh) #print(s) for i in x: print(*i) ```
output
1
39,077
12
78,155
Provide tags and a correct Python 3 solution for this coding contest problem. In this problem your goal is to sort an array consisting of n integers in at most n swaps. For the given array find the sequence of swaps that makes the array sorted in the non-descending order. Swaps are performed consecutively, one after another. Note that in this problem you do not have to minimize the number of swaps — your task is to find any sequence that is no longer than n. Input The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of array elements. The second line contains elements of array: a0, a1, ..., an - 1 ( - 109 ≤ ai ≤ 109), where ai is the i-th element of the array. The elements are numerated from 0 to n - 1 from left to right. Some integers may appear in the array more than once. Output In the first line print k (0 ≤ k ≤ n) — the number of swaps. Next k lines must contain the descriptions of the k swaps, one per line. Each swap should be printed as a pair of integers i, j (0 ≤ i, j ≤ n - 1), representing the swap of elements ai and aj. You can print indices in the pairs in any order. The swaps are performed in the order they appear in the output, from the first to the last. It is allowed to print i = j and swap the same pair of elements multiple times. If there are multiple answers, print any of them. It is guaranteed that at least one answer exists. Examples Input 5 5 2 5 1 4 Output 2 0 3 4 2 Input 6 10 20 20 40 60 60 Output 0 Input 2 101 100 Output 1 0 1
instruction
0
39,078
12
78,156
Tags: greedy, implementation, sortings Correct Solution: ``` ''' Author : knight_byte File : A_SwapSort.py Created on : 2021-04-17 20:13:38 ''' def main(): n = int(input()) arr = list(map(int, input().split())) swap = 0 ind = 0 i_s = [] while ind < len(arr): mi = min(arr[ind:]) if mi != arr[ind]: for i in range(ind, n): if arr[i] == mi and i != ind: arr[ind], arr[i] = arr[i], arr[ind] i_s.append((ind, i)) swap += 1 break ind += 1 print(swap) for i in range(swap): print(*i_s[i]) if __name__ == '__main__': main() ```
output
1
39,078
12
78,157
Provide tags and a correct Python 3 solution for this coding contest problem. In this problem your goal is to sort an array consisting of n integers in at most n swaps. For the given array find the sequence of swaps that makes the array sorted in the non-descending order. Swaps are performed consecutively, one after another. Note that in this problem you do not have to minimize the number of swaps — your task is to find any sequence that is no longer than n. Input The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of array elements. The second line contains elements of array: a0, a1, ..., an - 1 ( - 109 ≤ ai ≤ 109), where ai is the i-th element of the array. The elements are numerated from 0 to n - 1 from left to right. Some integers may appear in the array more than once. Output In the first line print k (0 ≤ k ≤ n) — the number of swaps. Next k lines must contain the descriptions of the k swaps, one per line. Each swap should be printed as a pair of integers i, j (0 ≤ i, j ≤ n - 1), representing the swap of elements ai and aj. You can print indices in the pairs in any order. The swaps are performed in the order they appear in the output, from the first to the last. It is allowed to print i = j and swap the same pair of elements multiple times. If there are multiple answers, print any of them. It is guaranteed that at least one answer exists. Examples Input 5 5 2 5 1 4 Output 2 0 3 4 2 Input 6 10 20 20 40 60 60 Output 0 Input 2 101 100 Output 1 0 1
instruction
0
39,079
12
78,158
Tags: greedy, implementation, sortings Correct Solution: ``` import sys import os.path if(os.path.exists('input_file.txt')): sys.stdin = open("input_file.txt", "r") sys.stdout = open("output_file.txt", "w") n=int(input()) a=list(map(int,input().split())) aa=sorted(a) i=0 # print(a,aa) f=1 l=[] while i<n: if a[i]==aa[i]:i+=1 else: f=0 s=aa[i] for j in range(i,n): if a[j]==s: l.append((i,j)) a[i],a[j]=a[j],a[i] break if f:print(0) else: print(len(l)) for i in l: a,b=i print(a,b) ```
output
1
39,079
12
78,159
Provide tags and a correct Python 3 solution for this coding contest problem. In this problem your goal is to sort an array consisting of n integers in at most n swaps. For the given array find the sequence of swaps that makes the array sorted in the non-descending order. Swaps are performed consecutively, one after another. Note that in this problem you do not have to minimize the number of swaps — your task is to find any sequence that is no longer than n. Input The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of array elements. The second line contains elements of array: a0, a1, ..., an - 1 ( - 109 ≤ ai ≤ 109), where ai is the i-th element of the array. The elements are numerated from 0 to n - 1 from left to right. Some integers may appear in the array more than once. Output In the first line print k (0 ≤ k ≤ n) — the number of swaps. Next k lines must contain the descriptions of the k swaps, one per line. Each swap should be printed as a pair of integers i, j (0 ≤ i, j ≤ n - 1), representing the swap of elements ai and aj. You can print indices in the pairs in any order. The swaps are performed in the order they appear in the output, from the first to the last. It is allowed to print i = j and swap the same pair of elements multiple times. If there are multiple answers, print any of them. It is guaranteed that at least one answer exists. Examples Input 5 5 2 5 1 4 Output 2 0 3 4 2 Input 6 10 20 20 40 60 60 Output 0 Input 2 101 100 Output 1 0 1
instruction
0
39,080
12
78,160
Tags: greedy, implementation, sortings Correct Solution: ``` n=int(input()) l=list(map(int,input().split())) swaps=0 ans=[] for i in range(n): t=i for j in range(i,n): if l[t]>l[j]: t=j if i!=t: ans.append([i,t]) l[i],l[t]=l[t],l[i] print(len(ans)) for i in ans: print(*i) ```
output
1
39,080
12
78,161
Provide tags and a correct Python 3 solution for this coding contest problem. In this problem your goal is to sort an array consisting of n integers in at most n swaps. For the given array find the sequence of swaps that makes the array sorted in the non-descending order. Swaps are performed consecutively, one after another. Note that in this problem you do not have to minimize the number of swaps — your task is to find any sequence that is no longer than n. Input The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of array elements. The second line contains elements of array: a0, a1, ..., an - 1 ( - 109 ≤ ai ≤ 109), where ai is the i-th element of the array. The elements are numerated from 0 to n - 1 from left to right. Some integers may appear in the array more than once. Output In the first line print k (0 ≤ k ≤ n) — the number of swaps. Next k lines must contain the descriptions of the k swaps, one per line. Each swap should be printed as a pair of integers i, j (0 ≤ i, j ≤ n - 1), representing the swap of elements ai and aj. You can print indices in the pairs in any order. The swaps are performed in the order they appear in the output, from the first to the last. It is allowed to print i = j and swap the same pair of elements multiple times. If there are multiple answers, print any of them. It is guaranteed that at least one answer exists. Examples Input 5 5 2 5 1 4 Output 2 0 3 4 2 Input 6 10 20 20 40 60 60 Output 0 Input 2 101 100 Output 1 0 1
instruction
0
39,081
12
78,162
Tags: greedy, implementation, sortings Correct Solution: ``` size=int(input()) array=list(map(int,input().split())) ans=[] for i in range(size): j=i for t in range(i,size): if(array[j]>array[t]): j=t if(i!=j): ans.append((i,j)) t=array[i] array[i]=array[j] array[j]=t print(len(ans)) for p in ans: print(p[0],p[1]) ```
output
1
39,081
12
78,163
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem your goal is to sort an array consisting of n integers in at most n swaps. For the given array find the sequence of swaps that makes the array sorted in the non-descending order. Swaps are performed consecutively, one after another. Note that in this problem you do not have to minimize the number of swaps — your task is to find any sequence that is no longer than n. Input The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of array elements. The second line contains elements of array: a0, a1, ..., an - 1 ( - 109 ≤ ai ≤ 109), where ai is the i-th element of the array. The elements are numerated from 0 to n - 1 from left to right. Some integers may appear in the array more than once. Output In the first line print k (0 ≤ k ≤ n) — the number of swaps. Next k lines must contain the descriptions of the k swaps, one per line. Each swap should be printed as a pair of integers i, j (0 ≤ i, j ≤ n - 1), representing the swap of elements ai and aj. You can print indices in the pairs in any order. The swaps are performed in the order they appear in the output, from the first to the last. It is allowed to print i = j and swap the same pair of elements multiple times. If there are multiple answers, print any of them. It is guaranteed that at least one answer exists. Examples Input 5 5 2 5 1 4 Output 2 0 3 4 2 Input 6 10 20 20 40 60 60 Output 0 Input 2 101 100 Output 1 0 1 Submitted Solution: ``` n = int(input()) A = [int(x) for x in input().split()] transpositions = [] for i in range(n): argmin = -1 for j in range(i, n): if argmin < 0 or A[argmin] > A[j]: argmin = j if i < argmin: transpositions.append((i, argmin)) A[i], A[argmin] = A[argmin], A[i] print(len(transpositions)) for t in transpositions: print(t[0], t[1]) ```
instruction
0
39,082
12
78,164
Yes
output
1
39,082
12
78,165
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem your goal is to sort an array consisting of n integers in at most n swaps. For the given array find the sequence of swaps that makes the array sorted in the non-descending order. Swaps are performed consecutively, one after another. Note that in this problem you do not have to minimize the number of swaps — your task is to find any sequence that is no longer than n. Input The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of array elements. The second line contains elements of array: a0, a1, ..., an - 1 ( - 109 ≤ ai ≤ 109), where ai is the i-th element of the array. The elements are numerated from 0 to n - 1 from left to right. Some integers may appear in the array more than once. Output In the first line print k (0 ≤ k ≤ n) — the number of swaps. Next k lines must contain the descriptions of the k swaps, one per line. Each swap should be printed as a pair of integers i, j (0 ≤ i, j ≤ n - 1), representing the swap of elements ai and aj. You can print indices in the pairs in any order. The swaps are performed in the order they appear in the output, from the first to the last. It is allowed to print i = j and swap the same pair of elements multiple times. If there are multiple answers, print any of them. It is guaranteed that at least one answer exists. Examples Input 5 5 2 5 1 4 Output 2 0 3 4 2 Input 6 10 20 20 40 60 60 Output 0 Input 2 101 100 Output 1 0 1 Submitted Solution: ``` numero = int(input()) lista = [int(x) for x in input().split()] listIndex = [] for i in range(len(lista)): menor = lista[i] index = i for j in range(i+1,len(lista)): if lista[j] < menor: menor = lista[j] index = j else: if lista[i] != menor: listIndex.append([i,index]) lista[index] = lista[i] lista[i] = menor print(len(listIndex)) for i in range(len(listIndex)): print(listIndex[i][0],listIndex[i][1]) ```
instruction
0
39,083
12
78,166
Yes
output
1
39,083
12
78,167
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem your goal is to sort an array consisting of n integers in at most n swaps. For the given array find the sequence of swaps that makes the array sorted in the non-descending order. Swaps are performed consecutively, one after another. Note that in this problem you do not have to minimize the number of swaps — your task is to find any sequence that is no longer than n. Input The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of array elements. The second line contains elements of array: a0, a1, ..., an - 1 ( - 109 ≤ ai ≤ 109), where ai is the i-th element of the array. The elements are numerated from 0 to n - 1 from left to right. Some integers may appear in the array more than once. Output In the first line print k (0 ≤ k ≤ n) — the number of swaps. Next k lines must contain the descriptions of the k swaps, one per line. Each swap should be printed as a pair of integers i, j (0 ≤ i, j ≤ n - 1), representing the swap of elements ai and aj. You can print indices in the pairs in any order. The swaps are performed in the order they appear in the output, from the first to the last. It is allowed to print i = j and swap the same pair of elements multiple times. If there are multiple answers, print any of them. It is guaranteed that at least one answer exists. Examples Input 5 5 2 5 1 4 Output 2 0 3 4 2 Input 6 10 20 20 40 60 60 Output 0 Input 2 101 100 Output 1 0 1 Submitted Solution: ``` n = int(input()) l = [int(x) for x in input().split()] res = [] for i in range(len(l)): id = i min = l[i] for j in range(i+1,len(l)): if l[j] < min: min = l[j] id = j if l[i] != l[id]: res.append((i, id)) l[i], l[id] = l[id], l[i] print(len(res)) for l in res: print(l[0], l[1]) ```
instruction
0
39,084
12
78,168
Yes
output
1
39,084
12
78,169
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem your goal is to sort an array consisting of n integers in at most n swaps. For the given array find the sequence of swaps that makes the array sorted in the non-descending order. Swaps are performed consecutively, one after another. Note that in this problem you do not have to minimize the number of swaps — your task is to find any sequence that is no longer than n. Input The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of array elements. The second line contains elements of array: a0, a1, ..., an - 1 ( - 109 ≤ ai ≤ 109), where ai is the i-th element of the array. The elements are numerated from 0 to n - 1 from left to right. Some integers may appear in the array more than once. Output In the first line print k (0 ≤ k ≤ n) — the number of swaps. Next k lines must contain the descriptions of the k swaps, one per line. Each swap should be printed as a pair of integers i, j (0 ≤ i, j ≤ n - 1), representing the swap of elements ai and aj. You can print indices in the pairs in any order. The swaps are performed in the order they appear in the output, from the first to the last. It is allowed to print i = j and swap the same pair of elements multiple times. If there are multiple answers, print any of them. It is guaranteed that at least one answer exists. Examples Input 5 5 2 5 1 4 Output 2 0 3 4 2 Input 6 10 20 20 40 60 60 Output 0 Input 2 101 100 Output 1 0 1 Submitted Solution: ``` from math import * from collections import * n = int(input()) a = list(map(int,input().split())) ans = [] for i in range(n): m = 0 for j in range(n-i): if(a[j] > a[m]): m = j if(a[m] != a[n-i-1]): ans.append([m,n-i-1]) a[m],a[n-i-1] = a[n-i-1],a[m] print(len(ans)) for i in ans: print(i[0],i[1]) ```
instruction
0
39,085
12
78,170
Yes
output
1
39,085
12
78,171
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem your goal is to sort an array consisting of n integers in at most n swaps. For the given array find the sequence of swaps that makes the array sorted in the non-descending order. Swaps are performed consecutively, one after another. Note that in this problem you do not have to minimize the number of swaps — your task is to find any sequence that is no longer than n. Input The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of array elements. The second line contains elements of array: a0, a1, ..., an - 1 ( - 109 ≤ ai ≤ 109), where ai is the i-th element of the array. The elements are numerated from 0 to n - 1 from left to right. Some integers may appear in the array more than once. Output In the first line print k (0 ≤ k ≤ n) — the number of swaps. Next k lines must contain the descriptions of the k swaps, one per line. Each swap should be printed as a pair of integers i, j (0 ≤ i, j ≤ n - 1), representing the swap of elements ai and aj. You can print indices in the pairs in any order. The swaps are performed in the order they appear in the output, from the first to the last. It is allowed to print i = j and swap the same pair of elements multiple times. If there are multiple answers, print any of them. It is guaranteed that at least one answer exists. Examples Input 5 5 2 5 1 4 Output 2 0 3 4 2 Input 6 10 20 20 40 60 60 Output 0 Input 2 101 100 Output 1 0 1 Submitted Solution: ``` def arr_enu(): return [[i, int(x)] for i, x in enumerate(input().split())] n, a = int(input()), arr_enu() a.sort(key=lambda x: x[1]) arr = set() for i in range(n): if i < a[i][0]: arr.add(tuple(sorted([i, a[i][0]]))) l,arr=len(arr),list(arr) print(l) for i in range(l): print(arr[i][0], arr[i][1]) ```
instruction
0
39,086
12
78,172
No
output
1
39,086
12
78,173
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem your goal is to sort an array consisting of n integers in at most n swaps. For the given array find the sequence of swaps that makes the array sorted in the non-descending order. Swaps are performed consecutively, one after another. Note that in this problem you do not have to minimize the number of swaps — your task is to find any sequence that is no longer than n. Input The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of array elements. The second line contains elements of array: a0, a1, ..., an - 1 ( - 109 ≤ ai ≤ 109), where ai is the i-th element of the array. The elements are numerated from 0 to n - 1 from left to right. Some integers may appear in the array more than once. Output In the first line print k (0 ≤ k ≤ n) — the number of swaps. Next k lines must contain the descriptions of the k swaps, one per line. Each swap should be printed as a pair of integers i, j (0 ≤ i, j ≤ n - 1), representing the swap of elements ai and aj. You can print indices in the pairs in any order. The swaps are performed in the order they appear in the output, from the first to the last. It is allowed to print i = j and swap the same pair of elements multiple times. If there are multiple answers, print any of them. It is guaranteed that at least one answer exists. Examples Input 5 5 2 5 1 4 Output 2 0 3 4 2 Input 6 10 20 20 40 60 60 Output 0 Input 2 101 100 Output 1 0 1 Submitted Solution: ``` n=int(input()) p=input().rstrip().split(' ') C=list(p) C.sort(key=int) l=[] q=[] D=0; for i in range(0,len(C)): if int(C[i])!=int(p[i]): v=p.index(C[i]) temp=p[i]; p[i]=p[v]; p[v]=temp; l.append(i) q.append(v) D+=1; print(D) for i in range(0,len(l)): print(l[i],q[i]) ```
instruction
0
39,087
12
78,174
No
output
1
39,087
12
78,175
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem your goal is to sort an array consisting of n integers in at most n swaps. For the given array find the sequence of swaps that makes the array sorted in the non-descending order. Swaps are performed consecutively, one after another. Note that in this problem you do not have to minimize the number of swaps — your task is to find any sequence that is no longer than n. Input The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of array elements. The second line contains elements of array: a0, a1, ..., an - 1 ( - 109 ≤ ai ≤ 109), where ai is the i-th element of the array. The elements are numerated from 0 to n - 1 from left to right. Some integers may appear in the array more than once. Output In the first line print k (0 ≤ k ≤ n) — the number of swaps. Next k lines must contain the descriptions of the k swaps, one per line. Each swap should be printed as a pair of integers i, j (0 ≤ i, j ≤ n - 1), representing the swap of elements ai and aj. You can print indices in the pairs in any order. The swaps are performed in the order they appear in the output, from the first to the last. It is allowed to print i = j and swap the same pair of elements multiple times. If there are multiple answers, print any of them. It is guaranteed that at least one answer exists. Examples Input 5 5 2 5 1 4 Output 2 0 3 4 2 Input 6 10 20 20 40 60 60 Output 0 Input 2 101 100 Output 1 0 1 Submitted Solution: ``` n=int(input()) a=list(map(int,input().split())) b=[] for i in range(n): b.append([a[i],i]) b.sort() d=[0]*n for i in range(n): d[b[i][1]]=i b=a.copy() b.sort() p=[0]*n c=[] for i in range(n): if p[i]==0: j=i k=d[j] while(p[k]==0 and k!=i): p[k]=1 c.append([j,k]) k=d[j] j=k n=len(c) print(n) for i in range(n): print(c[i][0],c[i][1]) ```
instruction
0
39,088
12
78,176
No
output
1
39,088
12
78,177
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem your goal is to sort an array consisting of n integers in at most n swaps. For the given array find the sequence of swaps that makes the array sorted in the non-descending order. Swaps are performed consecutively, one after another. Note that in this problem you do not have to minimize the number of swaps — your task is to find any sequence that is no longer than n. Input The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of array elements. The second line contains elements of array: a0, a1, ..., an - 1 ( - 109 ≤ ai ≤ 109), where ai is the i-th element of the array. The elements are numerated from 0 to n - 1 from left to right. Some integers may appear in the array more than once. Output In the first line print k (0 ≤ k ≤ n) — the number of swaps. Next k lines must contain the descriptions of the k swaps, one per line. Each swap should be printed as a pair of integers i, j (0 ≤ i, j ≤ n - 1), representing the swap of elements ai and aj. You can print indices in the pairs in any order. The swaps are performed in the order they appear in the output, from the first to the last. It is allowed to print i = j and swap the same pair of elements multiple times. If there are multiple answers, print any of them. It is guaranteed that at least one answer exists. Examples Input 5 5 2 5 1 4 Output 2 0 3 4 2 Input 6 10 20 20 40 60 60 Output 0 Input 2 101 100 Output 1 0 1 Submitted Solution: ``` def getMin(arr): min = arr[0] for a in arr: if a < min: min = a return min numel = input("") elem = list(map(int, input("").split())) swaps = [] i = 0 count = 0 while i < len(elem): minelem = getMin(elem[i:]) minindex = elem.index(minelem) if not (elem[i:][0] == minelem): temp = elem[i] elem[i] = minelem elem[minindex] = temp swap = [i, minindex] swaps += [swap, ] count += 1 i += 1 print(count) for k in swaps: print(k[0], " ", k[1]) ```
instruction
0
39,089
12
78,178
No
output
1
39,089
12
78,179
Provide tags and a correct Python 3 solution for this coding contest problem. Leha like all kinds of strange things. Recently he liked the function F(n, k). Consider all possible k-element subsets of the set [1, 2, ..., n]. For subset find minimal element in it. F(n, k) — mathematical expectation of the minimal element among all k-element subsets. But only function does not interest him. He wants to do interesting things with it. Mom brought him two arrays A and B, each consists of m integers. For all i, j such that 1 ≤ i, j ≤ m the condition Ai ≥ Bj holds. Help Leha rearrange the numbers in the array A so that the sum <image> is maximally possible, where A' is already rearranged array. Input First line of input data contains single integer m (1 ≤ m ≤ 2·105) — length of arrays A and B. Next line contains m integers a1, a2, ..., am (1 ≤ ai ≤ 109) — array A. Next line contains m integers b1, b2, ..., bm (1 ≤ bi ≤ 109) — array B. Output Output m integers a'1, a'2, ..., a'm — array A' which is permutation of the array A. Examples Input 5 7 3 5 3 4 2 1 3 2 3 Output 4 7 3 5 3 Input 7 4 6 5 8 8 2 6 2 1 2 2 1 1 2 Output 2 6 4 5 8 8 6
instruction
0
39,259
12
78,518
Tags: combinatorics, greedy, math, number theory, sortings Correct Solution: ``` m = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) b_s = sorted(b) a_s = sorted(a, reverse = True) d = {} ans = [0 for i in range(m)] for i in range(m): d[b_s[i]] = d.get(b_s[i], []) d[b_s[i]].append(a_s[i]) last = {} for i in range(m): last[b[i]] = last.get(b[i], -1)+1 ans[i] = d.get(b[i])[last[b[i]]] print(*ans) ```
output
1
39,259
12
78,519