message stringlengths 2 433k | message_type stringclasses 2
values | message_id int64 0 1 | conversation_id int64 113 108k | cluster float64 12 12 | __index_level_0__ int64 226 217k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
An array is called beautiful if all the elements in the array are equal.
You can transform an array using the following steps any number of times:
1. Choose two indices i and j (1 ≤ i,j ≤ n), and an integer x (1 ≤ x ≤ a_i). Let i be the source index and j be the sink index.
2. Decrease the i-th element by x, and increase the j-th element by x. The resulting values at i-th and j-th index are a_i-x and a_j+x respectively.
3. The cost of this operation is x ⋅ |j-i| .
4. Now the i-th index can no longer be the sink and the j-th index can no longer be the source.
The total cost of a transformation is the sum of all the costs in step 3.
For example, array [0, 2, 3, 3] can be transformed into a beautiful array [2, 2, 2, 2] with total cost 1 ⋅ |1-3| + 1 ⋅ |1-4| = 5.
An array is called balanced, if it can be transformed into a beautiful array, and the cost of such transformation is uniquely defined. In other words, the minimum cost of transformation into a beautiful array equals the maximum cost.
You are given an array a_1, a_2, …, a_n of length n, consisting of non-negative integers. Your task is to find the number of balanced arrays which are permutations of the given array. Two arrays are considered different, if elements at some position differ. Since the answer can be large, output it modulo 10^9 + 7.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the size of the array.
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9).
Output
Output a single integer — the number of balanced permutations modulo 10^9+7.
Examples
Input
3
1 2 3
Output
6
Input
4
0 4 0 4
Output
2
Input
5
0 11 12 13 14
Output
120
Note
In the first example, [1, 2, 3] is a valid permutation as we can consider the index with value 3 as the source and index with value 1 as the sink. Thus, after conversion we get a beautiful array [2, 2, 2], and the total cost would be 2. We can show that this is the only transformation of this array that leads to a beautiful array. Similarly, we can check for other permutations too.
In the second example, [0, 0, 4, 4] and [4, 4, 0, 0] are balanced permutations.
In the third example, all permutations are balanced. | instruction | 0 | 29,372 | 12 | 58,744 |
Tags: combinatorics, constructive algorithms, math, sortings
Correct Solution:
```
import sys
from sys import stdin
def modfac(n, MOD):
f = 1
factorials = [1]
for m in range(1, n + 1):
f *= m
f %= MOD
factorials.append(f)
inv = pow(f, MOD - 2, MOD)
invs = [1] * (n + 1)
invs[n] = inv
for m in range(n, 1, -1):
inv *= m
inv %= MOD
invs[m - 1] = inv
return factorials, invs
def modnCr(n,r,mod,fac,inv):
return fac[n] * inv[n-r] * inv[r] % mod
mod = 10**9+7
fac,inv = modfac(100010,mod)
tt = 1
ANS = []
for loop in range(tt):
n = int(stdin.readline())
a = list(map(int,stdin.readline().split()))
allsum = sum(a)
if allsum % n != 0:
ANS.append("0")
continue
dic = {}
s = 0
d = 0
mid = 0
border = allsum // n
for i in a:
if i not in dic:
dic[i] = 1
else:
dic[i] += 1
if i > border:
s += 1
elif i == border:
mid += 1
else:
d += 1
print (s,d,mid,file=sys.stderr)
if min(s,d) <= 1:
nans = fac[n]
for i in dic:
nans *= inv[dic[i]]
nans %= mod
ANS.append(str(nans))
else:
nans = modnCr(n,mid,mod,fac,inv) * fac[s] * fac[d] * fac[mid] * 2 % mod
for i in dic:
nans *= inv[dic[i]]
nans %= mod
ANS.append(str(nans))
print ("\n".join(ANS))
``` | output | 1 | 29,372 | 12 | 58,745 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
An array is called beautiful if all the elements in the array are equal.
You can transform an array using the following steps any number of times:
1. Choose two indices i and j (1 ≤ i,j ≤ n), and an integer x (1 ≤ x ≤ a_i). Let i be the source index and j be the sink index.
2. Decrease the i-th element by x, and increase the j-th element by x. The resulting values at i-th and j-th index are a_i-x and a_j+x respectively.
3. The cost of this operation is x ⋅ |j-i| .
4. Now the i-th index can no longer be the sink and the j-th index can no longer be the source.
The total cost of a transformation is the sum of all the costs in step 3.
For example, array [0, 2, 3, 3] can be transformed into a beautiful array [2, 2, 2, 2] with total cost 1 ⋅ |1-3| + 1 ⋅ |1-4| = 5.
An array is called balanced, if it can be transformed into a beautiful array, and the cost of such transformation is uniquely defined. In other words, the minimum cost of transformation into a beautiful array equals the maximum cost.
You are given an array a_1, a_2, …, a_n of length n, consisting of non-negative integers. Your task is to find the number of balanced arrays which are permutations of the given array. Two arrays are considered different, if elements at some position differ. Since the answer can be large, output it modulo 10^9 + 7.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the size of the array.
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9).
Output
Output a single integer — the number of balanced permutations modulo 10^9+7.
Examples
Input
3
1 2 3
Output
6
Input
4
0 4 0 4
Output
2
Input
5
0 11 12 13 14
Output
120
Note
In the first example, [1, 2, 3] is a valid permutation as we can consider the index with value 3 as the source and index with value 1 as the sink. Thus, after conversion we get a beautiful array [2, 2, 2], and the total cost would be 2. We can show that this is the only transformation of this array that leads to a beautiful array. Similarly, we can check for other permutations too.
In the second example, [0, 0, 4, 4] and [4, 4, 0, 0] are balanced permutations.
In the third example, all permutations are balanced.
Submitted Solution:
```
a=*map(int,[*open(0)][1].split()),;n=len(a);s=sum(a)
if s%n:exit(print(0))
M=10**9+7;s//=n;f=[1]*(n+1);b=[0]*3;d=dict()
for i in range(2,n+1):f[i]=f[i-1]*i%M
for x in a:b[(x>s)-(x<s)]+=1;d[x]=d[x]+1if x in d else 1
k=1
for x in d:k*=f[d[x]]
print([1,f[b[1]]*f[b[-1]]*2*pow(f[n-b[0]],M-2,M)][b[1]>1and b[-1]>1]*f[n]*pow(k,M-2,M)%M)
``` | instruction | 0 | 29,373 | 12 | 58,746 |
Yes | output | 1 | 29,373 | 12 | 58,747 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
An array is called beautiful if all the elements in the array are equal.
You can transform an array using the following steps any number of times:
1. Choose two indices i and j (1 ≤ i,j ≤ n), and an integer x (1 ≤ x ≤ a_i). Let i be the source index and j be the sink index.
2. Decrease the i-th element by x, and increase the j-th element by x. The resulting values at i-th and j-th index are a_i-x and a_j+x respectively.
3. The cost of this operation is x ⋅ |j-i| .
4. Now the i-th index can no longer be the sink and the j-th index can no longer be the source.
The total cost of a transformation is the sum of all the costs in step 3.
For example, array [0, 2, 3, 3] can be transformed into a beautiful array [2, 2, 2, 2] with total cost 1 ⋅ |1-3| + 1 ⋅ |1-4| = 5.
An array is called balanced, if it can be transformed into a beautiful array, and the cost of such transformation is uniquely defined. In other words, the minimum cost of transformation into a beautiful array equals the maximum cost.
You are given an array a_1, a_2, …, a_n of length n, consisting of non-negative integers. Your task is to find the number of balanced arrays which are permutations of the given array. Two arrays are considered different, if elements at some position differ. Since the answer can be large, output it modulo 10^9 + 7.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the size of the array.
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9).
Output
Output a single integer — the number of balanced permutations modulo 10^9+7.
Examples
Input
3
1 2 3
Output
6
Input
4
0 4 0 4
Output
2
Input
5
0 11 12 13 14
Output
120
Note
In the first example, [1, 2, 3] is a valid permutation as we can consider the index with value 3 as the source and index with value 1 as the sink. Thus, after conversion we get a beautiful array [2, 2, 2], and the total cost would be 2. We can show that this is the only transformation of this array that leads to a beautiful array. Similarly, we can check for other permutations too.
In the second example, [0, 0, 4, 4] and [4, 4, 0, 0] are balanced permutations.
In the third example, all permutations are balanced.
Submitted Solution:
```
import sys
input = sys.stdin.readline
from collections import Counter
mod=10**9+7
FACT=[1]
for i in range(1,2*10**5+1):
FACT.append(FACT[-1]*i%mod)
FACT_INV=[pow(FACT[-1],mod-2,mod)]
for i in range(2*10**5,0,-1):
FACT_INV.append(FACT_INV[-1]*i%mod)
FACT_INV.reverse()
def Combi(a,b):
if 0<=b<=a:
return FACT[a]*FACT_INV[b]%mod*FACT_INV[a-b]%mod
else:
return 0
n=int(input())
A=list(map(int,input().split()))
S=sum(A)
if S%n!=0:
print(0)
exit()
B=S//n
MINUS=[]
PLUS=[]
EQ=0
for a in A:
if a<B:
MINUS.append(a)
elif a==B:
EQ+=1
else:
PLUS.append(a)
#print(MINUS,PLUS,EQ)
if len(PLUS)==0 or len(MINUS)==0:
print(1)
elif len(PLUS)==1 or len(MINUS)==1:
C=Counter(A)
ANS=1
now=n
for v in C.values():
ANS=ANS*Combi(now,v)%mod
now-=v
print(ANS)
else:
ANSEQ=Combi(n,EQ)
now=len(MINUS)
C=Counter(MINUS)
ANSM=1
for v in C.values():
ANSM=ANSM*Combi(now,v)%mod
now-=v
now=len(PLUS)
C=Counter(PLUS)
ANSP=1
for v in C.values():
ANSP=ANSP*Combi(now,v)%mod
now-=v
print(2*ANSEQ*ANSM*ANSP%mod)
``` | instruction | 0 | 29,374 | 12 | 58,748 |
Yes | output | 1 | 29,374 | 12 | 58,749 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
An array is called beautiful if all the elements in the array are equal.
You can transform an array using the following steps any number of times:
1. Choose two indices i and j (1 ≤ i,j ≤ n), and an integer x (1 ≤ x ≤ a_i). Let i be the source index and j be the sink index.
2. Decrease the i-th element by x, and increase the j-th element by x. The resulting values at i-th and j-th index are a_i-x and a_j+x respectively.
3. The cost of this operation is x ⋅ |j-i| .
4. Now the i-th index can no longer be the sink and the j-th index can no longer be the source.
The total cost of a transformation is the sum of all the costs in step 3.
For example, array [0, 2, 3, 3] can be transformed into a beautiful array [2, 2, 2, 2] with total cost 1 ⋅ |1-3| + 1 ⋅ |1-4| = 5.
An array is called balanced, if it can be transformed into a beautiful array, and the cost of such transformation is uniquely defined. In other words, the minimum cost of transformation into a beautiful array equals the maximum cost.
You are given an array a_1, a_2, …, a_n of length n, consisting of non-negative integers. Your task is to find the number of balanced arrays which are permutations of the given array. Two arrays are considered different, if elements at some position differ. Since the answer can be large, output it modulo 10^9 + 7.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the size of the array.
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9).
Output
Output a single integer — the number of balanced permutations modulo 10^9+7.
Examples
Input
3
1 2 3
Output
6
Input
4
0 4 0 4
Output
2
Input
5
0 11 12 13 14
Output
120
Note
In the first example, [1, 2, 3] is a valid permutation as we can consider the index with value 3 as the source and index with value 1 as the sink. Thus, after conversion we get a beautiful array [2, 2, 2], and the total cost would be 2. We can show that this is the only transformation of this array that leads to a beautiful array. Similarly, we can check for other permutations too.
In the second example, [0, 0, 4, 4] and [4, 4, 0, 0] are balanced permutations.
In the third example, all permutations are balanced.
Submitted Solution:
```
from collections import defaultdict
p = 1_000_000_007
fact = [0]*100_001
fact[0] = 1
for i in range(1,100_001):
fact[i] = (fact[i-1]*i)%p
def fast_exp(x,n):
if n == 0:
return 1
if n%2 == 1:
return (x*fast_exp(x,n-1))%p
return fast_exp((x*x)%p, n//2)
n = int(input())
l = [int(x) for x in input().split()]
mean = sum(l)//n
if n*mean != sum(l):
print(0)
else:
low = defaultdict(int)
high = defaultdict(int)
n_low = 0
n_high = 0
neut = 0
for x in l:
if x < mean:
low[x] += 1
n_low += 1
elif x > mean:
high[x] += 1
n_high += 1
else:
neut += 1
if n_low == 1 or n_high == 1:
res = fact[n]
for x in low:
res = (res*fast_exp(fact[low[x]], p-2))%p
for x in high:
res = (res*fast_exp(fact[high[x]], p-2))%p
res = (res*fast_exp(fact[neut], p-2))%p
print(res)
elif n_low == 0 or n_high == 0:
print(1)
else:
res = 2
res = (res*fact[n_low])%p
for x in low:
res = (res*fast_exp(fact[low[x]], p-2))%p
res = (res*fact[n_high])%p
for x in high:
res = (res*fast_exp(fact[high[x]], p-2))%p
res = (res * fact[n])%p
res = (res * fast_exp(fact[n_low + n_high], p-2))%p
res = (res * fast_exp(fact[neut], p-2))%p
print(res)
``` | instruction | 0 | 29,375 | 12 | 58,750 |
Yes | output | 1 | 29,375 | 12 | 58,751 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
An array is called beautiful if all the elements in the array are equal.
You can transform an array using the following steps any number of times:
1. Choose two indices i and j (1 ≤ i,j ≤ n), and an integer x (1 ≤ x ≤ a_i). Let i be the source index and j be the sink index.
2. Decrease the i-th element by x, and increase the j-th element by x. The resulting values at i-th and j-th index are a_i-x and a_j+x respectively.
3. The cost of this operation is x ⋅ |j-i| .
4. Now the i-th index can no longer be the sink and the j-th index can no longer be the source.
The total cost of a transformation is the sum of all the costs in step 3.
For example, array [0, 2, 3, 3] can be transformed into a beautiful array [2, 2, 2, 2] with total cost 1 ⋅ |1-3| + 1 ⋅ |1-4| = 5.
An array is called balanced, if it can be transformed into a beautiful array, and the cost of such transformation is uniquely defined. In other words, the minimum cost of transformation into a beautiful array equals the maximum cost.
You are given an array a_1, a_2, …, a_n of length n, consisting of non-negative integers. Your task is to find the number of balanced arrays which are permutations of the given array. Two arrays are considered different, if elements at some position differ. Since the answer can be large, output it modulo 10^9 + 7.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the size of the array.
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9).
Output
Output a single integer — the number of balanced permutations modulo 10^9+7.
Examples
Input
3
1 2 3
Output
6
Input
4
0 4 0 4
Output
2
Input
5
0 11 12 13 14
Output
120
Note
In the first example, [1, 2, 3] is a valid permutation as we can consider the index with value 3 as the source and index with value 1 as the sink. Thus, after conversion we get a beautiful array [2, 2, 2], and the total cost would be 2. We can show that this is the only transformation of this array that leads to a beautiful array. Similarly, we can check for other permutations too.
In the second example, [0, 0, 4, 4] and [4, 4, 0, 0] are balanced permutations.
In the third example, all permutations are balanced.
Submitted Solution:
```
a=*map(int,[*open(0)][1].split()),;n=len(a);s=sum(a)
if s%n:exit(print(0))
M=10**9+7;f=[1]*(n+1);b=[0]*3;d={};k=1
for i in range(2,n+1):f[i]=f[i-1]*i%M
for x in a:b[(n*x>s)-(n*x<s)]+=1;d[x]=d[x]+1if x in d else 1
for x in d:k*=f[d[x]]
A,B,C=b;print([1,f[B]*f[C]*2*pow(f[n-A],M-2,M)][B>1and C>1]*f[n]*pow(k,M-2,M)%M)
``` | instruction | 0 | 29,376 | 12 | 58,752 |
Yes | output | 1 | 29,376 | 12 | 58,753 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
An array is called beautiful if all the elements in the array are equal.
You can transform an array using the following steps any number of times:
1. Choose two indices i and j (1 ≤ i,j ≤ n), and an integer x (1 ≤ x ≤ a_i). Let i be the source index and j be the sink index.
2. Decrease the i-th element by x, and increase the j-th element by x. The resulting values at i-th and j-th index are a_i-x and a_j+x respectively.
3. The cost of this operation is x ⋅ |j-i| .
4. Now the i-th index can no longer be the sink and the j-th index can no longer be the source.
The total cost of a transformation is the sum of all the costs in step 3.
For example, array [0, 2, 3, 3] can be transformed into a beautiful array [2, 2, 2, 2] with total cost 1 ⋅ |1-3| + 1 ⋅ |1-4| = 5.
An array is called balanced, if it can be transformed into a beautiful array, and the cost of such transformation is uniquely defined. In other words, the minimum cost of transformation into a beautiful array equals the maximum cost.
You are given an array a_1, a_2, …, a_n of length n, consisting of non-negative integers. Your task is to find the number of balanced arrays which are permutations of the given array. Two arrays are considered different, if elements at some position differ. Since the answer can be large, output it modulo 10^9 + 7.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the size of the array.
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9).
Output
Output a single integer — the number of balanced permutations modulo 10^9+7.
Examples
Input
3
1 2 3
Output
6
Input
4
0 4 0 4
Output
2
Input
5
0 11 12 13 14
Output
120
Note
In the first example, [1, 2, 3] is a valid permutation as we can consider the index with value 3 as the source and index with value 1 as the sink. Thus, after conversion we get a beautiful array [2, 2, 2], and the total cost would be 2. We can show that this is the only transformation of this array that leads to a beautiful array. Similarly, we can check for other permutations too.
In the second example, [0, 0, 4, 4] and [4, 4, 0, 0] are balanced permutations.
In the third example, all permutations are balanced.
Submitted Solution:
```
# -*- coding: utf-8 -*-
class FactMod():
def __init__(self, n, mod):
self.mod = mod
self.f = [1]*(n+1)
for i in range(1, n+1):
self.f[i] = self.f[i-1]*i % mod
self.inv_f = [pow(self.f[-1], mod-2, mod)]
for i in range(1, n+1)[::-1]:
self.inv_f.append(self.inv_f[-1]*i % mod)
self.inv_f.reverse()
def fact(self, n):
return self.f[n]
def comb(self, n, r):
if r==0:
return 1
ret = self.f[n] * self.inv_f[n-r]*self.inv_f[r]
ret %= self.mod
return ret
def perm(self, n, r):
ret = self.f[n] * self.inv_f[n-r]
ret %= self.mod
return ret
def div(self,x,y):
return (x*pow(y,self.mod-2,self.mod))%self.mod
N = int(input())
L = list(map(int,input().split()))
MOD=10**9+7
avg = sum(L)/N
F = FactMod(N,MOD)
if avg==int(avg):
s = len(set(L))
ans = F.fact(s)
else:
ans=0
print(ans)
``` | instruction | 0 | 29,377 | 12 | 58,754 |
No | output | 1 | 29,377 | 12 | 58,755 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
An array is called beautiful if all the elements in the array are equal.
You can transform an array using the following steps any number of times:
1. Choose two indices i and j (1 ≤ i,j ≤ n), and an integer x (1 ≤ x ≤ a_i). Let i be the source index and j be the sink index.
2. Decrease the i-th element by x, and increase the j-th element by x. The resulting values at i-th and j-th index are a_i-x and a_j+x respectively.
3. The cost of this operation is x ⋅ |j-i| .
4. Now the i-th index can no longer be the sink and the j-th index can no longer be the source.
The total cost of a transformation is the sum of all the costs in step 3.
For example, array [0, 2, 3, 3] can be transformed into a beautiful array [2, 2, 2, 2] with total cost 1 ⋅ |1-3| + 1 ⋅ |1-4| = 5.
An array is called balanced, if it can be transformed into a beautiful array, and the cost of such transformation is uniquely defined. In other words, the minimum cost of transformation into a beautiful array equals the maximum cost.
You are given an array a_1, a_2, …, a_n of length n, consisting of non-negative integers. Your task is to find the number of balanced arrays which are permutations of the given array. Two arrays are considered different, if elements at some position differ. Since the answer can be large, output it modulo 10^9 + 7.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the size of the array.
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9).
Output
Output a single integer — the number of balanced permutations modulo 10^9+7.
Examples
Input
3
1 2 3
Output
6
Input
4
0 4 0 4
Output
2
Input
5
0 11 12 13 14
Output
120
Note
In the first example, [1, 2, 3] is a valid permutation as we can consider the index with value 3 as the source and index with value 1 as the sink. Thus, after conversion we get a beautiful array [2, 2, 2], and the total cost would be 2. We can show that this is the only transformation of this array that leads to a beautiful array. Similarly, we can check for other permutations too.
In the second example, [0, 0, 4, 4] and [4, 4, 0, 0] are balanced permutations.
In the third example, all permutations are balanced.
Submitted Solution:
```
from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush,heappop
import math
from collections import *
from functools import reduce,cmp_to_key,lru_cache
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
import sys
# input = sys.stdin.readline
M = mod = 10**9 + 7
def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
def inv_mod(n):return pow(n, mod - 2, mod)
def li():return [int(i) for i in input().rstrip().split()]
def st():return str(input().rstrip())[2:-1]
def val():return int(input().rstrip())
def li2():return [str(i)[2:-1] for i in input().rstrip().split()]
def li3():return [int(i) for i in st()]
N = 10 ** 5 + 10
facts = [1]
for i in range(1, N):
facts.append(facts[-1] * i % mod)
inversemods = [0 for i in range(N)]
inversemods[-1] = inv_mod(facts[-1]) % mod
for i in range(N - 2, -1, -1):
inversemods[i] = inversemods[i + 1] * (i + 1) % mod
def ncr(n, r):
if n < r:return 0
return facts[n] * inversemods[n - r] * inversemods[r] % mod
n = val()
l = sorted(li())
s = sum(l)
if s % n:
print(0)
exit()
midvalue = s // n
mid = low = high = 0
cnt1 = Counter()
cnt2 = Counter()
for i in range(n):
if l[i] < midvalue:
low += 1
cnt1[l[i]] += 1
elif l[i] > midvalue:
high += 1
cnt2[l[i]] += 1
else:mid += 1
ans = 1
if low == high == 0:
print(1)
exit()
if low == 1 or high == 1:
ans = facts[n]
for i in (cnt1 + cnt2).values():ans = (ans * inversemods[i]) % mod
print(ans)
exit()
if mid:
ans = ncr(n, mid)
ans = (ans * facts[low]) % mod
for i in cnt1.values():ans = (ans * inversemods[i]) % mod
ans = (ans * facts[high]) % mod
for i in cnt2.values():ans = (ans * inversemods[i]) % mod
ans = (ans * 2) % mod
print(ans)
``` | instruction | 0 | 29,378 | 12 | 58,756 |
No | output | 1 | 29,378 | 12 | 58,757 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
An array is called beautiful if all the elements in the array are equal.
You can transform an array using the following steps any number of times:
1. Choose two indices i and j (1 ≤ i,j ≤ n), and an integer x (1 ≤ x ≤ a_i). Let i be the source index and j be the sink index.
2. Decrease the i-th element by x, and increase the j-th element by x. The resulting values at i-th and j-th index are a_i-x and a_j+x respectively.
3. The cost of this operation is x ⋅ |j-i| .
4. Now the i-th index can no longer be the sink and the j-th index can no longer be the source.
The total cost of a transformation is the sum of all the costs in step 3.
For example, array [0, 2, 3, 3] can be transformed into a beautiful array [2, 2, 2, 2] with total cost 1 ⋅ |1-3| + 1 ⋅ |1-4| = 5.
An array is called balanced, if it can be transformed into a beautiful array, and the cost of such transformation is uniquely defined. In other words, the minimum cost of transformation into a beautiful array equals the maximum cost.
You are given an array a_1, a_2, …, a_n of length n, consisting of non-negative integers. Your task is to find the number of balanced arrays which are permutations of the given array. Two arrays are considered different, if elements at some position differ. Since the answer can be large, output it modulo 10^9 + 7.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the size of the array.
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9).
Output
Output a single integer — the number of balanced permutations modulo 10^9+7.
Examples
Input
3
1 2 3
Output
6
Input
4
0 4 0 4
Output
2
Input
5
0 11 12 13 14
Output
120
Note
In the first example, [1, 2, 3] is a valid permutation as we can consider the index with value 3 as the source and index with value 1 as the sink. Thus, after conversion we get a beautiful array [2, 2, 2], and the total cost would be 2. We can show that this is the only transformation of this array that leads to a beautiful array. Similarly, we can check for other permutations too.
In the second example, [0, 0, 4, 4] and [4, 4, 0, 0] are balanced permutations.
In the third example, all permutations are balanced.
Submitted Solution:
```
from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush,heappop
import math
from collections import *
from functools import reduce,cmp_to_key,lru_cache
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
import sys
# input = sys.stdin.readline
M = mod = 10**9 + 7
def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
def inv_mod(n):return pow(n, mod - 2, mod)
def li():return [int(i) for i in input().rstrip().split()]
def st():return str(input().rstrip())[2:-1]
def val():return int(input().rstrip())
def li2():return [str(i)[2:-1] for i in input().rstrip().split()]
def li3():return [int(i) for i in st()]
N = 10 ** 5 + 10
facts = [1]
for i in range(1, N):
facts.append(facts[-1] * i % mod)
inversemods = [0 for i in range(N)]
inversemods[-1] = inv_mod(facts[-1]) % mod
for i in range(N - 2, -1, -1):
inversemods[i] = inversemods[i + 1] * (i + 1) % mod
def ncr(n, r):
if n < r:return 0
return facts[n] * inversemods[n - r] * inversemods[r] % mod
n = val()
l = sorted(li())
s = sum(l)
if s % n:
print(0)
exit()
midvalue = s // n
mid = low = high = 0
cnt1 = Counter()
cnt2 = Counter()
for i in range(n):
if l[i] < midvalue:
low += 1
cnt1[l[i]] += 1
elif l[i] > midvalue:
high += 1
cnt2[l[i]] += 1
else:mid += 1
ans = 1
if low == high == 0:
print(1)
exit()
if low == 1 or high == 1:
ans = facts[n]
for i in (cnt1).values():ans = (ans * inversemods[i]) % mod
for i in (cnt2).values():ans = (ans * inversemods[i]) % mod
print(ans)
exit()
if mid:
ans = ncr(n, mid)
ans = (ans * facts[low]) % mod
for i in cnt1.values():ans = (ans * inversemods[i]) % mod
ans = (ans * facts[high]) % mod
for i in cnt2.values():ans = (ans * inversemods[i]) % mod
ans = (ans * 2) % mod
print(ans)
``` | instruction | 0 | 29,379 | 12 | 58,758 |
No | output | 1 | 29,379 | 12 | 58,759 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
An array is called beautiful if all the elements in the array are equal.
You can transform an array using the following steps any number of times:
1. Choose two indices i and j (1 ≤ i,j ≤ n), and an integer x (1 ≤ x ≤ a_i). Let i be the source index and j be the sink index.
2. Decrease the i-th element by x, and increase the j-th element by x. The resulting values at i-th and j-th index are a_i-x and a_j+x respectively.
3. The cost of this operation is x ⋅ |j-i| .
4. Now the i-th index can no longer be the sink and the j-th index can no longer be the source.
The total cost of a transformation is the sum of all the costs in step 3.
For example, array [0, 2, 3, 3] can be transformed into a beautiful array [2, 2, 2, 2] with total cost 1 ⋅ |1-3| + 1 ⋅ |1-4| = 5.
An array is called balanced, if it can be transformed into a beautiful array, and the cost of such transformation is uniquely defined. In other words, the minimum cost of transformation into a beautiful array equals the maximum cost.
You are given an array a_1, a_2, …, a_n of length n, consisting of non-negative integers. Your task is to find the number of balanced arrays which are permutations of the given array. Two arrays are considered different, if elements at some position differ. Since the answer can be large, output it modulo 10^9 + 7.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the size of the array.
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9).
Output
Output a single integer — the number of balanced permutations modulo 10^9+7.
Examples
Input
3
1 2 3
Output
6
Input
4
0 4 0 4
Output
2
Input
5
0 11 12 13 14
Output
120
Note
In the first example, [1, 2, 3] is a valid permutation as we can consider the index with value 3 as the source and index with value 1 as the sink. Thus, after conversion we get a beautiful array [2, 2, 2], and the total cost would be 2. We can show that this is the only transformation of this array that leads to a beautiful array. Similarly, we can check for other permutations too.
In the second example, [0, 0, 4, 4] and [4, 4, 0, 0] are balanced permutations.
In the third example, all permutations are balanced.
Submitted Solution:
```
from bisect import *
from collections import *
from math import gcd,ceil,sqrt,floor,inf
from heapq import *
from itertools import *
from operator import add,mul,sub,xor,truediv,floordiv
from functools import *
#------------------------------------------------------------------------
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#------------------------------------------------------------------------
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def A(n):return [0]*n
def AI(n,x): return [x]*n
def A2(n,m): return [[0]*m for i in range(n)]
def G(n): return [[] for i in range(n)]
def GP(it): return [[ch,len(list(g))] for ch,g in groupby(it)]
#------------------------------------------------------------------------
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
mod=10**9+7
farr=[1]
ifa=[]
def fact(x,mod=0):
if mod:
while x>=len(farr):
farr.append(farr[-1]*len(farr)%mod)
else:
while x>=len(farr):
farr.append(farr[-1]*len(farr))
return farr[x]
def ifact(x,mod):
global ifa
fact(x,mod)
ifa.append(pow(farr[-1],mod-2,mod))
for i in range(x,0,-1):
ifa.append(ifa[-1]*i%mod)
ifa.reverse()
def per(i,j,mod=0):
if i<j: return 0
if not mod:
return fact(i)//fact(i-j)
return farr[i]*ifa[i-j]%mod
def com(i,j,mod=0):
if i<j: return 0
if not mod:
return per(i,j)//fact(j)
return per(i,j,mod)*ifa[j]%mod
def catalan(n):
return com(2*n,n)//(n+1)
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def floorsum(a,b,c,n):#sum((a*i+b)//c for i in range(n+1))
if a==0:return b//c*(n+1)
if a>=c or b>=c: return floorsum(a%c,b%c,c,n)+b//c*(n+1)+a//c*n*(n+1)//2
m=(a*n+b)//c
return n*m-floorsum(c,c-b-1,a,m-1)
def inverse(a,m):
a%=m
if a<=1: return a
return ((1-inverse(m,a)*m)//a)%m
def lowbit(n):
return n&-n
class BIT:
def __init__(self,arr):
self.arr=arr
self.n=len(arr)-1
def update(self,x,v):
while x<=self.n:
self.arr[x]+=v
x+=x&-x
def query(self,x):
ans=0
while x:
ans+=self.arr[x]
x&=x-1
return ans
class ST:
def __init__(self,arr):#n!=0
n=len(arr)
mx=n.bit_length()#取不到
self.st=[[0]*mx for i in range(n)]
for i in range(n):
self.st[i][0]=arr[i]
for j in range(1,mx):
for i in range(n-(1<<j)+1):
self.st[i][j]=max(self.st[i][j-1],self.st[i+(1<<j-1)][j-1])
def query(self,l,r):
if l>r:return -inf
s=(r+1-l).bit_length()-1
return max(self.st[l][s],self.st[r-(1<<s)+1][s])
'''
class DSU:#容量+路径压缩
def __init__(self,n):
self.c=[-1]*n
def same(self,x,y):
return self.find(x)==self.find(y)
def find(self,x):
if self.c[x]<0:
return x
self.c[x]=self.find(self.c[x])
return self.c[x]
def union(self,u,v):
u,v=self.find(u),self.find(v)
if u==v:
return False
if self.c[u]>self.c[v]:
u,v=v,u
self.c[u]+=self.c[v]
self.c[v]=u
return True
def size(self,x): return -self.c[self.find(x)]'''
class UFS:#秩+路径
def __init__(self,n):
self.parent=[i for i in range(n)]
self.ranks=[0]*n
def find(self,x):
if x!=self.parent[x]:
self.parent[x]=self.find(self.parent[x])
return self.parent[x]
def union(self,u,v):
pu,pv=self.find(u),self.find(v)
if pu==pv:
return False
if self.ranks[pu]>=self.ranks[pv]:
self.parent[pv]=pu
if self.ranks[pv]==self.ranks[pu]:
self.ranks[pu]+=1
else:
self.parent[pu]=pv
def Prime(n):
c=0
prime=[]
flag=[0]*(n+1)
for i in range(2,n+1):
if not flag[i]:
prime.append(i)
c+=1
for j in range(c):
if i*prime[j]>n: break
flag[i*prime[j]]=prime[j]
if i%prime[j]==0: break
return prime
def dij(s,graph):
d={}
d[s]=0
heap=[(0,s)]
seen=set()
while heap:
dis,u=heappop(heap)
if u in seen:
continue
seen.add(u)
for v,w in graph[u]:
if v not in d or d[v]>d[u]+w:
d[v]=d[u]+w
heappush(heap,(d[v],v))
return d
def bell(s,g):#bellman-Ford
dis=AI(n,inf)
dis[s]=0
for i in range(n-1):
for u,v,w in edge:
if dis[v]>dis[u]+w:
dis[v]=dis[u]+w
change=A(n)
for i in range(n):
for u,v,w in edge:
if dis[v]>dis[u]+w:
dis[v]=dis[u]+w
change[v]=1
return dis
def lcm(a,b): return a*b//gcd(a,b)
def lis(nums):
res=[]
for k in nums:
i=bisect.bisect_left(res,k)
if i==len(res):
res.append(k)
else:
res[i]=k
return len(res)
def RP(nums):#逆序对
n = len(nums)
s=set(nums)
d={}
for i,k in enumerate(sorted(s),1):
d[k]=i
bi=BIT([0]*(len(s)+1))
ans=0
for i in range(n-1,-1,-1):
ans+=bi.query(d[nums[i]]-1)
bi.update(d[nums[i]],1)
return ans
class DLN:
def __init__(self,val):
self.val=val
self.pre=None
self.next=None
def nb(i,j,n,m):
for ni,nj in [[i+1,j],[i-1,j],[i,j-1],[i,j+1]]:
if 0<=ni<n and 0<=nj<m:
yield ni,nj
def topo(n):
q=deque()
res=[]
for i in range(1,n+1):
if ind[i]==0:
q.append(i)
res.append(i)
while q:
u=q.popleft()
for v in g[u]:
ind[v]-=1
if ind[v]==0:
q.append(v)
res.append(v)
return res
@bootstrap
def gdfs(r,p):
for ch in g[r]:
if ch!=p:
yield gdfs(ch,r)
yield None
@bootstrap
def dfs(r,p,path):
path[c[r]]+=1
if path[c[r]]==1:
ans.append(r+1)
for ch in g[r]:
if ch!=p:
yield dfs(ch,r,path)
path[c[r]]-=1
yield None
t=1
for i in range(t):
n=N()
a=RLL()
s=sum(a)
ifact(n,mod)
cb=Counter()
cs=Counter()
if s%n!=0:
print(0)
else:
s=s//n
b=sm=0
for i in range(n):
if a[i]>s:
b+=1
cb[a[i]]+=1
elif a[i]<s:
sm+=1
cs[a[i]]+=1
ans=per(n,n-sm-b,mod)
if b==1:
ans=ans*per(sm+b,b,mod)%mod*fact(sm,mod)%mod
for k in cs:
ans=ans*ifa[cs[k]]%mod
elif sm==1:
ans=ans*per(sm+b,sm,mod)%mod*fact(b,mod)%mod
for k in cb:
ans=ans*ifa[cb[k]]%mod
else:
if b:
ans*=2*fact(sm,mod)%mod*fact(b,mod)%mod
ans%=mod
for k in cb:
ans=ans*ifa[cb[k]]%mod
for k in cs:
ans=ans*ifa[cs[k]]%mod
print(ans)
'''
sys.setrecursionlimit(200000)
import threading
threading.stack_size(10**8)
t=threading.Thr
ead(target=main)
t.start()
t.join()
'''
``` | instruction | 0 | 29,380 | 12 | 58,760 |
No | output | 1 | 29,380 | 12 | 58,761 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Doubly linked list is one of the fundamental data structures. A doubly linked list is a sequence of elements, each containing information about the previous and the next elements of the list. In this problem all lists have linear structure. I.e. each element except the first has exactly one previous element, each element except the last has exactly one next element. The list is not closed in a cycle.
In this problem you are given n memory cells forming one or more doubly linked lists. Each cell contains information about element from some list. Memory cells are numbered from 1 to n.
For each cell i you are given two values:
* li — cell containing previous element for the element in the cell i;
* ri — cell containing next element for the element in the cell i.
If cell i contains information about the element which has no previous element then li = 0. Similarly, if cell i contains information about the element which has no next element then ri = 0.
<image> Three lists are shown on the picture.
For example, for the picture above the values of l and r are the following: l1 = 4, r1 = 7; l2 = 5, r2 = 0; l3 = 0, r3 = 0; l4 = 6, r4 = 1; l5 = 0, r5 = 2; l6 = 0, r6 = 4; l7 = 1, r7 = 0.
Your task is to unite all given lists in a single list, joining them to each other in any order. In particular, if the input data already contains a single list, then there is no need to perform any actions. Print the resulting list in the form of values li, ri.
Any other action, other than joining the beginning of one list to the end of another, can not be performed.
Input
The first line contains a single integer n (1 ≤ n ≤ 100) — the number of memory cells where the doubly linked lists are located.
Each of the following n lines contains two integers li, ri (0 ≤ li, ri ≤ n) — the cells of the previous and the next element of list for cell i. Value li = 0 if element in cell i has no previous element in its list. Value ri = 0 if element in cell i has no next element in its list.
It is guaranteed that the input contains the correct description of a single or more doubly linked lists. All lists have linear structure: each element of list except the first has exactly one previous element; each element of list except the last has exactly one next element. Each memory cell contains information about one element from some list, each element of each list written in one of n given cells.
Output
Print n lines, the i-th line must contain two integers li and ri — the cells of the previous and the next element of list for cell i after all lists from the input are united in a single list. If there are many solutions print any of them.
Example
Input
7
4 7
5 0
0 0
6 1
0 2
0 4
1 0
Output
4 7
5 6
0 5
6 1
3 2
2 4
1 0 | instruction | 0 | 29,663 | 12 | 59,326 |
Tags: implementation
Correct Solution:
```
import sys
input = sys.stdin.readline
from collections import defaultdict
n = int(input())
left = [-1 for _ in range(n + 1)]
right = [-1 for _ in range(n + 1)]
cannot = defaultdict(int)
for x in range(1, n + 1):
l,r = map(int, input().split())
left[x] = l
right[x] = r
for i in range(1, n + 1):
if left[i] == 0:
x = i
while right[x] != 0:
x = right[x]
cannot[i] = x
for i in range(1, n + 1):
if left.count(0) == 1:
break
if left[i] == 0:
for j in range(1, n + 1):
if right[j] == 0 and cannot[i] != j:
left[i] = j
right[j] = i
cannot.clear()
for i in range(1, n + 1):
if left[i] == 0:
x = i
while right[x] != 0:
x = right[x]
cannot[i] = x
break
for i in range(1, n + 1):
print(left[i], right[i])
``` | output | 1 | 29,663 | 12 | 59,327 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Doubly linked list is one of the fundamental data structures. A doubly linked list is a sequence of elements, each containing information about the previous and the next elements of the list. In this problem all lists have linear structure. I.e. each element except the first has exactly one previous element, each element except the last has exactly one next element. The list is not closed in a cycle.
In this problem you are given n memory cells forming one or more doubly linked lists. Each cell contains information about element from some list. Memory cells are numbered from 1 to n.
For each cell i you are given two values:
* li — cell containing previous element for the element in the cell i;
* ri — cell containing next element for the element in the cell i.
If cell i contains information about the element which has no previous element then li = 0. Similarly, if cell i contains information about the element which has no next element then ri = 0.
<image> Three lists are shown on the picture.
For example, for the picture above the values of l and r are the following: l1 = 4, r1 = 7; l2 = 5, r2 = 0; l3 = 0, r3 = 0; l4 = 6, r4 = 1; l5 = 0, r5 = 2; l6 = 0, r6 = 4; l7 = 1, r7 = 0.
Your task is to unite all given lists in a single list, joining them to each other in any order. In particular, if the input data already contains a single list, then there is no need to perform any actions. Print the resulting list in the form of values li, ri.
Any other action, other than joining the beginning of one list to the end of another, can not be performed.
Input
The first line contains a single integer n (1 ≤ n ≤ 100) — the number of memory cells where the doubly linked lists are located.
Each of the following n lines contains two integers li, ri (0 ≤ li, ri ≤ n) — the cells of the previous and the next element of list for cell i. Value li = 0 if element in cell i has no previous element in its list. Value ri = 0 if element in cell i has no next element in its list.
It is guaranteed that the input contains the correct description of a single or more doubly linked lists. All lists have linear structure: each element of list except the first has exactly one previous element; each element of list except the last has exactly one next element. Each memory cell contains information about one element from some list, each element of each list written in one of n given cells.
Output
Print n lines, the i-th line must contain two integers li and ri — the cells of the previous and the next element of list for cell i after all lists from the input are united in a single list. If there are many solutions print any of them.
Example
Input
7
4 7
5 0
0 0
6 1
0 2
0 4
1 0
Output
4 7
5 6
0 5
6 1
3 2
2 4
1 0 | instruction | 0 | 29,664 | 12 | 59,328 |
Tags: implementation
Correct Solution:
```
n = int(input())
L, R = [], []
zL, zR = [], []
A = []
for i in range(1, n+1):
l, r = map(int, input().split())
if l==0 and r==0:
A.append(i)
elif l == 0:
zL.append(i)
elif r == 0:
zR.append(i)
L.append(l)
R.append(r)
for i in zL:
A.append(i)
while R[i-1] != 0:
A.append(R[i-1])
i = R[i-1]
for i in range(1, n+1):
index = A.index(i)
if index == 0:
a = 0
else:
a = A[max(0, index-1)]
if index == len(A)-1:
b = 0
else:
b = A[min(len(A)-1, index+1)]
print(a, b)
``` | output | 1 | 29,664 | 12 | 59,329 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Doubly linked list is one of the fundamental data structures. A doubly linked list is a sequence of elements, each containing information about the previous and the next elements of the list. In this problem all lists have linear structure. I.e. each element except the first has exactly one previous element, each element except the last has exactly one next element. The list is not closed in a cycle.
In this problem you are given n memory cells forming one or more doubly linked lists. Each cell contains information about element from some list. Memory cells are numbered from 1 to n.
For each cell i you are given two values:
* li — cell containing previous element for the element in the cell i;
* ri — cell containing next element for the element in the cell i.
If cell i contains information about the element which has no previous element then li = 0. Similarly, if cell i contains information about the element which has no next element then ri = 0.
<image> Three lists are shown on the picture.
For example, for the picture above the values of l and r are the following: l1 = 4, r1 = 7; l2 = 5, r2 = 0; l3 = 0, r3 = 0; l4 = 6, r4 = 1; l5 = 0, r5 = 2; l6 = 0, r6 = 4; l7 = 1, r7 = 0.
Your task is to unite all given lists in a single list, joining them to each other in any order. In particular, if the input data already contains a single list, then there is no need to perform any actions. Print the resulting list in the form of values li, ri.
Any other action, other than joining the beginning of one list to the end of another, can not be performed.
Input
The first line contains a single integer n (1 ≤ n ≤ 100) — the number of memory cells where the doubly linked lists are located.
Each of the following n lines contains two integers li, ri (0 ≤ li, ri ≤ n) — the cells of the previous and the next element of list for cell i. Value li = 0 if element in cell i has no previous element in its list. Value ri = 0 if element in cell i has no next element in its list.
It is guaranteed that the input contains the correct description of a single or more doubly linked lists. All lists have linear structure: each element of list except the first has exactly one previous element; each element of list except the last has exactly one next element. Each memory cell contains information about one element from some list, each element of each list written in one of n given cells.
Output
Print n lines, the i-th line must contain two integers li and ri — the cells of the previous and the next element of list for cell i after all lists from the input are united in a single list. If there are many solutions print any of them.
Example
Input
7
4 7
5 0
0 0
6 1
0 2
0 4
1 0
Output
4 7
5 6
0 5
6 1
3 2
2 4
1 0 | instruction | 0 | 29,665 | 12 | 59,330 |
Tags: implementation
Correct Solution:
```
n = int(input())
if n == 1:
print(0, 0)
exit()
a = []
for i in range(n):
a.append(list(map(int, input().split())))
s = []
i = 0
while i < n:
if a[i][0] == 0:
k = i
s.append([i + 1])
while a[k][1] != 0:
k = a[k][1] - 1
s[-1].append(k + 1)
i += 1
p = []
for i in s:
p.extend(i)
for i in range(n):
if i == 0:
a[p[i] - 1] = [0, p[1]]
elif i == n - 1:
a[p[i] - 1] = [p[i - 1], 0]
else:
a[p[i] - 1] = [p[i - 1], p[i + 1]]
for i in a:
print(i[0], i[1])
``` | output | 1 | 29,665 | 12 | 59,331 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Doubly linked list is one of the fundamental data structures. A doubly linked list is a sequence of elements, each containing information about the previous and the next elements of the list. In this problem all lists have linear structure. I.e. each element except the first has exactly one previous element, each element except the last has exactly one next element. The list is not closed in a cycle.
In this problem you are given n memory cells forming one or more doubly linked lists. Each cell contains information about element from some list. Memory cells are numbered from 1 to n.
For each cell i you are given two values:
* li — cell containing previous element for the element in the cell i;
* ri — cell containing next element for the element in the cell i.
If cell i contains information about the element which has no previous element then li = 0. Similarly, if cell i contains information about the element which has no next element then ri = 0.
<image> Three lists are shown on the picture.
For example, for the picture above the values of l and r are the following: l1 = 4, r1 = 7; l2 = 5, r2 = 0; l3 = 0, r3 = 0; l4 = 6, r4 = 1; l5 = 0, r5 = 2; l6 = 0, r6 = 4; l7 = 1, r7 = 0.
Your task is to unite all given lists in a single list, joining them to each other in any order. In particular, if the input data already contains a single list, then there is no need to perform any actions. Print the resulting list in the form of values li, ri.
Any other action, other than joining the beginning of one list to the end of another, can not be performed.
Input
The first line contains a single integer n (1 ≤ n ≤ 100) — the number of memory cells where the doubly linked lists are located.
Each of the following n lines contains two integers li, ri (0 ≤ li, ri ≤ n) — the cells of the previous and the next element of list for cell i. Value li = 0 if element in cell i has no previous element in its list. Value ri = 0 if element in cell i has no next element in its list.
It is guaranteed that the input contains the correct description of a single or more doubly linked lists. All lists have linear structure: each element of list except the first has exactly one previous element; each element of list except the last has exactly one next element. Each memory cell contains information about one element from some list, each element of each list written in one of n given cells.
Output
Print n lines, the i-th line must contain two integers li and ri — the cells of the previous and the next element of list for cell i after all lists from the input are united in a single list. If there are many solutions print any of them.
Example
Input
7
4 7
5 0
0 0
6 1
0 2
0 4
1 0
Output
4 7
5 6
0 5
6 1
3 2
2 4
1 0 | instruction | 0 | 29,666 | 12 | 59,332 |
Tags: implementation
Correct Solution:
```
if __name__=='__main__':
n=int(input())
dl=[[0,0]]
end=0
for i in range(n):
dl.append(list(map(int,input().split())))
for i in range(1,n+1):
if not dl[i][0]:
dl[end][1]=i
dl[i][0]=end
j=i
while(dl[j][1]):
#print(dl[j])
#j+=1
j=dl[j][1]
end=j
for node in dl[1:]:
print(*node)
``` | output | 1 | 29,666 | 12 | 59,333 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Doubly linked list is one of the fundamental data structures. A doubly linked list is a sequence of elements, each containing information about the previous and the next elements of the list. In this problem all lists have linear structure. I.e. each element except the first has exactly one previous element, each element except the last has exactly one next element. The list is not closed in a cycle.
In this problem you are given n memory cells forming one or more doubly linked lists. Each cell contains information about element from some list. Memory cells are numbered from 1 to n.
For each cell i you are given two values:
* li — cell containing previous element for the element in the cell i;
* ri — cell containing next element for the element in the cell i.
If cell i contains information about the element which has no previous element then li = 0. Similarly, if cell i contains information about the element which has no next element then ri = 0.
<image> Three lists are shown on the picture.
For example, for the picture above the values of l and r are the following: l1 = 4, r1 = 7; l2 = 5, r2 = 0; l3 = 0, r3 = 0; l4 = 6, r4 = 1; l5 = 0, r5 = 2; l6 = 0, r6 = 4; l7 = 1, r7 = 0.
Your task is to unite all given lists in a single list, joining them to each other in any order. In particular, if the input data already contains a single list, then there is no need to perform any actions. Print the resulting list in the form of values li, ri.
Any other action, other than joining the beginning of one list to the end of another, can not be performed.
Input
The first line contains a single integer n (1 ≤ n ≤ 100) — the number of memory cells where the doubly linked lists are located.
Each of the following n lines contains two integers li, ri (0 ≤ li, ri ≤ n) — the cells of the previous and the next element of list for cell i. Value li = 0 if element in cell i has no previous element in its list. Value ri = 0 if element in cell i has no next element in its list.
It is guaranteed that the input contains the correct description of a single or more doubly linked lists. All lists have linear structure: each element of list except the first has exactly one previous element; each element of list except the last has exactly one next element. Each memory cell contains information about one element from some list, each element of each list written in one of n given cells.
Output
Print n lines, the i-th line must contain two integers li and ri — the cells of the previous and the next element of list for cell i after all lists from the input are united in a single list. If there are many solutions print any of them.
Example
Input
7
4 7
5 0
0 0
6 1
0 2
0 4
1 0
Output
4 7
5 6
0 5
6 1
3 2
2 4
1 0 | instruction | 0 | 29,667 | 12 | 59,334 |
Tags: implementation
Correct Solution:
```
n = int(input())
arr = []
for i in range(n):
l,r = map(int, input().split())
arr.append([l,r])
lts = []
for i in range(n):
if arr[i][0] == 0:
l = i
j = i
while arr[j][1] != 0:
j = arr[j][1] - 1
r = j
lts.append([l,r])
for i in range(1, len(lts)):
arr[lts[i-1][1]][1] = lts[i][0] + 1
arr[lts[i][0]][0] = lts[i-1][1] + 1
for i in range(n):
print(arr[i][0], arr[i][1])
``` | output | 1 | 29,667 | 12 | 59,335 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Doubly linked list is one of the fundamental data structures. A doubly linked list is a sequence of elements, each containing information about the previous and the next elements of the list. In this problem all lists have linear structure. I.e. each element except the first has exactly one previous element, each element except the last has exactly one next element. The list is not closed in a cycle.
In this problem you are given n memory cells forming one or more doubly linked lists. Each cell contains information about element from some list. Memory cells are numbered from 1 to n.
For each cell i you are given two values:
* li — cell containing previous element for the element in the cell i;
* ri — cell containing next element for the element in the cell i.
If cell i contains information about the element which has no previous element then li = 0. Similarly, if cell i contains information about the element which has no next element then ri = 0.
<image> Three lists are shown on the picture.
For example, for the picture above the values of l and r are the following: l1 = 4, r1 = 7; l2 = 5, r2 = 0; l3 = 0, r3 = 0; l4 = 6, r4 = 1; l5 = 0, r5 = 2; l6 = 0, r6 = 4; l7 = 1, r7 = 0.
Your task is to unite all given lists in a single list, joining them to each other in any order. In particular, if the input data already contains a single list, then there is no need to perform any actions. Print the resulting list in the form of values li, ri.
Any other action, other than joining the beginning of one list to the end of another, can not be performed.
Input
The first line contains a single integer n (1 ≤ n ≤ 100) — the number of memory cells where the doubly linked lists are located.
Each of the following n lines contains two integers li, ri (0 ≤ li, ri ≤ n) — the cells of the previous and the next element of list for cell i. Value li = 0 if element in cell i has no previous element in its list. Value ri = 0 if element in cell i has no next element in its list.
It is guaranteed that the input contains the correct description of a single or more doubly linked lists. All lists have linear structure: each element of list except the first has exactly one previous element; each element of list except the last has exactly one next element. Each memory cell contains information about one element from some list, each element of each list written in one of n given cells.
Output
Print n lines, the i-th line must contain two integers li and ri — the cells of the previous and the next element of list for cell i after all lists from the input are united in a single list. If there are many solutions print any of them.
Example
Input
7
4 7
5 0
0 0
6 1
0 2
0 4
1 0
Output
4 7
5 6
0 5
6 1
3 2
2 4
1 0 | instruction | 0 | 29,668 | 12 | 59,336 |
Tags: implementation
Correct Solution:
```
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
from collections import defaultdict
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------game starts now-----------------------------------------------------
n = int(input())
A = [list(map(int, input().split())) for i in range(n)]
start = []
end = []
for i in range(n):
if A[i][0] == 0:
start.append(i)
elif A[i][1] == 0:
end.append(i)
for curr in range(len(start)):
x = start[curr]
#print(curr)
while A[x][1] != 0:
#print(x)
x = A[x][1] - 1
#print(x)
if curr != len(start) - 1:
A[x][1] = start[curr + 1] + 1
A[A[x][1] - 1][0] = x + 1
for i in range(n):
print(A[i][0], A[i][1])
``` | output | 1 | 29,668 | 12 | 59,337 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Doubly linked list is one of the fundamental data structures. A doubly linked list is a sequence of elements, each containing information about the previous and the next elements of the list. In this problem all lists have linear structure. I.e. each element except the first has exactly one previous element, each element except the last has exactly one next element. The list is not closed in a cycle.
In this problem you are given n memory cells forming one or more doubly linked lists. Each cell contains information about element from some list. Memory cells are numbered from 1 to n.
For each cell i you are given two values:
* li — cell containing previous element for the element in the cell i;
* ri — cell containing next element for the element in the cell i.
If cell i contains information about the element which has no previous element then li = 0. Similarly, if cell i contains information about the element which has no next element then ri = 0.
<image> Three lists are shown on the picture.
For example, for the picture above the values of l and r are the following: l1 = 4, r1 = 7; l2 = 5, r2 = 0; l3 = 0, r3 = 0; l4 = 6, r4 = 1; l5 = 0, r5 = 2; l6 = 0, r6 = 4; l7 = 1, r7 = 0.
Your task is to unite all given lists in a single list, joining them to each other in any order. In particular, if the input data already contains a single list, then there is no need to perform any actions. Print the resulting list in the form of values li, ri.
Any other action, other than joining the beginning of one list to the end of another, can not be performed.
Input
The first line contains a single integer n (1 ≤ n ≤ 100) — the number of memory cells where the doubly linked lists are located.
Each of the following n lines contains two integers li, ri (0 ≤ li, ri ≤ n) — the cells of the previous and the next element of list for cell i. Value li = 0 if element in cell i has no previous element in its list. Value ri = 0 if element in cell i has no next element in its list.
It is guaranteed that the input contains the correct description of a single or more doubly linked lists. All lists have linear structure: each element of list except the first has exactly one previous element; each element of list except the last has exactly one next element. Each memory cell contains information about one element from some list, each element of each list written in one of n given cells.
Output
Print n lines, the i-th line must contain two integers li and ri — the cells of the previous and the next element of list for cell i after all lists from the input are united in a single list. If there are many solutions print any of them.
Example
Input
7
4 7
5 0
0 0
6 1
0 2
0 4
1 0
Output
4 7
5 6
0 5
6 1
3 2
2 4
1 0 | instruction | 0 | 29,669 | 12 | 59,338 |
Tags: implementation
Correct Solution:
```
nodes = []
start_nodes = []
for i in range(int(input().strip())):
left, right = input().strip().split()
left = int(left)
right = int(right)
current = i + 1
if left == 0:
start_nodes.append([left, current, right])
else:
nodes.append([left, current, right])
lists = []
for node in start_nodes:
links = [node]
while True:
prevlen = len(links)
for i in range(len(nodes)):
if links[-1][-1] == nodes[i][1]:
links.append(nodes[i])
nextlen = len(links)
if prevlen == nextlen:
break
lists.append(links)
flattened = [node for ll in lists for node in ll]
for i in range(1, len(flattened)):
if flattened[i][0] == 0:
flattened[i][0] = flattened[i - 1][1]
flattened[i - 1][2] = flattened[i][1]
sorted_union = sorted(flattened, key = lambda x: x[1])
for node in sorted_union:
print(node[0], node[2])
``` | output | 1 | 29,669 | 12 | 59,339 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Doubly linked list is one of the fundamental data structures. A doubly linked list is a sequence of elements, each containing information about the previous and the next elements of the list. In this problem all lists have linear structure. I.e. each element except the first has exactly one previous element, each element except the last has exactly one next element. The list is not closed in a cycle.
In this problem you are given n memory cells forming one or more doubly linked lists. Each cell contains information about element from some list. Memory cells are numbered from 1 to n.
For each cell i you are given two values:
* li — cell containing previous element for the element in the cell i;
* ri — cell containing next element for the element in the cell i.
If cell i contains information about the element which has no previous element then li = 0. Similarly, if cell i contains information about the element which has no next element then ri = 0.
<image> Three lists are shown on the picture.
For example, for the picture above the values of l and r are the following: l1 = 4, r1 = 7; l2 = 5, r2 = 0; l3 = 0, r3 = 0; l4 = 6, r4 = 1; l5 = 0, r5 = 2; l6 = 0, r6 = 4; l7 = 1, r7 = 0.
Your task is to unite all given lists in a single list, joining them to each other in any order. In particular, if the input data already contains a single list, then there is no need to perform any actions. Print the resulting list in the form of values li, ri.
Any other action, other than joining the beginning of one list to the end of another, can not be performed.
Input
The first line contains a single integer n (1 ≤ n ≤ 100) — the number of memory cells where the doubly linked lists are located.
Each of the following n lines contains two integers li, ri (0 ≤ li, ri ≤ n) — the cells of the previous and the next element of list for cell i. Value li = 0 if element in cell i has no previous element in its list. Value ri = 0 if element in cell i has no next element in its list.
It is guaranteed that the input contains the correct description of a single or more doubly linked lists. All lists have linear structure: each element of list except the first has exactly one previous element; each element of list except the last has exactly one next element. Each memory cell contains information about one element from some list, each element of each list written in one of n given cells.
Output
Print n lines, the i-th line must contain two integers li and ri — the cells of the previous and the next element of list for cell i after all lists from the input are united in a single list. If there are many solutions print any of them.
Example
Input
7
4 7
5 0
0 0
6 1
0 2
0 4
1 0
Output
4 7
5 6
0 5
6 1
3 2
2 4
1 0 | instruction | 0 | 29,670 | 12 | 59,340 |
Tags: implementation
Correct Solution:
```
n = int(input())
starts = dict()
ends = dict()
start_points = set()
for i in range(n):
st, en = map(int, input().split())
if st == 0:
start_points.add(i + 1)
starts[i + 1] = st
ends[i + 1] = en
lists = []
it = iter(start_points)
x = next(it)
while ends[x] != 0:
x = ends[x]
for st in it:
starts[st] = x
ends[x] = st
while ends[x] != 0:
x = ends[x]
for i in range(1, n + 1):
print(starts[i], ends[i], sep=' ')
``` | output | 1 | 29,670 | 12 | 59,341 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Doubly linked list is one of the fundamental data structures. A doubly linked list is a sequence of elements, each containing information about the previous and the next elements of the list. In this problem all lists have linear structure. I.e. each element except the first has exactly one previous element, each element except the last has exactly one next element. The list is not closed in a cycle.
In this problem you are given n memory cells forming one or more doubly linked lists. Each cell contains information about element from some list. Memory cells are numbered from 1 to n.
For each cell i you are given two values:
* li — cell containing previous element for the element in the cell i;
* ri — cell containing next element for the element in the cell i.
If cell i contains information about the element which has no previous element then li = 0. Similarly, if cell i contains information about the element which has no next element then ri = 0.
<image> Three lists are shown on the picture.
For example, for the picture above the values of l and r are the following: l1 = 4, r1 = 7; l2 = 5, r2 = 0; l3 = 0, r3 = 0; l4 = 6, r4 = 1; l5 = 0, r5 = 2; l6 = 0, r6 = 4; l7 = 1, r7 = 0.
Your task is to unite all given lists in a single list, joining them to each other in any order. In particular, if the input data already contains a single list, then there is no need to perform any actions. Print the resulting list in the form of values li, ri.
Any other action, other than joining the beginning of one list to the end of another, can not be performed.
Input
The first line contains a single integer n (1 ≤ n ≤ 100) — the number of memory cells where the doubly linked lists are located.
Each of the following n lines contains two integers li, ri (0 ≤ li, ri ≤ n) — the cells of the previous and the next element of list for cell i. Value li = 0 if element in cell i has no previous element in its list. Value ri = 0 if element in cell i has no next element in its list.
It is guaranteed that the input contains the correct description of a single or more doubly linked lists. All lists have linear structure: each element of list except the first has exactly one previous element; each element of list except the last has exactly one next element. Each memory cell contains information about one element from some list, each element of each list written in one of n given cells.
Output
Print n lines, the i-th line must contain two integers li and ri — the cells of the previous and the next element of list for cell i after all lists from the input are united in a single list. If there are many solutions print any of them.
Example
Input
7
4 7
5 0
0 0
6 1
0 2
0 4
1 0
Output
4 7
5 6
0 5
6 1
3 2
2 4
1 0
Submitted Solution:
```
import sys
import math
data = sys.stdin.read().split()
data_ptr = 0
def data_next():
global data_ptr, data
data_ptr += 1
return data[data_ptr - 1]
N = int(data_next())
pre = [0] + list(map(int, data[1::2]))
nxt = [0] + list(map(int, data[2::2]))
vis = [False] * (N + 1)
def find_last(u, nxt):
while nxt[u] != 0:
u = nxt[u]
vis[u] = True
return u
pre_last = -1
for i in range(1, N + 1):
if not(vis[i]):
vis[i] = True
first = find_last(i, pre)
last = find_last(i, nxt)
if pre_last != -1:
nxt[pre_last] = first
pre[first] = pre_last
pre_last = last
for i in range(1, N + 1):
print(pre[i], nxt[i])
``` | instruction | 0 | 29,671 | 12 | 59,342 |
Yes | output | 1 | 29,671 | 12 | 59,343 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Doubly linked list is one of the fundamental data structures. A doubly linked list is a sequence of elements, each containing information about the previous and the next elements of the list. In this problem all lists have linear structure. I.e. each element except the first has exactly one previous element, each element except the last has exactly one next element. The list is not closed in a cycle.
In this problem you are given n memory cells forming one or more doubly linked lists. Each cell contains information about element from some list. Memory cells are numbered from 1 to n.
For each cell i you are given two values:
* li — cell containing previous element for the element in the cell i;
* ri — cell containing next element for the element in the cell i.
If cell i contains information about the element which has no previous element then li = 0. Similarly, if cell i contains information about the element which has no next element then ri = 0.
<image> Three lists are shown on the picture.
For example, for the picture above the values of l and r are the following: l1 = 4, r1 = 7; l2 = 5, r2 = 0; l3 = 0, r3 = 0; l4 = 6, r4 = 1; l5 = 0, r5 = 2; l6 = 0, r6 = 4; l7 = 1, r7 = 0.
Your task is to unite all given lists in a single list, joining them to each other in any order. In particular, if the input data already contains a single list, then there is no need to perform any actions. Print the resulting list in the form of values li, ri.
Any other action, other than joining the beginning of one list to the end of another, can not be performed.
Input
The first line contains a single integer n (1 ≤ n ≤ 100) — the number of memory cells where the doubly linked lists are located.
Each of the following n lines contains two integers li, ri (0 ≤ li, ri ≤ n) — the cells of the previous and the next element of list for cell i. Value li = 0 if element in cell i has no previous element in its list. Value ri = 0 if element in cell i has no next element in its list.
It is guaranteed that the input contains the correct description of a single or more doubly linked lists. All lists have linear structure: each element of list except the first has exactly one previous element; each element of list except the last has exactly one next element. Each memory cell contains information about one element from some list, each element of each list written in one of n given cells.
Output
Print n lines, the i-th line must contain two integers li and ri — the cells of the previous and the next element of list for cell i after all lists from the input are united in a single list. If there are many solutions print any of them.
Example
Input
7
4 7
5 0
0 0
6 1
0 2
0 4
1 0
Output
4 7
5 6
0 5
6 1
3 2
2 4
1 0
Submitted Solution:
```
n = int(input())
A = [list(map(int, input().split())) for i in range(n)]
start = []
end = []
for i in range(n):
if A[i][0] == 0:
start.append(i)
elif A[i][1] == 0:
end.append(i)
for curr in range(len(start)):
x = start[curr]
#print(curr)
while A[x][1] != 0:
#print(x)
x = A[x][1] - 1
#print(x)
if curr != len(start) - 1:
A[x][1] = start[curr + 1] + 1
A[A[x][1] - 1][0] = x + 1
for i in range(n):
print(A[i][0], A[i][1])
``` | instruction | 0 | 29,672 | 12 | 59,344 |
Yes | output | 1 | 29,672 | 12 | 59,345 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Doubly linked list is one of the fundamental data structures. A doubly linked list is a sequence of elements, each containing information about the previous and the next elements of the list. In this problem all lists have linear structure. I.e. each element except the first has exactly one previous element, each element except the last has exactly one next element. The list is not closed in a cycle.
In this problem you are given n memory cells forming one or more doubly linked lists. Each cell contains information about element from some list. Memory cells are numbered from 1 to n.
For each cell i you are given two values:
* li — cell containing previous element for the element in the cell i;
* ri — cell containing next element for the element in the cell i.
If cell i contains information about the element which has no previous element then li = 0. Similarly, if cell i contains information about the element which has no next element then ri = 0.
<image> Three lists are shown on the picture.
For example, for the picture above the values of l and r are the following: l1 = 4, r1 = 7; l2 = 5, r2 = 0; l3 = 0, r3 = 0; l4 = 6, r4 = 1; l5 = 0, r5 = 2; l6 = 0, r6 = 4; l7 = 1, r7 = 0.
Your task is to unite all given lists in a single list, joining them to each other in any order. In particular, if the input data already contains a single list, then there is no need to perform any actions. Print the resulting list in the form of values li, ri.
Any other action, other than joining the beginning of one list to the end of another, can not be performed.
Input
The first line contains a single integer n (1 ≤ n ≤ 100) — the number of memory cells where the doubly linked lists are located.
Each of the following n lines contains two integers li, ri (0 ≤ li, ri ≤ n) — the cells of the previous and the next element of list for cell i. Value li = 0 if element in cell i has no previous element in its list. Value ri = 0 if element in cell i has no next element in its list.
It is guaranteed that the input contains the correct description of a single or more doubly linked lists. All lists have linear structure: each element of list except the first has exactly one previous element; each element of list except the last has exactly one next element. Each memory cell contains information about one element from some list, each element of each list written in one of n given cells.
Output
Print n lines, the i-th line must contain two integers li and ri — the cells of the previous and the next element of list for cell i after all lists from the input are united in a single list. If there are many solutions print any of them.
Example
Input
7
4 7
5 0
0 0
6 1
0 2
0 4
1 0
Output
4 7
5 6
0 5
6 1
3 2
2 4
1 0
Submitted Solution:
```
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
from math import gcd, ceil
def pre(s):
n = len(s)
pi = [0] * n
for i in range(1, n):
j = pi[i - 1]
while j and s[i] != s[j]:
j = pi[j - 1]
if s[i] == s[j]:
j += 1
pi[i] = j
return pi
def prod(a):
ans = 1
for each in a:
ans = (ans * each)
return ans
def lcm(a, b): return a * b // gcd(a, b)
def binary(x, length=16):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def connected_components(n, graph):
components, visited = [], [False] * n
def dfs(start):
component, stack = [], [start]
while stack:
start = stack[-1]
if visited[start]:
stack.pop()
continue
else:
visited[start] = True
component.append(start)
for i in graph[start]:
if not visited[i]:
stack.append(i)
return component
for i in range(n):
if not visited[i]:
components.append(dfs(i))
return components
for _ in range(int(input()) if not True else 1):
n = int(input())
alpha = []
a = []
comps = 0
for i in range(n):
x, y = map(int, input().split())
if not x:
alpha+=[i]
comps += 1
a += [[x, y]]
for i in range(comps):
x = alpha[i]
while a[x][1]:
x = a[x][1]-1
if i+1!=len(alpha):
y = alpha[i+1]
a[x][1] = y+1
a[y][0] = x+1
for each in a:
print(*each)
``` | instruction | 0 | 29,673 | 12 | 59,346 |
Yes | output | 1 | 29,673 | 12 | 59,347 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Doubly linked list is one of the fundamental data structures. A doubly linked list is a sequence of elements, each containing information about the previous and the next elements of the list. In this problem all lists have linear structure. I.e. each element except the first has exactly one previous element, each element except the last has exactly one next element. The list is not closed in a cycle.
In this problem you are given n memory cells forming one or more doubly linked lists. Each cell contains information about element from some list. Memory cells are numbered from 1 to n.
For each cell i you are given two values:
* li — cell containing previous element for the element in the cell i;
* ri — cell containing next element for the element in the cell i.
If cell i contains information about the element which has no previous element then li = 0. Similarly, if cell i contains information about the element which has no next element then ri = 0.
<image> Three lists are shown on the picture.
For example, for the picture above the values of l and r are the following: l1 = 4, r1 = 7; l2 = 5, r2 = 0; l3 = 0, r3 = 0; l4 = 6, r4 = 1; l5 = 0, r5 = 2; l6 = 0, r6 = 4; l7 = 1, r7 = 0.
Your task is to unite all given lists in a single list, joining them to each other in any order. In particular, if the input data already contains a single list, then there is no need to perform any actions. Print the resulting list in the form of values li, ri.
Any other action, other than joining the beginning of one list to the end of another, can not be performed.
Input
The first line contains a single integer n (1 ≤ n ≤ 100) — the number of memory cells where the doubly linked lists are located.
Each of the following n lines contains two integers li, ri (0 ≤ li, ri ≤ n) — the cells of the previous and the next element of list for cell i. Value li = 0 if element in cell i has no previous element in its list. Value ri = 0 if element in cell i has no next element in its list.
It is guaranteed that the input contains the correct description of a single or more doubly linked lists. All lists have linear structure: each element of list except the first has exactly one previous element; each element of list except the last has exactly one next element. Each memory cell contains information about one element from some list, each element of each list written in one of n given cells.
Output
Print n lines, the i-th line must contain two integers li and ri — the cells of the previous and the next element of list for cell i after all lists from the input are united in a single list. If there are many solutions print any of them.
Example
Input
7
4 7
5 0
0 0
6 1
0 2
0 4
1 0
Output
4 7
5 6
0 5
6 1
3 2
2 4
1 0
Submitted Solution:
```
n = int(input())
ll = [list(map(int, input().split())) for _ in range(n)]
ll = [[0,0]] + ll
tail = 0
visited = [False]*(n+1)
cnt = 0
while cnt < n:
for i in range(1, n+1):
if ll[i][0] == 0 and not visited[i]:
head = i
visited[head] = True
cnt += 1
break
ll[tail][1] = head
ll[head][0] = tail
while ll[head][1] != 0:
head = ll[head][1]
visited[head] = True
cnt += 1
tail = head
for i in range(1, n+1):
print(ll[i][0], ll[i][1])
``` | instruction | 0 | 29,674 | 12 | 59,348 |
Yes | output | 1 | 29,674 | 12 | 59,349 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Doubly linked list is one of the fundamental data structures. A doubly linked list is a sequence of elements, each containing information about the previous and the next elements of the list. In this problem all lists have linear structure. I.e. each element except the first has exactly one previous element, each element except the last has exactly one next element. The list is not closed in a cycle.
In this problem you are given n memory cells forming one or more doubly linked lists. Each cell contains information about element from some list. Memory cells are numbered from 1 to n.
For each cell i you are given two values:
* li — cell containing previous element for the element in the cell i;
* ri — cell containing next element for the element in the cell i.
If cell i contains information about the element which has no previous element then li = 0. Similarly, if cell i contains information about the element which has no next element then ri = 0.
<image> Three lists are shown on the picture.
For example, for the picture above the values of l and r are the following: l1 = 4, r1 = 7; l2 = 5, r2 = 0; l3 = 0, r3 = 0; l4 = 6, r4 = 1; l5 = 0, r5 = 2; l6 = 0, r6 = 4; l7 = 1, r7 = 0.
Your task is to unite all given lists in a single list, joining them to each other in any order. In particular, if the input data already contains a single list, then there is no need to perform any actions. Print the resulting list in the form of values li, ri.
Any other action, other than joining the beginning of one list to the end of another, can not be performed.
Input
The first line contains a single integer n (1 ≤ n ≤ 100) — the number of memory cells where the doubly linked lists are located.
Each of the following n lines contains two integers li, ri (0 ≤ li, ri ≤ n) — the cells of the previous and the next element of list for cell i. Value li = 0 if element in cell i has no previous element in its list. Value ri = 0 if element in cell i has no next element in its list.
It is guaranteed that the input contains the correct description of a single or more doubly linked lists. All lists have linear structure: each element of list except the first has exactly one previous element; each element of list except the last has exactly one next element. Each memory cell contains information about one element from some list, each element of each list written in one of n given cells.
Output
Print n lines, the i-th line must contain two integers li and ri — the cells of the previous and the next element of list for cell i after all lists from the input are united in a single list. If there are many solutions print any of them.
Example
Input
7
4 7
5 0
0 0
6 1
0 2
0 4
1 0
Output
4 7
5 6
0 5
6 1
3 2
2 4
1 0
Submitted Solution:
```
def solution(array_2d):
hashmap = {}
for i in range(len(array_2d)):
if array_2d[i][0]==0 or array_2d[i][1]==0:
hashmap[i+1] = array_2d[i]
required_keys = list(hashmap.keys())
for index in range(len(required_keys)):
key = required_keys[index]
prevE = hashmap[key][0]
nextE = hashmap[key][1]
if prevE == 0 and nextE == 0:
use_index = index
counter_index = required_keys[use_index]
while counter_index < required_keys[-1]:
counter_prev = hashmap[counter_index][0]
counter_next = hashmap[counter_index][1]
if counter_prev == 0 and counter_next!=0:
hashmap[key][1] = counter_index
hashmap[counter_index][0] = key
break
use_index += 1
counter_index = required_keys[use_index]
elif prevE != 0 and nextE == 0:
use_index = index
counter_index = required_keys[use_index]
while counter_index < required_keys[-1]:
counter_prev = hashmap[counter_index][0]
counter_next = hashmap[counter_index][1]
if counter_prev == 0 and counter_next !=0 and counter_index != prevE:
hashmap[key][1] = counter_index
hashmap[counter_index][0] = key
use_index += 1
counter_index = required_keys[use_index]
for i in range(len(required_keys)):
if i+1 == required_keys[i]:
array_2d[i] = hashmap[i+1]
return array_2d
if __name__ == '__main__':
array_2d = []
num_test_cases = int(input())
for i in range(num_test_cases):
array_2d.append(list(map(int,input().split(' '))))
print(solution(array_2d))
``` | instruction | 0 | 29,675 | 12 | 59,350 |
No | output | 1 | 29,675 | 12 | 59,351 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Doubly linked list is one of the fundamental data structures. A doubly linked list is a sequence of elements, each containing information about the previous and the next elements of the list. In this problem all lists have linear structure. I.e. each element except the first has exactly one previous element, each element except the last has exactly one next element. The list is not closed in a cycle.
In this problem you are given n memory cells forming one or more doubly linked lists. Each cell contains information about element from some list. Memory cells are numbered from 1 to n.
For each cell i you are given two values:
* li — cell containing previous element for the element in the cell i;
* ri — cell containing next element for the element in the cell i.
If cell i contains information about the element which has no previous element then li = 0. Similarly, if cell i contains information about the element which has no next element then ri = 0.
<image> Three lists are shown on the picture.
For example, for the picture above the values of l and r are the following: l1 = 4, r1 = 7; l2 = 5, r2 = 0; l3 = 0, r3 = 0; l4 = 6, r4 = 1; l5 = 0, r5 = 2; l6 = 0, r6 = 4; l7 = 1, r7 = 0.
Your task is to unite all given lists in a single list, joining them to each other in any order. In particular, if the input data already contains a single list, then there is no need to perform any actions. Print the resulting list in the form of values li, ri.
Any other action, other than joining the beginning of one list to the end of another, can not be performed.
Input
The first line contains a single integer n (1 ≤ n ≤ 100) — the number of memory cells where the doubly linked lists are located.
Each of the following n lines contains two integers li, ri (0 ≤ li, ri ≤ n) — the cells of the previous and the next element of list for cell i. Value li = 0 if element in cell i has no previous element in its list. Value ri = 0 if element in cell i has no next element in its list.
It is guaranteed that the input contains the correct description of a single or more doubly linked lists. All lists have linear structure: each element of list except the first has exactly one previous element; each element of list except the last has exactly one next element. Each memory cell contains information about one element from some list, each element of each list written in one of n given cells.
Output
Print n lines, the i-th line must contain two integers li and ri — the cells of the previous and the next element of list for cell i after all lists from the input are united in a single list. If there are many solutions print any of them.
Example
Input
7
4 7
5 0
0 0
6 1
0 2
0 4
1 0
Output
4 7
5 6
0 5
6 1
3 2
2 4
1 0
Submitted Solution:
```
def solution(array_2d):
hashmap = {}
for i in range(len(array_2d)):
if array_2d[i][0]==0 or array_2d[i][1]==0:
hashmap[i+1] = array_2d[i]
required_keys = list(hashmap.keys())
for index in range(len(required_keys)):
key = required_keys[index]
prevE = hashmap[key][0]
nextE = hashmap[key][1]
if prevE == 0 and nextE == 0:
use_index = index
counter_index = required_keys[use_index]
while counter_index < required_keys[-1]:
counter_prev = hashmap[counter_index][0]
counter_next = hashmap[counter_index][1]
if counter_prev == 0 and counter_next!=0:
hashmap[key][1] = counter_index
hashmap[counter_index][0] = key
break
use_index += 1
counter_index = required_keys[use_index]
elif prevE != 0 and nextE == 0:
use_index = index
counter_index = required_keys[use_index]
while counter_index < required_keys[-1]:
counter_prev = hashmap[counter_index][0]
counter_next = hashmap[counter_index][1]
if counter_prev == 0 and counter_next !=0 and counter_index != prevE:
hashmap[key][1] = counter_index
hashmap[counter_index][0] = key
use_index += 1
counter_index = required_keys[use_index]
for i in range(len(required_keys)):
if i+1 == required_keys[i]:
array_2d[i] = hashmap[i+1]
return array_2d
if __name__ == '__main__':
array_2d = []
num_test_cases = int(input())
for i in range(num_test_cases):
array_2d.append(list(map(int,input().split(' '))))
r = solution(array_2d)
for i in r:
print(i[0],i[1])
``` | instruction | 0 | 29,676 | 12 | 59,352 |
No | output | 1 | 29,676 | 12 | 59,353 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Doubly linked list is one of the fundamental data structures. A doubly linked list is a sequence of elements, each containing information about the previous and the next elements of the list. In this problem all lists have linear structure. I.e. each element except the first has exactly one previous element, each element except the last has exactly one next element. The list is not closed in a cycle.
In this problem you are given n memory cells forming one or more doubly linked lists. Each cell contains information about element from some list. Memory cells are numbered from 1 to n.
For each cell i you are given two values:
* li — cell containing previous element for the element in the cell i;
* ri — cell containing next element for the element in the cell i.
If cell i contains information about the element which has no previous element then li = 0. Similarly, if cell i contains information about the element which has no next element then ri = 0.
<image> Three lists are shown on the picture.
For example, for the picture above the values of l and r are the following: l1 = 4, r1 = 7; l2 = 5, r2 = 0; l3 = 0, r3 = 0; l4 = 6, r4 = 1; l5 = 0, r5 = 2; l6 = 0, r6 = 4; l7 = 1, r7 = 0.
Your task is to unite all given lists in a single list, joining them to each other in any order. In particular, if the input data already contains a single list, then there is no need to perform any actions. Print the resulting list in the form of values li, ri.
Any other action, other than joining the beginning of one list to the end of another, can not be performed.
Input
The first line contains a single integer n (1 ≤ n ≤ 100) — the number of memory cells where the doubly linked lists are located.
Each of the following n lines contains two integers li, ri (0 ≤ li, ri ≤ n) — the cells of the previous and the next element of list for cell i. Value li = 0 if element in cell i has no previous element in its list. Value ri = 0 if element in cell i has no next element in its list.
It is guaranteed that the input contains the correct description of a single or more doubly linked lists. All lists have linear structure: each element of list except the first has exactly one previous element; each element of list except the last has exactly one next element. Each memory cell contains information about one element from some list, each element of each list written in one of n given cells.
Output
Print n lines, the i-th line must contain two integers li and ri — the cells of the previous and the next element of list for cell i after all lists from the input are united in a single list. If there are many solutions print any of them.
Example
Input
7
4 7
5 0
0 0
6 1
0 2
0 4
1 0
Output
4 7
5 6
0 5
6 1
3 2
2 4
1 0
Submitted Solution:
```
n = int(input())
l, r = [0] * n, [0] * n
for i in range(n):
l[i], r[i] = map(int, input().split())
for it in range(1000):
if (l.count(0) == 1): break
a = l.index(0)
b = -1
for i in range(n):
if i == a: continue
if r[i] == 0: b = i
l[a] = b + 1
r[b] = a + 1
for i in range(n):
print(l[i], r[i])
``` | instruction | 0 | 29,677 | 12 | 59,354 |
No | output | 1 | 29,677 | 12 | 59,355 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Doubly linked list is one of the fundamental data structures. A doubly linked list is a sequence of elements, each containing information about the previous and the next elements of the list. In this problem all lists have linear structure. I.e. each element except the first has exactly one previous element, each element except the last has exactly one next element. The list is not closed in a cycle.
In this problem you are given n memory cells forming one or more doubly linked lists. Each cell contains information about element from some list. Memory cells are numbered from 1 to n.
For each cell i you are given two values:
* li — cell containing previous element for the element in the cell i;
* ri — cell containing next element for the element in the cell i.
If cell i contains information about the element which has no previous element then li = 0. Similarly, if cell i contains information about the element which has no next element then ri = 0.
<image> Three lists are shown on the picture.
For example, for the picture above the values of l and r are the following: l1 = 4, r1 = 7; l2 = 5, r2 = 0; l3 = 0, r3 = 0; l4 = 6, r4 = 1; l5 = 0, r5 = 2; l6 = 0, r6 = 4; l7 = 1, r7 = 0.
Your task is to unite all given lists in a single list, joining them to each other in any order. In particular, if the input data already contains a single list, then there is no need to perform any actions. Print the resulting list in the form of values li, ri.
Any other action, other than joining the beginning of one list to the end of another, can not be performed.
Input
The first line contains a single integer n (1 ≤ n ≤ 100) — the number of memory cells where the doubly linked lists are located.
Each of the following n lines contains two integers li, ri (0 ≤ li, ri ≤ n) — the cells of the previous and the next element of list for cell i. Value li = 0 if element in cell i has no previous element in its list. Value ri = 0 if element in cell i has no next element in its list.
It is guaranteed that the input contains the correct description of a single or more doubly linked lists. All lists have linear structure: each element of list except the first has exactly one previous element; each element of list except the last has exactly one next element. Each memory cell contains information about one element from some list, each element of each list written in one of n given cells.
Output
Print n lines, the i-th line must contain two integers li and ri — the cells of the previous and the next element of list for cell i after all lists from the input are united in a single list. If there are many solutions print any of them.
Example
Input
7
4 7
5 0
0 0
6 1
0 2
0 4
1 0
Output
4 7
5 6
0 5
6 1
3 2
2 4
1 0
Submitted Solution:
```
n = int(input())
unit = []
for i in range(1,n+1):
[l, r] = map(int, input().split())
find = -1
arrow = -1
for j in range(len(unit)):
if r != 0 and ((unit[j][0] == r) or (i == unit[j][0] and r == unit[j][1])):
find = j
if unit[j][0] == r:
arrow = 0
if i == unit[j][0] and r == unit[j][1]:
arrow = 1
if l != 0 and ((unit[j][-1] == l) or (i == unit[j][-1] and l == unit[j][-2])):
find = j
if unit[j][-1] == l and arrow != 1:
arrow = 2
if i == unit[j][-1] and l == unit[j][-2]:
arrow = 3
if find != -1:
break
if find == -1:
unit.append([l, i, r])
else:
if arrow == 0:
unit[find] = [l, i] + unit[find]
elif arrow == 1:
unit[find] = [l] + unit[find]
elif arrow == 2:
unit[find] = unit[find] + [i, r]
else:
unit[find] = unit[find] + [r]
result = []
result += unit[0]
for i in range(1, len(unit)):
if result[-1] == 0:
result.pop()
if unit[i][0] == 0:
result += unit[i][1:]
else:
result += unit[i]
for i in range(1, n+1):
k = result.index(i)
p = len(result)
print(result[(k-1+p) % p], result[(k+1+p)%p])
``` | instruction | 0 | 29,678 | 12 | 59,356 |
No | output | 1 | 29,678 | 12 | 59,357 |
Provide a correct Python 3 solution for this coding contest problem.
Shell Sort
Shell Sort is a generalization of Insertion Sort to arrange a list of $n$ elements $A$.
1 insertionSort(A, n, g)
2 for i = g to n-1
3 v = A[i]
4 j = i - g
5 while j >= 0 && A[j] > v
6 A[j+g] = A[j]
7 j = j - g
8 cnt++
9 A[j+g] = v
10
11 shellSort(A, n)
12 cnt = 0
13 m = ?
14 G[] = {?, ?,..., ?}
15 for i = 0 to m-1
16 insertionSort(A, n, G[i])
A function shellSort(A, n) performs a function insertionSort(A, n, g), which considers every $g$-th elements. Beginning with large values of $g$, it repeats the insertion sort with smaller $g$.
Your task is to complete the above program by filling ?. Write a program which reads an integer $n$ and a sequence $A$, and prints $m$, $G_i (i = 0, 1, ..., m − 1)$ in the pseudo code and the sequence $A$ in ascending order. The output of your program must meet the following requirements:
* $1 \leq m \leq 100$
* $0 \leq G_i \leq n$
* cnt does not exceed $\lceil n^{1.5}\rceil$
Constraints
* $1 \leq n \leq 1,000,000$
* $0 \leq A_i \leq 10^9$
Input
In the first line, an integer $n$ is given. In the following $n$ lines, $A_i (i=0,1,...,n-1)$ are given for each line.
Output
In the first line, print an integer $m$. In the second line, print $m$ integers $G_i (i=0,1,...,m-1)$ separated by single space character in a line.
In the third line, print cnt in a line. In the following $n$ lines, print $A_i (i=0,1,...,n-1)$ respectively.
This problem has multiple solutions and the judge will be performed by a special validator.
Examples
Input
5
5
1
4
3
2
Output
2
4 1
3
1
2
3
4
5
Input
3
3
2
1
Output
1
1
3
1
2
3 | instruction | 0 | 30,028 | 12 | 60,056 |
"Correct Solution:
```
import sys
n = int(input())
A=[int(e)for e in sys.stdin]
cnt = 0
G = [int((3**i-1)/2)for i in range(14,0,-1)]
G = [v for v in G if v <= n]
def insertionSort(A, n, g):
global cnt
for i in range(g, n):
v = A[i]
j = i - g
while j >= 0 and A[j] > v:
A[j+g] = A[j]
j = j - g
cnt += 1
A[j+g] = v
for g in G:
insertionSort(A, n, g)
print(len(G))
print(*G)
print(cnt)
print(*A,sep='\n')
``` | output | 1 | 30,028 | 12 | 60,057 |
Provide a correct Python 3 solution for this coding contest problem.
Shell Sort
Shell Sort is a generalization of Insertion Sort to arrange a list of $n$ elements $A$.
1 insertionSort(A, n, g)
2 for i = g to n-1
3 v = A[i]
4 j = i - g
5 while j >= 0 && A[j] > v
6 A[j+g] = A[j]
7 j = j - g
8 cnt++
9 A[j+g] = v
10
11 shellSort(A, n)
12 cnt = 0
13 m = ?
14 G[] = {?, ?,..., ?}
15 for i = 0 to m-1
16 insertionSort(A, n, G[i])
A function shellSort(A, n) performs a function insertionSort(A, n, g), which considers every $g$-th elements. Beginning with large values of $g$, it repeats the insertion sort with smaller $g$.
Your task is to complete the above program by filling ?. Write a program which reads an integer $n$ and a sequence $A$, and prints $m$, $G_i (i = 0, 1, ..., m − 1)$ in the pseudo code and the sequence $A$ in ascending order. The output of your program must meet the following requirements:
* $1 \leq m \leq 100$
* $0 \leq G_i \leq n$
* cnt does not exceed $\lceil n^{1.5}\rceil$
Constraints
* $1 \leq n \leq 1,000,000$
* $0 \leq A_i \leq 10^9$
Input
In the first line, an integer $n$ is given. In the following $n$ lines, $A_i (i=0,1,...,n-1)$ are given for each line.
Output
In the first line, print an integer $m$. In the second line, print $m$ integers $G_i (i=0,1,...,m-1)$ separated by single space character in a line.
In the third line, print cnt in a line. In the following $n$ lines, print $A_i (i=0,1,...,n-1)$ respectively.
This problem has multiple solutions and the judge will be performed by a special validator.
Examples
Input
5
5
1
4
3
2
Output
2
4 1
3
1
2
3
4
5
Input
3
3
2
1
Output
1
1
3
1
2
3 | instruction | 0 | 30,029 | 12 | 60,058 |
"Correct Solution:
```
cnt = 0
def insertionSort(A, n, g):
global cnt
for i in range(g, n):
v = A[i]
j = i - g
while (j >= 0) and (A[j] > v):
A[j + g] = A[j]
j = j - g
cnt += 1
A[j + g] = v
def shellSort(A, n):
G = [1]
for i in range(1, 100):
G.append(G[i - 1] * 3 + 1)
G = list(reversed([g for g in G if g <= n]))
m = len(G)
print(m)
if G:
print(*G)
for i in range(m):
insertionSort(A, n, G[i])
print(cnt)
n = int(input())
A = [int(input()) for _ in range(n)]
shellSort(A, n)
[print(a) for a in A]
``` | output | 1 | 30,029 | 12 | 60,059 |
Provide a correct Python 3 solution for this coding contest problem.
Shell Sort
Shell Sort is a generalization of Insertion Sort to arrange a list of $n$ elements $A$.
1 insertionSort(A, n, g)
2 for i = g to n-1
3 v = A[i]
4 j = i - g
5 while j >= 0 && A[j] > v
6 A[j+g] = A[j]
7 j = j - g
8 cnt++
9 A[j+g] = v
10
11 shellSort(A, n)
12 cnt = 0
13 m = ?
14 G[] = {?, ?,..., ?}
15 for i = 0 to m-1
16 insertionSort(A, n, G[i])
A function shellSort(A, n) performs a function insertionSort(A, n, g), which considers every $g$-th elements. Beginning with large values of $g$, it repeats the insertion sort with smaller $g$.
Your task is to complete the above program by filling ?. Write a program which reads an integer $n$ and a sequence $A$, and prints $m$, $G_i (i = 0, 1, ..., m − 1)$ in the pseudo code and the sequence $A$ in ascending order. The output of your program must meet the following requirements:
* $1 \leq m \leq 100$
* $0 \leq G_i \leq n$
* cnt does not exceed $\lceil n^{1.5}\rceil$
Constraints
* $1 \leq n \leq 1,000,000$
* $0 \leq A_i \leq 10^9$
Input
In the first line, an integer $n$ is given. In the following $n$ lines, $A_i (i=0,1,...,n-1)$ are given for each line.
Output
In the first line, print an integer $m$. In the second line, print $m$ integers $G_i (i=0,1,...,m-1)$ separated by single space character in a line.
In the third line, print cnt in a line. In the following $n$ lines, print $A_i (i=0,1,...,n-1)$ respectively.
This problem has multiple solutions and the judge will be performed by a special validator.
Examples
Input
5
5
1
4
3
2
Output
2
4 1
3
1
2
3
4
5
Input
3
3
2
1
Output
1
1
3
1
2
3 | instruction | 0 | 30,030 | 12 | 60,060 |
"Correct Solution:
```
def insertionSort(A, n, g):
global cnt
for i in range(g, n):
v = A[i]
j = i - g
while j >= 0 and A[j] > v:
A[j + g] = A[j]
j -= g
cnt += 1
A[j + g] = v
def shellSort(A, n):
G = [1]
m = 1
while True:
g = 3 * G[-1] + 1
if g >= n:
break
G.append(g)
m += 1
G.reverse()
for i in range(m):
insertionSort(A, n, G[i])
print(m)
print(" ".join(map(str, G)))
n = int(input())
A = []
for i in range(n):
A.append(int(input()))
cnt = 0
shellSort(A, n)
print(cnt)
for i in range(n):
print(A[i])
``` | output | 1 | 30,030 | 12 | 60,061 |
Provide a correct Python 3 solution for this coding contest problem.
Shell Sort
Shell Sort is a generalization of Insertion Sort to arrange a list of $n$ elements $A$.
1 insertionSort(A, n, g)
2 for i = g to n-1
3 v = A[i]
4 j = i - g
5 while j >= 0 && A[j] > v
6 A[j+g] = A[j]
7 j = j - g
8 cnt++
9 A[j+g] = v
10
11 shellSort(A, n)
12 cnt = 0
13 m = ?
14 G[] = {?, ?,..., ?}
15 for i = 0 to m-1
16 insertionSort(A, n, G[i])
A function shellSort(A, n) performs a function insertionSort(A, n, g), which considers every $g$-th elements. Beginning with large values of $g$, it repeats the insertion sort with smaller $g$.
Your task is to complete the above program by filling ?. Write a program which reads an integer $n$ and a sequence $A$, and prints $m$, $G_i (i = 0, 1, ..., m − 1)$ in the pseudo code and the sequence $A$ in ascending order. The output of your program must meet the following requirements:
* $1 \leq m \leq 100$
* $0 \leq G_i \leq n$
* cnt does not exceed $\lceil n^{1.5}\rceil$
Constraints
* $1 \leq n \leq 1,000,000$
* $0 \leq A_i \leq 10^9$
Input
In the first line, an integer $n$ is given. In the following $n$ lines, $A_i (i=0,1,...,n-1)$ are given for each line.
Output
In the first line, print an integer $m$. In the second line, print $m$ integers $G_i (i=0,1,...,m-1)$ separated by single space character in a line.
In the third line, print cnt in a line. In the following $n$ lines, print $A_i (i=0,1,...,n-1)$ respectively.
This problem has multiple solutions and the judge will be performed by a special validator.
Examples
Input
5
5
1
4
3
2
Output
2
4 1
3
1
2
3
4
5
Input
3
3
2
1
Output
1
1
3
1
2
3 | instruction | 0 | 30,031 | 12 | 60,062 |
"Correct Solution:
```
import copy
def insertion_sort(arr, n, g, cnt):
for i in range(g, n):
v = arr[i]
k = i - g
while k >= 0 and arr[k] > v:
arr[k + g] = arr[k]
k = k - g
cnt += 1
arr[k + g] = v
return arr, cnt
def shell_sort(arr, n, G):
A = copy.deepcopy(arr)
c = 0
for i in G:
A, c = insertion_sort(A, n, i, c)
return A, c
n = int(input())
A = []
for i in range(n):
A.append(int(input()))
G = [1]
h = 1
while h * 3 + 1 <= n:
h = 3 * h + 1
G.append(h)
a, cnt = shell_sort(A, n, G[::-1])
print(len(G))
print(*G[::-1])
print(cnt)
for i in a:
print(i)
``` | output | 1 | 30,031 | 12 | 60,063 |
Provide a correct Python 3 solution for this coding contest problem.
Shell Sort
Shell Sort is a generalization of Insertion Sort to arrange a list of $n$ elements $A$.
1 insertionSort(A, n, g)
2 for i = g to n-1
3 v = A[i]
4 j = i - g
5 while j >= 0 && A[j] > v
6 A[j+g] = A[j]
7 j = j - g
8 cnt++
9 A[j+g] = v
10
11 shellSort(A, n)
12 cnt = 0
13 m = ?
14 G[] = {?, ?,..., ?}
15 for i = 0 to m-1
16 insertionSort(A, n, G[i])
A function shellSort(A, n) performs a function insertionSort(A, n, g), which considers every $g$-th elements. Beginning with large values of $g$, it repeats the insertion sort with smaller $g$.
Your task is to complete the above program by filling ?. Write a program which reads an integer $n$ and a sequence $A$, and prints $m$, $G_i (i = 0, 1, ..., m − 1)$ in the pseudo code and the sequence $A$ in ascending order. The output of your program must meet the following requirements:
* $1 \leq m \leq 100$
* $0 \leq G_i \leq n$
* cnt does not exceed $\lceil n^{1.5}\rceil$
Constraints
* $1 \leq n \leq 1,000,000$
* $0 \leq A_i \leq 10^9$
Input
In the first line, an integer $n$ is given. In the following $n$ lines, $A_i (i=0,1,...,n-1)$ are given for each line.
Output
In the first line, print an integer $m$. In the second line, print $m$ integers $G_i (i=0,1,...,m-1)$ separated by single space character in a line.
In the third line, print cnt in a line. In the following $n$ lines, print $A_i (i=0,1,...,n-1)$ respectively.
This problem has multiple solutions and the judge will be performed by a special validator.
Examples
Input
5
5
1
4
3
2
Output
2
4 1
3
1
2
3
4
5
Input
3
3
2
1
Output
1
1
3
1
2
3 | instruction | 0 | 30,032 | 12 | 60,064 |
"Correct Solution:
```
import sys
n = int(input())
A = [int(e)for e in sys.stdin]
cnt = 0
G = [int((2.25**i-1)/1.25)for i in range(19,0,-1)]
G = [v for v in G if v <= n]
def insertionSort(A, n, g):
global cnt
for i in range(g, n):
v = A[i]
j = i - g
while j >= 0 and A[j] > v:
A[j+g] = A[j]
j = j - g
cnt += 1
A[j+g] = v
for g in G:
insertionSort(A, n, g)
print(len(G))
print(*G)
print(cnt)
print(*A,sep='\n')
``` | output | 1 | 30,032 | 12 | 60,065 |
Provide a correct Python 3 solution for this coding contest problem.
Shell Sort
Shell Sort is a generalization of Insertion Sort to arrange a list of $n$ elements $A$.
1 insertionSort(A, n, g)
2 for i = g to n-1
3 v = A[i]
4 j = i - g
5 while j >= 0 && A[j] > v
6 A[j+g] = A[j]
7 j = j - g
8 cnt++
9 A[j+g] = v
10
11 shellSort(A, n)
12 cnt = 0
13 m = ?
14 G[] = {?, ?,..., ?}
15 for i = 0 to m-1
16 insertionSort(A, n, G[i])
A function shellSort(A, n) performs a function insertionSort(A, n, g), which considers every $g$-th elements. Beginning with large values of $g$, it repeats the insertion sort with smaller $g$.
Your task is to complete the above program by filling ?. Write a program which reads an integer $n$ and a sequence $A$, and prints $m$, $G_i (i = 0, 1, ..., m − 1)$ in the pseudo code and the sequence $A$ in ascending order. The output of your program must meet the following requirements:
* $1 \leq m \leq 100$
* $0 \leq G_i \leq n$
* cnt does not exceed $\lceil n^{1.5}\rceil$
Constraints
* $1 \leq n \leq 1,000,000$
* $0 \leq A_i \leq 10^9$
Input
In the first line, an integer $n$ is given. In the following $n$ lines, $A_i (i=0,1,...,n-1)$ are given for each line.
Output
In the first line, print an integer $m$. In the second line, print $m$ integers $G_i (i=0,1,...,m-1)$ separated by single space character in a line.
In the third line, print cnt in a line. In the following $n$ lines, print $A_i (i=0,1,...,n-1)$ respectively.
This problem has multiple solutions and the judge will be performed by a special validator.
Examples
Input
5
5
1
4
3
2
Output
2
4 1
3
1
2
3
4
5
Input
3
3
2
1
Output
1
1
3
1
2
3 | instruction | 0 | 30,033 | 12 | 60,066 |
"Correct Solution:
```
def insertionSort(a, n, g):
global cnt
for i in range(g, n):
v = a[i]
j = i - g
while j >= 0 and a[j] > v:
a[j+g] = a[j]
j = j - g
cnt = cnt + 1
a[j+g] = v
def shellSort(a, n):
global cnt
global G
global m
cnt = 0
G = [1]
while 3 * G[0] + 1 <= n:
G = [ 3*G[0]+1 ] + G
m = len(G)
for i in range(0, m):
insertionSort(a, n, G[i])
n = int(input())
a = [int(input()) for i in range(0, n)]
shellSort(a, n)
print(m)
print(*G)
print(cnt)
for i in range(0, n):
print(a[i])
``` | output | 1 | 30,033 | 12 | 60,067 |
Provide a correct Python 3 solution for this coding contest problem.
Shell Sort
Shell Sort is a generalization of Insertion Sort to arrange a list of $n$ elements $A$.
1 insertionSort(A, n, g)
2 for i = g to n-1
3 v = A[i]
4 j = i - g
5 while j >= 0 && A[j] > v
6 A[j+g] = A[j]
7 j = j - g
8 cnt++
9 A[j+g] = v
10
11 shellSort(A, n)
12 cnt = 0
13 m = ?
14 G[] = {?, ?,..., ?}
15 for i = 0 to m-1
16 insertionSort(A, n, G[i])
A function shellSort(A, n) performs a function insertionSort(A, n, g), which considers every $g$-th elements. Beginning with large values of $g$, it repeats the insertion sort with smaller $g$.
Your task is to complete the above program by filling ?. Write a program which reads an integer $n$ and a sequence $A$, and prints $m$, $G_i (i = 0, 1, ..., m − 1)$ in the pseudo code and the sequence $A$ in ascending order. The output of your program must meet the following requirements:
* $1 \leq m \leq 100$
* $0 \leq G_i \leq n$
* cnt does not exceed $\lceil n^{1.5}\rceil$
Constraints
* $1 \leq n \leq 1,000,000$
* $0 \leq A_i \leq 10^9$
Input
In the first line, an integer $n$ is given. In the following $n$ lines, $A_i (i=0,1,...,n-1)$ are given for each line.
Output
In the first line, print an integer $m$. In the second line, print $m$ integers $G_i (i=0,1,...,m-1)$ separated by single space character in a line.
In the third line, print cnt in a line. In the following $n$ lines, print $A_i (i=0,1,...,n-1)$ respectively.
This problem has multiple solutions and the judge will be performed by a special validator.
Examples
Input
5
5
1
4
3
2
Output
2
4 1
3
1
2
3
4
5
Input
3
3
2
1
Output
1
1
3
1
2
3 | instruction | 0 | 30,034 | 12 | 60,068 |
"Correct Solution:
```
import sys
count = 0
def insertionSort(A, n, g):
global count
for i in range(n):
v = A[i]
j = i - g
while j >= 0 and A[j] > v:
A[j+g] = A[j]
j = j - g
count += 1
A[j+g] = v
return A
def shellSort(A, n):
for i in range(m):
insertionSort(A, n, G[i])
return A
n = int(input())
A = []
for i in range(n):
A.append(int(input()))
G = [1]
m = 1
while True:
x = 3 * G[m-1] + 1
if x >= n: break
G.append(x)
m += 1
G = G[::-1]
shellSort(A, n)
print(m)
print(' '.join([str(i) for i in G]))
print(count)
for i in A:
print(i)
``` | output | 1 | 30,034 | 12 | 60,069 |
Provide a correct Python 3 solution for this coding contest problem.
Shell Sort
Shell Sort is a generalization of Insertion Sort to arrange a list of $n$ elements $A$.
1 insertionSort(A, n, g)
2 for i = g to n-1
3 v = A[i]
4 j = i - g
5 while j >= 0 && A[j] > v
6 A[j+g] = A[j]
7 j = j - g
8 cnt++
9 A[j+g] = v
10
11 shellSort(A, n)
12 cnt = 0
13 m = ?
14 G[] = {?, ?,..., ?}
15 for i = 0 to m-1
16 insertionSort(A, n, G[i])
A function shellSort(A, n) performs a function insertionSort(A, n, g), which considers every $g$-th elements. Beginning with large values of $g$, it repeats the insertion sort with smaller $g$.
Your task is to complete the above program by filling ?. Write a program which reads an integer $n$ and a sequence $A$, and prints $m$, $G_i (i = 0, 1, ..., m − 1)$ in the pseudo code and the sequence $A$ in ascending order. The output of your program must meet the following requirements:
* $1 \leq m \leq 100$
* $0 \leq G_i \leq n$
* cnt does not exceed $\lceil n^{1.5}\rceil$
Constraints
* $1 \leq n \leq 1,000,000$
* $0 \leq A_i \leq 10^9$
Input
In the first line, an integer $n$ is given. In the following $n$ lines, $A_i (i=0,1,...,n-1)$ are given for each line.
Output
In the first line, print an integer $m$. In the second line, print $m$ integers $G_i (i=0,1,...,m-1)$ separated by single space character in a line.
In the third line, print cnt in a line. In the following $n$ lines, print $A_i (i=0,1,...,n-1)$ respectively.
This problem has multiple solutions and the judge will be performed by a special validator.
Examples
Input
5
5
1
4
3
2
Output
2
4 1
3
1
2
3
4
5
Input
3
3
2
1
Output
1
1
3
1
2
3 | instruction | 0 | 30,035 | 12 | 60,070 |
"Correct Solution:
```
import sys
n = int(input())
A = [int(e)for e in sys.stdin]
cnt = 0
G = [int((2.1**i-1)/1.1)for i in range(19,1,-1)]+[1]
G = [v for v in G if v <= n]
def insertionSort(A, n, g):
global cnt
for i in range(g, n):
v = A[i]
j = i - g
while j >= 0 and A[j] > v:
A[j+g] = A[j]
j = j - g
cnt += 1
A[j+g] = v
for g in G:
insertionSort(A, n, g)
print(len(G))
print(*G)
print(cnt)
print(*A,sep='\n')
``` | output | 1 | 30,035 | 12 | 60,071 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Shell Sort
Shell Sort is a generalization of Insertion Sort to arrange a list of $n$ elements $A$.
1 insertionSort(A, n, g)
2 for i = g to n-1
3 v = A[i]
4 j = i - g
5 while j >= 0 && A[j] > v
6 A[j+g] = A[j]
7 j = j - g
8 cnt++
9 A[j+g] = v
10
11 shellSort(A, n)
12 cnt = 0
13 m = ?
14 G[] = {?, ?,..., ?}
15 for i = 0 to m-1
16 insertionSort(A, n, G[i])
A function shellSort(A, n) performs a function insertionSort(A, n, g), which considers every $g$-th elements. Beginning with large values of $g$, it repeats the insertion sort with smaller $g$.
Your task is to complete the above program by filling ?. Write a program which reads an integer $n$ and a sequence $A$, and prints $m$, $G_i (i = 0, 1, ..., m − 1)$ in the pseudo code and the sequence $A$ in ascending order. The output of your program must meet the following requirements:
* $1 \leq m \leq 100$
* $0 \leq G_i \leq n$
* cnt does not exceed $\lceil n^{1.5}\rceil$
Constraints
* $1 \leq n \leq 1,000,000$
* $0 \leq A_i \leq 10^9$
Input
In the first line, an integer $n$ is given. In the following $n$ lines, $A_i (i=0,1,...,n-1)$ are given for each line.
Output
In the first line, print an integer $m$. In the second line, print $m$ integers $G_i (i=0,1,...,m-1)$ separated by single space character in a line.
In the third line, print cnt in a line. In the following $n$ lines, print $A_i (i=0,1,...,n-1)$ respectively.
This problem has multiple solutions and the judge will be performed by a special validator.
Examples
Input
5
5
1
4
3
2
Output
2
4 1
3
1
2
3
4
5
Input
3
3
2
1
Output
1
1
3
1
2
3
Submitted Solution:
```
def insertionSort(A,n,g,count):
for i in range(g,N):
v = A[i]
j = i-g
while j >= 0 and A[j] > v:
A[j+g] = A[j]
j -= g
count += 1
A[j+g] = v
return count
def shellSort(A,n):
count = 0
m = 0
G = []
while (3**(m+1)-1)//2 <= n:
m += 1
G.append((3**m-1)//2)
for i in range(m):
count = insertionSort(A,n,G[-1-i],count)
return m,G,count
import sys
input = sys.stdin.readline
N = int(input())
A = [int(input()) for _ in range(N)]
m,G,count = shellSort(A,N)
print(m)
print(*G[::-1])
print(count)
print('\n'.join(map(str,A)))
``` | instruction | 0 | 30,036 | 12 | 60,072 |
Yes | output | 1 | 30,036 | 12 | 60,073 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Shell Sort
Shell Sort is a generalization of Insertion Sort to arrange a list of $n$ elements $A$.
1 insertionSort(A, n, g)
2 for i = g to n-1
3 v = A[i]
4 j = i - g
5 while j >= 0 && A[j] > v
6 A[j+g] = A[j]
7 j = j - g
8 cnt++
9 A[j+g] = v
10
11 shellSort(A, n)
12 cnt = 0
13 m = ?
14 G[] = {?, ?,..., ?}
15 for i = 0 to m-1
16 insertionSort(A, n, G[i])
A function shellSort(A, n) performs a function insertionSort(A, n, g), which considers every $g$-th elements. Beginning with large values of $g$, it repeats the insertion sort with smaller $g$.
Your task is to complete the above program by filling ?. Write a program which reads an integer $n$ and a sequence $A$, and prints $m$, $G_i (i = 0, 1, ..., m − 1)$ in the pseudo code and the sequence $A$ in ascending order. The output of your program must meet the following requirements:
* $1 \leq m \leq 100$
* $0 \leq G_i \leq n$
* cnt does not exceed $\lceil n^{1.5}\rceil$
Constraints
* $1 \leq n \leq 1,000,000$
* $0 \leq A_i \leq 10^9$
Input
In the first line, an integer $n$ is given. In the following $n$ lines, $A_i (i=0,1,...,n-1)$ are given for each line.
Output
In the first line, print an integer $m$. In the second line, print $m$ integers $G_i (i=0,1,...,m-1)$ separated by single space character in a line.
In the third line, print cnt in a line. In the following $n$ lines, print $A_i (i=0,1,...,n-1)$ respectively.
This problem has multiple solutions and the judge will be performed by a special validator.
Examples
Input
5
5
1
4
3
2
Output
2
4 1
3
1
2
3
4
5
Input
3
3
2
1
Output
1
1
3
1
2
3
Submitted Solution:
```
def insert_sort(A,n,g):
cnt = 0
for i in range(g,n):
key = A[i]
j = i - g
while j >= 0 and A[j] > key:
A[j+g] = A[j]
j -= g
cnt+=1
A[j+g] = key
return cnt
def shell_sort(A,n):
cnt = 0
g = []
tmp = 1
while tmp <= -(-n//3):
g.append(tmp)
tmp = tmp*3 + 1
g.reverse()
m = len(g)
print(m)
print(*g)
for i in range(m):
cnt += insert_sort(A,n,g[i])
print(cnt)
if __name__ == '__main__':
n = int(input())
A = []
for i in range(n):
A.append(int(input()))
shell_sort(A,n)
for i in A:
print(i)
``` | instruction | 0 | 30,037 | 12 | 60,074 |
Yes | output | 1 | 30,037 | 12 | 60,075 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Shell Sort
Shell Sort is a generalization of Insertion Sort to arrange a list of $n$ elements $A$.
1 insertionSort(A, n, g)
2 for i = g to n-1
3 v = A[i]
4 j = i - g
5 while j >= 0 && A[j] > v
6 A[j+g] = A[j]
7 j = j - g
8 cnt++
9 A[j+g] = v
10
11 shellSort(A, n)
12 cnt = 0
13 m = ?
14 G[] = {?, ?,..., ?}
15 for i = 0 to m-1
16 insertionSort(A, n, G[i])
A function shellSort(A, n) performs a function insertionSort(A, n, g), which considers every $g$-th elements. Beginning with large values of $g$, it repeats the insertion sort with smaller $g$.
Your task is to complete the above program by filling ?. Write a program which reads an integer $n$ and a sequence $A$, and prints $m$, $G_i (i = 0, 1, ..., m − 1)$ in the pseudo code and the sequence $A$ in ascending order. The output of your program must meet the following requirements:
* $1 \leq m \leq 100$
* $0 \leq G_i \leq n$
* cnt does not exceed $\lceil n^{1.5}\rceil$
Constraints
* $1 \leq n \leq 1,000,000$
* $0 \leq A_i \leq 10^9$
Input
In the first line, an integer $n$ is given. In the following $n$ lines, $A_i (i=0,1,...,n-1)$ are given for each line.
Output
In the first line, print an integer $m$. In the second line, print $m$ integers $G_i (i=0,1,...,m-1)$ separated by single space character in a line.
In the third line, print cnt in a line. In the following $n$ lines, print $A_i (i=0,1,...,n-1)$ respectively.
This problem has multiple solutions and the judge will be performed by a special validator.
Examples
Input
5
5
1
4
3
2
Output
2
4 1
3
1
2
3
4
5
Input
3
3
2
1
Output
1
1
3
1
2
3
Submitted Solution:
```
import math
import sys
def insertion_sort(a, n, g):
ct = 0
for i in range(g,n):
v = a[i]
j = i-g
while j >= 0 and a[j] > v:
a[j+g] = a[j]
j = j-g
ct += 1
a[j+g] = v
return ct
n = int(input())
a = list(map(int, sys.stdin.readlines()))
m = 0
b = 0
ct= 0
g = []
while True:
b = 2.25*b+1
if b > n:
break
g.append(math.ceil(b))
m += 1
g = g[::-1]
for i in g:
ct += insertion_sort(a, n, i)
print(m)
print(*g, sep=" ")
print(ct)
print(*a, sep="\n")
``` | instruction | 0 | 30,038 | 12 | 60,076 |
Yes | output | 1 | 30,038 | 12 | 60,077 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Shell Sort
Shell Sort is a generalization of Insertion Sort to arrange a list of $n$ elements $A$.
1 insertionSort(A, n, g)
2 for i = g to n-1
3 v = A[i]
4 j = i - g
5 while j >= 0 && A[j] > v
6 A[j+g] = A[j]
7 j = j - g
8 cnt++
9 A[j+g] = v
10
11 shellSort(A, n)
12 cnt = 0
13 m = ?
14 G[] = {?, ?,..., ?}
15 for i = 0 to m-1
16 insertionSort(A, n, G[i])
A function shellSort(A, n) performs a function insertionSort(A, n, g), which considers every $g$-th elements. Beginning with large values of $g$, it repeats the insertion sort with smaller $g$.
Your task is to complete the above program by filling ?. Write a program which reads an integer $n$ and a sequence $A$, and prints $m$, $G_i (i = 0, 1, ..., m − 1)$ in the pseudo code and the sequence $A$ in ascending order. The output of your program must meet the following requirements:
* $1 \leq m \leq 100$
* $0 \leq G_i \leq n$
* cnt does not exceed $\lceil n^{1.5}\rceil$
Constraints
* $1 \leq n \leq 1,000,000$
* $0 \leq A_i \leq 10^9$
Input
In the first line, an integer $n$ is given. In the following $n$ lines, $A_i (i=0,1,...,n-1)$ are given for each line.
Output
In the first line, print an integer $m$. In the second line, print $m$ integers $G_i (i=0,1,...,m-1)$ separated by single space character in a line.
In the third line, print cnt in a line. In the following $n$ lines, print $A_i (i=0,1,...,n-1)$ respectively.
This problem has multiple solutions and the judge will be performed by a special validator.
Examples
Input
5
5
1
4
3
2
Output
2
4 1
3
1
2
3
4
5
Input
3
3
2
1
Output
1
1
3
1
2
3
Submitted Solution:
```
import math
def insertionSort(A, N, h):
global cnt
for i in range(h, N):
v = A[i]
j = i - h
while j >= 0 and A[j] > v:
A[j + h] = A[j]
j = j - h
cnt += 1
A[j + h] = v
N = int(input())
A = [int(input()) for _ in range(N)]
G = [int((3 ** i - 1) // 2) for i in range(1, int(math.log(2 * N + 1)) + 1) if int((3 ** i - 1) // 2) < N]
if G == []: G.append(1)
G.reverse()
cnt = 0
for h in G:
insertionSort(A, N, h)
print(len(G))
print(*G)
print(cnt)
print(*A, sep = '\n')
``` | instruction | 0 | 30,039 | 12 | 60,078 |
Yes | output | 1 | 30,039 | 12 | 60,079 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Shell Sort
Shell Sort is a generalization of Insertion Sort to arrange a list of $n$ elements $A$.
1 insertionSort(A, n, g)
2 for i = g to n-1
3 v = A[i]
4 j = i - g
5 while j >= 0 && A[j] > v
6 A[j+g] = A[j]
7 j = j - g
8 cnt++
9 A[j+g] = v
10
11 shellSort(A, n)
12 cnt = 0
13 m = ?
14 G[] = {?, ?,..., ?}
15 for i = 0 to m-1
16 insertionSort(A, n, G[i])
A function shellSort(A, n) performs a function insertionSort(A, n, g), which considers every $g$-th elements. Beginning with large values of $g$, it repeats the insertion sort with smaller $g$.
Your task is to complete the above program by filling ?. Write a program which reads an integer $n$ and a sequence $A$, and prints $m$, $G_i (i = 0, 1, ..., m − 1)$ in the pseudo code and the sequence $A$ in ascending order. The output of your program must meet the following requirements:
* $1 \leq m \leq 100$
* $0 \leq G_i \leq n$
* cnt does not exceed $\lceil n^{1.5}\rceil$
Constraints
* $1 \leq n \leq 1,000,000$
* $0 \leq A_i \leq 10^9$
Input
In the first line, an integer $n$ is given. In the following $n$ lines, $A_i (i=0,1,...,n-1)$ are given for each line.
Output
In the first line, print an integer $m$. In the second line, print $m$ integers $G_i (i=0,1,...,m-1)$ separated by single space character in a line.
In the third line, print cnt in a line. In the following $n$ lines, print $A_i (i=0,1,...,n-1)$ respectively.
This problem has multiple solutions and the judge will be performed by a special validator.
Examples
Input
5
5
1
4
3
2
Output
2
4 1
3
1
2
3
4
5
Input
3
3
2
1
Output
1
1
3
1
2
3
Submitted Solution:
```
def insertionSort(A, n, g):
global cnt
for i in range(g, n):
v = A[i]
j = i - g
while j >= 0 and int(A[j]) > int(v):
A[j + g] = A[j]
j = j - g
cnt += 1
A[j + g] = v
def shellSort(A, n):
global m, G
for i in range(0, m):
insertionSort(A, n, G[i])
n = int(input())
A = []
for i in range(0, n):
A.append(int(input()))
G = []
h = 1
for i in range(1, 999999):
if h > n:
break
G.append(h)
h = 3 * h + 1
cnt = 0
m = len(G)
shellSort(A, n)
'''
m = 2
G = (4,1)
shellSort(A, n)
'''
print(m)
print(" ".join(map(str, G)))
print(cnt)
for i in range(0, n):
print(A[i])
``` | instruction | 0 | 30,040 | 12 | 60,080 |
No | output | 1 | 30,040 | 12 | 60,081 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Shell Sort
Shell Sort is a generalization of Insertion Sort to arrange a list of $n$ elements $A$.
1 insertionSort(A, n, g)
2 for i = g to n-1
3 v = A[i]
4 j = i - g
5 while j >= 0 && A[j] > v
6 A[j+g] = A[j]
7 j = j - g
8 cnt++
9 A[j+g] = v
10
11 shellSort(A, n)
12 cnt = 0
13 m = ?
14 G[] = {?, ?,..., ?}
15 for i = 0 to m-1
16 insertionSort(A, n, G[i])
A function shellSort(A, n) performs a function insertionSort(A, n, g), which considers every $g$-th elements. Beginning with large values of $g$, it repeats the insertion sort with smaller $g$.
Your task is to complete the above program by filling ?. Write a program which reads an integer $n$ and a sequence $A$, and prints $m$, $G_i (i = 0, 1, ..., m − 1)$ in the pseudo code and the sequence $A$ in ascending order. The output of your program must meet the following requirements:
* $1 \leq m \leq 100$
* $0 \leq G_i \leq n$
* cnt does not exceed $\lceil n^{1.5}\rceil$
Constraints
* $1 \leq n \leq 1,000,000$
* $0 \leq A_i \leq 10^9$
Input
In the first line, an integer $n$ is given. In the following $n$ lines, $A_i (i=0,1,...,n-1)$ are given for each line.
Output
In the first line, print an integer $m$. In the second line, print $m$ integers $G_i (i=0,1,...,m-1)$ separated by single space character in a line.
In the third line, print cnt in a line. In the following $n$ lines, print $A_i (i=0,1,...,n-1)$ respectively.
This problem has multiple solutions and the judge will be performed by a special validator.
Examples
Input
5
5
1
4
3
2
Output
2
4 1
3
1
2
3
4
5
Input
3
3
2
1
Output
1
1
3
1
2
3
Submitted Solution:
```
def shellsort(a):
l = len(a)
intervals = [n for n in (40, 13, 4, 1) if n <= l]
count = 0
for interval in intervals:
for i in range(interval, l):
j = 0
while i-interval*(j+1) >= 0:
n, m = i-interval*j, i-interval*(j+1)
if a[n] < a[m]:
a[n], a[m] = a[m], a[n]
j += 1
count += 1
else:
break
print(len(intervals))
print(" ".join([str(n) for n in intervals]))
print(count)
print("\n".join([str(n) for n in a]))
shellsort([int(input()) for _ in range(int(input()))])
``` | instruction | 0 | 30,041 | 12 | 60,082 |
No | output | 1 | 30,041 | 12 | 60,083 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Shell Sort
Shell Sort is a generalization of Insertion Sort to arrange a list of $n$ elements $A$.
1 insertionSort(A, n, g)
2 for i = g to n-1
3 v = A[i]
4 j = i - g
5 while j >= 0 && A[j] > v
6 A[j+g] = A[j]
7 j = j - g
8 cnt++
9 A[j+g] = v
10
11 shellSort(A, n)
12 cnt = 0
13 m = ?
14 G[] = {?, ?,..., ?}
15 for i = 0 to m-1
16 insertionSort(A, n, G[i])
A function shellSort(A, n) performs a function insertionSort(A, n, g), which considers every $g$-th elements. Beginning with large values of $g$, it repeats the insertion sort with smaller $g$.
Your task is to complete the above program by filling ?. Write a program which reads an integer $n$ and a sequence $A$, and prints $m$, $G_i (i = 0, 1, ..., m − 1)$ in the pseudo code and the sequence $A$ in ascending order. The output of your program must meet the following requirements:
* $1 \leq m \leq 100$
* $0 \leq G_i \leq n$
* cnt does not exceed $\lceil n^{1.5}\rceil$
Constraints
* $1 \leq n \leq 1,000,000$
* $0 \leq A_i \leq 10^9$
Input
In the first line, an integer $n$ is given. In the following $n$ lines, $A_i (i=0,1,...,n-1)$ are given for each line.
Output
In the first line, print an integer $m$. In the second line, print $m$ integers $G_i (i=0,1,...,m-1)$ separated by single space character in a line.
In the third line, print cnt in a line. In the following $n$ lines, print $A_i (i=0,1,...,n-1)$ respectively.
This problem has multiple solutions and the judge will be performed by a special validator.
Examples
Input
5
5
1
4
3
2
Output
2
4 1
3
1
2
3
4
5
Input
3
3
2
1
Output
1
1
3
1
2
3
Submitted Solution:
```
def InsertionSort(A, N, Gap):
c = 0
for i in range(Gap, N):
v = A[i]
j = i - Gap
while j >= 0 and A[j] > v:
A[j+Gap] = A[j]
j -= Gap
c += 1
A[j+Gap] = v
return A, c
def ShellSort(A, N):
cnt = 0
G = [3*i+1 for i in range(N) if (3*i+1) < N]
for g in G[::-1]:
A, c = InsertionSort(A, N, g)
cnt += c
return A, cnt, G
N = int(input())
A = []
cnt = 0
for _ in range(N):
A.append(int(input()))
sorted_A, cnt, G = ShellSort(A, N)
if len(G) > 0:
print(len(G))
print(*G[::-1])
print(cnt)
for s_a in sorted_A:
print(s_a)
``` | instruction | 0 | 30,042 | 12 | 60,084 |
No | output | 1 | 30,042 | 12 | 60,085 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Shell Sort
Shell Sort is a generalization of Insertion Sort to arrange a list of $n$ elements $A$.
1 insertionSort(A, n, g)
2 for i = g to n-1
3 v = A[i]
4 j = i - g
5 while j >= 0 && A[j] > v
6 A[j+g] = A[j]
7 j = j - g
8 cnt++
9 A[j+g] = v
10
11 shellSort(A, n)
12 cnt = 0
13 m = ?
14 G[] = {?, ?,..., ?}
15 for i = 0 to m-1
16 insertionSort(A, n, G[i])
A function shellSort(A, n) performs a function insertionSort(A, n, g), which considers every $g$-th elements. Beginning with large values of $g$, it repeats the insertion sort with smaller $g$.
Your task is to complete the above program by filling ?. Write a program which reads an integer $n$ and a sequence $A$, and prints $m$, $G_i (i = 0, 1, ..., m − 1)$ in the pseudo code and the sequence $A$ in ascending order. The output of your program must meet the following requirements:
* $1 \leq m \leq 100$
* $0 \leq G_i \leq n$
* cnt does not exceed $\lceil n^{1.5}\rceil$
Constraints
* $1 \leq n \leq 1,000,000$
* $0 \leq A_i \leq 10^9$
Input
In the first line, an integer $n$ is given. In the following $n$ lines, $A_i (i=0,1,...,n-1)$ are given for each line.
Output
In the first line, print an integer $m$. In the second line, print $m$ integers $G_i (i=0,1,...,m-1)$ separated by single space character in a line.
In the third line, print cnt in a line. In the following $n$ lines, print $A_i (i=0,1,...,n-1)$ respectively.
This problem has multiple solutions and the judge will be performed by a special validator.
Examples
Input
5
5
1
4
3
2
Output
2
4 1
3
1
2
3
4
5
Input
3
3
2
1
Output
1
1
3
1
2
3
Submitted Solution:
```
#ALDS1_2-C Sort 1 - Shell Sort
def insertionSort(A,n,g):
cnt=0
i=g
while(i<n):
v=A[i]
j=i-g
while(j>=0 and A[j]>v):
A[j+g]=A[j]
j=j-g
cnt+=1
A[j+g]=v
i+=1
return cnt
def shellSort(A,n):
cnt=0
G=[]
h=1
m=0
shells=""
while h<n:
G.insert(0,h)
shells = " "+str(h)+shells
h=h*3+1
m+=1
print(m)
if(shells==""):
shells=" 0"
print(shells[1:])
for i in range(m):
cnt+=insertionSort(A,n,G[i])
print(cnt)
n=int(input())
A=[]
for i in range(n):
A.append(int(input()))
shellSort(A,n)
for i in range(n):
print(A[i])
``` | instruction | 0 | 30,043 | 12 | 60,086 |
No | output | 1 | 30,043 | 12 | 60,087 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Initially there was an array a consisting of n integers. Positions in it are numbered from 1 to n.
Exactly q queries were performed on the array. During the i-th query some segment (l_i, r_i) (1 ≤ l_i ≤ r_i ≤ n) was selected and values of elements on positions from l_i to r_i inclusive got changed to i. The order of the queries couldn't be changed and all q queries were applied. It is also known that every position from 1 to n got covered by at least one segment.
We could have offered you the problem about checking if some given array (consisting of n integers with values from 1 to q) can be obtained by the aforementioned queries. However, we decided that it will come too easy for you.
So the enhancement we introduced to it is the following. Some set of positions (possibly empty) in this array is selected and values of elements on these positions are set to 0.
Your task is to check if this array can be obtained by the aforementioned queries. Also if it can be obtained then restore this array.
If there are multiple possible arrays then print any of them.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 2 ⋅ 10^5) — the number of elements of the array and the number of queries perfomed on it.
The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ q) — the resulting array. If element at some position j is equal to 0 then the value of element at this position can be any integer from 1 to q.
Output
Print "YES" if the array a can be obtained by performing q queries. Segments (l_i, r_i) (1 ≤ l_i ≤ r_i ≤ n) are chosen separately for each query. Every position from 1 to n should be covered by at least one segment.
Otherwise print "NO".
If some array can be obtained then print n integers on the second line — the i-th number should be equal to the i-th element of the resulting array and should have value from 1 to q. This array should be obtainable by performing exactly q queries.
If there are multiple possible arrays then print any of them.
Examples
Input
4 3
1 0 2 3
Output
YES
1 2 2 3
Input
3 10
10 10 10
Output
YES
10 10 10
Input
5 6
6 5 6 2 2
Output
NO
Input
3 5
0 0 0
Output
YES
5 4 2
Note
In the first example you can also replace 0 with 1 but not with 3.
In the second example it doesn't really matter what segments to choose until query 10 when the segment is (1, 3).
The third example showcases the fact that the order of queries can't be changed, you can't firstly set (1, 3) to 6 and after that change (2, 2) to 5. The segment of 5 should be applied before segment of 6.
There is a lot of correct resulting arrays for the fourth example. | instruction | 0 | 30,060 | 12 | 60,120 |
Tags: constructive algorithms, data structures
Correct Solution:
```
####################################### Define
oo = int(1e9)
maxN = int(2e5 + 10)
rmq = [[0 for i in range(20)] for j in range(maxN)]
a = [0] * maxN
ans = [0] * maxN
lst = [0] * maxN
nxt = [0] * maxN
check = [False] * maxN
####################################### Functions
def get(lef, rig) :
len = rig - lef + 1
pw2 = 0
while (1 << (pw2 + 1)) <= len: pw2 += 1
return min(rmq[lef][pw2], rmq[rig - (1 << pw2) + 1][pw2])
####################################### Main
n, q = (int(s) for s in input().split())
inp = input().split()
flag = False
for i in range(1, n + 1) :
a[i] = int(inp[i - 1])
if a[i] == q : flag = True
if a[i] == 0: a[i] = oo
if flag == False:
for i in range(1, n + 1) :
if a[i] == oo :
a[i] = q
flag = True
break
for i in range(1, n + 1) :
for j in range(0, 19) :
rmq[i][j] = oo
for i in range(n, 0, -1) :
rmq[i][0] = a[i];
for j in range(0, 18) :
if i + (1 << j) <= n:
rmq[i][j + 1] = min(rmq[i][j], rmq[i + (1 << j)][j])
for i in range(1, n + 1) :
if a[i] < oo and check[ a[i] ] == False :
lst[ a[i] ] = i
check[ a[i] ] = True
for i in range(1, maxN): check[i] = False
for i in range(n, 0, -1) :
if a[i] < oo and check[a[i]] == False :
tmp = get(lst[ a[i] ], i)
if tmp < a[i] or flag == False :
print("NO")
exit()
nxt[ a[i] ] = i;
check[ a[i] ] = True
cur = [0]
for i in range(1, n + 1) :
if a[i] < oo :
ans[i] = a[i]
if lst[ a[i] ] == i : cur.append(a[i])
if nxt[ a[i] ] == i : cur.pop()
elif len(cur) > 1 : ans[i] = cur[-1]
for i in range(2, n + 1) :
if ans[i] == 0 : ans[i] = ans[i - 1]
for i in range(n - 1, 0, -1) :
if ans[i] == 0 : ans[i] = ans[i + 1]
print("YES")
for i in range(1, n + 1):
print(ans[i])
``` | output | 1 | 30,060 | 12 | 60,121 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Initially there was an array a consisting of n integers. Positions in it are numbered from 1 to n.
Exactly q queries were performed on the array. During the i-th query some segment (l_i, r_i) (1 ≤ l_i ≤ r_i ≤ n) was selected and values of elements on positions from l_i to r_i inclusive got changed to i. The order of the queries couldn't be changed and all q queries were applied. It is also known that every position from 1 to n got covered by at least one segment.
We could have offered you the problem about checking if some given array (consisting of n integers with values from 1 to q) can be obtained by the aforementioned queries. However, we decided that it will come too easy for you.
So the enhancement we introduced to it is the following. Some set of positions (possibly empty) in this array is selected and values of elements on these positions are set to 0.
Your task is to check if this array can be obtained by the aforementioned queries. Also if it can be obtained then restore this array.
If there are multiple possible arrays then print any of them.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 2 ⋅ 10^5) — the number of elements of the array and the number of queries perfomed on it.
The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ q) — the resulting array. If element at some position j is equal to 0 then the value of element at this position can be any integer from 1 to q.
Output
Print "YES" if the array a can be obtained by performing q queries. Segments (l_i, r_i) (1 ≤ l_i ≤ r_i ≤ n) are chosen separately for each query. Every position from 1 to n should be covered by at least one segment.
Otherwise print "NO".
If some array can be obtained then print n integers on the second line — the i-th number should be equal to the i-th element of the resulting array and should have value from 1 to q. This array should be obtainable by performing exactly q queries.
If there are multiple possible arrays then print any of them.
Examples
Input
4 3
1 0 2 3
Output
YES
1 2 2 3
Input
3 10
10 10 10
Output
YES
10 10 10
Input
5 6
6 5 6 2 2
Output
NO
Input
3 5
0 0 0
Output
YES
5 4 2
Note
In the first example you can also replace 0 with 1 but not with 3.
In the second example it doesn't really matter what segments to choose until query 10 when the segment is (1, 3).
The third example showcases the fact that the order of queries can't be changed, you can't firstly set (1, 3) to 6 and after that change (2, 2) to 5. The segment of 5 should be applied before segment of 6.
There is a lot of correct resulting arrays for the fourth example. | instruction | 0 | 30,061 | 12 | 60,122 |
Tags: constructive algorithms, data structures
Correct Solution:
```
n,q=map(int,input().split())
arr=list(map(int,input().split()))
count_zero=arr.count(0)
count_q=arr.count(q)
if count_q ==0 and count_zero ==0:
print("NO")
exit()
if count_q ==0:
for i in range(n):
if arr[i] ==0:
arr[i] =q
break
for i in range(n):
r=arr[i]
if r >0:
j=i-1
while j>=0 and arr[j] ==0:
arr[j] =r
j-=1
j=i+1
while j<n and arr[j] ==0:
arr[j] =r
j+=1
a=[]
visited=[0 for i in range(q+1)]
for i in range(n):
if a and arr[i] ==arr[i-1]:
continue
a.append(arr[i])
counted=[0 for i in range(q+1)]
l=len(a)
stack=[]
flag=0
for i in range(l):
r=a[i]
if visited[r] ==1:
flag=1
break
counted[r] +=1
if counted[r] ==1:
stack.append(r)
continue
while stack[-1] !=r:
q=stack.pop()
if q <r:
flag=1
break
visited[q] =1
if flag==1:
break
if flag==1:
print("NO")
else:
print("YES")
if arr[0] ==0:
arr[0]=arr[1]
print(*arr)
``` | output | 1 | 30,061 | 12 | 60,123 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Initially there was an array a consisting of n integers. Positions in it are numbered from 1 to n.
Exactly q queries were performed on the array. During the i-th query some segment (l_i, r_i) (1 ≤ l_i ≤ r_i ≤ n) was selected and values of elements on positions from l_i to r_i inclusive got changed to i. The order of the queries couldn't be changed and all q queries were applied. It is also known that every position from 1 to n got covered by at least one segment.
We could have offered you the problem about checking if some given array (consisting of n integers with values from 1 to q) can be obtained by the aforementioned queries. However, we decided that it will come too easy for you.
So the enhancement we introduced to it is the following. Some set of positions (possibly empty) in this array is selected and values of elements on these positions are set to 0.
Your task is to check if this array can be obtained by the aforementioned queries. Also if it can be obtained then restore this array.
If there are multiple possible arrays then print any of them.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 2 ⋅ 10^5) — the number of elements of the array and the number of queries perfomed on it.
The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ q) — the resulting array. If element at some position j is equal to 0 then the value of element at this position can be any integer from 1 to q.
Output
Print "YES" if the array a can be obtained by performing q queries. Segments (l_i, r_i) (1 ≤ l_i ≤ r_i ≤ n) are chosen separately for each query. Every position from 1 to n should be covered by at least one segment.
Otherwise print "NO".
If some array can be obtained then print n integers on the second line — the i-th number should be equal to the i-th element of the resulting array and should have value from 1 to q. This array should be obtainable by performing exactly q queries.
If there are multiple possible arrays then print any of them.
Examples
Input
4 3
1 0 2 3
Output
YES
1 2 2 3
Input
3 10
10 10 10
Output
YES
10 10 10
Input
5 6
6 5 6 2 2
Output
NO
Input
3 5
0 0 0
Output
YES
5 4 2
Note
In the first example you can also replace 0 with 1 but not with 3.
In the second example it doesn't really matter what segments to choose until query 10 when the segment is (1, 3).
The third example showcases the fact that the order of queries can't be changed, you can't firstly set (1, 3) to 6 and after that change (2, 2) to 5. The segment of 5 should be applied before segment of 6.
There is a lot of correct resulting arrays for the fourth example. | instruction | 0 | 30,062 | 12 | 60,124 |
Tags: constructive algorithms, data structures
Correct Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
from math import inf
def cons(n,x):
xx = n.bit_length()
dp = [[inf]*n for _ in range(xx)]
for i in range(n):
dp[0][i] = (inf if not x[i] else x[i])
for i in range(1,xx):
for j in range(n-(1<<i)+1):
dp[i][j] = min(dp[i-1][j],dp[i-1][j+(1<<(i-1))])
return dp
def ask(l,r,dp):
xx1 = (r-l+1).bit_length()-1
return min(dp[xx1][l],dp[xx1][r-(1<<xx1)+1])
def main():
n,q = map(int,input().split())
a = list(map(int,input().split()))
sp = cons(n,a)
xxx = a.count(q)
xxx1 = a.count(0)
if xxx1:
rrr = a.index(0)
if a == [0]*n:
print('YES')
print(*[q]*n)
return
if not xxx and not xxx1:
print('NO')
return
pos = [-1]*(q+1)
fi = 0
for ind,i in enumerate(a):
if not i:
continue
if not fi:
fi = i
if pos[i] != -1:
if ask(pos[i],ind,sp) < i:
print('NO')
return
pos[i] = ind
a[0] = fi
for i in range(1,n):
if not a[i]:
a[i] = a[i-1]
if not xxx:
a[rrr] = q
print('YES')
print(*a)
#Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == '__main__':
main()
``` | output | 1 | 30,062 | 12 | 60,125 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Initially there was an array a consisting of n integers. Positions in it are numbered from 1 to n.
Exactly q queries were performed on the array. During the i-th query some segment (l_i, r_i) (1 ≤ l_i ≤ r_i ≤ n) was selected and values of elements on positions from l_i to r_i inclusive got changed to i. The order of the queries couldn't be changed and all q queries were applied. It is also known that every position from 1 to n got covered by at least one segment.
We could have offered you the problem about checking if some given array (consisting of n integers with values from 1 to q) can be obtained by the aforementioned queries. However, we decided that it will come too easy for you.
So the enhancement we introduced to it is the following. Some set of positions (possibly empty) in this array is selected and values of elements on these positions are set to 0.
Your task is to check if this array can be obtained by the aforementioned queries. Also if it can be obtained then restore this array.
If there are multiple possible arrays then print any of them.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 2 ⋅ 10^5) — the number of elements of the array and the number of queries perfomed on it.
The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ q) — the resulting array. If element at some position j is equal to 0 then the value of element at this position can be any integer from 1 to q.
Output
Print "YES" if the array a can be obtained by performing q queries. Segments (l_i, r_i) (1 ≤ l_i ≤ r_i ≤ n) are chosen separately for each query. Every position from 1 to n should be covered by at least one segment.
Otherwise print "NO".
If some array can be obtained then print n integers on the second line — the i-th number should be equal to the i-th element of the resulting array and should have value from 1 to q. This array should be obtainable by performing exactly q queries.
If there are multiple possible arrays then print any of them.
Examples
Input
4 3
1 0 2 3
Output
YES
1 2 2 3
Input
3 10
10 10 10
Output
YES
10 10 10
Input
5 6
6 5 6 2 2
Output
NO
Input
3 5
0 0 0
Output
YES
5 4 2
Note
In the first example you can also replace 0 with 1 but not with 3.
In the second example it doesn't really matter what segments to choose until query 10 when the segment is (1, 3).
The third example showcases the fact that the order of queries can't be changed, you can't firstly set (1, 3) to 6 and after that change (2, 2) to 5. The segment of 5 should be applied before segment of 6.
There is a lot of correct resulting arrays for the fourth example. | instruction | 0 | 30,063 | 12 | 60,126 |
Tags: constructive algorithms, data structures
Correct Solution:
```
import sys
n, k = map(int, input().split())
a = list(map(int, input().split()))
cur_max = 0
last_max = 1
last = dict()
zeros = []
for i in range(len(a))[::-1]:
if a[i] == 0:
zeros.append(i)
elif a[i] not in last:
last[a[i]] = i
stack = []
for i in range(len(a)):
if a[i] == 0:
a[i] = max(cur_max, 1)
elif a[i] > cur_max and last[a[i]] != i:
stack.append(cur_max)
cur_max = a[i]
elif cur_max != 0 and i == last[cur_max]:
cur_max = stack.pop()
elif a[i] < cur_max:
print("NO")
sys.exit(0)
if k > max(a):
if zeros:
print("YES")
a[zeros[0]] = k
print(*a)
else:
print("NO")
elif k == max(a):
print("YES")
print(*a)
elif k < max(a):
print("NO")
``` | output | 1 | 30,063 | 12 | 60,127 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Initially there was an array a consisting of n integers. Positions in it are numbered from 1 to n.
Exactly q queries were performed on the array. During the i-th query some segment (l_i, r_i) (1 ≤ l_i ≤ r_i ≤ n) was selected and values of elements on positions from l_i to r_i inclusive got changed to i. The order of the queries couldn't be changed and all q queries were applied. It is also known that every position from 1 to n got covered by at least one segment.
We could have offered you the problem about checking if some given array (consisting of n integers with values from 1 to q) can be obtained by the aforementioned queries. However, we decided that it will come too easy for you.
So the enhancement we introduced to it is the following. Some set of positions (possibly empty) in this array is selected and values of elements on these positions are set to 0.
Your task is to check if this array can be obtained by the aforementioned queries. Also if it can be obtained then restore this array.
If there are multiple possible arrays then print any of them.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 2 ⋅ 10^5) — the number of elements of the array and the number of queries perfomed on it.
The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ q) — the resulting array. If element at some position j is equal to 0 then the value of element at this position can be any integer from 1 to q.
Output
Print "YES" if the array a can be obtained by performing q queries. Segments (l_i, r_i) (1 ≤ l_i ≤ r_i ≤ n) are chosen separately for each query. Every position from 1 to n should be covered by at least one segment.
Otherwise print "NO".
If some array can be obtained then print n integers on the second line — the i-th number should be equal to the i-th element of the resulting array and should have value from 1 to q. This array should be obtainable by performing exactly q queries.
If there are multiple possible arrays then print any of them.
Examples
Input
4 3
1 0 2 3
Output
YES
1 2 2 3
Input
3 10
10 10 10
Output
YES
10 10 10
Input
5 6
6 5 6 2 2
Output
NO
Input
3 5
0 0 0
Output
YES
5 4 2
Note
In the first example you can also replace 0 with 1 but not with 3.
In the second example it doesn't really matter what segments to choose until query 10 when the segment is (1, 3).
The third example showcases the fact that the order of queries can't be changed, you can't firstly set (1, 3) to 6 and after that change (2, 2) to 5. The segment of 5 should be applied before segment of 6.
There is a lot of correct resulting arrays for the fourth example. | instruction | 0 | 30,064 | 12 | 60,128 |
Tags: constructive algorithms, data structures
Correct Solution:
```
import sys
class SegmentTree:
def __init__(self, data, default=999999999999999999999999999999999, 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)
n,q=map(int,input().split())
l=list(map(int,input().split()))
re=0
ma=max(l)
if ma>q:
print("NO")
sys.exit()
elif ma<q:
re=1
for i in range(n-2,-1,-1):
if l[i]==0:
l[i]=l[i+1]
if re==1:
l[i]=q
re=0
for i in range(n):
if l[i]==0:
#print(i)
l[i]=l[i-1]
if re==1:
l[i]=q
re=0
if l[0]==0:
l[0]=l[1]
if sum(l)==0:
re=0
l=[q]*n
ind=dict()
if re==1:
print("NO")
sys.exit()
s=set()
f=0
sw=SegmentTree(l)
for i in range(n):
if l[i] not in s:
ind.update({l[i]:i})
s.add(l[i])
else:
mi=sw.query(ind[l[i]],i)
if mi<l[i]:
f=1
break
else:
ind[l[i]]=i
if f==1:
print("NO")
else:
print("YES")
print(*l,sep=" ")
``` | output | 1 | 30,064 | 12 | 60,129 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Initially there was an array a consisting of n integers. Positions in it are numbered from 1 to n.
Exactly q queries were performed on the array. During the i-th query some segment (l_i, r_i) (1 ≤ l_i ≤ r_i ≤ n) was selected and values of elements on positions from l_i to r_i inclusive got changed to i. The order of the queries couldn't be changed and all q queries were applied. It is also known that every position from 1 to n got covered by at least one segment.
We could have offered you the problem about checking if some given array (consisting of n integers with values from 1 to q) can be obtained by the aforementioned queries. However, we decided that it will come too easy for you.
So the enhancement we introduced to it is the following. Some set of positions (possibly empty) in this array is selected and values of elements on these positions are set to 0.
Your task is to check if this array can be obtained by the aforementioned queries. Also if it can be obtained then restore this array.
If there are multiple possible arrays then print any of them.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 2 ⋅ 10^5) — the number of elements of the array and the number of queries perfomed on it.
The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ q) — the resulting array. If element at some position j is equal to 0 then the value of element at this position can be any integer from 1 to q.
Output
Print "YES" if the array a can be obtained by performing q queries. Segments (l_i, r_i) (1 ≤ l_i ≤ r_i ≤ n) are chosen separately for each query. Every position from 1 to n should be covered by at least one segment.
Otherwise print "NO".
If some array can be obtained then print n integers on the second line — the i-th number should be equal to the i-th element of the resulting array and should have value from 1 to q. This array should be obtainable by performing exactly q queries.
If there are multiple possible arrays then print any of them.
Examples
Input
4 3
1 0 2 3
Output
YES
1 2 2 3
Input
3 10
10 10 10
Output
YES
10 10 10
Input
5 6
6 5 6 2 2
Output
NO
Input
3 5
0 0 0
Output
YES
5 4 2
Note
In the first example you can also replace 0 with 1 but not with 3.
In the second example it doesn't really matter what segments to choose until query 10 when the segment is (1, 3).
The third example showcases the fact that the order of queries can't be changed, you can't firstly set (1, 3) to 6 and after that change (2, 2) to 5. The segment of 5 should be applied before segment of 6.
There is a lot of correct resulting arrays for the fourth example. | instruction | 0 | 30,065 | 12 | 60,130 |
Tags: constructive algorithms, data structures
Correct Solution:
```
from sys import stdin
n,q=map(int,stdin.readline().strip().split())
s=list(map(int,stdin.readline().strip().split()))
t=False
y=max(s)
if y!=q:
t=True
for i in range(1,n):
if s[i]==0:
if t:
s[i]=q
t=False
y=q
else:
s[i]=s[i-1]
for i in range(n-2,-1,-1):
if s[i]==0:
if t:
s[i]=q
t=False
y=q
else:
s[i]=s[i+1]
s1=[[-1,-1] for i in range(200005)]
for i in range(n):
if s1[s[i]][0]==-1:
s1[s[i]][0]=i
s1[s[i]][1]=i
if s[0]==0:
print("YES")
print((str(q)+" ")*n)
exit(0)
if y<q:
print("NO")
exit(0)
maxx=200005
sg=[maxx for i in range(n*2)]
for i in range(n,n*2):
sg[i]=s[i-n]
for i in range(n-1,-1,-1):
sg[i]=min(sg[i<<1],sg[(i<<1)+1]);
for i in range(200001):
if s1[i][0]!=-1:
l =n+s1[i][0];
r=n+s1[i][1];
ans=maxx;
while(l < r):
if (l & 1):
ans=min(ans,sg[l])
l+=1
if (r & 1):
r-=1
ans=min(sg[r],ans)
l>>=1
r>>=1
if ans<i:
print("NO")
exit(0)
print("YES")
print(*s)
``` | output | 1 | 30,065 | 12 | 60,131 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Initially there was an array a consisting of n integers. Positions in it are numbered from 1 to n.
Exactly q queries were performed on the array. During the i-th query some segment (l_i, r_i) (1 ≤ l_i ≤ r_i ≤ n) was selected and values of elements on positions from l_i to r_i inclusive got changed to i. The order of the queries couldn't be changed and all q queries were applied. It is also known that every position from 1 to n got covered by at least one segment.
We could have offered you the problem about checking if some given array (consisting of n integers with values from 1 to q) can be obtained by the aforementioned queries. However, we decided that it will come too easy for you.
So the enhancement we introduced to it is the following. Some set of positions (possibly empty) in this array is selected and values of elements on these positions are set to 0.
Your task is to check if this array can be obtained by the aforementioned queries. Also if it can be obtained then restore this array.
If there are multiple possible arrays then print any of them.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 2 ⋅ 10^5) — the number of elements of the array and the number of queries perfomed on it.
The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ q) — the resulting array. If element at some position j is equal to 0 then the value of element at this position can be any integer from 1 to q.
Output
Print "YES" if the array a can be obtained by performing q queries. Segments (l_i, r_i) (1 ≤ l_i ≤ r_i ≤ n) are chosen separately for each query. Every position from 1 to n should be covered by at least one segment.
Otherwise print "NO".
If some array can be obtained then print n integers on the second line — the i-th number should be equal to the i-th element of the resulting array and should have value from 1 to q. This array should be obtainable by performing exactly q queries.
If there are multiple possible arrays then print any of them.
Examples
Input
4 3
1 0 2 3
Output
YES
1 2 2 3
Input
3 10
10 10 10
Output
YES
10 10 10
Input
5 6
6 5 6 2 2
Output
NO
Input
3 5
0 0 0
Output
YES
5 4 2
Note
In the first example you can also replace 0 with 1 but not with 3.
In the second example it doesn't really matter what segments to choose until query 10 when the segment is (1, 3).
The third example showcases the fact that the order of queries can't be changed, you can't firstly set (1, 3) to 6 and after that change (2, 2) to 5. The segment of 5 should be applied before segment of 6.
There is a lot of correct resulting arrays for the fourth example. | instruction | 0 | 30,066 | 12 | 60,132 |
Tags: constructive algorithms, data structures
Correct Solution:
```
import sys
n,q = map(int,input().split())
a = list(map(int,input().split()))
l = len(a)
zeros = []
last = dict()
cur_max = 0
last_max = 1
stack = []
for i in range(l-1,-1,-1):
if a[i] == 0:
zeros.append(i)
elif a[i] not in last:
last[a[i]] = i
for i in range(l):
if a[i] == 0:
a[i] = max(cur_max,1)
elif a[i] > cur_max and last[a[i]] != i:
stack.append(cur_max)
cur_max = a[i]
elif cur_max != 0 and i == last[cur_max]:
cur_max = stack.pop()
elif a[i] < cur_max:
print("NO")
sys.exit(0)
if q > max(a):
if zeros:
print("YES")
a[zeros[0]] = q
print(*a)
else:
print("NO")
elif q == max(a):
print("YES")
print(*a)
elif q < max(a):
print("NO")
``` | output | 1 | 30,066 | 12 | 60,133 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Initially there was an array a consisting of n integers. Positions in it are numbered from 1 to n.
Exactly q queries were performed on the array. During the i-th query some segment (l_i, r_i) (1 ≤ l_i ≤ r_i ≤ n) was selected and values of elements on positions from l_i to r_i inclusive got changed to i. The order of the queries couldn't be changed and all q queries were applied. It is also known that every position from 1 to n got covered by at least one segment.
We could have offered you the problem about checking if some given array (consisting of n integers with values from 1 to q) can be obtained by the aforementioned queries. However, we decided that it will come too easy for you.
So the enhancement we introduced to it is the following. Some set of positions (possibly empty) in this array is selected and values of elements on these positions are set to 0.
Your task is to check if this array can be obtained by the aforementioned queries. Also if it can be obtained then restore this array.
If there are multiple possible arrays then print any of them.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 2 ⋅ 10^5) — the number of elements of the array and the number of queries perfomed on it.
The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ q) — the resulting array. If element at some position j is equal to 0 then the value of element at this position can be any integer from 1 to q.
Output
Print "YES" if the array a can be obtained by performing q queries. Segments (l_i, r_i) (1 ≤ l_i ≤ r_i ≤ n) are chosen separately for each query. Every position from 1 to n should be covered by at least one segment.
Otherwise print "NO".
If some array can be obtained then print n integers on the second line — the i-th number should be equal to the i-th element of the resulting array and should have value from 1 to q. This array should be obtainable by performing exactly q queries.
If there are multiple possible arrays then print any of them.
Examples
Input
4 3
1 0 2 3
Output
YES
1 2 2 3
Input
3 10
10 10 10
Output
YES
10 10 10
Input
5 6
6 5 6 2 2
Output
NO
Input
3 5
0 0 0
Output
YES
5 4 2
Note
In the first example you can also replace 0 with 1 but not with 3.
In the second example it doesn't really matter what segments to choose until query 10 when the segment is (1, 3).
The third example showcases the fact that the order of queries can't be changed, you can't firstly set (1, 3) to 6 and after that change (2, 2) to 5. The segment of 5 should be applied before segment of 6.
There is a lot of correct resulting arrays for the fourth example. | instruction | 0 | 30,067 | 12 | 60,134 |
Tags: constructive algorithms, data structures
Correct Solution:
```
def readNums(type=int):
return list(map(type, input().split()))
def solve():
n, q = readNums()
arr = readNums()
f = set()
p = None
for i in range(n):
if not arr[i]: continue
if arr[i] in f:
return None
if p is None:
p = arr[i]
else:
if arr[i] < p:
f.add(p)
p = arr[i]
if 0 not in arr:
if q > max(arr): return None
return arr
if q not in arr:
i = 0
while i < n and arr[i]: i += 1
while i < n and not arr[i]: arr[i] = q; i += 1
i = 0
while i < n and not arr[i]: arr[i] = 1; i += 1
if i == n: return arr
p = arr[i]
i += 1
while i < n:
if not arr[i]:
arr[i] = p
else:
p = arr[i]
i += 1
return arr
a = solve()
if a is None:
print("NO")
else:
print("YES")
for x in a:
print(x, end=' ')
``` | output | 1 | 30,067 | 12 | 60,135 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Initially there was an array a consisting of n integers. Positions in it are numbered from 1 to n.
Exactly q queries were performed on the array. During the i-th query some segment (l_i, r_i) (1 ≤ l_i ≤ r_i ≤ n) was selected and values of elements on positions from l_i to r_i inclusive got changed to i. The order of the queries couldn't be changed and all q queries were applied. It is also known that every position from 1 to n got covered by at least one segment.
We could have offered you the problem about checking if some given array (consisting of n integers with values from 1 to q) can be obtained by the aforementioned queries. However, we decided that it will come too easy for you.
So the enhancement we introduced to it is the following. Some set of positions (possibly empty) in this array is selected and values of elements on these positions are set to 0.
Your task is to check if this array can be obtained by the aforementioned queries. Also if it can be obtained then restore this array.
If there are multiple possible arrays then print any of them.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 2 ⋅ 10^5) — the number of elements of the array and the number of queries perfomed on it.
The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ q) — the resulting array. If element at some position j is equal to 0 then the value of element at this position can be any integer from 1 to q.
Output
Print "YES" if the array a can be obtained by performing q queries. Segments (l_i, r_i) (1 ≤ l_i ≤ r_i ≤ n) are chosen separately for each query. Every position from 1 to n should be covered by at least one segment.
Otherwise print "NO".
If some array can be obtained then print n integers on the second line — the i-th number should be equal to the i-th element of the resulting array and should have value from 1 to q. This array should be obtainable by performing exactly q queries.
If there are multiple possible arrays then print any of them.
Examples
Input
4 3
1 0 2 3
Output
YES
1 2 2 3
Input
3 10
10 10 10
Output
YES
10 10 10
Input
5 6
6 5 6 2 2
Output
NO
Input
3 5
0 0 0
Output
YES
5 4 2
Note
In the first example you can also replace 0 with 1 but not with 3.
In the second example it doesn't really matter what segments to choose until query 10 when the segment is (1, 3).
The third example showcases the fact that the order of queries can't be changed, you can't firstly set (1, 3) to 6 and after that change (2, 2) to 5. The segment of 5 should be applied before segment of 6.
There is a lot of correct resulting arrays for the fourth example.
Submitted Solution:
```
def getRawInteger():
return [int(x) for x in input().split()]
n, q = getRawInteger()
a = getRawInteger()
if n != len(a):
raise ValueError('n is not correct.')
l, r = [n] * (q + 5), [0] * (q + 5)
f = [i for i in range(n + 5)]
def getRoot(u):
while f[u] != u:
f[u] = f[f[u]]
u = f[f[u]]
return u
for i in range(n):
l[a[i]] = min(l[a[i]], i)
r[a[i]] = max(r[a[i]], i)
if l[q] > r[q]:
if l[0] > r[0]:
print('NO')
exit()
a[l[0]] = q
f[l[0]] = getRoot(l[0] + 1)
for i in reversed(range(1, q + 1)):
it = getRoot(l[i])
while it <= r[i]:
if a[it] < i and a[it]:
print('NO')
exit()
a[it] = i
f[it] = getRoot(it + 1)
it = getRoot(it)
out = 'YES\n'
for x in a:
if x:
out += str(x) + ' '
else:
out += '1 '
print(out)
``` | instruction | 0 | 30,068 | 12 | 60,136 |
Yes | output | 1 | 30,068 | 12 | 60,137 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.