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 a correct Python 3 solution for this coding contest problem.
You are given a permutation of 1,2,...,N: p_1,p_2,...,p_N. Determine if the state where p_i=i for every i can be reached by performing the following operation any number of times:
* Choose three elements p_{i-1},p_{i},p_{i+1} (2\leq i\leq N-1) such that p_{i-1}>p_{i}>p_{i+1} and reverse the order of these three.
Constraints
* 3 \leq N \leq 3 × 10^5
* p_1,p_2,...,p_N is a permutation of 1,2,...,N.
Input
Input is given from Standard Input in the following format:
N
p_1
:
p_N
Output
If the state where p_i=i for every i can be reached by performing the operation, print `Yes`; otherwise, print `No`.
Examples
Input
5
5
2
1
4
3
Output
Yes
Input
4
3
2
4
1
Output
No
Input
7
3
2
1
6
5
4
7
Output
Yes
Input
6
5
3
4
1
2
6
Output
No | instruction | 0 | 45,242 | 12 | 90,484 |
"Correct Solution:
```
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N = int(readline())
P = [0] + list(map(int,read().split()))
# permutationになっている極小区間に分ける
intervals = []
left = 0
right = -1
for i,p in enumerate(P):
if right < p:
right = p
if i == right:
intervals.append((left,right))
left = i+1
right = -1
def check(L,R):
if L == R:
return True
to_left = []
fixed = []
to_right = []
for i,p in enumerate(P[L:R+1],L):
if i > p:
to_left.append(p)
elif i == p:
fixed.append(p)
else:
to_right.append(p)
if fixed != list(range(L+1,R+1,2)):
return False
if any(x > y for x,y in zip(to_left, to_left[1:])):
return False
if any(x > y for x,y in zip(to_right, to_right[1:])):
return False
return True
answer = 'Yes' if all(check(L,R) for L,R in intervals) else 'No'
print(answer)
``` | output | 1 | 45,242 | 12 | 90,485 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two arrays a and b, both of length n. All elements of both arrays are from 0 to n-1.
You can reorder elements of the array b (if you want, you may leave the order of elements as it is). After that, let array c be the array of length n, the i-th element of this array is c_i = (a_i + b_i) \% n, where x \% y is x modulo y.
Your task is to reorder elements of the array b to obtain the lexicographically minimum possible array c.
Array x of length n is lexicographically less than array y of length n, if there exists such i (1 ≤ i ≤ n), that x_i < y_i, and for any j (1 ≤ j < i) x_j = y_j.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a, b and c.
The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i < n), where a_i is the i-th element of a.
The third line of the input contains n integers b_1, b_2, ..., b_n (0 ≤ b_i < n), where b_i is the i-th element of b.
Output
Print the lexicographically minimum possible array c. Recall that your task is to reorder elements of the array b and obtain the lexicographically minimum possible array c, where the i-th element of c is c_i = (a_i + b_i) \% n.
Examples
Input
4
0 1 2 1
3 2 1 1
Output
1 0 0 2
Input
7
2 5 1 5 3 4 3
2 4 3 5 6 5 1
Output
0 0 0 1 0 2 4 | instruction | 0 | 45,440 | 12 | 90,880 |
Tags: binary search, data structures, greedy
Correct Solution:
```
n = int(input())
l1 = list(map(int,input().split()))
l2 = list(map(int,input().split()))
g = [i for i in range(1,n)]
g.append(0)
r=[]
c=[0]*n
for i in l2:
c[i]+=1
for i in l1:
d = (n-i)%n
while c[d]==0:
if c[g[d]]==0:
g[d]=g[g[d]]
d = g[d]
c[d%n]-=1
r.append((d+i)%n)
print(*r)
``` | output | 1 | 45,440 | 12 | 90,881 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two arrays a and b, both of length n. All elements of both arrays are from 0 to n-1.
You can reorder elements of the array b (if you want, you may leave the order of elements as it is). After that, let array c be the array of length n, the i-th element of this array is c_i = (a_i + b_i) \% n, where x \% y is x modulo y.
Your task is to reorder elements of the array b to obtain the lexicographically minimum possible array c.
Array x of length n is lexicographically less than array y of length n, if there exists such i (1 ≤ i ≤ n), that x_i < y_i, and for any j (1 ≤ j < i) x_j = y_j.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a, b and c.
The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i < n), where a_i is the i-th element of a.
The third line of the input contains n integers b_1, b_2, ..., b_n (0 ≤ b_i < n), where b_i is the i-th element of b.
Output
Print the lexicographically minimum possible array c. Recall that your task is to reorder elements of the array b and obtain the lexicographically minimum possible array c, where the i-th element of c is c_i = (a_i + b_i) \% n.
Examples
Input
4
0 1 2 1
3 2 1 1
Output
1 0 0 2
Input
7
2 5 1 5 3 4 3
2 4 3 5 6 5 1
Output
0 0 0 1 0 2 4 | instruction | 0 | 45,441 | 12 | 90,882 |
Tags: binary search, data structures, greedy
Correct Solution:
```
from collections import Counter
n,a,b=int(input()),[int(i) for i in input().split()],[int(i) for i in input().split()]
c=Counter(b)
nex=list(range(1,n))+[0]
ans=[]
for i in a:
v=(n-i)%n
while c[v]==0:
if c[nex[v]]==0:
nex[v]=nex[nex[v]]
v=nex[v]
c[v]-=1
ans.append((i+v)%n)
print(*ans)
``` | output | 1 | 45,441 | 12 | 90,883 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two arrays a and b, both of length n. All elements of both arrays are from 0 to n-1.
You can reorder elements of the array b (if you want, you may leave the order of elements as it is). After that, let array c be the array of length n, the i-th element of this array is c_i = (a_i + b_i) \% n, where x \% y is x modulo y.
Your task is to reorder elements of the array b to obtain the lexicographically minimum possible array c.
Array x of length n is lexicographically less than array y of length n, if there exists such i (1 ≤ i ≤ n), that x_i < y_i, and for any j (1 ≤ j < i) x_j = y_j.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a, b and c.
The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i < n), where a_i is the i-th element of a.
The third line of the input contains n integers b_1, b_2, ..., b_n (0 ≤ b_i < n), where b_i is the i-th element of b.
Output
Print the lexicographically minimum possible array c. Recall that your task is to reorder elements of the array b and obtain the lexicographically minimum possible array c, where the i-th element of c is c_i = (a_i + b_i) \% n.
Examples
Input
4
0 1 2 1
3 2 1 1
Output
1 0 0 2
Input
7
2 5 1 5 3 4 3
2 4 3 5 6 5 1
Output
0 0 0 1 0 2 4 | instruction | 0 | 45,442 | 12 | 90,884 |
Tags: binary search, data structures, greedy
Correct Solution:
```
import sys
input=sys.stdin.readline
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
right=[(i+1)%n for i in range(n)]
c=[]
cnt=[0]*n
for bb in b:
cnt[bb]+=1
for aa in a:
tar=(n-aa)%n
while cnt[tar]==0:
if cnt[right[tar]]==0:
right[tar]=right[right[tar]]
tar=right[tar]
cnt[tar]-=1
c.append((aa+tar)%n)
print(*c)
``` | output | 1 | 45,442 | 12 | 90,885 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two arrays a and b, both of length n. All elements of both arrays are from 0 to n-1.
You can reorder elements of the array b (if you want, you may leave the order of elements as it is). After that, let array c be the array of length n, the i-th element of this array is c_i = (a_i + b_i) \% n, where x \% y is x modulo y.
Your task is to reorder elements of the array b to obtain the lexicographically minimum possible array c.
Array x of length n is lexicographically less than array y of length n, if there exists such i (1 ≤ i ≤ n), that x_i < y_i, and for any j (1 ≤ j < i) x_j = y_j.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a, b and c.
The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i < n), where a_i is the i-th element of a.
The third line of the input contains n integers b_1, b_2, ..., b_n (0 ≤ b_i < n), where b_i is the i-th element of b.
Output
Print the lexicographically minimum possible array c. Recall that your task is to reorder elements of the array b and obtain the lexicographically minimum possible array c, where the i-th element of c is c_i = (a_i + b_i) \% n.
Examples
Input
4
0 1 2 1
3 2 1 1
Output
1 0 0 2
Input
7
2 5 1 5 3 4 3
2 4 3 5 6 5 1
Output
0 0 0 1 0 2 4 | instruction | 0 | 45,443 | 12 | 90,886 |
Tags: binary search, data structures, greedy
Correct Solution:
```
from collections import Counter
n=int(input())
a=[int(i) for i in input().split()]
b=[int(i) for i in input().split()]
d=Counter(b)
ans=[]
e=list(range(1,n))+[0]
for i in a:
v=(n-i)%n
while d[v]==0:
if d[e[v]]==0:
e[v]=e[e[v]]
v=e[v]
d[v]-=1
ans.append((i+v)%n)
print(*ans)
``` | output | 1 | 45,443 | 12 | 90,887 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two arrays a and b, both of length n. All elements of both arrays are from 0 to n-1.
You can reorder elements of the array b (if you want, you may leave the order of elements as it is). After that, let array c be the array of length n, the i-th element of this array is c_i = (a_i + b_i) \% n, where x \% y is x modulo y.
Your task is to reorder elements of the array b to obtain the lexicographically minimum possible array c.
Array x of length n is lexicographically less than array y of length n, if there exists such i (1 ≤ i ≤ n), that x_i < y_i, and for any j (1 ≤ j < i) x_j = y_j.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a, b and c.
The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i < n), where a_i is the i-th element of a.
The third line of the input contains n integers b_1, b_2, ..., b_n (0 ≤ b_i < n), where b_i is the i-th element of b.
Output
Print the lexicographically minimum possible array c. Recall that your task is to reorder elements of the array b and obtain the lexicographically minimum possible array c, where the i-th element of c is c_i = (a_i + b_i) \% n.
Examples
Input
4
0 1 2 1
3 2 1 1
Output
1 0 0 2
Input
7
2 5 1 5 3 4 3
2 4 3 5 6 5 1
Output
0 0 0 1 0 2 4 | instruction | 0 | 45,444 | 12 | 90,888 |
Tags: binary search, data structures, greedy
Correct Solution:
```
from collections import defaultdict, deque, Counter
from sys import stdin, stdout
from heapq import heappush, heappop, heapify
import math
import io
import os
import math
import bisect
#?############################################################
def isPrime(x):
for i in range(2, x):
if i*i > x:
break
if (x % i == 0):
return False
return True
#?############################################################
def ncr(n, r, p):
num = den = 1
for i in range(r):
num = (num * (n - i)) % p
den = (den * (i + 1)) % p
return (num * pow(den, p - 2, p)) % p
#?############################################################
def primeFactors(n):
l = []
while n % 2 == 0:
l.append(2)
n = n / 2
for i in range(3, int(math.sqrt(n))+1, 2):
while n % i == 0:
l.append(int(i))
n = n / i
if n > 2:
l.append(n)
return list(set(l))
#?############################################################
def power(x, y, p):
ab = 1
x = x % p
if (x == 0):
return 0
while (y > 0):
if ((y & 1) == 1):
ab = (ab * x) % p
y = y >> 1
x = (x * x) % p
return ab
#?############################################################
def sieve(n):
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
return prime
#?############################################################
def digits(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
#?############################################################
def ceil(n, x):
if (n % x == 0):
return n//x
return n//x+1
#?############################################################
def mapin():
return [int(x) for x in input().split()]
#?############################################################
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError('{0!r} not in list'.format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return 'SortedList({0})'.format(list(self))
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
# python3 15.py<in>op
n = int(input())
a = mapin()
b = mapin()
c = [0]*n
d = SortedList(b)
for i in range(n):
temp = a[i]
temp2 = n-a[i]
temp3 = d.bisect_left(temp2)
# print(i, temp3, d[temp3])
if(temp3 <len(d)):
temp4 = temp+d[temp3]
d.pop(temp3)
else:
temp4 = temp+d[0]
d.pop(0)
c[i] = temp4%n
print(*c)
``` | output | 1 | 45,444 | 12 | 90,889 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two arrays a and b, both of length n. All elements of both arrays are from 0 to n-1.
You can reorder elements of the array b (if you want, you may leave the order of elements as it is). After that, let array c be the array of length n, the i-th element of this array is c_i = (a_i + b_i) \% n, where x \% y is x modulo y.
Your task is to reorder elements of the array b to obtain the lexicographically minimum possible array c.
Array x of length n is lexicographically less than array y of length n, if there exists such i (1 ≤ i ≤ n), that x_i < y_i, and for any j (1 ≤ j < i) x_j = y_j.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a, b and c.
The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i < n), where a_i is the i-th element of a.
The third line of the input contains n integers b_1, b_2, ..., b_n (0 ≤ b_i < n), where b_i is the i-th element of b.
Output
Print the lexicographically minimum possible array c. Recall that your task is to reorder elements of the array b and obtain the lexicographically minimum possible array c, where the i-th element of c is c_i = (a_i + b_i) \% n.
Examples
Input
4
0 1 2 1
3 2 1 1
Output
1 0 0 2
Input
7
2 5 1 5 3 4 3
2 4 3 5 6 5 1
Output
0 0 0 1 0 2 4 | instruction | 0 | 45,445 | 12 | 90,890 |
Tags: binary search, data structures, greedy
Correct Solution:
```
# Legends Always Come Up with Solution
# Author: Manvir Singh
import os
import sys
from io import BytesIO, IOBase
class SortedList:
def __init__(self, iterable=None, _load=200):
"""Initialize sorted list instance."""
if iterable is None:
iterable = []
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError('{0!r} not in list'.format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return 'SortedList({0})'.format(list(self))
def main():
n = int(input())
a=list(map(int,input().split()))
b=SortedList(map(int,input().split()))
c=[]
for i in range(n):
x=(a[i]+b[0])%n
z=b.bisect_left(n-a[i])
z-=(z==len(b))
y=(a[i]+b[z])%n
if x<y:
c.append(x)
b.discard(b[0])
else:
c.append(y)
b.discard(b[z])
print(*c)
# (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")
if __name__ == "__main__":
main()
``` | output | 1 | 45,445 | 12 | 90,891 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two arrays a and b, both of length n. All elements of both arrays are from 0 to n-1.
You can reorder elements of the array b (if you want, you may leave the order of elements as it is). After that, let array c be the array of length n, the i-th element of this array is c_i = (a_i + b_i) \% n, where x \% y is x modulo y.
Your task is to reorder elements of the array b to obtain the lexicographically minimum possible array c.
Array x of length n is lexicographically less than array y of length n, if there exists such i (1 ≤ i ≤ n), that x_i < y_i, and for any j (1 ≤ j < i) x_j = y_j.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a, b and c.
The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i < n), where a_i is the i-th element of a.
The third line of the input contains n integers b_1, b_2, ..., b_n (0 ≤ b_i < n), where b_i is the i-th element of b.
Output
Print the lexicographically minimum possible array c. Recall that your task is to reorder elements of the array b and obtain the lexicographically minimum possible array c, where the i-th element of c is c_i = (a_i + b_i) \% n.
Examples
Input
4
0 1 2 1
3 2 1 1
Output
1 0 0 2
Input
7
2 5 1 5 3 4 3
2 4 3 5 6 5 1
Output
0 0 0 1 0 2 4 | instruction | 0 | 45,446 | 12 | 90,892 |
Tags: binary search, data structures, greedy
Correct Solution:
```
class SegmentTree:
@classmethod
def all_identity(cls, operator, equality, identity, size):
return cls(operator, equality, identity, [identity]*(2 << (size-1).bit_length()))
@classmethod
def from_initial_data(cls, operator, equality, identity, data):
size = 1 << (len(data)-1).bit_length()
temp = [identity]*(2*size)
temp[size:size+len(data)] = data
data = temp
for i in reversed(range(size)):
data[i] = operator(data[2*i],data[2*i+1])
return cls(operator, equality, identity, data)
def __init__(self, operator, equality, identity, data):
if equality is None:
equality = lambda a,b: False
self.op = operator
self.eq = equality
self.id = identity
self.data = data
self.size = len(data)//2
def _interval(self, a, b):
a += self.size
b += self.size
ra = self.id
rb = self.id
data = self.data
op = self.op
while a < b:
if a & 1:
ra = op(ra,data[a])
a += 1
if b & 1:
b -= 1
rb = op(data[b],rb)
a >>= 1
b >>= 1
return op(ra,rb)
def __getitem__(self, i):
if isinstance(i, slice):
return self._interval(
0 if i.start is None else i.start,
self.size if i.stop is None else i.stop)
elif isinstance(i, int):
return self.data[i+self.size]
def __setitem__(self, i, v):
i += self.size
data = self.data
op = self.op
eq = self.eq
while i and not eq(data[i],v):
data[i] = v
v = op(data[i^1],v) if i & 1 else op(v,data[i^1])
i >>= 1
def __iter__(self):
return self.data[self.size:]
def solve(A,B):
from operator import eq
N = len(B)
counts = [0]*N
for b in B:
counts[b] += 1
init_data = [i if counts[i] > 0 else N for i in range(N)]
seg = SegmentTree.from_initial_data(min, eq, N, init_data)
def it():
for a in A:
best_b = -a%N
p = seg[best_b:]
if p == N:
p = seg[:best_b]
counts[p] -= 1
if counts[p] == 0:
seg[p] = N
yield (a+p)%N
return tuple(it())
def main():
input()
A = tuple(map(int,input().split()))
B = list(map(int,input().split()))
res = solve(A,B)
print(*res)
main()
``` | output | 1 | 45,446 | 12 | 90,893 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two arrays a and b, both of length n. All elements of both arrays are from 0 to n-1.
You can reorder elements of the array b (if you want, you may leave the order of elements as it is). After that, let array c be the array of length n, the i-th element of this array is c_i = (a_i + b_i) \% n, where x \% y is x modulo y.
Your task is to reorder elements of the array b to obtain the lexicographically minimum possible array c.
Array x of length n is lexicographically less than array y of length n, if there exists such i (1 ≤ i ≤ n), that x_i < y_i, and for any j (1 ≤ j < i) x_j = y_j.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a, b and c.
The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i < n), where a_i is the i-th element of a.
The third line of the input contains n integers b_1, b_2, ..., b_n (0 ≤ b_i < n), where b_i is the i-th element of b.
Output
Print the lexicographically minimum possible array c. Recall that your task is to reorder elements of the array b and obtain the lexicographically minimum possible array c, where the i-th element of c is c_i = (a_i + b_i) \% n.
Examples
Input
4
0 1 2 1
3 2 1 1
Output
1 0 0 2
Input
7
2 5 1 5 3 4 3
2 4 3 5 6 5 1
Output
0 0 0 1 0 2 4 | instruction | 0 | 45,447 | 12 | 90,894 |
Tags: binary search, data structures, greedy
Correct Solution:
```
n = int(input())
a = map(int, input().split())
d = [0] * n
for v in map(int, input().split()):
d[v] += 1
p = list(range(1, n)) + [0]
r = []
for x in a:
v = (n - x) % n
while d[v] == 0:
if d[p[v]] == 0:
p[v] = p[p[v]]
v = p[v]
r += [(x + v) % n]
d[v] -= 1
for i in r:
print(i,end=" ")
``` | output | 1 | 45,447 | 12 | 90,895 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two arrays a and b, both of length n. All elements of both arrays are from 0 to n-1.
You can reorder elements of the array b (if you want, you may leave the order of elements as it is). After that, let array c be the array of length n, the i-th element of this array is c_i = (a_i + b_i) \% n, where x \% y is x modulo y.
Your task is to reorder elements of the array b to obtain the lexicographically minimum possible array c.
Array x of length n is lexicographically less than array y of length n, if there exists such i (1 ≤ i ≤ n), that x_i < y_i, and for any j (1 ≤ j < i) x_j = y_j.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a, b and c.
The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i < n), where a_i is the i-th element of a.
The third line of the input contains n integers b_1, b_2, ..., b_n (0 ≤ b_i < n), where b_i is the i-th element of b.
Output
Print the lexicographically minimum possible array c. Recall that your task is to reorder elements of the array b and obtain the lexicographically minimum possible array c, where the i-th element of c is c_i = (a_i + b_i) \% n.
Examples
Input
4
0 1 2 1
3 2 1 1
Output
1 0 0 2
Input
7
2 5 1 5 3 4 3
2 4 3 5 6 5 1
Output
0 0 0 1 0 2 4
Submitted Solution:
```
import collections
def solve(n, a, b):
c = collections.Counter(b)
nex = list(range(1, n)) + [0]
res = []
for x in a:
v = (n - x) % n
while c[v] == 0:
if c[nex[v]] == 0:
nex[v] = nex[nex[v]]
v = nex[v]
c[v] -= 1
res.append((x + v) % n)
return ' '.join(map(str, res))
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
print(solve(n, a, b))
``` | instruction | 0 | 45,448 | 12 | 90,896 |
Yes | output | 1 | 45,448 | 12 | 90,897 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two arrays a and b, both of length n. All elements of both arrays are from 0 to n-1.
You can reorder elements of the array b (if you want, you may leave the order of elements as it is). After that, let array c be the array of length n, the i-th element of this array is c_i = (a_i + b_i) \% n, where x \% y is x modulo y.
Your task is to reorder elements of the array b to obtain the lexicographically minimum possible array c.
Array x of length n is lexicographically less than array y of length n, if there exists such i (1 ≤ i ≤ n), that x_i < y_i, and for any j (1 ≤ j < i) x_j = y_j.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a, b and c.
The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i < n), where a_i is the i-th element of a.
The third line of the input contains n integers b_1, b_2, ..., b_n (0 ≤ b_i < n), where b_i is the i-th element of b.
Output
Print the lexicographically minimum possible array c. Recall that your task is to reorder elements of the array b and obtain the lexicographically minimum possible array c, where the i-th element of c is c_i = (a_i + b_i) \% n.
Examples
Input
4
0 1 2 1
3 2 1 1
Output
1 0 0 2
Input
7
2 5 1 5 3 4 3
2 4 3 5 6 5 1
Output
0 0 0 1 0 2 4
Submitted Solution:
```
# input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
# input = io.StringIO(os.read(0, os.fstat(0).st_size).decode()).readline
ii = lambda:int(input())
kk=lambda:map(int,input().split())
# k2=lambda:map(lambda x:int(x)-1, input().split())
ll=lambda:list(kk())
n = ii()
parents, rank = [-1]*n, [0]*n
loc = [i for i in range(n)]
def findParent(x):
stack = []
curr = x
while parents[curr] != -1:
stack.append(curr)
curr = parents[curr]
for v in stack:
parents[v] = curr
return curr
def union(x, y):
best = None
xP, yP = findParent(x), findParent(y)
if rank[x] < rank[y]: best=parents[xP] = yP;
elif rank[x] > rank[y]: best=parents[yP] = xP
else:
best=parents[yP] = xP
rank[xP]+=1
if values[loc[best]] == 0:
loc[best] = loc[xP] if yP is best else loc[yP]
a = kk()
values = [0]*n
tbp=[]
for x in kk(): values[x]+=1
for i in range(n):
if values[i] == 0: union(i, (i+1)%n)
for v in a:
p = loc[findParent((n-v)%n)]
tbp.append((v+p)%n)
values[p]-=1
if values[p] == 0: union(p, (p+1)%n)
print(*tbp)
``` | instruction | 0 | 45,449 | 12 | 90,898 |
Yes | output | 1 | 45,449 | 12 | 90,899 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two arrays a and b, both of length n. All elements of both arrays are from 0 to n-1.
You can reorder elements of the array b (if you want, you may leave the order of elements as it is). After that, let array c be the array of length n, the i-th element of this array is c_i = (a_i + b_i) \% n, where x \% y is x modulo y.
Your task is to reorder elements of the array b to obtain the lexicographically minimum possible array c.
Array x of length n is lexicographically less than array y of length n, if there exists such i (1 ≤ i ≤ n), that x_i < y_i, and for any j (1 ≤ j < i) x_j = y_j.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a, b and c.
The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i < n), where a_i is the i-th element of a.
The third line of the input contains n integers b_1, b_2, ..., b_n (0 ≤ b_i < n), where b_i is the i-th element of b.
Output
Print the lexicographically minimum possible array c. Recall that your task is to reorder elements of the array b and obtain the lexicographically minimum possible array c, where the i-th element of c is c_i = (a_i + b_i) \% n.
Examples
Input
4
0 1 2 1
3 2 1 1
Output
1 0 0 2
Input
7
2 5 1 5 3 4 3
2 4 3 5 6 5 1
Output
0 0 0 1 0 2 4
Submitted Solution:
```
import bisect
import sys
input = sys.stdin.readline
def main():
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
cnt = [0] * n
for val in b:
cnt[val] += 1
all_set = sorted(set(b))
n_all_set = len(all_set)
nextL = [0] * n
nextR = [0] * n
for i in range(1, n_all_set):
nextL[all_set[i]] = all_set[i-1]
for i in range(n_all_set-1):
nextR[all_set[i]] = all_set[i+1]
nextR[all_set[-1]] = all_set[0]
nextL[all_set[0]] = all_set[-1]
res = []
def opositeMod(x):
return 0 if x == 0 else n-x
for val in a:
cand_pos = bisect.bisect_left(all_set, opositeMod(val))
if cand_pos == n_all_set:
cand_pos = 0
cand_val = all_set[cand_pos]
if cnt[cand_val] == 0:
to_update = []
current = nextR[cand_val]
while cnt[current] == 0:
to_update.append(current)
current = nextR[current]
for upd in to_update:
nextR[upd] = current
nextL[upd] = nextL[current]
cand_val = current
res.append((val+cand_val) % n)
cnt[cand_val] -= 1
if cnt[cand_val] == 0:
nextL[nextR[cand_val]] = nextL[cand_val]
nextR[nextL[cand_val]] = nextR[cand_val]
print(*res)
if __name__ == '__main__':
main()
``` | instruction | 0 | 45,450 | 12 | 90,900 |
Yes | output | 1 | 45,450 | 12 | 90,901 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two arrays a and b, both of length n. All elements of both arrays are from 0 to n-1.
You can reorder elements of the array b (if you want, you may leave the order of elements as it is). After that, let array c be the array of length n, the i-th element of this array is c_i = (a_i + b_i) \% n, where x \% y is x modulo y.
Your task is to reorder elements of the array b to obtain the lexicographically minimum possible array c.
Array x of length n is lexicographically less than array y of length n, if there exists such i (1 ≤ i ≤ n), that x_i < y_i, and for any j (1 ≤ j < i) x_j = y_j.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a, b and c.
The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i < n), where a_i is the i-th element of a.
The third line of the input contains n integers b_1, b_2, ..., b_n (0 ≤ b_i < n), where b_i is the i-th element of b.
Output
Print the lexicographically minimum possible array c. Recall that your task is to reorder elements of the array b and obtain the lexicographically minimum possible array c, where the i-th element of c is c_i = (a_i + b_i) \% n.
Examples
Input
4
0 1 2 1
3 2 1 1
Output
1 0 0 2
Input
7
2 5 1 5 3 4 3
2 4 3 5 6 5 1
Output
0 0 0 1 0 2 4
Submitted Solution:
```
import sys
input = sys.stdin.readline
def make_tree(n):
i = 2
while True:
if i >= n * 2:
tree = [inf] * i
break
else:
i *= 2
return tree
def initialization(a):
l = len(tree) // 2
for i in range(l, l + len(a)):
tree[i] = a[i - l]
for i in range(l - 1, 0, -1):
tree[i] = min(tree[2 * i], tree[2 * i + 1])
return
def update(i, x):
i += len(tree) // 2
tree[i] = x
i //= 2
while True:
if i == 0:
break
tree[i] = min(tree[2 * i], tree[2 * i + 1])
i //= 2
return
def find(s, t):
s += len(tree) // 2
t += len(tree) // 2
ans = inf
while True:
if s > t:
break
if s % 2 == 0:
s //= 2
else:
ans = min(ans, tree[s])
s = (s + 1) // 2
if t % 2 == 1:
t //= 2
else:
ans = min(ans, tree[t])
t = (t - 1) // 2
return ans
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
inf = 114514810
tree = make_tree(2 * n + 1)
cnt = [0] * n
x = [inf] * (2 * n)
for i in b:
cnt[i] += 1
x[i] = i
x[i + n] = i + n
initialization(x)
c = []
for i in a:
l = n - i
r = l + n - 1
m = find(l, r) % n
c.append((i + m) % n)
cnt[m] -= 1
if not cnt[m]:
update(m, inf)
update(m + n, inf)
print(*c)
``` | instruction | 0 | 45,451 | 12 | 90,902 |
Yes | output | 1 | 45,451 | 12 | 90,903 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two arrays a and b, both of length n. All elements of both arrays are from 0 to n-1.
You can reorder elements of the array b (if you want, you may leave the order of elements as it is). After that, let array c be the array of length n, the i-th element of this array is c_i = (a_i + b_i) \% n, where x \% y is x modulo y.
Your task is to reorder elements of the array b to obtain the lexicographically minimum possible array c.
Array x of length n is lexicographically less than array y of length n, if there exists such i (1 ≤ i ≤ n), that x_i < y_i, and for any j (1 ≤ j < i) x_j = y_j.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a, b and c.
The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i < n), where a_i is the i-th element of a.
The third line of the input contains n integers b_1, b_2, ..., b_n (0 ≤ b_i < n), where b_i is the i-th element of b.
Output
Print the lexicographically minimum possible array c. Recall that your task is to reorder elements of the array b and obtain the lexicographically minimum possible array c, where the i-th element of c is c_i = (a_i + b_i) \% n.
Examples
Input
4
0 1 2 1
3 2 1 1
Output
1 0 0 2
Input
7
2 5 1 5 3 4 3
2 4 3 5 6 5 1
Output
0 0 0 1 0 2 4
Submitted Solution:
```
size = int(input())
array1 = [int(i) for i in input().split()]
array2 = [int(i) for i in input().split()]
array3 = []
for item in array1:
diff = size - item
i = diff
while 1:
if i > max(array2):
i = min(array2)
if i in array2:
array3.append((item + i) % size)
array2.remove(i)
break
else:
i += 1
print(array2)
print(array3)
``` | instruction | 0 | 45,452 | 12 | 90,904 |
No | output | 1 | 45,452 | 12 | 90,905 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two arrays a and b, both of length n. All elements of both arrays are from 0 to n-1.
You can reorder elements of the array b (if you want, you may leave the order of elements as it is). After that, let array c be the array of length n, the i-th element of this array is c_i = (a_i + b_i) \% n, where x \% y is x modulo y.
Your task is to reorder elements of the array b to obtain the lexicographically minimum possible array c.
Array x of length n is lexicographically less than array y of length n, if there exists such i (1 ≤ i ≤ n), that x_i < y_i, and for any j (1 ≤ j < i) x_j = y_j.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a, b and c.
The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i < n), where a_i is the i-th element of a.
The third line of the input contains n integers b_1, b_2, ..., b_n (0 ≤ b_i < n), where b_i is the i-th element of b.
Output
Print the lexicographically minimum possible array c. Recall that your task is to reorder elements of the array b and obtain the lexicographically minimum possible array c, where the i-th element of c is c_i = (a_i + b_i) \% n.
Examples
Input
4
0 1 2 1
3 2 1 1
Output
1 0 0 2
Input
7
2 5 1 5 3 4 3
2 4 3 5 6 5 1
Output
0 0 0 1 0 2 4
Submitted Solution:
```
import collections
n = 7
a = [2, 5, 1, 5, 3, 4, 3]
b = [2, 4, 3, 5, 6, 5, 1]
def solve(n, a, b):
c = collections.Counter(b)
b = sorted(set(b))
nex = list(range(1,n)) + [0]
res = []
for x in a:
target = (n - x) % n
while c[target] == 0:
if nex[target] == 0:
nex[target] = nex[nex[target]]
target = nex[target]
res.append((x+target)%n)
c[target] -= 1
return ' '.join(map(str, res))
print(solve(n, a, b))
``` | instruction | 0 | 45,453 | 12 | 90,906 |
No | output | 1 | 45,453 | 12 | 90,907 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two arrays a and b, both of length n. All elements of both arrays are from 0 to n-1.
You can reorder elements of the array b (if you want, you may leave the order of elements as it is). After that, let array c be the array of length n, the i-th element of this array is c_i = (a_i + b_i) \% n, where x \% y is x modulo y.
Your task is to reorder elements of the array b to obtain the lexicographically minimum possible array c.
Array x of length n is lexicographically less than array y of length n, if there exists such i (1 ≤ i ≤ n), that x_i < y_i, and for any j (1 ≤ j < i) x_j = y_j.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a, b and c.
The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i < n), where a_i is the i-th element of a.
The third line of the input contains n integers b_1, b_2, ..., b_n (0 ≤ b_i < n), where b_i is the i-th element of b.
Output
Print the lexicographically minimum possible array c. Recall that your task is to reorder elements of the array b and obtain the lexicographically minimum possible array c, where the i-th element of c is c_i = (a_i + b_i) \% n.
Examples
Input
4
0 1 2 1
3 2 1 1
Output
1 0 0 2
Input
7
2 5 1 5 3 4 3
2 4 3 5 6 5 1
Output
0 0 0 1 0 2 4
Submitted Solution:
```
n = int(input())
A = []
A = list(map(int, input().split(" ")))
s = []
x = 0
l = 0
r = n
while l <= r:
if A[l] <= A[r - 1] and A[l] > x:
s.append('L')
x = A[l]
l = l + 1
elif A[r-1] > x:
s.append('R')
x = A[r-1]
r = r - 1
else:
break
print(len(s))
for i in range(len(s)):
print(s[i], end = '')
``` | instruction | 0 | 45,454 | 12 | 90,908 |
No | output | 1 | 45,454 | 12 | 90,909 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two arrays a and b, both of length n. All elements of both arrays are from 0 to n-1.
You can reorder elements of the array b (if you want, you may leave the order of elements as it is). After that, let array c be the array of length n, the i-th element of this array is c_i = (a_i + b_i) \% n, where x \% y is x modulo y.
Your task is to reorder elements of the array b to obtain the lexicographically minimum possible array c.
Array x of length n is lexicographically less than array y of length n, if there exists such i (1 ≤ i ≤ n), that x_i < y_i, and for any j (1 ≤ j < i) x_j = y_j.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a, b and c.
The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i < n), where a_i is the i-th element of a.
The third line of the input contains n integers b_1, b_2, ..., b_n (0 ≤ b_i < n), where b_i is the i-th element of b.
Output
Print the lexicographically minimum possible array c. Recall that your task is to reorder elements of the array b and obtain the lexicographically minimum possible array c, where the i-th element of c is c_i = (a_i + b_i) \% n.
Examples
Input
4
0 1 2 1
3 2 1 1
Output
1 0 0 2
Input
7
2 5 1 5 3 4 3
2 4 3 5 6 5 1
Output
0 0 0 1 0 2 4
Submitted Solution:
```
n=int(input())
a=[int(x) for x in input().split()]
m=0
sol=''
while(len(a)>0):
if(a[0]>m and a[-1]>m and a[0]!=a[-1]):
if(a[0]<a[-1]):
sol+='L'
m=a[0]
a.pop(0)
else:
sol+='R'
m=a[-1]
a.pop(-1)
elif(a[0]>m and a[-1]>m and a[0]==a[-1]):
k1=1
k2=1
s2=sol+'L'
s3=sol+'R'
for i in range(1,len(a)):
if(a[i]>a[i-1]):
s2+='L'
else:
break
i=len(a)-2
while(i>=0):
if(a[i]>a[i+1]):
s3+='R'
else:
break
i-=1
if(len(s2)>len(s3)):
print(len(s2))
print(s2)
exit()
else:
print(len(s3))
print(s3)
exit()
elif(a[0]>m):
sol+='L'
m=a[0]
a.pop(0)
elif(a[-1]>m):
sol+='R'
m=a[-1]
a.pop(-1)
else:
break
print(len(sol))
print(sol)
``` | instruction | 0 | 45,455 | 12 | 90,910 |
No | output | 1 | 45,455 | 12 | 90,911 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a sequence a_1, a_2, ..., a_n consisting of n non-zero integers (i.e. a_i ≠ 0).
You have to calculate two following values:
1. the number of pairs of indices (l, r) (l ≤ r) such that a_l ⋅ a_{l + 1} ... a_{r - 1} ⋅ a_r is negative;
2. the number of pairs of indices (l, r) (l ≤ r) such that a_l ⋅ a_{l + 1} ... a_{r - 1} ⋅ a_r is positive;
Input
The first line contains one integer n (1 ≤ n ≤ 2 ⋅ 10^{5}) — the number of elements in the sequence.
The second line contains n integers a_1, a_2, ..., a_n (-10^{9} ≤ a_i ≤ 10^{9}; a_i ≠ 0) — the elements of the sequence.
Output
Print two integers — the number of subsegments with negative product and the number of subsegments with positive product, respectively.
Examples
Input
5
5 -3 3 -1 1
Output
8 7
Input
10
4 2 -4 3 1 2 -4 3 2 3
Output
28 27
Input
5
-1 -2 -3 -4 -5
Output
9 6 | instruction | 0 | 45,480 | 12 | 90,960 |
Tags: combinatorics, dp, implementation
Correct Solution:
```
import sys
input = sys.stdin.readline
t = 1
# t = int(input())
for _ in range(t):
n = int(input())
a = [int(x) for x in input().split()]
total = n*(n+1)//2
neg = 0
pos = 0
ans = 0
for i in range(n):
if a[i] < 0:
temp = neg
neg = pos + 1
pos = temp
else:
pos += 1
neg = neg
ans += neg
print(ans, total-ans)
``` | output | 1 | 45,480 | 12 | 90,961 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a sequence a_1, a_2, ..., a_n consisting of n non-zero integers (i.e. a_i ≠ 0).
You have to calculate two following values:
1. the number of pairs of indices (l, r) (l ≤ r) such that a_l ⋅ a_{l + 1} ... a_{r - 1} ⋅ a_r is negative;
2. the number of pairs of indices (l, r) (l ≤ r) such that a_l ⋅ a_{l + 1} ... a_{r - 1} ⋅ a_r is positive;
Input
The first line contains one integer n (1 ≤ n ≤ 2 ⋅ 10^{5}) — the number of elements in the sequence.
The second line contains n integers a_1, a_2, ..., a_n (-10^{9} ≤ a_i ≤ 10^{9}; a_i ≠ 0) — the elements of the sequence.
Output
Print two integers — the number of subsegments with negative product and the number of subsegments with positive product, respectively.
Examples
Input
5
5 -3 3 -1 1
Output
8 7
Input
10
4 2 -4 3 1 2 -4 3 2 3
Output
28 27
Input
5
-1 -2 -3 -4 -5
Output
9 6 | instruction | 0 | 45,481 | 12 | 90,962 |
Tags: combinatorics, dp, implementation
Correct Solution:
```
from sys import stdin,stdout
for _ in range(1):#int(stdin.readline())):
n=int(stdin.readline())
a=list(map(int,stdin.readline().split()))
dp=[[0 for _ in range(2)] for _ in range(n)]
if a[0]<0:dp[0][1]=1
else:dp[0][0]=1
for i in range(1,n):
if a[i]<0:
dp[i][0]=dp[i-1][1]
dp[i][1]=dp[i-1][0]+1
else:
dp[i][0]=dp[i-1][0]+1
dp[i][1]=dp[i-1][1]
pos=neg=0
for p,ne in dp:
pos+=p
neg+=ne
# print(dp)
print(neg,pos)
``` | output | 1 | 45,481 | 12 | 90,963 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a sequence a_1, a_2, ..., a_n consisting of n non-zero integers (i.e. a_i ≠ 0).
You have to calculate two following values:
1. the number of pairs of indices (l, r) (l ≤ r) such that a_l ⋅ a_{l + 1} ... a_{r - 1} ⋅ a_r is negative;
2. the number of pairs of indices (l, r) (l ≤ r) such that a_l ⋅ a_{l + 1} ... a_{r - 1} ⋅ a_r is positive;
Input
The first line contains one integer n (1 ≤ n ≤ 2 ⋅ 10^{5}) — the number of elements in the sequence.
The second line contains n integers a_1, a_2, ..., a_n (-10^{9} ≤ a_i ≤ 10^{9}; a_i ≠ 0) — the elements of the sequence.
Output
Print two integers — the number of subsegments with negative product and the number of subsegments with positive product, respectively.
Examples
Input
5
5 -3 3 -1 1
Output
8 7
Input
10
4 2 -4 3 1 2 -4 3 2 3
Output
28 27
Input
5
-1 -2 -3 -4 -5
Output
9 6 | instruction | 0 | 45,482 | 12 | 90,964 |
Tags: combinatorics, dp, implementation
Correct Solution:
```
n = int(input())
def m(x):
return -1 if int(x) < 0 else 1
l = list(map(m, input().split()))
pos = 1
neg = 0
t = 1
for x in l:
t *= x
if t < 0:
neg += 1
else:
pos += 1
print(neg * pos, neg * (neg - 1) // 2 + (pos * (pos - 1) // 2))
``` | output | 1 | 45,482 | 12 | 90,965 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a sequence a_1, a_2, ..., a_n consisting of n non-zero integers (i.e. a_i ≠ 0).
You have to calculate two following values:
1. the number of pairs of indices (l, r) (l ≤ r) such that a_l ⋅ a_{l + 1} ... a_{r - 1} ⋅ a_r is negative;
2. the number of pairs of indices (l, r) (l ≤ r) such that a_l ⋅ a_{l + 1} ... a_{r - 1} ⋅ a_r is positive;
Input
The first line contains one integer n (1 ≤ n ≤ 2 ⋅ 10^{5}) — the number of elements in the sequence.
The second line contains n integers a_1, a_2, ..., a_n (-10^{9} ≤ a_i ≤ 10^{9}; a_i ≠ 0) — the elements of the sequence.
Output
Print two integers — the number of subsegments with negative product and the number of subsegments with positive product, respectively.
Examples
Input
5
5 -3 3 -1 1
Output
8 7
Input
10
4 2 -4 3 1 2 -4 3 2 3
Output
28 27
Input
5
-1 -2 -3 -4 -5
Output
9 6 | instruction | 0 | 45,483 | 12 | 90,966 |
Tags: combinatorics, dp, implementation
Correct Solution:
```
'''
Auther: ghoshashis545 Ashis Ghosh
College: jalpaiguri Govt Enggineering College
Date:09/06/2020
'''
from os import path
import sys
from functools import cmp_to_key as ctk
from collections import deque,defaultdict as dd
from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
from itertools import permutations
from datetime import datetime
from math import ceil,sqrt,log,gcd
def ii():return int(input())
def si():return input()
def mi():return map(int,input().split())
def li():return list(mi())
abc='abcdefghijklmnopqrstuvwxyz'
abd={'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod=1000000007
#mod=998244353
inf = float("inf")
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]
def solve():
n=ii()
a=li()
dp=[[0,0]for i in range(n+1)]
pos,neg=0,0
for i in range(n):
if a[i]>0:
dp[i+1][0]=dp[i][0]+1
dp[i+1][1]=dp[i][1]
else:
dp[i+1][0]=dp[i][1]
dp[i+1][1]=dp[i][0]+1
pos+=dp[i+1][0]
neg+=dp[i+1][1]
print(neg,pos)
if __name__ =="__main__":
solve()
``` | output | 1 | 45,483 | 12 | 90,967 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a sequence a_1, a_2, ..., a_n consisting of n non-zero integers (i.e. a_i ≠ 0).
You have to calculate two following values:
1. the number of pairs of indices (l, r) (l ≤ r) such that a_l ⋅ a_{l + 1} ... a_{r - 1} ⋅ a_r is negative;
2. the number of pairs of indices (l, r) (l ≤ r) such that a_l ⋅ a_{l + 1} ... a_{r - 1} ⋅ a_r is positive;
Input
The first line contains one integer n (1 ≤ n ≤ 2 ⋅ 10^{5}) — the number of elements in the sequence.
The second line contains n integers a_1, a_2, ..., a_n (-10^{9} ≤ a_i ≤ 10^{9}; a_i ≠ 0) — the elements of the sequence.
Output
Print two integers — the number of subsegments with negative product and the number of subsegments with positive product, respectively.
Examples
Input
5
5 -3 3 -1 1
Output
8 7
Input
10
4 2 -4 3 1 2 -4 3 2 3
Output
28 27
Input
5
-1 -2 -3 -4 -5
Output
9 6 | instruction | 0 | 45,484 | 12 | 90,968 |
Tags: combinatorics, dp, implementation
Correct Solution:
```
n = int(input())
a = [int(x) for x in input().split()]
N = (n*(n+1))//2
total = 0
pos = 0
for i in range(0, n):
if(a[i] < 0):
pos = i - pos
total += pos
else:
pos += 1
total += pos
print(N - total, total)
``` | output | 1 | 45,484 | 12 | 90,969 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a sequence a_1, a_2, ..., a_n consisting of n non-zero integers (i.e. a_i ≠ 0).
You have to calculate two following values:
1. the number of pairs of indices (l, r) (l ≤ r) such that a_l ⋅ a_{l + 1} ... a_{r - 1} ⋅ a_r is negative;
2. the number of pairs of indices (l, r) (l ≤ r) such that a_l ⋅ a_{l + 1} ... a_{r - 1} ⋅ a_r is positive;
Input
The first line contains one integer n (1 ≤ n ≤ 2 ⋅ 10^{5}) — the number of elements in the sequence.
The second line contains n integers a_1, a_2, ..., a_n (-10^{9} ≤ a_i ≤ 10^{9}; a_i ≠ 0) — the elements of the sequence.
Output
Print two integers — the number of subsegments with negative product and the number of subsegments with positive product, respectively.
Examples
Input
5
5 -3 3 -1 1
Output
8 7
Input
10
4 2 -4 3 1 2 -4 3 2 3
Output
28 27
Input
5
-1 -2 -3 -4 -5
Output
9 6 | instruction | 0 | 45,485 | 12 | 90,970 |
Tags: combinatorics, dp, implementation
Correct Solution:
```
n = int(input())
a = list(map(int,input().split()))
dp = [[0 for i in range(2)]for j in range(n)]
dp[0][1] = 1 if a[0]<0 else 0
dp[0][0] = 1 if a[0]>0 else 0
for i in range(1,n):
if a[i]>0:
dp[i][0] = 1+dp[i-1][0]
dp[i][1] = dp[i-1][1]
else:
dp[i][0] = dp[i-1][1]
dp[i][1] = 1+dp[i-1][0]
pos = 0
neg = 0
for i in range(n):
pos+=dp[i][0]
neg+=dp[i][1]
print(neg,pos)
``` | output | 1 | 45,485 | 12 | 90,971 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a sequence a_1, a_2, ..., a_n consisting of n non-zero integers (i.e. a_i ≠ 0).
You have to calculate two following values:
1. the number of pairs of indices (l, r) (l ≤ r) such that a_l ⋅ a_{l + 1} ... a_{r - 1} ⋅ a_r is negative;
2. the number of pairs of indices (l, r) (l ≤ r) such that a_l ⋅ a_{l + 1} ... a_{r - 1} ⋅ a_r is positive;
Input
The first line contains one integer n (1 ≤ n ≤ 2 ⋅ 10^{5}) — the number of elements in the sequence.
The second line contains n integers a_1, a_2, ..., a_n (-10^{9} ≤ a_i ≤ 10^{9}; a_i ≠ 0) — the elements of the sequence.
Output
Print two integers — the number of subsegments with negative product and the number of subsegments with positive product, respectively.
Examples
Input
5
5 -3 3 -1 1
Output
8 7
Input
10
4 2 -4 3 1 2 -4 3 2 3
Output
28 27
Input
5
-1 -2 -3 -4 -5
Output
9 6 | instruction | 0 | 45,486 | 12 | 90,972 |
Tags: combinatorics, dp, implementation
Correct Solution:
```
n = int(input())
lis = [int(x) for x in input().split()]
total = 0
negative_elements = 0
even_before = 0
odd_before = 0
for i in (lis):
if i < 0:
if negative_elements % 2 == 0:
total += odd_before
even_before+=1
else:
total += even_before
odd_before+=1
negative_elements += 1
else:
if negative_elements % 2 == 0:
total += even_before + 1
even_before +=1
else:
total += odd_before + 1
odd_before += 1
#print(total,even_before,odd_before)
print((n)*(n+1)//2 - total,total)
``` | output | 1 | 45,486 | 12 | 90,973 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a sequence a_1, a_2, ..., a_n consisting of n non-zero integers (i.e. a_i ≠ 0).
You have to calculate two following values:
1. the number of pairs of indices (l, r) (l ≤ r) such that a_l ⋅ a_{l + 1} ... a_{r - 1} ⋅ a_r is negative;
2. the number of pairs of indices (l, r) (l ≤ r) such that a_l ⋅ a_{l + 1} ... a_{r - 1} ⋅ a_r is positive;
Input
The first line contains one integer n (1 ≤ n ≤ 2 ⋅ 10^{5}) — the number of elements in the sequence.
The second line contains n integers a_1, a_2, ..., a_n (-10^{9} ≤ a_i ≤ 10^{9}; a_i ≠ 0) — the elements of the sequence.
Output
Print two integers — the number of subsegments with negative product and the number of subsegments with positive product, respectively.
Examples
Input
5
5 -3 3 -1 1
Output
8 7
Input
10
4 2 -4 3 1 2 -4 3 2 3
Output
28 27
Input
5
-1 -2 -3 -4 -5
Output
9 6 | instruction | 0 | 45,487 | 12 | 90,974 |
Tags: combinatorics, dp, implementation
Correct Solution:
```
n = int(input())
a = [int(x) for x in input().split(' ')]
a = [c // (abs(c)) for c in a]
p = [1]
for i in range(n):
p.append(p[-1] * a[i])
del p[0]
m = len([c for c in p if c < 0])
ans = m * (n - m + 1)
print(ans, (n * (n + 1)) // 2 - ans)
``` | output | 1 | 45,487 | 12 | 90,975 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a sequence a_1, a_2, ..., a_n consisting of n non-zero integers (i.e. a_i ≠ 0).
You have to calculate two following values:
1. the number of pairs of indices (l, r) (l ≤ r) such that a_l ⋅ a_{l + 1} ... a_{r - 1} ⋅ a_r is negative;
2. the number of pairs of indices (l, r) (l ≤ r) such that a_l ⋅ a_{l + 1} ... a_{r - 1} ⋅ a_r is positive;
Input
The first line contains one integer n (1 ≤ n ≤ 2 ⋅ 10^{5}) — the number of elements in the sequence.
The second line contains n integers a_1, a_2, ..., a_n (-10^{9} ≤ a_i ≤ 10^{9}; a_i ≠ 0) — the elements of the sequence.
Output
Print two integers — the number of subsegments with negative product and the number of subsegments with positive product, respectively.
Examples
Input
5
5 -3 3 -1 1
Output
8 7
Input
10
4 2 -4 3 1 2 -4 3 2 3
Output
28 27
Input
5
-1 -2 -3 -4 -5
Output
9 6
Submitted Solution:
```
'''
Auther: ghoshashis545 Ashis Ghosh
College: jalpaiguri Govt Enggineering College
Date:09/06/2020
'''
from os import path
import sys
from functools import cmp_to_key as ctk
from collections import deque,defaultdict as dd
from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
from itertools import permutations
from datetime import datetime
from math import ceil,sqrt,log,gcd
def ii():return int(input())
def si():return input()
def mi():return map(int,input().split())
def li():return list(mi())
abc='abcdefghijklmnopqrstuvwxyz'
abd={'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod=1000000007
#mod=998244353
inf = float("inf")
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]
def solve():
n=ii()
a=li()
x=[]
tot=n*(n+1)//2
c,c1=0,0
x1=[]
for i in range(n):
if a[i]<0:
if c>0:
x.append(c)
c=0
c1+=1
else:
c+=1
if c1>1:
x1.append(c1)
c1=0
if c>0:
x.append(c)
if c1>1:
x1.append(c1)
pos=0
for i in x1:
if i&1:
x2=(i-1)//2
else:
x2=i//2
pos+=(n-x2)*x2
for i in x:
pos+=i*(i+1)//2
n=len(x)
pre1=[0]*(n+1)
pre2=[0]*(n+1)
for i in range(n):
pre1[i+1]=pre1[i]
pre2[i+1]=pre2[i]
if i%2==0:
pre1[i+1]+=x[i]
else:
pre2[i+1]+=x[i]
for i in range(n):
if i%2==0:
x1=pre1[n]-pre1[i+1]
if x1==0:
continue
pos+=(x1+1)*(x[i]+1)
else:
x1=pre2[n]-pre2[i+1]
if x1==0:
continue
pos+=(x1+1)*(x[i]+1)
print(tot-pos,pos)
if __name__ =="__main__":
solve()
``` | instruction | 0 | 45,492 | 12 | 90,984 |
No | output | 1 | 45,492 | 12 | 90,985 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a deck of n cards numbered from 1 to n (not necessarily in this order in the deck). You have to sort the deck by repeating the following operation.
* Choose 2 ≤ k ≤ n and split the deck in k nonempty contiguous parts D_1, D_2,..., D_k (D_1 contains the first |D_1| cards of the deck, D_2 contains the following |D_2| cards and so on). Then reverse the order of the parts, transforming the deck into D_k, D_{k-1}, ..., D_2, D_1 (so, the first |D_k| cards of the new deck are D_k, the following |D_{k-1}| cards are D_{k-1} and so on). The internal order of each packet of cards D_i is unchanged by the operation.
You have to obtain a sorted deck (i.e., a deck where the first card is 1, the second is 2 and so on) performing at most n operations. It can be proven that it is always possible to sort the deck performing at most n operations.
Examples of operation: The following are three examples of valid operations (on three decks with different sizes).
* If the deck is [3 6 2 1 4 5 7] (so 3 is the first card and 7 is the last card), we may apply the operation with k=4 and D_1=[3 6], D_2=[2 1 4], D_3=[5], D_4=[7]. Doing so, the deck becomes [7 5 2 1 4 3 6].
* If the deck is [3 1 2], we may apply the operation with k=3 and D_1=[3], D_2=[1], D_3=[2]. Doing so, the deck becomes [2 1 3].
* If the deck is [5 1 2 4 3 6], we may apply the operation with k=2 and D_1=[5 1], D_2=[2 4 3 6]. Doing so, the deck becomes [2 4 3 6 5 1].
Input
The first line of the input contains one integer n (1≤ n≤ 52) — the number of cards in the deck.
The second line contains n integers c_1, c_2, ..., c_n — the cards in the deck. The first card is c_1, the second is c_2 and so on.
It is guaranteed that for all i=1,...,n there is exactly one j∈\{1,...,n\} such that c_j = i.
Output
On the first line, print the number q of operations you perform (it must hold 0≤ q≤ n).
Then, print q lines, each describing one operation.
To describe an operation, print on a single line the number k of parts you are going to split the deck in, followed by the size of the k parts: |D_1|, |D_2|, ... , |D_k|.
It must hold 2≤ k≤ n, and |D_i|≥ 1 for all i=1,...,k, and |D_1|+|D_2|+⋅⋅⋅ + |D_k| = n.
It can be proven that it is always possible to sort the deck performing at most n operations. If there are several ways to sort the deck you can output any of them.
Examples
Input
4
3 1 2 4
Output
2
3 1 2 1
2 1 3
Input
6
6 5 4 3 2 1
Output
1
6 1 1 1 1 1 1
Input
1
1
Output
0
Note
Explanation of the first testcase: Initially the deck is [3 1 2 4].
* The first operation splits the deck as [(3) (1 2) (4)] and then transforms it into [4 1 2 3].
* The second operation splits the deck as [(4) (1 2 3)] and then transforms it into [1 2 3 4].
Explanation of the second testcase: Initially the deck is [6 5 4 3 2 1].
* The first (and only) operation splits the deck as [(6) (5) (4) (3) (2) (1)] and then transforms it into [1 2 3 4 5 6]. | instruction | 0 | 45,571 | 12 | 91,142 |
Tags: constructive algorithms, implementation
Correct Solution:
```
import os,io
input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n=int(input())
a=list(map(int,input().split()))
ans=[]
if a[n-1]==1:
parity=1
else:
parity=0
for i in range(n-1):
if parity%2==0:
for j in range(n):
if a[j]==i+1 and j!=i:
ans.append([])
for k in range(i):
ans[-1].append(str(1))
ans[-1].append(str(j-i+1))
if n-j-1>0:
ans[-1].append(str(n-j-1))
ans[-1].reverse()
t=len(ans[-1])
ans[-1].append(str(t))
ans[-1].reverse()
b=[]
for k in range(j+1,n):
b.append(a[k])
for k in range(i,j+1):
b.append(a[k])
for k in range(i-1,-1,-1):
b.append(k+1)
a=b.copy()
parity+=1
break
else:
for j in range(n):
if a[j]==i+1 and j!=n-i-1:
ans.append([])
if j>0:
ans[-1].append(str(j))
if n-j-1>0:
ans[-1].append(str(n-j-i))
for k in range(i):
ans[-1].append(str(1))
ans[-1].reverse()
t=len(ans[-1])
ans[-1].append(str(t))
ans[-1].reverse()
b=[]
for k in range(i):
b.append(k+1)
for k in range(j,n-i):
b.append(a[k])
for k in range(j):
b.append(a[k])
a=b.copy()
parity+=1
break
if a[0]!=1:
ans.append([str(n)])
for i in range(n):
ans[-1].append(str(1))
print(len(ans))
for i in ans:
print(' '.join(i))
``` | output | 1 | 45,571 | 12 | 91,143 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a deck of n cards numbered from 1 to n (not necessarily in this order in the deck). You have to sort the deck by repeating the following operation.
* Choose 2 ≤ k ≤ n and split the deck in k nonempty contiguous parts D_1, D_2,..., D_k (D_1 contains the first |D_1| cards of the deck, D_2 contains the following |D_2| cards and so on). Then reverse the order of the parts, transforming the deck into D_k, D_{k-1}, ..., D_2, D_1 (so, the first |D_k| cards of the new deck are D_k, the following |D_{k-1}| cards are D_{k-1} and so on). The internal order of each packet of cards D_i is unchanged by the operation.
You have to obtain a sorted deck (i.e., a deck where the first card is 1, the second is 2 and so on) performing at most n operations. It can be proven that it is always possible to sort the deck performing at most n operations.
Examples of operation: The following are three examples of valid operations (on three decks with different sizes).
* If the deck is [3 6 2 1 4 5 7] (so 3 is the first card and 7 is the last card), we may apply the operation with k=4 and D_1=[3 6], D_2=[2 1 4], D_3=[5], D_4=[7]. Doing so, the deck becomes [7 5 2 1 4 3 6].
* If the deck is [3 1 2], we may apply the operation with k=3 and D_1=[3], D_2=[1], D_3=[2]. Doing so, the deck becomes [2 1 3].
* If the deck is [5 1 2 4 3 6], we may apply the operation with k=2 and D_1=[5 1], D_2=[2 4 3 6]. Doing so, the deck becomes [2 4 3 6 5 1].
Input
The first line of the input contains one integer n (1≤ n≤ 52) — the number of cards in the deck.
The second line contains n integers c_1, c_2, ..., c_n — the cards in the deck. The first card is c_1, the second is c_2 and so on.
It is guaranteed that for all i=1,...,n there is exactly one j∈\{1,...,n\} such that c_j = i.
Output
On the first line, print the number q of operations you perform (it must hold 0≤ q≤ n).
Then, print q lines, each describing one operation.
To describe an operation, print on a single line the number k of parts you are going to split the deck in, followed by the size of the k parts: |D_1|, |D_2|, ... , |D_k|.
It must hold 2≤ k≤ n, and |D_i|≥ 1 for all i=1,...,k, and |D_1|+|D_2|+⋅⋅⋅ + |D_k| = n.
It can be proven that it is always possible to sort the deck performing at most n operations. If there are several ways to sort the deck you can output any of them.
Examples
Input
4
3 1 2 4
Output
2
3 1 2 1
2 1 3
Input
6
6 5 4 3 2 1
Output
1
6 1 1 1 1 1 1
Input
1
1
Output
0
Note
Explanation of the first testcase: Initially the deck is [3 1 2 4].
* The first operation splits the deck as [(3) (1 2) (4)] and then transforms it into [4 1 2 3].
* The second operation splits the deck as [(4) (1 2 3)] and then transforms it into [1 2 3 4].
Explanation of the second testcase: Initially the deck is [6 5 4 3 2 1].
* The first (and only) operation splits the deck as [(6) (5) (4) (3) (2) (1)] and then transforms it into [1 2 3 4 5 6]. | instruction | 0 | 45,572 | 12 | 91,144 |
Tags: constructive algorithms, implementation
Correct Solution:
```
n = int(input())
*arr, = map(int, input().split())
orig_arr = arr.copy()
operations = []
left = not bool(n % 2)
sorted_len = 0
def apply(arr, op):
# print("applying", op, "to", arr)
new_arr = []
offset = 0
for dist in op:
new_arr = (arr[offset: offset + dist]) + new_arr
offset += dist
return new_arr
for i in range(1, n):
idx = arr.index(i)
if left:
# operations.append([idx] + [n - idx])
# operations.append([1] * sorted_len + [idx - sorted_len] + [n - idx])
operations.append([idx] + [n - idx - sorted_len] + [1] * sorted_len)
else:
sorted_start = n - sorted_len
# operations.append([1] * sorted_len + [n - sorted_len])
operations.append([1] * sorted_len + [idx - sorted_len + 1] + [n - idx - 1])
# operations.append([idx + 1] + [n - idx - sorted_len] + [1] * sorted_len)
# operations.append([idx] + [n - idx])
sorted_len += 1
# print("left=", left)
arr = apply(arr, operations[-1])
# print(arr)
if sorted(arr) == arr:
break
left = not left
assert sorted(orig_arr) == arr
new_ops = []
for op in operations:
op = [v for v in op if v]
if len(op) > 1:
new_ops.append(op)
print(len(new_ops))
for op in new_ops:
# output = [len(op)] + op
assert sum(op) == n
print(len(op), end=" ")
print(*op)
``` | output | 1 | 45,572 | 12 | 91,145 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a deck of n cards numbered from 1 to n (not necessarily in this order in the deck). You have to sort the deck by repeating the following operation.
* Choose 2 ≤ k ≤ n and split the deck in k nonempty contiguous parts D_1, D_2,..., D_k (D_1 contains the first |D_1| cards of the deck, D_2 contains the following |D_2| cards and so on). Then reverse the order of the parts, transforming the deck into D_k, D_{k-1}, ..., D_2, D_1 (so, the first |D_k| cards of the new deck are D_k, the following |D_{k-1}| cards are D_{k-1} and so on). The internal order of each packet of cards D_i is unchanged by the operation.
You have to obtain a sorted deck (i.e., a deck where the first card is 1, the second is 2 and so on) performing at most n operations. It can be proven that it is always possible to sort the deck performing at most n operations.
Examples of operation: The following are three examples of valid operations (on three decks with different sizes).
* If the deck is [3 6 2 1 4 5 7] (so 3 is the first card and 7 is the last card), we may apply the operation with k=4 and D_1=[3 6], D_2=[2 1 4], D_3=[5], D_4=[7]. Doing so, the deck becomes [7 5 2 1 4 3 6].
* If the deck is [3 1 2], we may apply the operation with k=3 and D_1=[3], D_2=[1], D_3=[2]. Doing so, the deck becomes [2 1 3].
* If the deck is [5 1 2 4 3 6], we may apply the operation with k=2 and D_1=[5 1], D_2=[2 4 3 6]. Doing so, the deck becomes [2 4 3 6 5 1].
Input
The first line of the input contains one integer n (1≤ n≤ 52) — the number of cards in the deck.
The second line contains n integers c_1, c_2, ..., c_n — the cards in the deck. The first card is c_1, the second is c_2 and so on.
It is guaranteed that for all i=1,...,n there is exactly one j∈\{1,...,n\} such that c_j = i.
Output
On the first line, print the number q of operations you perform (it must hold 0≤ q≤ n).
Then, print q lines, each describing one operation.
To describe an operation, print on a single line the number k of parts you are going to split the deck in, followed by the size of the k parts: |D_1|, |D_2|, ... , |D_k|.
It must hold 2≤ k≤ n, and |D_i|≥ 1 for all i=1,...,k, and |D_1|+|D_2|+⋅⋅⋅ + |D_k| = n.
It can be proven that it is always possible to sort the deck performing at most n operations. If there are several ways to sort the deck you can output any of them.
Examples
Input
4
3 1 2 4
Output
2
3 1 2 1
2 1 3
Input
6
6 5 4 3 2 1
Output
1
6 1 1 1 1 1 1
Input
1
1
Output
0
Note
Explanation of the first testcase: Initially the deck is [3 1 2 4].
* The first operation splits the deck as [(3) (1 2) (4)] and then transforms it into [4 1 2 3].
* The second operation splits the deck as [(4) (1 2 3)] and then transforms it into [1 2 3 4].
Explanation of the second testcase: Initially the deck is [6 5 4 3 2 1].
* The first (and only) operation splits the deck as [(6) (5) (4) (3) (2) (1)] and then transforms it into [1 2 3 4 5 6]. | instruction | 0 | 45,573 | 12 | 91,146 |
Tags: constructive algorithms, implementation
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
res = []
for _ in range(n):
li = []
flag = False
for i in range(n):
if flag:
break
for j in range(i + 1, n):
if a[i] - 1 == a[j]:
cnt1 = 1
for k in range(i, j):
if a[k] + 1 == a[k + 1]:
cnt1 += 1
else:
break
if i > 0:
li.append(i)
li.append(cnt1)
li.append(j - i + 1 - cnt1)
if n - (j + 1) > 0:
li.append(n - (j + 1))
flag = True
break
if not li:
break
else:
res.append(li)
l, r = n, n
ind = 0
b = [0] * n
for val in li[::-1]:
l = l - val
for i in range(l, r):
b[ind] = a[i]
ind += 1
r = l
a = b[:]
print(len(res))
for r in res:
print(len(r), *r)
``` | output | 1 | 45,573 | 12 | 91,147 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a deck of n cards numbered from 1 to n (not necessarily in this order in the deck). You have to sort the deck by repeating the following operation.
* Choose 2 ≤ k ≤ n and split the deck in k nonempty contiguous parts D_1, D_2,..., D_k (D_1 contains the first |D_1| cards of the deck, D_2 contains the following |D_2| cards and so on). Then reverse the order of the parts, transforming the deck into D_k, D_{k-1}, ..., D_2, D_1 (so, the first |D_k| cards of the new deck are D_k, the following |D_{k-1}| cards are D_{k-1} and so on). The internal order of each packet of cards D_i is unchanged by the operation.
You have to obtain a sorted deck (i.e., a deck where the first card is 1, the second is 2 and so on) performing at most n operations. It can be proven that it is always possible to sort the deck performing at most n operations.
Examples of operation: The following are three examples of valid operations (on three decks with different sizes).
* If the deck is [3 6 2 1 4 5 7] (so 3 is the first card and 7 is the last card), we may apply the operation with k=4 and D_1=[3 6], D_2=[2 1 4], D_3=[5], D_4=[7]. Doing so, the deck becomes [7 5 2 1 4 3 6].
* If the deck is [3 1 2], we may apply the operation with k=3 and D_1=[3], D_2=[1], D_3=[2]. Doing so, the deck becomes [2 1 3].
* If the deck is [5 1 2 4 3 6], we may apply the operation with k=2 and D_1=[5 1], D_2=[2 4 3 6]. Doing so, the deck becomes [2 4 3 6 5 1].
Input
The first line of the input contains one integer n (1≤ n≤ 52) — the number of cards in the deck.
The second line contains n integers c_1, c_2, ..., c_n — the cards in the deck. The first card is c_1, the second is c_2 and so on.
It is guaranteed that for all i=1,...,n there is exactly one j∈\{1,...,n\} such that c_j = i.
Output
On the first line, print the number q of operations you perform (it must hold 0≤ q≤ n).
Then, print q lines, each describing one operation.
To describe an operation, print on a single line the number k of parts you are going to split the deck in, followed by the size of the k parts: |D_1|, |D_2|, ... , |D_k|.
It must hold 2≤ k≤ n, and |D_i|≥ 1 for all i=1,...,k, and |D_1|+|D_2|+⋅⋅⋅ + |D_k| = n.
It can be proven that it is always possible to sort the deck performing at most n operations. If there are several ways to sort the deck you can output any of them.
Examples
Input
4
3 1 2 4
Output
2
3 1 2 1
2 1 3
Input
6
6 5 4 3 2 1
Output
1
6 1 1 1 1 1 1
Input
1
1
Output
0
Note
Explanation of the first testcase: Initially the deck is [3 1 2 4].
* The first operation splits the deck as [(3) (1 2) (4)] and then transforms it into [4 1 2 3].
* The second operation splits the deck as [(4) (1 2 3)] and then transforms it into [1 2 3 4].
Explanation of the second testcase: Initially the deck is [6 5 4 3 2 1].
* The first (and only) operation splits the deck as [(6) (5) (4) (3) (2) (1)] and then transforms it into [1 2 3 4 5 6]. | instruction | 0 | 45,574 | 12 | 91,148 |
Tags: constructive algorithms, implementation
Correct Solution:
```
def ope(li, ti):
ans = []
if ti % 2 == 0:
tmp = []
for a in range(len(li) - 1):
tmp.append(li[a])
if li[a] > li[a + 1]:
ans.append(tmp)
tmp = []
tmp.append(li[a + 1])
ans.append(tmp)
else:
tmp = []
for a in range(len(li) - 1):
tmp.append(li[a])
if li[a] < li[a + 1]:
ans.append(tmp)
tmp = []
tmp.append(li[a + 1])
ans.append(tmp)
ans = ans[::-1]
fans = []
q = len(ans)
leng = []
for a in ans:
leng.append(len(a))
fans += a
return fans, leng[::-1], q
n = int(input())
dec = list(map(int, input().split()))
ans = sorted(dec)
tu = 0
if dec == ans:
print(0)
exit()
fans = []
while dec != ans:
dec, leng, q = ope(dec, tu)
fans.append([q] + leng)
tu += 1
print(tu)
for a in range(tu):
print(*fans[a])
``` | output | 1 | 45,574 | 12 | 91,149 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a deck of n cards numbered from 1 to n (not necessarily in this order in the deck). You have to sort the deck by repeating the following operation.
* Choose 2 ≤ k ≤ n and split the deck in k nonempty contiguous parts D_1, D_2,..., D_k (D_1 contains the first |D_1| cards of the deck, D_2 contains the following |D_2| cards and so on). Then reverse the order of the parts, transforming the deck into D_k, D_{k-1}, ..., D_2, D_1 (so, the first |D_k| cards of the new deck are D_k, the following |D_{k-1}| cards are D_{k-1} and so on). The internal order of each packet of cards D_i is unchanged by the operation.
You have to obtain a sorted deck (i.e., a deck where the first card is 1, the second is 2 and so on) performing at most n operations. It can be proven that it is always possible to sort the deck performing at most n operations.
Examples of operation: The following are three examples of valid operations (on three decks with different sizes).
* If the deck is [3 6 2 1 4 5 7] (so 3 is the first card and 7 is the last card), we may apply the operation with k=4 and D_1=[3 6], D_2=[2 1 4], D_3=[5], D_4=[7]. Doing so, the deck becomes [7 5 2 1 4 3 6].
* If the deck is [3 1 2], we may apply the operation with k=3 and D_1=[3], D_2=[1], D_3=[2]. Doing so, the deck becomes [2 1 3].
* If the deck is [5 1 2 4 3 6], we may apply the operation with k=2 and D_1=[5 1], D_2=[2 4 3 6]. Doing so, the deck becomes [2 4 3 6 5 1].
Input
The first line of the input contains one integer n (1≤ n≤ 52) — the number of cards in the deck.
The second line contains n integers c_1, c_2, ..., c_n — the cards in the deck. The first card is c_1, the second is c_2 and so on.
It is guaranteed that for all i=1,...,n there is exactly one j∈\{1,...,n\} such that c_j = i.
Output
On the first line, print the number q of operations you perform (it must hold 0≤ q≤ n).
Then, print q lines, each describing one operation.
To describe an operation, print on a single line the number k of parts you are going to split the deck in, followed by the size of the k parts: |D_1|, |D_2|, ... , |D_k|.
It must hold 2≤ k≤ n, and |D_i|≥ 1 for all i=1,...,k, and |D_1|+|D_2|+⋅⋅⋅ + |D_k| = n.
It can be proven that it is always possible to sort the deck performing at most n operations. If there are several ways to sort the deck you can output any of them.
Examples
Input
4
3 1 2 4
Output
2
3 1 2 1
2 1 3
Input
6
6 5 4 3 2 1
Output
1
6 1 1 1 1 1 1
Input
1
1
Output
0
Note
Explanation of the first testcase: Initially the deck is [3 1 2 4].
* The first operation splits the deck as [(3) (1 2) (4)] and then transforms it into [4 1 2 3].
* The second operation splits the deck as [(4) (1 2 3)] and then transforms it into [1 2 3 4].
Explanation of the second testcase: Initially the deck is [6 5 4 3 2 1].
* The first (and only) operation splits the deck as [(6) (5) (4) (3) (2) (1)] and then transforms it into [1 2 3 4 5 6]. | instruction | 0 | 45,575 | 12 | 91,150 |
Tags: constructive algorithms, implementation
Correct Solution:
```
n = int(input())
c = list(map(int, input().split()))
ans = []
while True:
seen = [False]*60
for i in range(n):
if seen[c[i]+1]:
break
seen[c[i]] = True
else:
break
if i+1<n:
sep = [i+1]
else:
sep = []
flg = True
for j in range(i-1, -1, -1):
if c[j]+1!=c[j+1] and flg:
sep.append(j+1)
flg = False
if c[j]==c[i]+1:
if j>0:
sep.append(j)
break
sep += [0, n]
sep.sort()
tmp = []
nc = []
for i in range(len(sep)-1):
tmp.append(sep[i+1]-sep[i])
for i in range(len(sep)-2, -1, -1):
nc += c[sep[i]:sep[i+1]]
ans.append(tmp)
c = nc
print(len(ans))
for i in ans:
i = [len(i)] + i
print(*i)
``` | output | 1 | 45,575 | 12 | 91,151 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a deck of n cards numbered from 1 to n (not necessarily in this order in the deck). You have to sort the deck by repeating the following operation.
* Choose 2 ≤ k ≤ n and split the deck in k nonempty contiguous parts D_1, D_2,..., D_k (D_1 contains the first |D_1| cards of the deck, D_2 contains the following |D_2| cards and so on). Then reverse the order of the parts, transforming the deck into D_k, D_{k-1}, ..., D_2, D_1 (so, the first |D_k| cards of the new deck are D_k, the following |D_{k-1}| cards are D_{k-1} and so on). The internal order of each packet of cards D_i is unchanged by the operation.
You have to obtain a sorted deck (i.e., a deck where the first card is 1, the second is 2 and so on) performing at most n operations. It can be proven that it is always possible to sort the deck performing at most n operations.
Examples of operation: The following are three examples of valid operations (on three decks with different sizes).
* If the deck is [3 6 2 1 4 5 7] (so 3 is the first card and 7 is the last card), we may apply the operation with k=4 and D_1=[3 6], D_2=[2 1 4], D_3=[5], D_4=[7]. Doing so, the deck becomes [7 5 2 1 4 3 6].
* If the deck is [3 1 2], we may apply the operation with k=3 and D_1=[3], D_2=[1], D_3=[2]. Doing so, the deck becomes [2 1 3].
* If the deck is [5 1 2 4 3 6], we may apply the operation with k=2 and D_1=[5 1], D_2=[2 4 3 6]. Doing so, the deck becomes [2 4 3 6 5 1].
Input
The first line of the input contains one integer n (1≤ n≤ 52) — the number of cards in the deck.
The second line contains n integers c_1, c_2, ..., c_n — the cards in the deck. The first card is c_1, the second is c_2 and so on.
It is guaranteed that for all i=1,...,n there is exactly one j∈\{1,...,n\} such that c_j = i.
Output
On the first line, print the number q of operations you perform (it must hold 0≤ q≤ n).
Then, print q lines, each describing one operation.
To describe an operation, print on a single line the number k of parts you are going to split the deck in, followed by the size of the k parts: |D_1|, |D_2|, ... , |D_k|.
It must hold 2≤ k≤ n, and |D_i|≥ 1 for all i=1,...,k, and |D_1|+|D_2|+⋅⋅⋅ + |D_k| = n.
It can be proven that it is always possible to sort the deck performing at most n operations. If there are several ways to sort the deck you can output any of them.
Examples
Input
4
3 1 2 4
Output
2
3 1 2 1
2 1 3
Input
6
6 5 4 3 2 1
Output
1
6 1 1 1 1 1 1
Input
1
1
Output
0
Note
Explanation of the first testcase: Initially the deck is [3 1 2 4].
* The first operation splits the deck as [(3) (1 2) (4)] and then transforms it into [4 1 2 3].
* The second operation splits the deck as [(4) (1 2 3)] and then transforms it into [1 2 3 4].
Explanation of the second testcase: Initially the deck is [6 5 4 3 2 1].
* The first (and only) operation splits the deck as [(6) (5) (4) (3) (2) (1)] and then transforms it into [1 2 3 4 5 6]. | instruction | 0 | 45,576 | 12 | 91,152 |
Tags: constructive algorithms, implementation
Correct Solution:
```
n = int(input())
c = [int(i) for i in input().split(" ")]
ans = []
left = 0
right = 0
m = (n+1)//2+1
target = m-1
# print(c)
for t in range(n):
now0 = []
if n % 2 == 0:
if t % 2 == 0:
target = m + t//2
else:
target = 1 + t//2
else:
if t % 2 == 0:
target = 1 + t//2
else:
target = m + t//2
if right == 0:
loc = c[left:].index(target)
else:
loc = c[left:-right].index(target)
now0.append(left)
now0.append(loc)
now0.append(n-left-right-loc)
now0.append(right)
now = []
for i in now0:
if i > 0:
now.append(i)
if t % 2 == 0:
left += 1
else:
right += 1
if len(now) > 1:
ans.append([len(now)] + now)
segs = []
cur = 0
for i in now:
segs.append(c[cur:cur+i])
cur += i
c2 = []
for i in reversed(segs):
c2 = c2 + i
for i in range(n):
c[i] = c2[i]
# print(c)
# if n % 2 == 0:
# ans.append([2, n//2, n//2])
print(len(ans))
for i in ans:
print(" ".join([str(j) for j in i]))
``` | output | 1 | 45,576 | 12 | 91,153 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a deck of n cards numbered from 1 to n (not necessarily in this order in the deck). You have to sort the deck by repeating the following operation.
* Choose 2 ≤ k ≤ n and split the deck in k nonempty contiguous parts D_1, D_2,..., D_k (D_1 contains the first |D_1| cards of the deck, D_2 contains the following |D_2| cards and so on). Then reverse the order of the parts, transforming the deck into D_k, D_{k-1}, ..., D_2, D_1 (so, the first |D_k| cards of the new deck are D_k, the following |D_{k-1}| cards are D_{k-1} and so on). The internal order of each packet of cards D_i is unchanged by the operation.
You have to obtain a sorted deck (i.e., a deck where the first card is 1, the second is 2 and so on) performing at most n operations. It can be proven that it is always possible to sort the deck performing at most n operations.
Examples of operation: The following are three examples of valid operations (on three decks with different sizes).
* If the deck is [3 6 2 1 4 5 7] (so 3 is the first card and 7 is the last card), we may apply the operation with k=4 and D_1=[3 6], D_2=[2 1 4], D_3=[5], D_4=[7]. Doing so, the deck becomes [7 5 2 1 4 3 6].
* If the deck is [3 1 2], we may apply the operation with k=3 and D_1=[3], D_2=[1], D_3=[2]. Doing so, the deck becomes [2 1 3].
* If the deck is [5 1 2 4 3 6], we may apply the operation with k=2 and D_1=[5 1], D_2=[2 4 3 6]. Doing so, the deck becomes [2 4 3 6 5 1].
Input
The first line of the input contains one integer n (1≤ n≤ 52) — the number of cards in the deck.
The second line contains n integers c_1, c_2, ..., c_n — the cards in the deck. The first card is c_1, the second is c_2 and so on.
It is guaranteed that for all i=1,...,n there is exactly one j∈\{1,...,n\} such that c_j = i.
Output
On the first line, print the number q of operations you perform (it must hold 0≤ q≤ n).
Then, print q lines, each describing one operation.
To describe an operation, print on a single line the number k of parts you are going to split the deck in, followed by the size of the k parts: |D_1|, |D_2|, ... , |D_k|.
It must hold 2≤ k≤ n, and |D_i|≥ 1 for all i=1,...,k, and |D_1|+|D_2|+⋅⋅⋅ + |D_k| = n.
It can be proven that it is always possible to sort the deck performing at most n operations. If there are several ways to sort the deck you can output any of them.
Examples
Input
4
3 1 2 4
Output
2
3 1 2 1
2 1 3
Input
6
6 5 4 3 2 1
Output
1
6 1 1 1 1 1 1
Input
1
1
Output
0
Note
Explanation of the first testcase: Initially the deck is [3 1 2 4].
* The first operation splits the deck as [(3) (1 2) (4)] and then transforms it into [4 1 2 3].
* The second operation splits the deck as [(4) (1 2 3)] and then transforms it into [1 2 3 4].
Explanation of the second testcase: Initially the deck is [6 5 4 3 2 1].
* The first (and only) operation splits the deck as [(6) (5) (4) (3) (2) (1)] and then transforms it into [1 2 3 4 5 6]. | instruction | 0 | 45,577 | 12 | 91,154 |
Tags: constructive algorithms, implementation
Correct Solution:
```
import io
import os
from collections import Counter, defaultdict, deque
def solve(N, C):
target = list(range(1, N + 1))
ops = []
while C != target:
for i in range(1, N):
j = i + 1
ii = C.index(i)
jj = C.index(j)
if ii + 1 == jj:
continue
if jj < ii:
k = 1
while jj + k < N and C[jj + k - 1] + 1 == C[jj + k]:
k += 1
groups = [C[:jj], C[jj : jj + k], C[jj + k : ii + 1], C[ii + 1 :]]
ops.append([len(group) for group in groups if group])
C = []
for group in reversed(groups):
C.extend(group)
# print("ops", ops[-1])
# print(C, "fixed", i, j)
# print(len(ops))
assert len(ops) <= N
return (
str(len(ops))
+ "\n"
+ "\n".join(str(len(op)) + " " + " ".join(map(str, op)) for op in ops)
)
DEBUG = False
if DEBUG:
import random
random.seed(0)
for _ in range(100):
N = random.randint(1, 52)
C = list(range(1, N + 1))
random.shuffle(C)
print("tc", _, N, C)
ans1 = solve(N, C)
# print(ans1)
exit()
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
(N,) = [int(x) for x in input().split()]
C = [int(x) for x in input().split()]
ans = solve(N, C)
print(ans)
``` | output | 1 | 45,577 | 12 | 91,155 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a deck of n cards numbered from 1 to n (not necessarily in this order in the deck). You have to sort the deck by repeating the following operation.
* Choose 2 ≤ k ≤ n and split the deck in k nonempty contiguous parts D_1, D_2,..., D_k (D_1 contains the first |D_1| cards of the deck, D_2 contains the following |D_2| cards and so on). Then reverse the order of the parts, transforming the deck into D_k, D_{k-1}, ..., D_2, D_1 (so, the first |D_k| cards of the new deck are D_k, the following |D_{k-1}| cards are D_{k-1} and so on). The internal order of each packet of cards D_i is unchanged by the operation.
You have to obtain a sorted deck (i.e., a deck where the first card is 1, the second is 2 and so on) performing at most n operations. It can be proven that it is always possible to sort the deck performing at most n operations.
Examples of operation: The following are three examples of valid operations (on three decks with different sizes).
* If the deck is [3 6 2 1 4 5 7] (so 3 is the first card and 7 is the last card), we may apply the operation with k=4 and D_1=[3 6], D_2=[2 1 4], D_3=[5], D_4=[7]. Doing so, the deck becomes [7 5 2 1 4 3 6].
* If the deck is [3 1 2], we may apply the operation with k=3 and D_1=[3], D_2=[1], D_3=[2]. Doing so, the deck becomes [2 1 3].
* If the deck is [5 1 2 4 3 6], we may apply the operation with k=2 and D_1=[5 1], D_2=[2 4 3 6]. Doing so, the deck becomes [2 4 3 6 5 1].
Input
The first line of the input contains one integer n (1≤ n≤ 52) — the number of cards in the deck.
The second line contains n integers c_1, c_2, ..., c_n — the cards in the deck. The first card is c_1, the second is c_2 and so on.
It is guaranteed that for all i=1,...,n there is exactly one j∈\{1,...,n\} such that c_j = i.
Output
On the first line, print the number q of operations you perform (it must hold 0≤ q≤ n).
Then, print q lines, each describing one operation.
To describe an operation, print on a single line the number k of parts you are going to split the deck in, followed by the size of the k parts: |D_1|, |D_2|, ... , |D_k|.
It must hold 2≤ k≤ n, and |D_i|≥ 1 for all i=1,...,k, and |D_1|+|D_2|+⋅⋅⋅ + |D_k| = n.
It can be proven that it is always possible to sort the deck performing at most n operations. If there are several ways to sort the deck you can output any of them.
Examples
Input
4
3 1 2 4
Output
2
3 1 2 1
2 1 3
Input
6
6 5 4 3 2 1
Output
1
6 1 1 1 1 1 1
Input
1
1
Output
0
Note
Explanation of the first testcase: Initially the deck is [3 1 2 4].
* The first operation splits the deck as [(3) (1 2) (4)] and then transforms it into [4 1 2 3].
* The second operation splits the deck as [(4) (1 2 3)] and then transforms it into [1 2 3 4].
Explanation of the second testcase: Initially the deck is [6 5 4 3 2 1].
* The first (and only) operation splits the deck as [(6) (5) (4) (3) (2) (1)] and then transforms it into [1 2 3 4 5 6]. | instruction | 0 | 45,578 | 12 | 91,156 |
Tags: constructive algorithms, implementation
Correct Solution:
```
n = int(input())
c = [int(x) for x in input().split()]
solved = c.copy()
solved.sort()
ans = []
for i in range(1, n):
for j in range(1, n):
a = c.index(j)
b = c.index(j+1)
z = b+1
if b > a:
if a+1 == b and a == solved:
break
continue
z = b+1
s1 = c[:b]
while z < a and c[z] == c[z-1]+1:
z += 1
s2 = c[b:z]
s3 = c[z:a+1]
s4 = c[a+1:]
c = s4 + s3 + s2 + s1
ans.append([str(len(x)) for x in [s1, s2, s3, s4] if x])
print(len(ans))
for an in ans:
print(len(an), ' '.join(an))
``` | output | 1 | 45,578 | 12 | 91,157 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On the competitive programming platform CodeCook, every person has a rating graph described by an array of integers a of length n. You are now updating the infrastructure, so you've created a program to compress these graphs.
The program works as follows. Given an integer parameter k, the program takes the minimum of each contiguous subarray of length k in a.
More formally, for an array a of length n and an integer k, define the k-compression array of a as an array b of length n-k+1, such that $$$b_j =min_{j≤ i≤ j+k-1}a_i$$$
For example, the 3-compression array of [1, 3, 4, 5, 2] is [min\{1, 3, 4\}, min\{3, 4, 5\}, min\{4, 5, 2\}]=[1, 3, 2].
A permutation of length m is an array consisting of m distinct integers from 1 to m in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (m=3 but there is 4 in the array).
A k-compression array will make CodeCook users happy if it will be a permutation. Given an array a, determine for all 1≤ k≤ n if CodeCook users will be happy after a k-compression of this array or not.
Input
The first line contains a single integer t (1≤ t≤ 10^4) — the number of test cases.
The first line of the description of each test case contains a single integer n (1≤ n≤ 3⋅ 10^5) — the length of the array.
The second line of the description of each test case contains n integers a_1,…,a_n (1≤ a_i≤ n) — the elements of the array.
It is guaranteed, that the sum of n for all test cases does not exceed 3⋅ 10^5.
Output
For each test case, print a binary string of length n.
The k-th character of the string should be 1 if CodeCook users will be happy after a k-compression of the array a, and 0 otherwise.
Example
Input
5
5
1 5 3 4 2
4
1 3 2 1
5
1 3 3 3 2
10
1 2 3 4 5 6 7 8 9 10
3
3 3 2
Output
10111
0001
00111
1111111111
000
Note
In the first test case, a=[1, 5, 3, 4, 2].
* The 1-compression of a is [1, 5, 3, 4, 2] and it is a permutation.
* The 2-compression of a is [1, 3, 3, 2] and it is not a permutation, since 3 appears twice.
* The 3-compression of a is [1, 3, 2] and it is a permutation.
* The 4-compression of a is [1, 2] and it is a permutation.
* The 5-compression of a is [1] and it is a permutation. | instruction | 0 | 45,587 | 12 | 91,174 |
Tags: binary search, data structures, greedy, implementation, two pointers
Correct Solution:
```
for _ in range(int(input())):
n = int(input())
arr = list(map(int, input().split()))
s = ["0" for i in range(n)]
c = [0]*n
for i in range(n):
c[arr[i]-1] += 1
if c[0]>0: s[-1] = "1"
i = 0
j = n-1
p = 1
s[0] = "1" if len(set(arr))==n else "0"
while p < n:
if (arr[i] == p or arr[j] == p) and c[p-1] == 1 and c[p] >= 1:
if arr[i] == p:
i+=1
s[n-1-p] = "1"
elif arr[j] == p:
j -= 1
s[n-1-p] = "1"
p += 1
continue
break
print("".join(s))
``` | output | 1 | 45,587 | 12 | 91,175 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On the competitive programming platform CodeCook, every person has a rating graph described by an array of integers a of length n. You are now updating the infrastructure, so you've created a program to compress these graphs.
The program works as follows. Given an integer parameter k, the program takes the minimum of each contiguous subarray of length k in a.
More formally, for an array a of length n and an integer k, define the k-compression array of a as an array b of length n-k+1, such that $$$b_j =min_{j≤ i≤ j+k-1}a_i$$$
For example, the 3-compression array of [1, 3, 4, 5, 2] is [min\{1, 3, 4\}, min\{3, 4, 5\}, min\{4, 5, 2\}]=[1, 3, 2].
A permutation of length m is an array consisting of m distinct integers from 1 to m in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (m=3 but there is 4 in the array).
A k-compression array will make CodeCook users happy if it will be a permutation. Given an array a, determine for all 1≤ k≤ n if CodeCook users will be happy after a k-compression of this array or not.
Input
The first line contains a single integer t (1≤ t≤ 10^4) — the number of test cases.
The first line of the description of each test case contains a single integer n (1≤ n≤ 3⋅ 10^5) — the length of the array.
The second line of the description of each test case contains n integers a_1,…,a_n (1≤ a_i≤ n) — the elements of the array.
It is guaranteed, that the sum of n for all test cases does not exceed 3⋅ 10^5.
Output
For each test case, print a binary string of length n.
The k-th character of the string should be 1 if CodeCook users will be happy after a k-compression of the array a, and 0 otherwise.
Example
Input
5
5
1 5 3 4 2
4
1 3 2 1
5
1 3 3 3 2
10
1 2 3 4 5 6 7 8 9 10
3
3 3 2
Output
10111
0001
00111
1111111111
000
Note
In the first test case, a=[1, 5, 3, 4, 2].
* The 1-compression of a is [1, 5, 3, 4, 2] and it is a permutation.
* The 2-compression of a is [1, 3, 3, 2] and it is not a permutation, since 3 appears twice.
* The 3-compression of a is [1, 3, 2] and it is a permutation.
* The 4-compression of a is [1, 2] and it is a permutation.
* The 5-compression of a is [1] and it is a permutation. | instruction | 0 | 45,588 | 12 | 91,176 |
Tags: binary search, data structures, greedy, implementation, two pointers
Correct Solution:
```
import sys
from collections import deque, Counter
readline = sys.stdin.readline
T = int(readline())
Ans = [None]*T
for qu in range(T):
N = int(readline())
A = list(map(int, readline().split()))
CA = Counter(A)
a1 = A.count(1)
if not a1:
Ans[qu] = ''.join(['0']*N)
continue
if a1 >= 2:
Ans[qu] = ''.join(['0']*(N-1) + ['1'])
continue
ans = [0]*N
if len(set(A)) == N:
ans[0] = 1
A = deque(A)
res = 1
cnt = 0
flag = 1
while A:
if A[-1] == res:
A.pop()
elif A[0] == res:
A.popleft()
else:
break
cnt += 1
if CA[res] > 1:
flag = 0
break
res += 1
if flag and res in A:
cnt += 1
for i in range(cnt):
idx = N-1-i
ans[idx] = 1
Ans[qu] = ''.join(map(str, ans))
print('\n'.join(Ans))
``` | output | 1 | 45,588 | 12 | 91,177 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On the competitive programming platform CodeCook, every person has a rating graph described by an array of integers a of length n. You are now updating the infrastructure, so you've created a program to compress these graphs.
The program works as follows. Given an integer parameter k, the program takes the minimum of each contiguous subarray of length k in a.
More formally, for an array a of length n and an integer k, define the k-compression array of a as an array b of length n-k+1, such that $$$b_j =min_{j≤ i≤ j+k-1}a_i$$$
For example, the 3-compression array of [1, 3, 4, 5, 2] is [min\{1, 3, 4\}, min\{3, 4, 5\}, min\{4, 5, 2\}]=[1, 3, 2].
A permutation of length m is an array consisting of m distinct integers from 1 to m in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (m=3 but there is 4 in the array).
A k-compression array will make CodeCook users happy if it will be a permutation. Given an array a, determine for all 1≤ k≤ n if CodeCook users will be happy after a k-compression of this array or not.
Input
The first line contains a single integer t (1≤ t≤ 10^4) — the number of test cases.
The first line of the description of each test case contains a single integer n (1≤ n≤ 3⋅ 10^5) — the length of the array.
The second line of the description of each test case contains n integers a_1,…,a_n (1≤ a_i≤ n) — the elements of the array.
It is guaranteed, that the sum of n for all test cases does not exceed 3⋅ 10^5.
Output
For each test case, print a binary string of length n.
The k-th character of the string should be 1 if CodeCook users will be happy after a k-compression of the array a, and 0 otherwise.
Example
Input
5
5
1 5 3 4 2
4
1 3 2 1
5
1 3 3 3 2
10
1 2 3 4 5 6 7 8 9 10
3
3 3 2
Output
10111
0001
00111
1111111111
000
Note
In the first test case, a=[1, 5, 3, 4, 2].
* The 1-compression of a is [1, 5, 3, 4, 2] and it is a permutation.
* The 2-compression of a is [1, 3, 3, 2] and it is not a permutation, since 3 appears twice.
* The 3-compression of a is [1, 3, 2] and it is a permutation.
* The 4-compression of a is [1, 2] and it is a permutation.
* The 5-compression of a is [1] and it is a permutation. | instruction | 0 | 45,589 | 12 | 91,178 |
Tags: binary search, data structures, greedy, implementation, two pointers
Correct Solution:
```
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError('{0!r} not in list'.format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return 'SortedList({0})'.format(list(self))
import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int, input().split()))
b = [(a[i], i) for i in range(n)]
b.sort()
sl = SortedList()
mem = [0] * n
for v, i in b:
ind = sl.bisect_left(i)
if ind > 0:
lo = sl[ind - 1] + 1
else:
lo = 0
if ind < len(sl):
hi = sl[ind] - 1
else:
hi = n - 1
mem[v - 1] = max(mem[v - 1], hi - lo + 1)
sl.add(i)
out = []
small = n + 12
for i in range(n):
small = min(small, mem[i])
if small < n - i:
out.append('0')
else:
out.append('1')
print(''.join(out)[::-1])
``` | output | 1 | 45,589 | 12 | 91,179 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On the competitive programming platform CodeCook, every person has a rating graph described by an array of integers a of length n. You are now updating the infrastructure, so you've created a program to compress these graphs.
The program works as follows. Given an integer parameter k, the program takes the minimum of each contiguous subarray of length k in a.
More formally, for an array a of length n and an integer k, define the k-compression array of a as an array b of length n-k+1, such that $$$b_j =min_{j≤ i≤ j+k-1}a_i$$$
For example, the 3-compression array of [1, 3, 4, 5, 2] is [min\{1, 3, 4\}, min\{3, 4, 5\}, min\{4, 5, 2\}]=[1, 3, 2].
A permutation of length m is an array consisting of m distinct integers from 1 to m in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (m=3 but there is 4 in the array).
A k-compression array will make CodeCook users happy if it will be a permutation. Given an array a, determine for all 1≤ k≤ n if CodeCook users will be happy after a k-compression of this array or not.
Input
The first line contains a single integer t (1≤ t≤ 10^4) — the number of test cases.
The first line of the description of each test case contains a single integer n (1≤ n≤ 3⋅ 10^5) — the length of the array.
The second line of the description of each test case contains n integers a_1,…,a_n (1≤ a_i≤ n) — the elements of the array.
It is guaranteed, that the sum of n for all test cases does not exceed 3⋅ 10^5.
Output
For each test case, print a binary string of length n.
The k-th character of the string should be 1 if CodeCook users will be happy after a k-compression of the array a, and 0 otherwise.
Example
Input
5
5
1 5 3 4 2
4
1 3 2 1
5
1 3 3 3 2
10
1 2 3 4 5 6 7 8 9 10
3
3 3 2
Output
10111
0001
00111
1111111111
000
Note
In the first test case, a=[1, 5, 3, 4, 2].
* The 1-compression of a is [1, 5, 3, 4, 2] and it is a permutation.
* The 2-compression of a is [1, 3, 3, 2] and it is not a permutation, since 3 appears twice.
* The 3-compression of a is [1, 3, 2] and it is a permutation.
* The 4-compression of a is [1, 2] and it is a permutation.
* The 5-compression of a is [1] and it is a permutation. | instruction | 0 | 45,590 | 12 | 91,180 |
Tags: binary search, data structures, greedy, implementation, two pointers
Correct Solution:
```
import sys
input=sys.stdin.readline
t=int(input())
for you in range(t):
n=int(input())
l=input().split()
li=[int(i) for i in l]
curr=1
start=0
end=n-1
while(start<=end):
if(li[start]==curr):
start+=1
curr+=1
elif(li[end]==curr):
end-=1
curr+=1
else:
break
ok=[0 for i in range(n)]
for i in range(n):
ok[li[i]-1]+=1
poss=1
for i in range(n):
if(ok[i]==0):
poss=0
break
lol=[0 for i in range(n)]
lol[0]=poss
for i in range(n-curr+1,n):
lol[i]=1
done=0
if(end<start):
done=1
else:
z=min(li[start:end+1])
if(z==curr):
done=1
else:
done=0
lol[n-curr]=done
li.sort()
ans=n+1
for i in range(1,n):
if(li[i]==li[i-1]):
ans=li[i]
break
for i in range(n-ans):
lol[i]=0
for i in lol:
print(i,end="")
print()
``` | output | 1 | 45,590 | 12 | 91,181 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On the competitive programming platform CodeCook, every person has a rating graph described by an array of integers a of length n. You are now updating the infrastructure, so you've created a program to compress these graphs.
The program works as follows. Given an integer parameter k, the program takes the minimum of each contiguous subarray of length k in a.
More formally, for an array a of length n and an integer k, define the k-compression array of a as an array b of length n-k+1, such that $$$b_j =min_{j≤ i≤ j+k-1}a_i$$$
For example, the 3-compression array of [1, 3, 4, 5, 2] is [min\{1, 3, 4\}, min\{3, 4, 5\}, min\{4, 5, 2\}]=[1, 3, 2].
A permutation of length m is an array consisting of m distinct integers from 1 to m in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (m=3 but there is 4 in the array).
A k-compression array will make CodeCook users happy if it will be a permutation. Given an array a, determine for all 1≤ k≤ n if CodeCook users will be happy after a k-compression of this array or not.
Input
The first line contains a single integer t (1≤ t≤ 10^4) — the number of test cases.
The first line of the description of each test case contains a single integer n (1≤ n≤ 3⋅ 10^5) — the length of the array.
The second line of the description of each test case contains n integers a_1,…,a_n (1≤ a_i≤ n) — the elements of the array.
It is guaranteed, that the sum of n for all test cases does not exceed 3⋅ 10^5.
Output
For each test case, print a binary string of length n.
The k-th character of the string should be 1 if CodeCook users will be happy after a k-compression of the array a, and 0 otherwise.
Example
Input
5
5
1 5 3 4 2
4
1 3 2 1
5
1 3 3 3 2
10
1 2 3 4 5 6 7 8 9 10
3
3 3 2
Output
10111
0001
00111
1111111111
000
Note
In the first test case, a=[1, 5, 3, 4, 2].
* The 1-compression of a is [1, 5, 3, 4, 2] and it is a permutation.
* The 2-compression of a is [1, 3, 3, 2] and it is not a permutation, since 3 appears twice.
* The 3-compression of a is [1, 3, 2] and it is a permutation.
* The 4-compression of a is [1, 2] and it is a permutation.
* The 5-compression of a is [1] and it is a permutation. | instruction | 0 | 45,591 | 12 | 91,182 |
Tags: binary search, data structures, greedy, implementation, two pointers
Correct Solution:
```
import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
import math
#MIN QUERIES
class RMQMIN(): #for MIN queries
def __init__(self,arr):
self.arr=arr
MAXN=len(arr)
K=int(math.log2(MAXN))+1
self.lookup=[[0 for _ in range(K+1)] for __ in range(MAXN)]
self.buildSparseTable()
def buildSparseTable(self):
n=len(self.arr)
for i in range(0, n):
self.lookup[i][0] = self.arr[i]
j = 1
while (1 << j) <= n:
i = 0
while (i + (1 << j) - 1) < n:
if (self.lookup[i][j-1]<self.lookup[i+(1<<(j-1))][j-1]):self.lookup[i][j]=self.lookup[i][j-1]
else:self.lookup[i][j]=self.lookup[i + (1 << (j - 1))][j - 1]
i += 1
j += 1
def query(self,L,R): #returns min on interval [l,r]
j = int(math.log2(R - L + 1))
if self.lookup[L][j] <= self.lookup[R - (1 << j) + 1][j]:
return self.lookup[L][j]
else:
return self.lookup[R - (1 << j) + 1][j]
#min query usage:
#a = [7, 2, 3, 0, 5,1,3,4,63,2,4,5,6,7,22]
#rmq=RMQMIN(a)
#rmq.query(6,len(a))
t=int(input())
for _ in range(t):
n=int(input())
a=[int(x) for x in input().split()]
ans=[0 for _ in range(n+1)]
#check for k=1
if sorted(a)==list(range(1,n+1)):
ans[1]=1
rmq=RMQMIN(a)
l=0
r=n-1
#for k==n, 1 has to be in the array
#for k==n-1 to make CodeCook people happy, 1 has to be at either end,rmq of the rest is 2
#for k==n-2, 2 has to be at either end, rmq of the rest is 3, and so on...
if rmq.query(l,r)==1:
ans[n]=1
k=n-1
smallest=1
while k>1:
if a[l]==smallest and rmq.query(l+1,r)==smallest+1:
l+=1
smallest+=1
ans[k]=1
k-=1
elif a[r]==smallest and rmq.query(l,r-1)==smallest+1:
r-=1
smallest+=1
ans[k]=1
k-=1
else:
break
ans2=[]
for i in range(1,n+1):
ans2.append(str(ans[i]))
print(''.join(ans2))
``` | output | 1 | 45,591 | 12 | 91,183 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On the competitive programming platform CodeCook, every person has a rating graph described by an array of integers a of length n. You are now updating the infrastructure, so you've created a program to compress these graphs.
The program works as follows. Given an integer parameter k, the program takes the minimum of each contiguous subarray of length k in a.
More formally, for an array a of length n and an integer k, define the k-compression array of a as an array b of length n-k+1, such that $$$b_j =min_{j≤ i≤ j+k-1}a_i$$$
For example, the 3-compression array of [1, 3, 4, 5, 2] is [min\{1, 3, 4\}, min\{3, 4, 5\}, min\{4, 5, 2\}]=[1, 3, 2].
A permutation of length m is an array consisting of m distinct integers from 1 to m in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (m=3 but there is 4 in the array).
A k-compression array will make CodeCook users happy if it will be a permutation. Given an array a, determine for all 1≤ k≤ n if CodeCook users will be happy after a k-compression of this array or not.
Input
The first line contains a single integer t (1≤ t≤ 10^4) — the number of test cases.
The first line of the description of each test case contains a single integer n (1≤ n≤ 3⋅ 10^5) — the length of the array.
The second line of the description of each test case contains n integers a_1,…,a_n (1≤ a_i≤ n) — the elements of the array.
It is guaranteed, that the sum of n for all test cases does not exceed 3⋅ 10^5.
Output
For each test case, print a binary string of length n.
The k-th character of the string should be 1 if CodeCook users will be happy after a k-compression of the array a, and 0 otherwise.
Example
Input
5
5
1 5 3 4 2
4
1 3 2 1
5
1 3 3 3 2
10
1 2 3 4 5 6 7 8 9 10
3
3 3 2
Output
10111
0001
00111
1111111111
000
Note
In the first test case, a=[1, 5, 3, 4, 2].
* The 1-compression of a is [1, 5, 3, 4, 2] and it is a permutation.
* The 2-compression of a is [1, 3, 3, 2] and it is not a permutation, since 3 appears twice.
* The 3-compression of a is [1, 3, 2] and it is a permutation.
* The 4-compression of a is [1, 2] and it is a permutation.
* The 5-compression of a is [1] and it is a permutation. | instruction | 0 | 45,592 | 12 | 91,184 |
Tags: binary search, data structures, greedy, implementation, two pointers
Correct Solution:
```
from math import sqrt
import sys
import os
from io import BytesIO, IOBase
#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")
T = int(input())
for _ in range(T):
n = int(input())
greater_or_eq, found = [0] * (n+1), [False] * (n + 1)
arr = list(map(int, input().split()))
ans = ['0'] * (n+1)
for i, v in enumerate(arr):
found[v] = True
if i and arr[i-1] >= v:
greater_or_eq[v] += 1
if i + 1 < n and arr[i+1] >= v:
greater_or_eq[v] += 1
for i in range(1, n+1):
if not found[i] or not greater_or_eq[i]:
break
ans[i] = '1'
if greater_or_eq[i] > 1:
break
if len(set(arr)) == n:
ans[n] = '1'
ans = ans[1:][::-1]
print(''.join(ans))
``` | output | 1 | 45,592 | 12 | 91,185 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On the competitive programming platform CodeCook, every person has a rating graph described by an array of integers a of length n. You are now updating the infrastructure, so you've created a program to compress these graphs.
The program works as follows. Given an integer parameter k, the program takes the minimum of each contiguous subarray of length k in a.
More formally, for an array a of length n and an integer k, define the k-compression array of a as an array b of length n-k+1, such that $$$b_j =min_{j≤ i≤ j+k-1}a_i$$$
For example, the 3-compression array of [1, 3, 4, 5, 2] is [min\{1, 3, 4\}, min\{3, 4, 5\}, min\{4, 5, 2\}]=[1, 3, 2].
A permutation of length m is an array consisting of m distinct integers from 1 to m in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (m=3 but there is 4 in the array).
A k-compression array will make CodeCook users happy if it will be a permutation. Given an array a, determine for all 1≤ k≤ n if CodeCook users will be happy after a k-compression of this array or not.
Input
The first line contains a single integer t (1≤ t≤ 10^4) — the number of test cases.
The first line of the description of each test case contains a single integer n (1≤ n≤ 3⋅ 10^5) — the length of the array.
The second line of the description of each test case contains n integers a_1,…,a_n (1≤ a_i≤ n) — the elements of the array.
It is guaranteed, that the sum of n for all test cases does not exceed 3⋅ 10^5.
Output
For each test case, print a binary string of length n.
The k-th character of the string should be 1 if CodeCook users will be happy after a k-compression of the array a, and 0 otherwise.
Example
Input
5
5
1 5 3 4 2
4
1 3 2 1
5
1 3 3 3 2
10
1 2 3 4 5 6 7 8 9 10
3
3 3 2
Output
10111
0001
00111
1111111111
000
Note
In the first test case, a=[1, 5, 3, 4, 2].
* The 1-compression of a is [1, 5, 3, 4, 2] and it is a permutation.
* The 2-compression of a is [1, 3, 3, 2] and it is not a permutation, since 3 appears twice.
* The 3-compression of a is [1, 3, 2] and it is a permutation.
* The 4-compression of a is [1, 2] and it is a permutation.
* The 5-compression of a is [1] and it is a permutation. | instruction | 0 | 45,593 | 12 | 91,186 |
Tags: binary search, data structures, greedy, implementation, two pointers
Correct Solution:
```
import sys
input = lambda: sys.stdin.readline().rstrip()
T = int(input())
for _ in range(T):
N = int(input())
A = [int(a) - 1 for a in input().split()]
C = [0] * N
for a in A:
C[a] += 1
l, r = 0, N - 1
for i in range(N):
if C[i] != 1:
break
if A[l] == i:
l += 1
elif A[r] == i:
r -= 1
else:
break
i = min(i, N - 1)
a0 = min(C)
k = min(i + 1, N - 1) if C[i] else i
ans = str(a0) + "0" * (N - k - 1) + "1" * (k)
print(ans)
``` | output | 1 | 45,593 | 12 | 91,187 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On the competitive programming platform CodeCook, every person has a rating graph described by an array of integers a of length n. You are now updating the infrastructure, so you've created a program to compress these graphs.
The program works as follows. Given an integer parameter k, the program takes the minimum of each contiguous subarray of length k in a.
More formally, for an array a of length n and an integer k, define the k-compression array of a as an array b of length n-k+1, such that $$$b_j =min_{j≤ i≤ j+k-1}a_i$$$
For example, the 3-compression array of [1, 3, 4, 5, 2] is [min\{1, 3, 4\}, min\{3, 4, 5\}, min\{4, 5, 2\}]=[1, 3, 2].
A permutation of length m is an array consisting of m distinct integers from 1 to m in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (m=3 but there is 4 in the array).
A k-compression array will make CodeCook users happy if it will be a permutation. Given an array a, determine for all 1≤ k≤ n if CodeCook users will be happy after a k-compression of this array or not.
Input
The first line contains a single integer t (1≤ t≤ 10^4) — the number of test cases.
The first line of the description of each test case contains a single integer n (1≤ n≤ 3⋅ 10^5) — the length of the array.
The second line of the description of each test case contains n integers a_1,…,a_n (1≤ a_i≤ n) — the elements of the array.
It is guaranteed, that the sum of n for all test cases does not exceed 3⋅ 10^5.
Output
For each test case, print a binary string of length n.
The k-th character of the string should be 1 if CodeCook users will be happy after a k-compression of the array a, and 0 otherwise.
Example
Input
5
5
1 5 3 4 2
4
1 3 2 1
5
1 3 3 3 2
10
1 2 3 4 5 6 7 8 9 10
3
3 3 2
Output
10111
0001
00111
1111111111
000
Note
In the first test case, a=[1, 5, 3, 4, 2].
* The 1-compression of a is [1, 5, 3, 4, 2] and it is a permutation.
* The 2-compression of a is [1, 3, 3, 2] and it is not a permutation, since 3 appears twice.
* The 3-compression of a is [1, 3, 2] and it is a permutation.
* The 4-compression of a is [1, 2] and it is a permutation.
* The 5-compression of a is [1] and it is a permutation. | instruction | 0 | 45,594 | 12 | 91,188 |
Tags: binary search, data structures, greedy, implementation, two pointers
Correct Solution:
```
import sys
import math,bisect,operator
inf,m = float('inf'),10**9+7
sys.setrecursionlimit(10 ** 5)
from itertools import groupby,accumulate
from heapq import heapify,heappop,heappush
from collections import deque,Counter,defaultdict
I = lambda : int(sys.stdin.readline())
neo = lambda : map(int, sys.stdin.readline().split())
Neo = lambda : list(map(int, sys.stdin.readline().split()))
for _ in range(I()):
n = I()
Ans = list('0'*n)
A = Neo()
d = Counter(A)
dq = deque(A)
i = 1
j = n-1
while d:
if not d.get(i,0):
break
Ans[j] = '1'
if dq[0] == i:
dq.popleft()
elif dq[-1] == i:
dq.pop()
else:
break
if d.get(i,0) > 1:
break
i += 1
j -= 1
if len(set(A)) == n:
Ans[0] = '1' #
print(''.join(Ans))
``` | output | 1 | 45,594 | 12 | 91,189 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On the competitive programming platform CodeCook, every person has a rating graph described by an array of integers a of length n. You are now updating the infrastructure, so you've created a program to compress these graphs.
The program works as follows. Given an integer parameter k, the program takes the minimum of each contiguous subarray of length k in a.
More formally, for an array a of length n and an integer k, define the k-compression array of a as an array b of length n-k+1, such that $$$b_j =min_{j≤ i≤ j+k-1}a_i$$$
For example, the 3-compression array of [1, 3, 4, 5, 2] is [min\{1, 3, 4\}, min\{3, 4, 5\}, min\{4, 5, 2\}]=[1, 3, 2].
A permutation of length m is an array consisting of m distinct integers from 1 to m in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (m=3 but there is 4 in the array).
A k-compression array will make CodeCook users happy if it will be a permutation. Given an array a, determine for all 1≤ k≤ n if CodeCook users will be happy after a k-compression of this array or not.
Input
The first line contains a single integer t (1≤ t≤ 10^4) — the number of test cases.
The first line of the description of each test case contains a single integer n (1≤ n≤ 3⋅ 10^5) — the length of the array.
The second line of the description of each test case contains n integers a_1,…,a_n (1≤ a_i≤ n) — the elements of the array.
It is guaranteed, that the sum of n for all test cases does not exceed 3⋅ 10^5.
Output
For each test case, print a binary string of length n.
The k-th character of the string should be 1 if CodeCook users will be happy after a k-compression of the array a, and 0 otherwise.
Example
Input
5
5
1 5 3 4 2
4
1 3 2 1
5
1 3 3 3 2
10
1 2 3 4 5 6 7 8 9 10
3
3 3 2
Output
10111
0001
00111
1111111111
000
Note
In the first test case, a=[1, 5, 3, 4, 2].
* The 1-compression of a is [1, 5, 3, 4, 2] and it is a permutation.
* The 2-compression of a is [1, 3, 3, 2] and it is not a permutation, since 3 appears twice.
* The 3-compression of a is [1, 3, 2] and it is a permutation.
* The 4-compression of a is [1, 2] and it is a permutation.
* The 5-compression of a is [1] and it is a permutation.
Submitted Solution:
```
from collections import deque
import sys
def input():
return sys.stdin.readline().rstrip()
def solve():
n = int(input())
A = list(map(int, input().split()))
b = A.copy()
a = deque(A)
b.sort(reverse=True)
good = False
if all(b[i] == n - i for i in range(n)):
good = True
expected_value = 0
ans = [0]*(n)
while b:
expected_value += 1
value = b.pop()
cnt = 1
while b and b[-1] == value:
cnt += 1
b.pop()
if value != expected_value:
b.clear()
continue
elif value == expected_value and cnt > 1:
ans[n - value] += 1
b.clear()
continue
else:
if a[0] == value:
a.popleft()
ans[n - value] += 1
continue
elif a[-1] == value:
a.pop()
ans[n - value] += 1
continue
else:
ans[n - value] += 1
b.clear()
continue
if good and ans[0] == 0:
ans[0] += 1
res = "".join(map(str, ans))
print(res)
return
def main():
t = 1
t = int(input())
for i in range(t):
solve()
return
if __name__ == "__main__":
main()
``` | instruction | 0 | 45,595 | 12 | 91,190 |
Yes | output | 1 | 45,595 | 12 | 91,191 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On the competitive programming platform CodeCook, every person has a rating graph described by an array of integers a of length n. You are now updating the infrastructure, so you've created a program to compress these graphs.
The program works as follows. Given an integer parameter k, the program takes the minimum of each contiguous subarray of length k in a.
More formally, for an array a of length n and an integer k, define the k-compression array of a as an array b of length n-k+1, such that $$$b_j =min_{j≤ i≤ j+k-1}a_i$$$
For example, the 3-compression array of [1, 3, 4, 5, 2] is [min\{1, 3, 4\}, min\{3, 4, 5\}, min\{4, 5, 2\}]=[1, 3, 2].
A permutation of length m is an array consisting of m distinct integers from 1 to m in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (m=3 but there is 4 in the array).
A k-compression array will make CodeCook users happy if it will be a permutation. Given an array a, determine for all 1≤ k≤ n if CodeCook users will be happy after a k-compression of this array or not.
Input
The first line contains a single integer t (1≤ t≤ 10^4) — the number of test cases.
The first line of the description of each test case contains a single integer n (1≤ n≤ 3⋅ 10^5) — the length of the array.
The second line of the description of each test case contains n integers a_1,…,a_n (1≤ a_i≤ n) — the elements of the array.
It is guaranteed, that the sum of n for all test cases does not exceed 3⋅ 10^5.
Output
For each test case, print a binary string of length n.
The k-th character of the string should be 1 if CodeCook users will be happy after a k-compression of the array a, and 0 otherwise.
Example
Input
5
5
1 5 3 4 2
4
1 3 2 1
5
1 3 3 3 2
10
1 2 3 4 5 6 7 8 9 10
3
3 3 2
Output
10111
0001
00111
1111111111
000
Note
In the first test case, a=[1, 5, 3, 4, 2].
* The 1-compression of a is [1, 5, 3, 4, 2] and it is a permutation.
* The 2-compression of a is [1, 3, 3, 2] and it is not a permutation, since 3 appears twice.
* The 3-compression of a is [1, 3, 2] and it is a permutation.
* The 4-compression of a is [1, 2] and it is a permutation.
* The 5-compression of a is [1] and it is a permutation.
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline()
# ------------------------------
def RL(): return map(int, sys.stdin.readline().split())
def RLL(): return list(map(int, sys.stdin.readline().split()))
def N(): return int(input())
def print_list(l):
print(' '.join(map(str,l)))
# sys.setrecursionlimit(100000)
# import random
# from functools import reduce
# from functools import lru_cache
# from heapq import *
# from collections import deque as dq
# from math import ceil,floor,sqrt,pow,gcd,log
# import bisect as bs
# from collections import Counter
# from collections import defaultdict as dc
for _ in range(N()):
n = N()
a = RLL()
stack = [(-1, -1)]
m = [0] * (n + 1)
for i in range(n):
v = a[i]
while stack[-1][0] > v:
t, _ = stack.pop()
m[t] = max(m[t], i - stack[-1][1] - 1)
stack.append((v, i))
while len(stack) > 1:
v, _ = stack.pop()
m[v] = max(m[v], n - stack[-1][1] - 1)
# print(m)
res = ['1'] * n
r = n + 10
for i in range(1, n + 1):
for j in range(m[i] + 1, min(r, n - i + 2)):
res[j - 1] = '0'
r = min(r, m[i] + 1)
print(''.join(res))
``` | instruction | 0 | 45,596 | 12 | 91,192 |
Yes | output | 1 | 45,596 | 12 | 91,193 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On the competitive programming platform CodeCook, every person has a rating graph described by an array of integers a of length n. You are now updating the infrastructure, so you've created a program to compress these graphs.
The program works as follows. Given an integer parameter k, the program takes the minimum of each contiguous subarray of length k in a.
More formally, for an array a of length n and an integer k, define the k-compression array of a as an array b of length n-k+1, such that $$$b_j =min_{j≤ i≤ j+k-1}a_i$$$
For example, the 3-compression array of [1, 3, 4, 5, 2] is [min\{1, 3, 4\}, min\{3, 4, 5\}, min\{4, 5, 2\}]=[1, 3, 2].
A permutation of length m is an array consisting of m distinct integers from 1 to m in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (m=3 but there is 4 in the array).
A k-compression array will make CodeCook users happy if it will be a permutation. Given an array a, determine for all 1≤ k≤ n if CodeCook users will be happy after a k-compression of this array or not.
Input
The first line contains a single integer t (1≤ t≤ 10^4) — the number of test cases.
The first line of the description of each test case contains a single integer n (1≤ n≤ 3⋅ 10^5) — the length of the array.
The second line of the description of each test case contains n integers a_1,…,a_n (1≤ a_i≤ n) — the elements of the array.
It is guaranteed, that the sum of n for all test cases does not exceed 3⋅ 10^5.
Output
For each test case, print a binary string of length n.
The k-th character of the string should be 1 if CodeCook users will be happy after a k-compression of the array a, and 0 otherwise.
Example
Input
5
5
1 5 3 4 2
4
1 3 2 1
5
1 3 3 3 2
10
1 2 3 4 5 6 7 8 9 10
3
3 3 2
Output
10111
0001
00111
1111111111
000
Note
In the first test case, a=[1, 5, 3, 4, 2].
* The 1-compression of a is [1, 5, 3, 4, 2] and it is a permutation.
* The 2-compression of a is [1, 3, 3, 2] and it is not a permutation, since 3 appears twice.
* The 3-compression of a is [1, 3, 2] and it is a permutation.
* The 4-compression of a is [1, 2] and it is a permutation.
* The 5-compression of a is [1] and it is a permutation.
Submitted Solution:
```
from collections import defaultdict
for _ in range(int(input())):
n=int(input())
l=list(map(int,input().split()))
s=list('0'*n)
d=defaultdict(lambda :0)
for i in l:
d[i]+=1
if len(set(l))==n:
s[0]='1'
c=0
ct=n-1
for i in range(n):
if d[i+1]>0:
s[n-i-1]='1'
else:
break
if d[i+1]>1:
break
if l[c]==i+1:
c+=1
elif l[ct]==i+1:
ct-=1
else:
break
print(''.join(s))
``` | instruction | 0 | 45,597 | 12 | 91,194 |
Yes | output | 1 | 45,597 | 12 | 91,195 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On the competitive programming platform CodeCook, every person has a rating graph described by an array of integers a of length n. You are now updating the infrastructure, so you've created a program to compress these graphs.
The program works as follows. Given an integer parameter k, the program takes the minimum of each contiguous subarray of length k in a.
More formally, for an array a of length n and an integer k, define the k-compression array of a as an array b of length n-k+1, such that $$$b_j =min_{j≤ i≤ j+k-1}a_i$$$
For example, the 3-compression array of [1, 3, 4, 5, 2] is [min\{1, 3, 4\}, min\{3, 4, 5\}, min\{4, 5, 2\}]=[1, 3, 2].
A permutation of length m is an array consisting of m distinct integers from 1 to m in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (m=3 but there is 4 in the array).
A k-compression array will make CodeCook users happy if it will be a permutation. Given an array a, determine for all 1≤ k≤ n if CodeCook users will be happy after a k-compression of this array or not.
Input
The first line contains a single integer t (1≤ t≤ 10^4) — the number of test cases.
The first line of the description of each test case contains a single integer n (1≤ n≤ 3⋅ 10^5) — the length of the array.
The second line of the description of each test case contains n integers a_1,…,a_n (1≤ a_i≤ n) — the elements of the array.
It is guaranteed, that the sum of n for all test cases does not exceed 3⋅ 10^5.
Output
For each test case, print a binary string of length n.
The k-th character of the string should be 1 if CodeCook users will be happy after a k-compression of the array a, and 0 otherwise.
Example
Input
5
5
1 5 3 4 2
4
1 3 2 1
5
1 3 3 3 2
10
1 2 3 4 5 6 7 8 9 10
3
3 3 2
Output
10111
0001
00111
1111111111
000
Note
In the first test case, a=[1, 5, 3, 4, 2].
* The 1-compression of a is [1, 5, 3, 4, 2] and it is a permutation.
* The 2-compression of a is [1, 3, 3, 2] and it is not a permutation, since 3 appears twice.
* The 3-compression of a is [1, 3, 2] and it is a permutation.
* The 4-compression of a is [1, 2] and it is a permutation.
* The 5-compression of a is [1] and it is a permutation.
Submitted Solution:
```
#!/usr/bin/env python3
from collections import *
from heapq import *
from itertools import *
from functools import *
from random import *
import sys
INF = float('Inf')
def genTokens(lines):
for line in lines:
for token in line.split():
yield token
def nextFn(fn):
return lambda it: fn(it.__next__())
nint = nextFn(int)
def genCases():
it = genTokens(sys.stdin)
T = nint(it)
for _ in range(T):
N = nint(it)
As = [nint(it) for _ in range(N)]
yield (N, As)
def main():
for case in genCases():
solve(case)
def solve(case):
N, As=case
index=dict()
for i,a in enumerate(As):
if a not in index:
index[a]=[]
index[a].append(i)
mark=0
lo,hi=0,N-1
for num in range(1,N):
if num not in index:
break
mark=num
if len(index[num])>1:
break
if index[num][0] != lo and index[num][0] != hi:
break
if index[num][0] == lo:
lo+=1
else:
hi-=1
sAs=set(As)
if all(i in sAs for i in range(1,N+1)):
first='1'
else:
first='0'
ones=mark*['1']
zeros=(N-1-mark)*['0']
print(''.join([first]+zeros+ones))
main()
``` | instruction | 0 | 45,598 | 12 | 91,196 |
Yes | output | 1 | 45,598 | 12 | 91,197 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On the competitive programming platform CodeCook, every person has a rating graph described by an array of integers a of length n. You are now updating the infrastructure, so you've created a program to compress these graphs.
The program works as follows. Given an integer parameter k, the program takes the minimum of each contiguous subarray of length k in a.
More formally, for an array a of length n and an integer k, define the k-compression array of a as an array b of length n-k+1, such that $$$b_j =min_{j≤ i≤ j+k-1}a_i$$$
For example, the 3-compression array of [1, 3, 4, 5, 2] is [min\{1, 3, 4\}, min\{3, 4, 5\}, min\{4, 5, 2\}]=[1, 3, 2].
A permutation of length m is an array consisting of m distinct integers from 1 to m in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (m=3 but there is 4 in the array).
A k-compression array will make CodeCook users happy if it will be a permutation. Given an array a, determine for all 1≤ k≤ n if CodeCook users will be happy after a k-compression of this array or not.
Input
The first line contains a single integer t (1≤ t≤ 10^4) — the number of test cases.
The first line of the description of each test case contains a single integer n (1≤ n≤ 3⋅ 10^5) — the length of the array.
The second line of the description of each test case contains n integers a_1,…,a_n (1≤ a_i≤ n) — the elements of the array.
It is guaranteed, that the sum of n for all test cases does not exceed 3⋅ 10^5.
Output
For each test case, print a binary string of length n.
The k-th character of the string should be 1 if CodeCook users will be happy after a k-compression of the array a, and 0 otherwise.
Example
Input
5
5
1 5 3 4 2
4
1 3 2 1
5
1 3 3 3 2
10
1 2 3 4 5 6 7 8 9 10
3
3 3 2
Output
10111
0001
00111
1111111111
000
Note
In the first test case, a=[1, 5, 3, 4, 2].
* The 1-compression of a is [1, 5, 3, 4, 2] and it is a permutation.
* The 2-compression of a is [1, 3, 3, 2] and it is not a permutation, since 3 appears twice.
* The 3-compression of a is [1, 3, 2] and it is a permutation.
* The 4-compression of a is [1, 2] and it is a permutation.
* The 5-compression of a is [1] and it is a permutation.
Submitted Solution:
```
from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(10**5)
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
sys.setrecursionlimit(10**5)
def main():
pass
# 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")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
from math import ceil,log2
class SegmentationTreeMn():
def __init__(self, input_list):
self._input_list=input_list[:]
self._init_tree()
self.is_propogated=True
def _init_tree(self):
### CREATE SEGMENTATION TREE INFRASTRUCTURE
#length of the list
self.n=len(self._input_list)
#calc. height
height=ceil(log2(self.n))
#calculate number of nodes
nodes=2*(2**height)-1
#create empty seg tree
self._seg_tree=[None]*nodes
###FILLING IN SEGMENTATION TREE###
arr_left=0
arr_right=self.n-1
seg_node_index=0
self._propogate(arr_left,arr_right,seg_node_index)
def _propogate(self,arr_left,arr_right,seg_node_index):
#base case
if arr_right<arr_left:
return
if arr_left==arr_right:
value=self._input_list[arr_left]
self._seg_tree[seg_node_index]=value
return
midpoint=(arr_left+arr_right)//2
#left side
left_seg_node_index=seg_node_index*2 +1
left_node_arr_left=arr_left
left_node_arr_right=midpoint
self._propogate(left_node_arr_left, left_node_arr_right, left_seg_node_index)
#right side
right_seg_node_index=seg_node_index*2 +2
right_node_arr_left=midpoint+1
right_node_arr_right=arr_right
self._propogate(right_node_arr_left, right_node_arr_right, right_seg_node_index)
left_val=self._seg_tree[left_seg_node_index]
right_val=self._seg_tree[right_seg_node_index]
self._seg_tree[seg_node_index]=min(left_val,right_val)
def query(self, query_left, query_right):
arr_left=0
arr_right=self.n-1
seg_node_index=0
if not self.is_propogated:
self.is_propogated=True
self._propogate(arr_left ,arr_right, seg_node_index)
return self._query_helper(query_left,query_right,arr_left, arr_right, seg_node_index)
def _query_helper(self,query_left, query_right, arr_left, arr_right, seg_node_index):
if arr_right<arr_left:
return float('Inf')
if query_right<arr_left or query_left>arr_right:
return float('Inf')
if query_left<=arr_left and query_right>=arr_right:
return self._seg_tree[seg_node_index]
midpoint=(arr_left+arr_right)//2
#left side
left_seg_node_index=seg_node_index*2 +1
left_node_arr_left=arr_left
left_node_arr_right=midpoint
left_val=self._query_helper(query_left, query_right, left_node_arr_left, left_node_arr_right, left_seg_node_index)
#right side
right_seg_node_index=seg_node_index*2 +2
right_node_arr_left=midpoint+1
right_node_arr_right=arr_right
right_val=self._query_helper(query_left, query_right, right_node_arr_left, right_node_arr_right, right_seg_node_index)
return min(left_val,right_val)
def update(self,arr_index,new_value):
old_val=self._input_list[arr_index]
if old_val!=new_value:
self._input_list[arr_index]=new_value
self.is_propogated=False
t=int(input())
while t:
t-=1
n=int(input())
arr=list(map(int,input().split()))
st=SegmentationTreeMn(arr)
ans=[0]*(n+1)
for k in range(1,n+1):
i=0
sm=0
while i+k-1<n:
right=i+k-1
val=st.query(i, right)
sm+=val
i+=1
p=n-k+1
expected=p*(p+1)/2
if expected==sm:
ans[k]=1
print(*ans[1:])
``` | instruction | 0 | 45,599 | 12 | 91,198 |
No | output | 1 | 45,599 | 12 | 91,199 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On the competitive programming platform CodeCook, every person has a rating graph described by an array of integers a of length n. You are now updating the infrastructure, so you've created a program to compress these graphs.
The program works as follows. Given an integer parameter k, the program takes the minimum of each contiguous subarray of length k in a.
More formally, for an array a of length n and an integer k, define the k-compression array of a as an array b of length n-k+1, such that $$$b_j =min_{j≤ i≤ j+k-1}a_i$$$
For example, the 3-compression array of [1, 3, 4, 5, 2] is [min\{1, 3, 4\}, min\{3, 4, 5\}, min\{4, 5, 2\}]=[1, 3, 2].
A permutation of length m is an array consisting of m distinct integers from 1 to m in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (m=3 but there is 4 in the array).
A k-compression array will make CodeCook users happy if it will be a permutation. Given an array a, determine for all 1≤ k≤ n if CodeCook users will be happy after a k-compression of this array or not.
Input
The first line contains a single integer t (1≤ t≤ 10^4) — the number of test cases.
The first line of the description of each test case contains a single integer n (1≤ n≤ 3⋅ 10^5) — the length of the array.
The second line of the description of each test case contains n integers a_1,…,a_n (1≤ a_i≤ n) — the elements of the array.
It is guaranteed, that the sum of n for all test cases does not exceed 3⋅ 10^5.
Output
For each test case, print a binary string of length n.
The k-th character of the string should be 1 if CodeCook users will be happy after a k-compression of the array a, and 0 otherwise.
Example
Input
5
5
1 5 3 4 2
4
1 3 2 1
5
1 3 3 3 2
10
1 2 3 4 5 6 7 8 9 10
3
3 3 2
Output
10111
0001
00111
1111111111
000
Note
In the first test case, a=[1, 5, 3, 4, 2].
* The 1-compression of a is [1, 5, 3, 4, 2] and it is a permutation.
* The 2-compression of a is [1, 3, 3, 2] and it is not a permutation, since 3 appears twice.
* The 3-compression of a is [1, 3, 2] and it is a permutation.
* The 4-compression of a is [1, 2] and it is a permutation.
* The 5-compression of a is [1] and it is a permutation.
Submitted Solution:
```
import sys
from math import log2, ceil
# For getting input from input.txt file
# sys.stdin = open('input.txt', 'r')
# Printing the Output to output.txt file
# sys.stdout = open('output.txt', 'w')
def build_tree(tree, curr, arr, l, r):
"""
total no of nodes of tree = 2 * len(arr) - 1
tree: Segment Tree
curr: Current Position of the Tree
arr: Original Array
l: Left Pointer
r: Right Pointer
"""
if l == r:
tree[curr] = arr[l]
return arr[l]
mid = (l+r)//2
tree[curr] = min(build_tree(tree, 2*curr+1, arr, l, mid),build_tree(tree, 2*curr+2, arr, mid+1, r))
return tree[curr]
def query_for_tree(tree, curr, start, end, l, r):
# Total Overlap
if l <= start and r >= end:
return tree[curr]
# No Overlap
if end < l or start > r:
return 10000
mid = (start+end)//2
return min(query_for_tree(tree, 2*curr+1, start, mid, l, r),query_for_tree(tree, 2*curr+2, mid+1, end, l, r))
def solve():
k = int(input())
arr = list(map(int, input().split()))
tree = ['x'] * 2**(int(log2(k*2-1))+1)
build_tree(tree, 0, arr, 0, k-1)
query_for_tree(tree, 0, 0, k-1, 1, 2)
output = ""
for i in range(k):
temp = [query_for_tree(tree, 0, 0, k-1, j, j+i) for j in range(len(arr)-i)]
if temp.count(1)>1:
output += '0'
continue
output += '1' if (len(temp)*(len(temp)+1))/2 == sum(set(temp)) else '0'
print(output)
num = int(input())
for n in range(num):
solve()
``` | instruction | 0 | 45,600 | 12 | 91,200 |
No | output | 1 | 45,600 | 12 | 91,201 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On the competitive programming platform CodeCook, every person has a rating graph described by an array of integers a of length n. You are now updating the infrastructure, so you've created a program to compress these graphs.
The program works as follows. Given an integer parameter k, the program takes the minimum of each contiguous subarray of length k in a.
More formally, for an array a of length n and an integer k, define the k-compression array of a as an array b of length n-k+1, such that $$$b_j =min_{j≤ i≤ j+k-1}a_i$$$
For example, the 3-compression array of [1, 3, 4, 5, 2] is [min\{1, 3, 4\}, min\{3, 4, 5\}, min\{4, 5, 2\}]=[1, 3, 2].
A permutation of length m is an array consisting of m distinct integers from 1 to m in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (m=3 but there is 4 in the array).
A k-compression array will make CodeCook users happy if it will be a permutation. Given an array a, determine for all 1≤ k≤ n if CodeCook users will be happy after a k-compression of this array or not.
Input
The first line contains a single integer t (1≤ t≤ 10^4) — the number of test cases.
The first line of the description of each test case contains a single integer n (1≤ n≤ 3⋅ 10^5) — the length of the array.
The second line of the description of each test case contains n integers a_1,…,a_n (1≤ a_i≤ n) — the elements of the array.
It is guaranteed, that the sum of n for all test cases does not exceed 3⋅ 10^5.
Output
For each test case, print a binary string of length n.
The k-th character of the string should be 1 if CodeCook users will be happy after a k-compression of the array a, and 0 otherwise.
Example
Input
5
5
1 5 3 4 2
4
1 3 2 1
5
1 3 3 3 2
10
1 2 3 4 5 6 7 8 9 10
3
3 3 2
Output
10111
0001
00111
1111111111
000
Note
In the first test case, a=[1, 5, 3, 4, 2].
* The 1-compression of a is [1, 5, 3, 4, 2] and it is a permutation.
* The 2-compression of a is [1, 3, 3, 2] and it is not a permutation, since 3 appears twice.
* The 3-compression of a is [1, 3, 2] and it is a permutation.
* The 4-compression of a is [1, 2] and it is a permutation.
* The 5-compression of a is [1] and it is a permutation.
Submitted Solution:
```
import math
# import sys
from collections import Counter, defaultdict, deque
def f(n, nums):
#n = len(nums)
k = math.floor(math.log(n, 2))
st = [[0 for j in range(k+1)]for i in range(n+1)]
for i in range(n):
st[i][0] = nums[i]
for j in range(1, k + 1):
for i in range(0, n + 1 - (1<<j)):
st[i][j] = min(st[i][j-1], st[i + (1<<(j-1))][j-1])
log = [0 for i in range(n+1)]
for i in range(2, n+1):
log[i] = log[i//2] + 1
finans = ""
for win in range(1, n+1):
ans = []
L = 0
R = win - 1
while R < n:
j = log[R - L + 1]
ans.append(min(st[L][j], st[R - (1<<j) + 1][j]))
R += 1
L += 1
##print(ans, [i+1 for i in range(n-win+1)], set(ans) == set([i+1 for i in range(n-win+1)]))
if sum(ans) == (n-win+1)*(n-win+2)//2:
finans += "1"
else:
finans += "0"
return finans
t = int(input())
result = []
for i in range(t):
n = int(input())
a = list(map(int, input().split()))
result.append(f(n, a))
for i in range(t):
print(result[i])
``` | instruction | 0 | 45,601 | 12 | 91,202 |
No | output | 1 | 45,601 | 12 | 91,203 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On the competitive programming platform CodeCook, every person has a rating graph described by an array of integers a of length n. You are now updating the infrastructure, so you've created a program to compress these graphs.
The program works as follows. Given an integer parameter k, the program takes the minimum of each contiguous subarray of length k in a.
More formally, for an array a of length n and an integer k, define the k-compression array of a as an array b of length n-k+1, such that $$$b_j =min_{j≤ i≤ j+k-1}a_i$$$
For example, the 3-compression array of [1, 3, 4, 5, 2] is [min\{1, 3, 4\}, min\{3, 4, 5\}, min\{4, 5, 2\}]=[1, 3, 2].
A permutation of length m is an array consisting of m distinct integers from 1 to m in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (m=3 but there is 4 in the array).
A k-compression array will make CodeCook users happy if it will be a permutation. Given an array a, determine for all 1≤ k≤ n if CodeCook users will be happy after a k-compression of this array or not.
Input
The first line contains a single integer t (1≤ t≤ 10^4) — the number of test cases.
The first line of the description of each test case contains a single integer n (1≤ n≤ 3⋅ 10^5) — the length of the array.
The second line of the description of each test case contains n integers a_1,…,a_n (1≤ a_i≤ n) — the elements of the array.
It is guaranteed, that the sum of n for all test cases does not exceed 3⋅ 10^5.
Output
For each test case, print a binary string of length n.
The k-th character of the string should be 1 if CodeCook users will be happy after a k-compression of the array a, and 0 otherwise.
Example
Input
5
5
1 5 3 4 2
4
1 3 2 1
5
1 3 3 3 2
10
1 2 3 4 5 6 7 8 9 10
3
3 3 2
Output
10111
0001
00111
1111111111
000
Note
In the first test case, a=[1, 5, 3, 4, 2].
* The 1-compression of a is [1, 5, 3, 4, 2] and it is a permutation.
* The 2-compression of a is [1, 3, 3, 2] and it is not a permutation, since 3 appears twice.
* The 3-compression of a is [1, 3, 2] and it is a permutation.
* The 4-compression of a is [1, 2] and it is a permutation.
* The 5-compression of a is [1] and it is a permutation.
Submitted Solution:
```
import sys
input = sys.stdin.readline
import math
for _ in range(int(input())):
n = int(input())
arr = list(map(int,input().split()))
midmin = [sys.maxsize]*((n+1)//2)
small = sys.maxsize
if n&1:
x = y = n//2
else:
x = n//2-1
y = n//2
for i in range(len(midmin)-1,-1,-1):
small = min(small,arr[x],arr[y])
midmin[i]=small
x-=1
y+=1
ans = [0]*(n+1)
val = 1
state = False
x = 0
y = len(arr)-1
for i in range(n,1,-1):
if state:
if val == max(arr[x],arr[y]) and val-1==min(arr[x],arr[y]):
ans[i]=1
else:
break
x+=1
y-=1
else:
if val == midmin[x]:
ans[i]=1
else:
break
val+=1
state = not state
inc = True
dec = True
for i in range(1,n):
if arr[i]<=arr[i-1]:
inc = False
if arr[i]>=arr[i-1]:
dec = False
incind = 0
if inc:
if arr[0]==1:
for i in range(1,n):
if arr[i]!=arr[i-1]+1:
incind = min(i,n-i-1)
break
else:
incind = n+1
for i in range(incind,len(ans)):
ans[i]=1
decind = 0
if dec:
if arr[n-1]==1:
for i in range(n-2,-1,-1):
if arr[i]!=arr[i+1]-1:
decind = min(i,n-i-1)
break
else:
incind = n+1
for i in range(decind,len(ans)):
ans[i]=1
arr.sort()
case1 = True
if arr[0]!=1:
case1=False
for i in range(1,len(arr)):
if arr[i]!=arr[i-1]+1:
case1=False
break
if case1:
ans[1]=1
else:
ans[1]=0
for num in ans[1:]:
print(num,end= "")
print()
``` | instruction | 0 | 45,602 | 12 | 91,204 |
No | output | 1 | 45,602 | 12 | 91,205 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.