text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Santa has n candies and he wants to gift them to k kids. He wants to divide as many candies as possible between all k kids. Santa can't divide one candy into parts but he is allowed to not use some candies at all.
Suppose the kid who recieves the minimum number of candies has a candies and the kid who recieves the maximum number of candies has b candies. Then Santa will be satisfied, if the both conditions are met at the same time:
* b - a ≤ 1 (it means b = a or b = a + 1);
* the number of kids who has a+1 candies (note that a+1 not necessarily equals b) does not exceed ⌊k/2⌋ (less than or equal to ⌊k/2⌋).
⌊k/2⌋ is k divided by 2 and rounded down to the nearest integer. For example, if k=5 then ⌊k/2⌋=⌊5/2⌋=2.
Your task is to find the maximum number of candies Santa can give to kids so that he will be satisfied.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 5 ⋅ 10^4) — the number of test cases.
The next t lines describe test cases. The i-th test case contains two integers n and k (1 ≤ n, k ≤ 10^9) — the number of candies and the number of kids.
Output
For each test case print the answer on it — the maximum number of candies Santa can give to kids so that he will be satisfied.
Example
Input
5
5 2
19 4
12 7
6 2
100000 50010
Output
5
18
10
6
75015
Note
In the first test case, Santa can give 3 and 2 candies to kids. There a=2, b=3,a+1=3.
In the second test case, Santa can give 5, 5, 4 and 4 candies. There a=4,b=5,a+1=5. The answer cannot be greater because then the number of kids with 5 candies will be 3.
In the third test case, Santa can distribute candies in the following way: [1, 2, 2, 1, 1, 2, 1]. There a=1,b=2,a+1=2. He cannot distribute two remaining candies in a way to be satisfied.
In the fourth test case, Santa can distribute candies in the following way: [3, 3]. There a=3, b=3, a+1=4. Santa distributed all 6 candies.
Submitted Solution:
```
t=int(input())
for _ in range(t):
#print(_)
n,k=map(int,input().split())
l=[]
d=n%k
d1=n//k
half=k//2
sum=0
sum1=0
for i in range(k):
l.append(d1)
#print(l)
for i in l:
sum+=i
#print(sum)
if(sum==n):
print(n)
break
else:
for i in range(half):
l[i]+=1
#print(l)
for i in l:
sum1+=i
print(sum1)
```
No
| 7,700 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Santa has n candies and he wants to gift them to k kids. He wants to divide as many candies as possible between all k kids. Santa can't divide one candy into parts but he is allowed to not use some candies at all.
Suppose the kid who recieves the minimum number of candies has a candies and the kid who recieves the maximum number of candies has b candies. Then Santa will be satisfied, if the both conditions are met at the same time:
* b - a ≤ 1 (it means b = a or b = a + 1);
* the number of kids who has a+1 candies (note that a+1 not necessarily equals b) does not exceed ⌊k/2⌋ (less than or equal to ⌊k/2⌋).
⌊k/2⌋ is k divided by 2 and rounded down to the nearest integer. For example, if k=5 then ⌊k/2⌋=⌊5/2⌋=2.
Your task is to find the maximum number of candies Santa can give to kids so that he will be satisfied.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 5 ⋅ 10^4) — the number of test cases.
The next t lines describe test cases. The i-th test case contains two integers n and k (1 ≤ n, k ≤ 10^9) — the number of candies and the number of kids.
Output
For each test case print the answer on it — the maximum number of candies Santa can give to kids so that he will be satisfied.
Example
Input
5
5 2
19 4
12 7
6 2
100000 50010
Output
5
18
10
6
75015
Note
In the first test case, Santa can give 3 and 2 candies to kids. There a=2, b=3,a+1=3.
In the second test case, Santa can give 5, 5, 4 and 4 candies. There a=4,b=5,a+1=5. The answer cannot be greater because then the number of kids with 5 candies will be 3.
In the third test case, Santa can distribute candies in the following way: [1, 2, 2, 1, 1, 2, 1]. There a=1,b=2,a+1=2. He cannot distribute two remaining candies in a way to be satisfied.
In the fourth test case, Santa can distribute candies in the following way: [3, 3]. There a=3, b=3, a+1=4. Santa distributed all 6 candies.
Submitted Solution:
```
import math
t=int(input())
for i in range(t):
n,k=map(int, input().split())
a=math.floor(n/k)
n1=n
s1=0
a_count=0
b_count=1
b=a
if (a>0):
a_count=k-math.floor(k/2)
b_count=k-a_count
else:
a_count=0
b_count=1
if (n>=(a*a_count+b*b_count)):
s=a*a_count+b*b_count
a_count=0
b_count=1
b=a+1
n1=n
if (a>0):
a_count=k-math.floor(k/2)
b_count=k-a_count
else:
a_count=0
b_count=1
if (n>=(a*a_count+b*b_count)):
s1=a*a_count+b*b_count
if(s>s1):
print(s)
else:
print(s1)
```
No
| 7,701 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Santa has n candies and he wants to gift them to k kids. He wants to divide as many candies as possible between all k kids. Santa can't divide one candy into parts but he is allowed to not use some candies at all.
Suppose the kid who recieves the minimum number of candies has a candies and the kid who recieves the maximum number of candies has b candies. Then Santa will be satisfied, if the both conditions are met at the same time:
* b - a ≤ 1 (it means b = a or b = a + 1);
* the number of kids who has a+1 candies (note that a+1 not necessarily equals b) does not exceed ⌊k/2⌋ (less than or equal to ⌊k/2⌋).
⌊k/2⌋ is k divided by 2 and rounded down to the nearest integer. For example, if k=5 then ⌊k/2⌋=⌊5/2⌋=2.
Your task is to find the maximum number of candies Santa can give to kids so that he will be satisfied.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 5 ⋅ 10^4) — the number of test cases.
The next t lines describe test cases. The i-th test case contains two integers n and k (1 ≤ n, k ≤ 10^9) — the number of candies and the number of kids.
Output
For each test case print the answer on it — the maximum number of candies Santa can give to kids so that he will be satisfied.
Example
Input
5
5 2
19 4
12 7
6 2
100000 50010
Output
5
18
10
6
75015
Note
In the first test case, Santa can give 3 and 2 candies to kids. There a=2, b=3,a+1=3.
In the second test case, Santa can give 5, 5, 4 and 4 candies. There a=4,b=5,a+1=5. The answer cannot be greater because then the number of kids with 5 candies will be 3.
In the third test case, Santa can distribute candies in the following way: [1, 2, 2, 1, 1, 2, 1]. There a=1,b=2,a+1=2. He cannot distribute two remaining candies in a way to be satisfied.
In the fourth test case, Santa can distribute candies in the following way: [3, 3]. There a=3, b=3, a+1=4. Santa distributed all 6 candies.
Submitted Solution:
```
import sys; import math;
CASE=0; rla=''
def solve() :
s=str(input())
print(len(s)+1)
while True :
rla=sys.stdin.readline()
cases=1
if not rla: break
if (rla=='\n')|(rla=='') : continue
if CASE==1 : cases=int(rla)
for cas in range(cases) :
solve()
```
No
| 7,702 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem.
You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements:
1. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the begin of the array;
2. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the end of the array.
For example, if n = 5, a = [4, 7, 2, 3, 9], then the following sequence of operations can be performed:
* after performing the operation of the first type to the second element, the array a will become [7, 4, 2, 3, 9];
* after performing the operation of the second type to the second element, the array a will become [7, 2, 3, 9, 4].
You can perform operations of any type any number of times in any order.
Find the minimum total number of operations of the first and second type that will make the a array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities a[1] ≤ a[2] ≤ … ≤ a[n].
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases in the test. Then t test cases follow.
Each test case starts with a line containing an integer n (1 ≤ n ≤ 3000) — length of the array a.
Then follow n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9) — an array that needs to be sorted by the given operations. All numbers in the given array are distinct.
The sum of n for all test cases in one test does not exceed 3000.
Output
For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order.
Example
Input
4
5
4 7 2 3 9
5
3 5 8 1 7
5
1 4 5 7 12
4
0 2 1 3
Output
2
2
0
2
Note
In the first test case, you first need to move 3, and then 2 to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 3, 9] → [3, 4, 7, 2, 9] → [2, 3, 4, 7, 9].
In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: [3, 5, 8, 1, 7] → [1, 3, 5, 8, 7] → [1, 3, 5, 7, 8].
In the third test case, the array is already sorted.
Tags: dp, greedy, two pointers
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
class seq():
def __init__(self, l, c):
self.length = l
self.final_ctr = c
t = int(input())
for _ in range(t):
n = int(input())
d = {}
c = {}
prev = {}
ctr = {}
li = [int(i) for i in input().split(' ')]
n = len(li)
for i in li:
ctr[i] = ctr.get(i, 0) + 1
so = sorted(ctr)
pp = -1
for i in so:
prev[i] = pp
pp = i
mx = 1
for i in li:
if i in d: # i在d内,表示前面出现过i
if prev[i] in d and d[prev[i]][1].final_ctr == ctr[prev[i]]: # 前一个元素已选满
if d[prev[i]][1].length > max(d[i][1].length,d[i][0].length):
d[i][0].length = d[prev[i]][1].length
d[i][0].final_ctr = 0
if c.get(prev[i],0) > max(d[i][1].length,d[i][0].length): # 前一个元素(不一定选满)的计数大于现在的,现在的不选满
d[i][0].length = c[prev[i]]
d[i][0].final_ctr = 0
d[i][1].final_ctr += 1
d[i][1].length += 1
d[i][0].final_ctr += 1
d[i][0].length += 1
else:
d.setdefault(i,[seq(0,0),seq(0,0)])
if prev[i] in d:
if d[prev[i]][1].final_ctr == ctr[prev[i]]:
d[i][1] = seq(d[prev[i]][1].length+1, 1)
d[i][0] = seq(d[prev[i]][1].length+1, 1)
if c.get(prev[i],0) > d[i][1].length:
d[i][1].length = c[prev[i]] + 1
d[i][0].length = c[prev[i]] + 1
d[i][1].final_ctr = 1
d[i][0].final_ctr = 1
else:
d[i][1] = seq(c[prev[i]]+1, 1)
d[i][0] = seq(c[prev[i]]+1, 1)
else:
d[i][1] = seq(1, 1)
mx = max(mx, d[i][1].length,d[i][0].length)
c[i] = c.get(i, 0) + 1
print(n-mx)
'''
1
17
0 0 0 0 1 1 1 0 0 0 0 1 1 1 2 2 2
4 and 6
'''
```
| 7,703 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem.
You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements:
1. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the begin of the array;
2. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the end of the array.
For example, if n = 5, a = [4, 7, 2, 3, 9], then the following sequence of operations can be performed:
* after performing the operation of the first type to the second element, the array a will become [7, 4, 2, 3, 9];
* after performing the operation of the second type to the second element, the array a will become [7, 2, 3, 9, 4].
You can perform operations of any type any number of times in any order.
Find the minimum total number of operations of the first and second type that will make the a array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities a[1] ≤ a[2] ≤ … ≤ a[n].
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases in the test. Then t test cases follow.
Each test case starts with a line containing an integer n (1 ≤ n ≤ 3000) — length of the array a.
Then follow n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9) — an array that needs to be sorted by the given operations. All numbers in the given array are distinct.
The sum of n for all test cases in one test does not exceed 3000.
Output
For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order.
Example
Input
4
5
4 7 2 3 9
5
3 5 8 1 7
5
1 4 5 7 12
4
0 2 1 3
Output
2
2
0
2
Note
In the first test case, you first need to move 3, and then 2 to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 3, 9] → [3, 4, 7, 2, 9] → [2, 3, 4, 7, 9].
In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: [3, 5, 8, 1, 7] → [1, 3, 5, 8, 7] → [1, 3, 5, 7, 8].
In the third test case, the array is already sorted.
Tags: dp, greedy, two pointers
Correct Solution:
```
import sys
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
INF = 10 ** 19
MOD = 10 ** 9 + 7
def compress(S):
zipped, unzipped = {}, {}
for i, a in enumerate(sorted(S)):
zipped[a] = i
unzipped[i] = a
return zipped, unzipped
for _ in range(INT()):
N = INT()
A = LIST()
zipped, _ = compress(A)
for i in range(N):
A[i] = zipped[A[i]]
B = [0] * N
for i, a in enumerate(A):
B[a] = i
mx = cnt = 1
for i in range(N-1):
if B[i] < B[i+1]:
cnt += 1
else:
cnt = 1
mx = max(mx, cnt)
print(N - mx)
```
| 7,704 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem.
You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements:
1. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the begin of the array;
2. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the end of the array.
For example, if n = 5, a = [4, 7, 2, 3, 9], then the following sequence of operations can be performed:
* after performing the operation of the first type to the second element, the array a will become [7, 4, 2, 3, 9];
* after performing the operation of the second type to the second element, the array a will become [7, 2, 3, 9, 4].
You can perform operations of any type any number of times in any order.
Find the minimum total number of operations of the first and second type that will make the a array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities a[1] ≤ a[2] ≤ … ≤ a[n].
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases in the test. Then t test cases follow.
Each test case starts with a line containing an integer n (1 ≤ n ≤ 3000) — length of the array a.
Then follow n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9) — an array that needs to be sorted by the given operations. All numbers in the given array are distinct.
The sum of n for all test cases in one test does not exceed 3000.
Output
For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order.
Example
Input
4
5
4 7 2 3 9
5
3 5 8 1 7
5
1 4 5 7 12
4
0 2 1 3
Output
2
2
0
2
Note
In the first test case, you first need to move 3, and then 2 to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 3, 9] → [3, 4, 7, 2, 9] → [2, 3, 4, 7, 9].
In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: [3, 5, 8, 1, 7] → [1, 3, 5, 8, 7] → [1, 3, 5, 7, 8].
In the third test case, the array is already sorted.
Tags: dp, greedy, two pointers
Correct Solution:
```
for _ in range(int(input())):
n = int(input())
a = list(map(int,input().split()))
b = sorted(list(set(a)))
max_r = 0
for i in range(n):
a[i] = b.index(a[i])
while a!=[]:
r = 0
last = a[-1]
for i in range(len(a)-1,-1,-1):
if a[i] == last or a[i]+1 == last:
r += 1
last = a[i]
a.pop(i)
if r>max_r:
max_r = r
print(n - max_r)
```
| 7,705 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem.
You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements:
1. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the begin of the array;
2. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the end of the array.
For example, if n = 5, a = [4, 7, 2, 3, 9], then the following sequence of operations can be performed:
* after performing the operation of the first type to the second element, the array a will become [7, 4, 2, 3, 9];
* after performing the operation of the second type to the second element, the array a will become [7, 2, 3, 9, 4].
You can perform operations of any type any number of times in any order.
Find the minimum total number of operations of the first and second type that will make the a array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities a[1] ≤ a[2] ≤ … ≤ a[n].
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases in the test. Then t test cases follow.
Each test case starts with a line containing an integer n (1 ≤ n ≤ 3000) — length of the array a.
Then follow n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9) — an array that needs to be sorted by the given operations. All numbers in the given array are distinct.
The sum of n for all test cases in one test does not exceed 3000.
Output
For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order.
Example
Input
4
5
4 7 2 3 9
5
3 5 8 1 7
5
1 4 5 7 12
4
0 2 1 3
Output
2
2
0
2
Note
In the first test case, you first need to move 3, and then 2 to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 3, 9] → [3, 4, 7, 2, 9] → [2, 3, 4, 7, 9].
In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: [3, 5, 8, 1, 7] → [1, 3, 5, 8, 7] → [1, 3, 5, 7, 8].
In the third test case, the array is already sorted.
Tags: dp, greedy, two pointers
Correct Solution:
```
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
from math import gcd, ceil
def prod(a, mod=10**9+7):
ans = 1
for each in a:
ans = (ans * each) % mod
return ans
def lcm(a, b): return a * b // gcd(a, b)
def binary(x, length=16):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
for _ in range(int(input()) if True else 1):
#n, k = map(int, input().split())
#a, b = map(int, input().split())
#c, d = map(int, input().split())
#a = list(map(int, input().split()))
#b = list(map(int, input().split()))
n = int(input())
a = list(map(int, input().split()))
se = sorted(list(set(a)))
di = {}
for i in range(len(se)):
di[se[i]] = i+1
a = [di[k] for k in a]
count = [0]*(n+1)
for i in a:count[i] += 1
c = [0]*(n+1)
seen, now = [-1]*(n+1), [-1]*(n+1)
dp = [0]*n
ans = 0
for i in range(n):
cur = a[i]
dp[i] = max(dp[i], c[cur-1] + 1)
if seen[cur] != -1:
dp[i] = max(dp[i], dp[seen[cur] if seen[cur]!=-1 else 0] + 1)
if c[cur-1] == count[cur-1]:
dp[i] = max(dp[i], (dp[now[cur-1]if now[cur-1]!=-1 else 0]) + c[cur-1])
c[cur] += 1
seen[cur] = i
if now[cur] == -1:now[cur] = i
print(n - max(dp))
```
| 7,706 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem.
You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements:
1. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the begin of the array;
2. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the end of the array.
For example, if n = 5, a = [4, 7, 2, 3, 9], then the following sequence of operations can be performed:
* after performing the operation of the first type to the second element, the array a will become [7, 4, 2, 3, 9];
* after performing the operation of the second type to the second element, the array a will become [7, 2, 3, 9, 4].
You can perform operations of any type any number of times in any order.
Find the minimum total number of operations of the first and second type that will make the a array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities a[1] ≤ a[2] ≤ … ≤ a[n].
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases in the test. Then t test cases follow.
Each test case starts with a line containing an integer n (1 ≤ n ≤ 3000) — length of the array a.
Then follow n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9) — an array that needs to be sorted by the given operations. All numbers in the given array are distinct.
The sum of n for all test cases in one test does not exceed 3000.
Output
For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order.
Example
Input
4
5
4 7 2 3 9
5
3 5 8 1 7
5
1 4 5 7 12
4
0 2 1 3
Output
2
2
0
2
Note
In the first test case, you first need to move 3, and then 2 to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 3, 9] → [3, 4, 7, 2, 9] → [2, 3, 4, 7, 9].
In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: [3, 5, 8, 1, 7] → [1, 3, 5, 8, 7] → [1, 3, 5, 7, 8].
In the third test case, the array is already sorted.
Tags: dp, greedy, two pointers
Correct Solution:
```
t = int(input())
for _ in range(t):
n = int(input())
l = list(map(int,input().split()))
id = list(zip(l,list(range(n))))
id.sort()
val, pos = zip(*id)
best = 1
i = 1
count = 1
while True:
if i >= n:
break
if pos[i] > pos[i-1]:
count += 1
best = max(count,best)
else:
count = 1
i += 1
print(n-best)
```
| 7,707 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem.
You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements:
1. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the begin of the array;
2. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the end of the array.
For example, if n = 5, a = [4, 7, 2, 3, 9], then the following sequence of operations can be performed:
* after performing the operation of the first type to the second element, the array a will become [7, 4, 2, 3, 9];
* after performing the operation of the second type to the second element, the array a will become [7, 2, 3, 9, 4].
You can perform operations of any type any number of times in any order.
Find the minimum total number of operations of the first and second type that will make the a array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities a[1] ≤ a[2] ≤ … ≤ a[n].
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases in the test. Then t test cases follow.
Each test case starts with a line containing an integer n (1 ≤ n ≤ 3000) — length of the array a.
Then follow n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9) — an array that needs to be sorted by the given operations. All numbers in the given array are distinct.
The sum of n for all test cases in one test does not exceed 3000.
Output
For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order.
Example
Input
4
5
4 7 2 3 9
5
3 5 8 1 7
5
1 4 5 7 12
4
0 2 1 3
Output
2
2
0
2
Note
In the first test case, you first need to move 3, and then 2 to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 3, 9] → [3, 4, 7, 2, 9] → [2, 3, 4, 7, 9].
In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: [3, 5, 8, 1, 7] → [1, 3, 5, 8, 7] → [1, 3, 5, 7, 8].
In the third test case, the array is already sorted.
Tags: dp, greedy, two pointers
Correct Solution:
```
def flyingsort(L):
# all elements distinct
d = {}
for i in range(len(L)):
d[L[i]] = i
L.sort()
prev = -1
run = 0
maxRun = -1
for i in L:
if d[i] > prev:
run += 1
else:
run = 1
maxRun = max(maxRun, run)
prev = d[i]
return len(L) - maxRun
T = int(input())
for i in range(T):
N = int(input())
L = list(map(int, input().split(' ')))
print(flyingsort(L))
```
| 7,708 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem.
You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements:
1. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the begin of the array;
2. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the end of the array.
For example, if n = 5, a = [4, 7, 2, 3, 9], then the following sequence of operations can be performed:
* after performing the operation of the first type to the second element, the array a will become [7, 4, 2, 3, 9];
* after performing the operation of the second type to the second element, the array a will become [7, 2, 3, 9, 4].
You can perform operations of any type any number of times in any order.
Find the minimum total number of operations of the first and second type that will make the a array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities a[1] ≤ a[2] ≤ … ≤ a[n].
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases in the test. Then t test cases follow.
Each test case starts with a line containing an integer n (1 ≤ n ≤ 3000) — length of the array a.
Then follow n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9) — an array that needs to be sorted by the given operations. All numbers in the given array are distinct.
The sum of n for all test cases in one test does not exceed 3000.
Output
For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order.
Example
Input
4
5
4 7 2 3 9
5
3 5 8 1 7
5
1 4 5 7 12
4
0 2 1 3
Output
2
2
0
2
Note
In the first test case, you first need to move 3, and then 2 to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 3, 9] → [3, 4, 7, 2, 9] → [2, 3, 4, 7, 9].
In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: [3, 5, 8, 1, 7] → [1, 3, 5, 8, 7] → [1, 3, 5, 7, 8].
In the third test case, the array is already sorted.
Tags: dp, greedy, two pointers
Correct Solution:
```
"""n=int(input())
a=list(map(int,input().split()))
ct=[0]*20
for x in a:
for sf in range(20):
ct[sf]+=(x>>sf)&1
ans=[0]*n
for i in range(20):
for j in range(ct[i]):
print(ans[j],1<<i,ans[j] | 1<<i)
ans[j]|=1<<i
print(sum([x**2 for x in ans]))
"""
"""k=int(input())
s='codeforces'
i,sm=0,1
l=[1]*10
while sm<k:
sm//=l[i]
print(sm,l[i])
l[i]+=1
print(l[i])
sm*=l[i]
print(sm)
i=(i+1)%10
print(l)
ans=[s[i]*l[i] for i in range(10)]
print(''.join(ans))"""
"""T =int(input())
for _ in range(T):
a=input()
if len(a)==2:
print(a)
else:
for i in range(0,len(a),2):
print(a[i],end="")
print(a[-1])"""
"""T = int(input())
for _ in range(T):
n = int(input())
arr = list(map(int,input().split()))
a=b=0
for i in range(n):
if i%2 != arr[i]%2:
if i%2==0:
a+=1
else:
b+=1
if a==b:
print(a)
else:
print(-1)"""
"""T= int(input())
for _ in range(T):
n,k = list(map(int,input().split()))
a = input()
e='0'*k+a+'0'*k
f = k*2+1
z=ct=0
for i in e.split('1'):
ct+=max((len(i)-k)//(k+1),0)
print(ct)"""
"""for _ in range(int(input())):
arr = ['#']+sorted(list(input()))
n = int(input())
num = [-1]+[int(i) for i in input().split()]
ans = ['#']*(n+1)
while 0 in num:
zero = []
for i in range(1,n+1):
if num[i]==0:
zero.append(i)
num[i]=-1
#print("zero",zero)
while arr.count(arr[-1])<len(zero):
p = arr[-1]
while p==arr[-1]:
arr.pop()
#print("arr",arr)
p=0
for i in zero:
p=ans[i]=arr[-1]
#print("ans",ans)
while arr[-1]==p:
arr.pop()
for i in range(1,n+1):
if ans[i]=='#':
for j in zero:
num[i]-=abs(j-i)
#print("num",num)
print(''.join(ans[1:]))"""
"""import math
import collections
for _ in range(int(input())):
n,k = map(int, input().split())
s = input()
ctr = collections.Counter(s)
ans = 0
for i in range(1,n+1):
g = math.gcd(i, k)
l = i // g
#print(i,k,g,l)
cnt = sum([(v//l)*l for v in ctr.values()])
#print(cnt)
if cnt >= i:
ans = i
print(ans)"""
t= int(input())
for _ in range(t):
n = int(input())
arr = list(map(int,input().split()))
narr = dict()
for i in range(n):
narr[arr[i]]=i
arr.sort()
ct=ans=0
for i in range(n):
if i>0 and narr[arr[i]]<narr[arr[i-1]]:
ct=0
ct+=1
ans = max(ct,ans)
print(n-ans)
```
| 7,709 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem.
You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements:
1. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the begin of the array;
2. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the end of the array.
For example, if n = 5, a = [4, 7, 2, 3, 9], then the following sequence of operations can be performed:
* after performing the operation of the first type to the second element, the array a will become [7, 4, 2, 3, 9];
* after performing the operation of the second type to the second element, the array a will become [7, 2, 3, 9, 4].
You can perform operations of any type any number of times in any order.
Find the minimum total number of operations of the first and second type that will make the a array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities a[1] ≤ a[2] ≤ … ≤ a[n].
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases in the test. Then t test cases follow.
Each test case starts with a line containing an integer n (1 ≤ n ≤ 3000) — length of the array a.
Then follow n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9) — an array that needs to be sorted by the given operations. All numbers in the given array are distinct.
The sum of n for all test cases in one test does not exceed 3000.
Output
For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order.
Example
Input
4
5
4 7 2 3 9
5
3 5 8 1 7
5
1 4 5 7 12
4
0 2 1 3
Output
2
2
0
2
Note
In the first test case, you first need to move 3, and then 2 to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 3, 9] → [3, 4, 7, 2, 9] → [2, 3, 4, 7, 9].
In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: [3, 5, 8, 1, 7] → [1, 3, 5, 8, 7] → [1, 3, 5, 7, 8].
In the third test case, the array is already sorted.
Tags: dp, greedy, two pointers
Correct Solution:
```
import sys
input = sys.stdin.readline
import bisect
#1st way
for _ in range(int(input())):
n = int(input())
a = [int(i) for i in input().split()]
b = sorted(a)
d = [0]*(n+1)
#print(a, b)
for i in a:
d[b.index(i)] = 1 + max(d[b.index(i)],d[b.index(i)-1])
#print(d)
print(n-max(d))
```
| 7,710 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem.
You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements:
1. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the begin of the array;
2. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the end of the array.
For example, if n = 5, a = [4, 7, 2, 3, 9], then the following sequence of operations can be performed:
* after performing the operation of the first type to the second element, the array a will become [7, 4, 2, 3, 9];
* after performing the operation of the second type to the second element, the array a will become [7, 2, 3, 9, 4].
You can perform operations of any type any number of times in any order.
Find the minimum total number of operations of the first and second type that will make the a array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities a[1] ≤ a[2] ≤ … ≤ a[n].
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases in the test. Then t test cases follow.
Each test case starts with a line containing an integer n (1 ≤ n ≤ 3000) — length of the array a.
Then follow n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9) — an array that needs to be sorted by the given operations. All numbers in the given array are distinct.
The sum of n for all test cases in one test does not exceed 3000.
Output
For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order.
Example
Input
4
5
4 7 2 3 9
5
3 5 8 1 7
5
1 4 5 7 12
4
0 2 1 3
Output
2
2
0
2
Note
In the first test case, you first need to move 3, and then 2 to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 3, 9] → [3, 4, 7, 2, 9] → [2, 3, 4, 7, 9].
In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: [3, 5, 8, 1, 7] → [1, 3, 5, 8, 7] → [1, 3, 5, 7, 8].
In the third test case, the array is already sorted.
Submitted Solution:
```
tt = int(input())
for loop in range(tt):
n = int(input())
a = list(map(int,input().split()))
ai = []
for i in range(n):
ai.append( ( a[i] , i ) )
ai.sort()
ind = 0
b = [0] * n #newlist
non = [0] * (n+1) #numbers of numbers
for i in range(n):
if i != 0 and ai[i][0] != ai[i-1][0]:
ind += 1
b[ai[i][1]] = ind
non[ind] += 1
dp = [0] * (n+1)
for i in range(n):
dp[b[i]] += max( dp[b[i]] , dp[b[i]-1] + 1)
print (n - max(dp))
```
Yes
| 7,711 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem.
You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements:
1. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the begin of the array;
2. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the end of the array.
For example, if n = 5, a = [4, 7, 2, 3, 9], then the following sequence of operations can be performed:
* after performing the operation of the first type to the second element, the array a will become [7, 4, 2, 3, 9];
* after performing the operation of the second type to the second element, the array a will become [7, 2, 3, 9, 4].
You can perform operations of any type any number of times in any order.
Find the minimum total number of operations of the first and second type that will make the a array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities a[1] ≤ a[2] ≤ … ≤ a[n].
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases in the test. Then t test cases follow.
Each test case starts with a line containing an integer n (1 ≤ n ≤ 3000) — length of the array a.
Then follow n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9) — an array that needs to be sorted by the given operations. All numbers in the given array are distinct.
The sum of n for all test cases in one test does not exceed 3000.
Output
For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order.
Example
Input
4
5
4 7 2 3 9
5
3 5 8 1 7
5
1 4 5 7 12
4
0 2 1 3
Output
2
2
0
2
Note
In the first test case, you first need to move 3, and then 2 to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 3, 9] → [3, 4, 7, 2, 9] → [2, 3, 4, 7, 9].
In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: [3, 5, 8, 1, 7] → [1, 3, 5, 8, 7] → [1, 3, 5, 7, 8].
In the third test case, the array is already sorted.
Submitted Solution:
```
from collections import defaultdict
t = int(input())
for _ in range(t):
n = int(input())
l = list(map(int,input().split()))
l2 = sorted(list(set(l)))
d = defaultdict(int)
ind = [[-1]*2 for i in range(len(l2))]
num = [0]*len(l2)
pos = [0]*len(l2)
for i in range(len(l2)):
d[l2[i]] = i
cl = [-1]
for i in range(n):
x = d[l[i]]
cl.append(x)
num[x] += 1
if ind[x][0] == -1:
ind[x][0] = i+1
ind[x][1] = i+1
dp = [[0]*3 for i in range(n+1)]
for i in range(1,n+1):
x = cl[i]
dp[i][0] = dp[pos[x]][0] + 1
if x == 0:
dp[i][1] = dp[pos[x]][1]+1
else:
dp[i][1] = max(dp[pos[x]][1],dp[pos[x-1]][0],dp[pos[x-1]][2])+1
if i == ind[x][1]:
dp[i][2] = dp[ind[x][0]][1]+num[x]-1
pos[x] = i
ans = 0
for i in dp:
ans = max(ans,max(i))
print(n-ans)
```
Yes
| 7,712 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem.
You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements:
1. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the begin of the array;
2. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the end of the array.
For example, if n = 5, a = [4, 7, 2, 3, 9], then the following sequence of operations can be performed:
* after performing the operation of the first type to the second element, the array a will become [7, 4, 2, 3, 9];
* after performing the operation of the second type to the second element, the array a will become [7, 2, 3, 9, 4].
You can perform operations of any type any number of times in any order.
Find the minimum total number of operations of the first and second type that will make the a array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities a[1] ≤ a[2] ≤ … ≤ a[n].
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases in the test. Then t test cases follow.
Each test case starts with a line containing an integer n (1 ≤ n ≤ 3000) — length of the array a.
Then follow n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9) — an array that needs to be sorted by the given operations. All numbers in the given array are distinct.
The sum of n for all test cases in one test does not exceed 3000.
Output
For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order.
Example
Input
4
5
4 7 2 3 9
5
3 5 8 1 7
5
1 4 5 7 12
4
0 2 1 3
Output
2
2
0
2
Note
In the first test case, you first need to move 3, and then 2 to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 3, 9] → [3, 4, 7, 2, 9] → [2, 3, 4, 7, 9].
In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: [3, 5, 8, 1, 7] → [1, 3, 5, 8, 7] → [1, 3, 5, 7, 8].
In the third test case, the array is already sorted.
Submitted Solution:
```
#!/usr/bin/env python
#pyrival orz
import os
import sys
from io import BytesIO, IOBase
"""
for _ in range(int(input())):
n,m=map(int,input().split())
n=int(input())
a = [int(x) for x in input().split()]
"""
def main():
for _ in range(int(input())):
n=int(input())
a = [int(x) for x in input().split()]
b = [x for x in a]
b.sort()
ans=n
# print(a)
for i in range(len(a)):
cnt=0
j=i
for y in a:
if j < len(b) and y==b[j]:
j+=1
cnt+=1
ans=min(ans,n-cnt)
# print(b[i],a,cnt)
print(ans)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
```
Yes
| 7,713 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem.
You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements:
1. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the begin of the array;
2. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the end of the array.
For example, if n = 5, a = [4, 7, 2, 3, 9], then the following sequence of operations can be performed:
* after performing the operation of the first type to the second element, the array a will become [7, 4, 2, 3, 9];
* after performing the operation of the second type to the second element, the array a will become [7, 2, 3, 9, 4].
You can perform operations of any type any number of times in any order.
Find the minimum total number of operations of the first and second type that will make the a array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities a[1] ≤ a[2] ≤ … ≤ a[n].
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases in the test. Then t test cases follow.
Each test case starts with a line containing an integer n (1 ≤ n ≤ 3000) — length of the array a.
Then follow n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9) — an array that needs to be sorted by the given operations. All numbers in the given array are distinct.
The sum of n for all test cases in one test does not exceed 3000.
Output
For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order.
Example
Input
4
5
4 7 2 3 9
5
3 5 8 1 7
5
1 4 5 7 12
4
0 2 1 3
Output
2
2
0
2
Note
In the first test case, you first need to move 3, and then 2 to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 3, 9] → [3, 4, 7, 2, 9] → [2, 3, 4, 7, 9].
In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: [3, 5, 8, 1, 7] → [1, 3, 5, 8, 7] → [1, 3, 5, 7, 8].
In the third test case, the array is already sorted.
Submitted Solution:
```
t = int(input())
for _ in range(t):
n = int(input())
a = [int(x) for x in input().split()]
# find longest subsequence of consecutive numbers
indices = {}
for i in range(n):
indices[a[i]] = i
ordered = sorted(a)
seq_length = [1]*n
for i in range(1, n):
if indices[ordered[i-1]] < indices[ordered[i]]:
seq_length[i] = seq_length[i-1] + 1
print(n - max(seq_length))
```
Yes
| 7,714 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem.
You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements:
1. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the begin of the array;
2. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the end of the array.
For example, if n = 5, a = [4, 7, 2, 3, 9], then the following sequence of operations can be performed:
* after performing the operation of the first type to the second element, the array a will become [7, 4, 2, 3, 9];
* after performing the operation of the second type to the second element, the array a will become [7, 2, 3, 9, 4].
You can perform operations of any type any number of times in any order.
Find the minimum total number of operations of the first and second type that will make the a array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities a[1] ≤ a[2] ≤ … ≤ a[n].
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases in the test. Then t test cases follow.
Each test case starts with a line containing an integer n (1 ≤ n ≤ 3000) — length of the array a.
Then follow n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9) — an array that needs to be sorted by the given operations. All numbers in the given array are distinct.
The sum of n for all test cases in one test does not exceed 3000.
Output
For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order.
Example
Input
4
5
4 7 2 3 9
5
3 5 8 1 7
5
1 4 5 7 12
4
0 2 1 3
Output
2
2
0
2
Note
In the first test case, you first need to move 3, and then 2 to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 3, 9] → [3, 4, 7, 2, 9] → [2, 3, 4, 7, 9].
In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: [3, 5, 8, 1, 7] → [1, 3, 5, 8, 7] → [1, 3, 5, 7, 8].
In the third test case, the array is already sorted.
Submitted Solution:
```
test = [3,5,8,1,7]
MAX_N = 3000
def ordenado(arr):
for i in range(len(arr)-1):
if(arr[i] > arr[i+1]):
return False
return True
def principio(arr,i):
temp = arr[:]
for p in range(i,0,-1):
temp[p] = temp[p-1]
temp[0] = arr[i]
return temp
def final(arr,i):
temp = arr[:]
for p in range(i,len(arr)-1):
temp[p] = temp[p+1]
temp[-1] = arr[i]
return temp
def solve(arr,i,mov):
if(i >= len(arr)):
return MAX_N
if(mov > len(arr) or ordenado(arr)):
return mov
p = principio(arr,i)
f = final(arr,i)
mov = min(solve(arr,i+1,mov),solve(p,mov+1,mov+1),solve(f,mov+1,mov+1))
return mov
t = int(input())
res = []
for i in range(t):
input() # Numero de numeros
arr = list(map(int,input().split())) #Numeros
res.append(solve(arr,0,0))
for r in res:
print(r)
# print(principio(test,2))
# print(test)
# print(solve(test,0,0))
```
No
| 7,715 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem.
You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements:
1. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the begin of the array;
2. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the end of the array.
For example, if n = 5, a = [4, 7, 2, 3, 9], then the following sequence of operations can be performed:
* after performing the operation of the first type to the second element, the array a will become [7, 4, 2, 3, 9];
* after performing the operation of the second type to the second element, the array a will become [7, 2, 3, 9, 4].
You can perform operations of any type any number of times in any order.
Find the minimum total number of operations of the first and second type that will make the a array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities a[1] ≤ a[2] ≤ … ≤ a[n].
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases in the test. Then t test cases follow.
Each test case starts with a line containing an integer n (1 ≤ n ≤ 3000) — length of the array a.
Then follow n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9) — an array that needs to be sorted by the given operations. All numbers in the given array are distinct.
The sum of n for all test cases in one test does not exceed 3000.
Output
For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order.
Example
Input
4
5
4 7 2 3 9
5
3 5 8 1 7
5
1 4 5 7 12
4
0 2 1 3
Output
2
2
0
2
Note
In the first test case, you first need to move 3, and then 2 to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 3, 9] → [3, 4, 7, 2, 9] → [2, 3, 4, 7, 9].
In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: [3, 5, 8, 1, 7] → [1, 3, 5, 8, 7] → [1, 3, 5, 7, 8].
In the third test case, the array is already sorted.
Submitted Solution:
```
from collections import Counter
import math
import sys
from bisect import bisect,bisect_left,bisect_right
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def mod(): return 10**9+7
for i in range(INT()):
n = INT()
arr = LIST()
arr1 = sorted(arr)
d = {}
ind = 0
for i in arr1:
d[i] = ind
ind += 1
# print(d)
c = []
for i in range(n):
c.append(abs(d[arr[i]]-i))
d1 = {}
for i in c:
if i not in d1:
d1[i] = 1
else:
d1[i] += 1
ans = 0
for i in d1:
ans += d1[i]//2
print(ans)
```
No
| 7,716 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem.
You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements:
1. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the begin of the array;
2. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the end of the array.
For example, if n = 5, a = [4, 7, 2, 3, 9], then the following sequence of operations can be performed:
* after performing the operation of the first type to the second element, the array a will become [7, 4, 2, 3, 9];
* after performing the operation of the second type to the second element, the array a will become [7, 2, 3, 9, 4].
You can perform operations of any type any number of times in any order.
Find the minimum total number of operations of the first and second type that will make the a array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities a[1] ≤ a[2] ≤ … ≤ a[n].
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases in the test. Then t test cases follow.
Each test case starts with a line containing an integer n (1 ≤ n ≤ 3000) — length of the array a.
Then follow n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9) — an array that needs to be sorted by the given operations. All numbers in the given array are distinct.
The sum of n for all test cases in one test does not exceed 3000.
Output
For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order.
Example
Input
4
5
4 7 2 3 9
5
3 5 8 1 7
5
1 4 5 7 12
4
0 2 1 3
Output
2
2
0
2
Note
In the first test case, you first need to move 3, and then 2 to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 3, 9] → [3, 4, 7, 2, 9] → [2, 3, 4, 7, 9].
In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: [3, 5, 8, 1, 7] → [1, 3, 5, 8, 7] → [1, 3, 5, 7, 8].
In the third test case, the array is already sorted.
Submitted Solution:
```
#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
import threading
from math import floor
from bisect import bisect_right
from collections import deque
from math import gcd
mod=998244353
def main():
for _ in range(int(input())):
n=int(input())
arr=list(map(int,input().split()))
s=list(set(arr))
s.sort()
s=list(zip(s,range(0,n)))
ind=dict(s)
last_ind=dict()
for i in range(n):
arr[i]=ind[arr[i]]
if arr[i] in last_ind:
last_ind[arr[i]]=i
else:
last_ind[arr[i]]=-1
# print(arr)
# print(last_ind)
dp=[0]*(len(s)+2)
ans=n
for i in range(n):
# print(i,dp)
if last_ind[arr[i]]==i:
dp[arr[i]]+=1
else:
dp[arr[i]]=1+max(dp[arr[i]],dp[arr[i]-1])
ans=min(ans,n-dp[arr[i]])
# print(dp)
print(ans)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
```
No
| 7,717 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem.
You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements:
1. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the begin of the array;
2. choose any index i (1 ≤ i ≤ n) and move the element a[i] to the end of the array.
For example, if n = 5, a = [4, 7, 2, 3, 9], then the following sequence of operations can be performed:
* after performing the operation of the first type to the second element, the array a will become [7, 4, 2, 3, 9];
* after performing the operation of the second type to the second element, the array a will become [7, 2, 3, 9, 4].
You can perform operations of any type any number of times in any order.
Find the minimum total number of operations of the first and second type that will make the a array sorted in non-decreasing order. In other words, what is the minimum number of operations that must be performed so the array satisfies the inequalities a[1] ≤ a[2] ≤ … ≤ a[n].
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases in the test. Then t test cases follow.
Each test case starts with a line containing an integer n (1 ≤ n ≤ 3000) — length of the array a.
Then follow n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9) — an array that needs to be sorted by the given operations. All numbers in the given array are distinct.
The sum of n for all test cases in one test does not exceed 3000.
Output
For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order.
Example
Input
4
5
4 7 2 3 9
5
3 5 8 1 7
5
1 4 5 7 12
4
0 2 1 3
Output
2
2
0
2
Note
In the first test case, you first need to move 3, and then 2 to the beginning of the array. Therefore, the desired sequence of operations: [4, 7, 2, 3, 9] → [3, 4, 7, 2, 9] → [2, 3, 4, 7, 9].
In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: [3, 5, 8, 1, 7] → [1, 3, 5, 8, 7] → [1, 3, 5, 7, 8].
In the third test case, the array is already sorted.
Submitted Solution:
```
def lengthOfLIS(nums):
if not nums:
return 0
dp=[1]*len(nums)
for i in range(1,len(nums)):
for j in range(i):
if dp[i]<=dp[j]:
if nums[i]>nums[j]:
dp[i]=dp[j]+1
return max(dp)
t=int(input())
while t>0:
n=int(input())
arr=list(map(int,input().split()))
print(lengthOfLIS(arr)-1)
t-=1
```
No
| 7,718 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let LCM(x, y) be the minimum positive integer that is divisible by both x and y. For example, LCM(13, 37) = 481, LCM(9, 6) = 18.
You are given two integers l and r. Find two integers x and y such that l ≤ x < y ≤ r and l ≤ LCM(x, y) ≤ r.
Input
The first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases.
Each test case is represented by one line containing two integers l and r (1 ≤ l < r ≤ 10^9).
Output
For each test case, print two integers:
* if it is impossible to find integers x and y meeting the constraints in the statement, print two integers equal to -1;
* otherwise, print the values of x and y (if there are multiple valid answers, you may print any of them).
Example
Input
4
1 1337
13 69
2 4
88 89
Output
6 7
14 21
2 4
-1 -1
Tags: constructive algorithms, greedy, math, number theory
Correct Solution:
```
t=int(input())
for i in range(t):
l,r=map(int,input().split())
rem=r%l
if (r-rem)!=l:
print(l,r-rem)
else:
print(-1,-1)
```
| 7,719 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let LCM(x, y) be the minimum positive integer that is divisible by both x and y. For example, LCM(13, 37) = 481, LCM(9, 6) = 18.
You are given two integers l and r. Find two integers x and y such that l ≤ x < y ≤ r and l ≤ LCM(x, y) ≤ r.
Input
The first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases.
Each test case is represented by one line containing two integers l and r (1 ≤ l < r ≤ 10^9).
Output
For each test case, print two integers:
* if it is impossible to find integers x and y meeting the constraints in the statement, print two integers equal to -1;
* otherwise, print the values of x and y (if there are multiple valid answers, you may print any of them).
Example
Input
4
1 1337
13 69
2 4
88 89
Output
6 7
14 21
2 4
-1 -1
Tags: constructive algorithms, greedy, math, number theory
Correct Solution:
```
t = int(input())
while(t!=0):
temp = input()
l,r = temp.split()
l = int(l)
r = int(r)
x = -1
y = -1
if r>= 2*l:
x, y = l, 2*l
print(x,y)
t-=1
```
| 7,720 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let LCM(x, y) be the minimum positive integer that is divisible by both x and y. For example, LCM(13, 37) = 481, LCM(9, 6) = 18.
You are given two integers l and r. Find two integers x and y such that l ≤ x < y ≤ r and l ≤ LCM(x, y) ≤ r.
Input
The first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases.
Each test case is represented by one line containing two integers l and r (1 ≤ l < r ≤ 10^9).
Output
For each test case, print two integers:
* if it is impossible to find integers x and y meeting the constraints in the statement, print two integers equal to -1;
* otherwise, print the values of x and y (if there are multiple valid answers, you may print any of them).
Example
Input
4
1 1337
13 69
2 4
88 89
Output
6 7
14 21
2 4
-1 -1
Tags: constructive algorithms, greedy, math, number theory
Correct Solution:
```
from collections import Counter
tests = int(input())
for _ in range(tests):
l, r = map(int, input().split())
# arr = [int(a) for a in input().strip().split(' ')]
x = l
y = 2*l
if y <= r:
print(x, y)
else:
print(-1, -1)
```
| 7,721 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let LCM(x, y) be the minimum positive integer that is divisible by both x and y. For example, LCM(13, 37) = 481, LCM(9, 6) = 18.
You are given two integers l and r. Find two integers x and y such that l ≤ x < y ≤ r and l ≤ LCM(x, y) ≤ r.
Input
The first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases.
Each test case is represented by one line containing two integers l and r (1 ≤ l < r ≤ 10^9).
Output
For each test case, print two integers:
* if it is impossible to find integers x and y meeting the constraints in the statement, print two integers equal to -1;
* otherwise, print the values of x and y (if there are multiple valid answers, you may print any of them).
Example
Input
4
1 1337
13 69
2 4
88 89
Output
6 7
14 21
2 4
-1 -1
Tags: constructive algorithms, greedy, math, number theory
Correct Solution:
```
def calcMinorLCM(a, b, results):
if b < a*2:
results.append(-1)
results.append(-1)
else:
results.append(a)
results.append(a*2)
t = int(input())
results = []
for i in range(t):
[a, b] = list(map(int, input().split(' ')))
calcMinorLCM(a, b, results)
for i in range(int(len(results)/2)):
print(results[2*i], results[2*i+1])
```
| 7,722 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let LCM(x, y) be the minimum positive integer that is divisible by both x and y. For example, LCM(13, 37) = 481, LCM(9, 6) = 18.
You are given two integers l and r. Find two integers x and y such that l ≤ x < y ≤ r and l ≤ LCM(x, y) ≤ r.
Input
The first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases.
Each test case is represented by one line containing two integers l and r (1 ≤ l < r ≤ 10^9).
Output
For each test case, print two integers:
* if it is impossible to find integers x and y meeting the constraints in the statement, print two integers equal to -1;
* otherwise, print the values of x and y (if there are multiple valid answers, you may print any of them).
Example
Input
4
1 1337
13 69
2 4
88 89
Output
6 7
14 21
2 4
-1 -1
Tags: constructive algorithms, greedy, math, number theory
Correct Solution:
```
t = int(input())
for _ in range(t):
l, r = [int(s) for s in input().split()]
if r < l + l:
print(-1, -1)
else:
print(l, l + l)
```
| 7,723 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let LCM(x, y) be the minimum positive integer that is divisible by both x and y. For example, LCM(13, 37) = 481, LCM(9, 6) = 18.
You are given two integers l and r. Find two integers x and y such that l ≤ x < y ≤ r and l ≤ LCM(x, y) ≤ r.
Input
The first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases.
Each test case is represented by one line containing two integers l and r (1 ≤ l < r ≤ 10^9).
Output
For each test case, print two integers:
* if it is impossible to find integers x and y meeting the constraints in the statement, print two integers equal to -1;
* otherwise, print the values of x and y (if there are multiple valid answers, you may print any of them).
Example
Input
4
1 1337
13 69
2 4
88 89
Output
6 7
14 21
2 4
-1 -1
Tags: constructive algorithms, greedy, math, number theory
Correct Solution:
```
t=int(input())
for _ in range(t):
l,r=map(int,input().split())
if r>=2*l:
print(l,2*l)
else:
print(-1,-1)
```
| 7,724 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let LCM(x, y) be the minimum positive integer that is divisible by both x and y. For example, LCM(13, 37) = 481, LCM(9, 6) = 18.
You are given two integers l and r. Find two integers x and y such that l ≤ x < y ≤ r and l ≤ LCM(x, y) ≤ r.
Input
The first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases.
Each test case is represented by one line containing two integers l and r (1 ≤ l < r ≤ 10^9).
Output
For each test case, print two integers:
* if it is impossible to find integers x and y meeting the constraints in the statement, print two integers equal to -1;
* otherwise, print the values of x and y (if there are multiple valid answers, you may print any of them).
Example
Input
4
1 1337
13 69
2 4
88 89
Output
6 7
14 21
2 4
-1 -1
Tags: constructive algorithms, greedy, math, number theory
Correct Solution:
```
t = int(input())
for _ in range(t):
l,r = map(int, input().split())
x, y = l, l*2
if y > r:
print(-1, -1)
else:
print(x, y)
```
| 7,725 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let LCM(x, y) be the minimum positive integer that is divisible by both x and y. For example, LCM(13, 37) = 481, LCM(9, 6) = 18.
You are given two integers l and r. Find two integers x and y such that l ≤ x < y ≤ r and l ≤ LCM(x, y) ≤ r.
Input
The first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases.
Each test case is represented by one line containing two integers l and r (1 ≤ l < r ≤ 10^9).
Output
For each test case, print two integers:
* if it is impossible to find integers x and y meeting the constraints in the statement, print two integers equal to -1;
* otherwise, print the values of x and y (if there are multiple valid answers, you may print any of them).
Example
Input
4
1 1337
13 69
2 4
88 89
Output
6 7
14 21
2 4
-1 -1
Tags: constructive algorithms, greedy, math, number theory
Correct Solution:
```
for _ in range(int(input())):
L, R = map(int, input().split())
if 2*L > R:
print(-1, -1)
else:
print(L, 2*L)
```
| 7,726 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let LCM(x, y) be the minimum positive integer that is divisible by both x and y. For example, LCM(13, 37) = 481, LCM(9, 6) = 18.
You are given two integers l and r. Find two integers x and y such that l ≤ x < y ≤ r and l ≤ LCM(x, y) ≤ r.
Input
The first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases.
Each test case is represented by one line containing two integers l and r (1 ≤ l < r ≤ 10^9).
Output
For each test case, print two integers:
* if it is impossible to find integers x and y meeting the constraints in the statement, print two integers equal to -1;
* otherwise, print the values of x and y (if there are multiple valid answers, you may print any of them).
Example
Input
4
1 1337
13 69
2 4
88 89
Output
6 7
14 21
2 4
-1 -1
Submitted Solution:
```
from math import *
sInt = lambda: int(input())
mInt = lambda: map(int, input().split())
lInt = lambda: list(map(int, input().split()))
t = sInt()
for _ in range(t):
n,m = mInt()
if 2*n<=m:
print(n,2*n)
else:
print(-1,-1)
```
Yes
| 7,727 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let LCM(x, y) be the minimum positive integer that is divisible by both x and y. For example, LCM(13, 37) = 481, LCM(9, 6) = 18.
You are given two integers l and r. Find two integers x and y such that l ≤ x < y ≤ r and l ≤ LCM(x, y) ≤ r.
Input
The first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases.
Each test case is represented by one line containing two integers l and r (1 ≤ l < r ≤ 10^9).
Output
For each test case, print two integers:
* if it is impossible to find integers x and y meeting the constraints in the statement, print two integers equal to -1;
* otherwise, print the values of x and y (if there are multiple valid answers, you may print any of them).
Example
Input
4
1 1337
13 69
2 4
88 89
Output
6 7
14 21
2 4
-1 -1
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().rstrip("\r\n")
# ------------------------------
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def print_list(l):
print(' '.join(map(str,l)))
# import heapq as hq
# import bisect as bs
# from collections import deque as dq
# from collections import defaultdict as dc
# from math import ceil,floor,sqrt
# from collections import Counter
for _ in range(N()):
l,r = RL()
if r<l*2:
print(-1,-1)
else:
print(l,l*2)
```
Yes
| 7,728 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let LCM(x, y) be the minimum positive integer that is divisible by both x and y. For example, LCM(13, 37) = 481, LCM(9, 6) = 18.
You are given two integers l and r. Find two integers x and y such that l ≤ x < y ≤ r and l ≤ LCM(x, y) ≤ r.
Input
The first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases.
Each test case is represented by one line containing two integers l and r (1 ≤ l < r ≤ 10^9).
Output
For each test case, print two integers:
* if it is impossible to find integers x and y meeting the constraints in the statement, print two integers equal to -1;
* otherwise, print the values of x and y (if there are multiple valid answers, you may print any of them).
Example
Input
4
1 1337
13 69
2 4
88 89
Output
6 7
14 21
2 4
-1 -1
Submitted Solution:
```
for _ in range(int(input())):
l,r=map(int,input().split())
c=0
while 2*l<r+1:
if 2*l<=r:
print(l,l*2)
c=1
break
l+=1
if c==0:
print("-1 -1")
```
Yes
| 7,729 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let LCM(x, y) be the minimum positive integer that is divisible by both x and y. For example, LCM(13, 37) = 481, LCM(9, 6) = 18.
You are given two integers l and r. Find two integers x and y such that l ≤ x < y ≤ r and l ≤ LCM(x, y) ≤ r.
Input
The first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases.
Each test case is represented by one line containing two integers l and r (1 ≤ l < r ≤ 10^9).
Output
For each test case, print two integers:
* if it is impossible to find integers x and y meeting the constraints in the statement, print two integers equal to -1;
* otherwise, print the values of x and y (if there are multiple valid answers, you may print any of them).
Example
Input
4
1 1337
13 69
2 4
88 89
Output
6 7
14 21
2 4
-1 -1
Submitted Solution:
```
for s in[*open(0)][1:]:l,r=map(int,s.split());print(*([l,2*l],[-1]*2)[r<2*l])
```
Yes
| 7,730 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let LCM(x, y) be the minimum positive integer that is divisible by both x and y. For example, LCM(13, 37) = 481, LCM(9, 6) = 18.
You are given two integers l and r. Find two integers x and y such that l ≤ x < y ≤ r and l ≤ LCM(x, y) ≤ r.
Input
The first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases.
Each test case is represented by one line containing two integers l and r (1 ≤ l < r ≤ 10^9).
Output
For each test case, print two integers:
* if it is impossible to find integers x and y meeting the constraints in the statement, print two integers equal to -1;
* otherwise, print the values of x and y (if there are multiple valid answers, you may print any of them).
Example
Input
4
1 1337
13 69
2 4
88 89
Output
6 7
14 21
2 4
-1 -1
Submitted Solution:
```
for i in range (int(input())):
m,n=map(int,input().split())
if n%m==0:
print(m,n)
elif (m+1)*2 <=n:
print(m+1,(m+1)*2)
else:
print(-1,-1)
```
No
| 7,731 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let LCM(x, y) be the minimum positive integer that is divisible by both x and y. For example, LCM(13, 37) = 481, LCM(9, 6) = 18.
You are given two integers l and r. Find two integers x and y such that l ≤ x < y ≤ r and l ≤ LCM(x, y) ≤ r.
Input
The first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases.
Each test case is represented by one line containing two integers l and r (1 ≤ l < r ≤ 10^9).
Output
For each test case, print two integers:
* if it is impossible to find integers x and y meeting the constraints in the statement, print two integers equal to -1;
* otherwise, print the values of x and y (if there are multiple valid answers, you may print any of them).
Example
Input
4
1 1337
13 69
2 4
88 89
Output
6 7
14 21
2 4
-1 -1
Submitted Solution:
```
import math
for i in range(int(input())):
a,b=map(int,input().split())
if a%2==0:
x=a
y=a+1
else:
x=a+1
y=a+2
while y<=b:
if (x*y)//math.gcd(x,y)<=b:
print(x,y)
break
if y>=b:
print("-1","-1")
break
else:
y+=1
```
No
| 7,732 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let LCM(x, y) be the minimum positive integer that is divisible by both x and y. For example, LCM(13, 37) = 481, LCM(9, 6) = 18.
You are given two integers l and r. Find two integers x and y such that l ≤ x < y ≤ r and l ≤ LCM(x, y) ≤ r.
Input
The first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases.
Each test case is represented by one line containing two integers l and r (1 ≤ l < r ≤ 10^9).
Output
For each test case, print two integers:
* if it is impossible to find integers x and y meeting the constraints in the statement, print two integers equal to -1;
* otherwise, print the values of x and y (if there are multiple valid answers, you may print any of them).
Example
Input
4
1 1337
13 69
2 4
88 89
Output
6 7
14 21
2 4
-1 -1
Submitted Solution:
```
t = int(input())
def gcd(a, b):
while b != 0:
t = b
b = a % b
a = t
return a
def lcm(x, y):
return x / gcd(x, y) * y
for kkk in range(t):
s = [int(i) for i in input().split()]
l, r = s[0], s[1]
x = l
y = x + 1
while 1:
if lcm(x, y) > r:
y+=1
if y > (l+r)//2 + 1:
x+=1
y = x + 1
else:
print(x, y)
break
if x>(l+r)//2:
print("-1 -1")
break
```
No
| 7,733 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let LCM(x, y) be the minimum positive integer that is divisible by both x and y. For example, LCM(13, 37) = 481, LCM(9, 6) = 18.
You are given two integers l and r. Find two integers x and y such that l ≤ x < y ≤ r and l ≤ LCM(x, y) ≤ r.
Input
The first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases.
Each test case is represented by one line containing two integers l and r (1 ≤ l < r ≤ 10^9).
Output
For each test case, print two integers:
* if it is impossible to find integers x and y meeting the constraints in the statement, print two integers equal to -1;
* otherwise, print the values of x and y (if there are multiple valid answers, you may print any of them).
Example
Input
4
1 1337
13 69
2 4
88 89
Output
6 7
14 21
2 4
-1 -1
Submitted Solution:
```
def gcd(a,b):
while b > 0:
a, b = b, a % b
return a
def lcm(a, b):
return a * b / gcd(a, b)
n = int(input())
for times in range(n):
l,r = map(int, input().split(" "))
first = l
second = first + 1
last = lcm(first, second)
while last > r:
second += 1
if second > r:
break
last = lcm(first, second)
if second <= r:
print(first,second)
else:
print(str(-1))
```
No
| 7,734 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The only line of the test case contains two integers n and s (1 ≤ n ≤ 10^{18}; 1 ≤ s ≤ 162).
Output
For each test case, print the answer: the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
Example
Input
5
2 1
1 1
500 4
217871987498122 10
100000000000000001 1
Output
8
0
500
2128012501878
899999999999999999
Tags: greedy, math
Correct Solution:
```
ans = ""
for i in range(int(input())):
n, m = [int(s) for s in input().split()]
a = (m - (n % m)) % m
ans += str(a) + "\n"
print(ans)
```
| 7,735 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The only line of the test case contains two integers n and s (1 ≤ n ≤ 10^{18}; 1 ≤ s ≤ 162).
Output
For each test case, print the answer: the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
Example
Input
5
2 1
1 1
500 4
217871987498122 10
100000000000000001 1
Output
8
0
500
2128012501878
899999999999999999
Tags: greedy, math
Correct Solution:
```
T = int(input())
for t in range(T):
n, s = input().split()
fixn = n
n_list = [0] + [int(i) for i in n]
m = len(n_list)
s = int(s)
cur_sum = sum(n_list)
ans = 0
right_pointer = m-1
while cur_sum > s:
while n_list[right_pointer] == 0:
right_pointer -= 1
# now i stop at the first non-zero
n_list[right_pointer-1] += 1
n_list[right_pointer] = 0
new_pointer = right_pointer -1
while n_list[new_pointer] >= 10:
n_list[new_pointer] %= 10
n_list[new_pointer-1] += 1
new_pointer -= 1
cur_sum = sum(n_list)
# now evaluate the difference
tmp = 0
for i in range(m):
tmp *= 10
tmp += n_list[i]
print(tmp - int(fixn))
```
| 7,736 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The only line of the test case contains two integers n and s (1 ≤ n ≤ 10^{18}; 1 ≤ s ≤ 162).
Output
For each test case, print the answer: the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
Example
Input
5
2 1
1 1
500 4
217871987498122 10
100000000000000001 1
Output
8
0
500
2128012501878
899999999999999999
Tags: greedy, math
Correct Solution:
```
T=int(input())
for t in range(T):
a,b=map(int,input().split())
f=a//b
if a%b==0:
print(0)
else:
print(b*(f+1)-a)
```
| 7,737 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The only line of the test case contains two integers n and s (1 ≤ n ≤ 10^{18}; 1 ≤ s ≤ 162).
Output
For each test case, print the answer: the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
Example
Input
5
2 1
1 1
500 4
217871987498122 10
100000000000000001 1
Output
8
0
500
2128012501878
899999999999999999
Tags: greedy, math
Correct Solution:
```
import sys
input = sys.stdin.readline
sm = lambda x: sum(map(int, str(x)))
for _ in range(int(input())):
n, s = map(int, input().split())
res = 0
while sm(n) > s:
t = 0
while n % pow(10, t) == 0: t += 1
d = -n % pow(10, t)
res += d
n += d
print(res)
```
| 7,738 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The only line of the test case contains two integers n and s (1 ≤ n ≤ 10^{18}; 1 ≤ s ≤ 162).
Output
For each test case, print the answer: the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
Example
Input
5
2 1
1 1
500 4
217871987498122 10
100000000000000001 1
Output
8
0
500
2128012501878
899999999999999999
Tags: greedy, math
Correct Solution:
```
n = int(input())
c = []
for i in range(n):
a, b = input().split()
a, b = int(a), int(b)
if a % b != 0:
c.append(b - a % b)
else:
c.append(0)
for i in c:
print(i)
```
| 7,739 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The only line of the test case contains two integers n and s (1 ≤ n ≤ 10^{18}; 1 ≤ s ≤ 162).
Output
For each test case, print the answer: the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
Example
Input
5
2 1
1 1
500 4
217871987498122 10
100000000000000001 1
Output
8
0
500
2128012501878
899999999999999999
Tags: greedy, math
Correct Solution:
```
R = lambda:map(int,input().split())
t = int(input())
for _ in range(t):
a,b = R()
if a%b == 0: print (0)
else: print ( b - a%b)
```
| 7,740 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The only line of the test case contains two integers n and s (1 ≤ n ≤ 10^{18}; 1 ≤ s ≤ 162).
Output
For each test case, print the answer: the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
Example
Input
5
2 1
1 1
500 4
217871987498122 10
100000000000000001 1
Output
8
0
500
2128012501878
899999999999999999
Tags: greedy, math
Correct Solution:
```
# cook your dish here
t=int(input())
for _ in range(t):
a,b=map(int,input().split())
f=1
if a%b==0:
f=0
print("0")
elif a<b:
f=0
print(b-a)
if f==1:
n=a//b
n+=1
d=b*n
print(d-a)
```
| 7,741 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The only line of the test case contains two integers n and s (1 ≤ n ≤ 10^{18}; 1 ≤ s ≤ 162).
Output
For each test case, print the answer: the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
Example
Input
5
2 1
1 1
500 4
217871987498122 10
100000000000000001 1
Output
8
0
500
2128012501878
899999999999999999
Tags: greedy, math
Correct Solution:
```
def get_x(n):
x=0
while(n>0):
x+=n%10
n=n//10
return x
def find(k, s):
pos = 1
init = get_x(k)
n=0
while(init > s):
n += pos*(10-k%10)
pos*=10
k = k//10 + 1
init = get_x(k)
return n
for i in range(int(input())):
k, s = [int(j) for j in input().split()]
print(find(k,s))
```
| 7,742 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The only line of the test case contains two integers n and s (1 ≤ n ≤ 10^{18}; 1 ≤ s ≤ 162).
Output
For each test case, print the answer: the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
Example
Input
5
2 1
1 1
500 4
217871987498122 10
100000000000000001 1
Output
8
0
500
2128012501878
899999999999999999
Submitted Solution:
```
t=int(input())
c=0
for i in range(0,t):
a,b=input().split()
a=int(a)
b=int(b)
c=0
if(a%b==0):
c=0
else:
c=b-(a%b)
print(c)
```
Yes
| 7,743 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The only line of the test case contains two integers n and s (1 ≤ n ≤ 10^{18}; 1 ≤ s ≤ 162).
Output
For each test case, print the answer: the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
Example
Input
5
2 1
1 1
500 4
217871987498122 10
100000000000000001 1
Output
8
0
500
2128012501878
899999999999999999
Submitted Solution:
```
T = int(input())
for i in range(T):
a, b = map(int, input().split())
div = int(a/b)
if a % b == 0:
print(0)
continue
else:
print((div + 1) * b - a)
```
Yes
| 7,744 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The only line of the test case contains two integers n and s (1 ≤ n ≤ 10^{18}; 1 ≤ s ≤ 162).
Output
For each test case, print the answer: the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
Example
Input
5
2 1
1 1
500 4
217871987498122 10
100000000000000001 1
Output
8
0
500
2128012501878
899999999999999999
Submitted Solution:
```
from datetime import datetime
instanteInicial = datetime.now()
instanteFinal = datetime.now()
testcases = input()
testcases = int(testcases)
for i in range (testcases):
entrada = input().split(" ")
a = int(entrada[0])
b = int(entrada[1])
if a % b == 0:
print(0)
continue
moves = 0
first = True
status = ((a // b) + 1) * b
print(status - a)
```
Yes
| 7,745 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The only line of the test case contains two integers n and s (1 ≤ n ≤ 10^{18}; 1 ≤ s ≤ 162).
Output
For each test case, print the answer: the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
Example
Input
5
2 1
1 1
500 4
217871987498122 10
100000000000000001 1
Output
8
0
500
2128012501878
899999999999999999
Submitted Solution:
```
t = int(input())
for i in range(t):
a, b = list(map(int, input().split()))
if a % b == 0:
print(0)
else:
div = a % b
print(b-div)
```
Yes
| 7,746 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The only line of the test case contains two integers n and s (1 ≤ n ≤ 10^{18}; 1 ≤ s ≤ 162).
Output
For each test case, print the answer: the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
Example
Input
5
2 1
1 1
500 4
217871987498122 10
100000000000000001 1
Output
8
0
500
2128012501878
899999999999999999
Submitted Solution:
```
import sys
import argparse
def main():
for _ in(range(int(input()))):
ns = list(map(int,input().split()))
n, s = ns
ss = str(n)
l = "1" + len(ss) * "0"
l = int(l)
steps = l - n
ss = list(map(int,list(ss)))
lss = len(ss)
if sum(ss) == s:
print('0')
else:
strx = ""
tmpsum = 0
for i in range(0,lss):
for j in range(ss[i]+1, 9):
tmp = strx + str(j) + "0" * (lss-i-1)
tmp = int(tmp)
tsum = tmpsum + j
if tsum < s:
steps = min(steps, tmp - n)
strx += str(ss[i])
tmpsum += ss[i]
print(steps)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--file', dest='filename', default=None)
args = parser.parse_args()
if args.filename is not None:
sys.stdin = open(args.filename)
main()
```
No
| 7,747 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The only line of the test case contains two integers n and s (1 ≤ n ≤ 10^{18}; 1 ≤ s ≤ 162).
Output
For each test case, print the answer: the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
Example
Input
5
2 1
1 1
500 4
217871987498122 10
100000000000000001 1
Output
8
0
500
2128012501878
899999999999999999
Submitted Solution:
```
for i in range(int(input())):
(a, b) = map(int, input().split(' '))
c = 0
if a==b:
c+=1
else:
while(1):
if a%b == 0:
break
else:
a += 1
c += 1
print(c)
print(c)
```
No
| 7,748 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The only line of the test case contains two integers n and s (1 ≤ n ≤ 10^{18}; 1 ≤ s ≤ 162).
Output
For each test case, print the answer: the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
Example
Input
5
2 1
1 1
500 4
217871987498122 10
100000000000000001 1
Output
8
0
500
2128012501878
899999999999999999
Submitted Solution:
```
print(input())
```
No
| 7,749 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The only line of the test case contains two integers n and s (1 ≤ n ≤ 10^{18}; 1 ≤ s ≤ 162).
Output
For each test case, print the answer: the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
Example
Input
5
2 1
1 1
500 4
217871987498122 10
100000000000000001 1
Output
8
0
500
2128012501878
899999999999999999
Submitted Solution:
```
for i in range(int(input())):
n,s=map(int,input().split())
a=[]
while (n>0):
a.append(n%10)
n=n//10
a=a[::-1]
if sum(a)==s:
print(0)
else:
tm=0
for j in range(len(a)):
tm+=a[j]
if tm>=s:
tm-=a[j]
break
if (True):
an=[]
f=0
for p in range(len(a)-1,j-1,-1):
if f==1:
an.append(str((10-a[p]-1)%10))
else:
an.append(str((10-a[p])%10))
if a[p]>0:
f=1
print(''.join(an[::-1]))
```
No
| 7,750 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have n barrels lined up in a row, numbered from left to right from one. Initially, the i-th barrel contains a_i liters of water.
You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels x and y (the x-th barrel shouldn't be empty) and pour any possible amount of water from barrel x to barrel y (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them.
Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most k times.
Some examples:
* if you have four barrels, each containing 5 liters of water, and k = 1, you may pour 5 liters from the second barrel into the fourth, so the amounts of water in the barrels are [5, 0, 5, 10], and the difference between the maximum and the minimum is 10;
* if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still 0.
Input
The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of each test case contains two integers n and k (1 ≤ k < n ≤ 2 ⋅ 10^5) — the number of barrels and the number of pourings you can make.
The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{9}), where a_i is the initial amount of water the i-th barrel has.
It's guaranteed that the total sum of n over test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most k times.
Example
Input
2
4 1
5 5 5 5
3 2
0 0 0
Output
10
0
Tags: greedy, implementation, sortings
Correct Solution:
```
for _ in range(int(input())):
n,k = input().split()
lis=list(map(int, input().split()))
lis.sort(reverse=True)
for i in range(1,int(k)+1):
if(i<int(n)):
lis[0]+=lis[i]
print(lis[0])
```
| 7,751 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have n barrels lined up in a row, numbered from left to right from one. Initially, the i-th barrel contains a_i liters of water.
You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels x and y (the x-th barrel shouldn't be empty) and pour any possible amount of water from barrel x to barrel y (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them.
Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most k times.
Some examples:
* if you have four barrels, each containing 5 liters of water, and k = 1, you may pour 5 liters from the second barrel into the fourth, so the amounts of water in the barrels are [5, 0, 5, 10], and the difference between the maximum and the minimum is 10;
* if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still 0.
Input
The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of each test case contains two integers n and k (1 ≤ k < n ≤ 2 ⋅ 10^5) — the number of barrels and the number of pourings you can make.
The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{9}), where a_i is the initial amount of water the i-th barrel has.
It's guaranteed that the total sum of n over test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most k times.
Example
Input
2
4 1
5 5 5 5
3 2
0 0 0
Output
10
0
Tags: greedy, implementation, sortings
Correct Solution:
```
from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush,heappop
import math
from collections import *
from functools import reduce,cmp_to_key,lru_cache
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
# import sys
# input = sys.stdin.readline
M = mod = 10**9 + 7
def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
def inv_mod(n):return pow(n, mod - 2, mod)
def li():return [int(i) for i in input().rstrip().split()]
def st():return str(input().rstrip())[2:-1]
def val():return int(input().rstrip())
def li2():return [str(i)[2:-1] for i in input().rstrip().split()]
def li3():return [int(i) for i in st()]
for _ in range(val()):
n, k = li()
l = sorted(li())
for i in range(k):
l[-1] += l[n - i - 2]
print(l[-1])
```
| 7,752 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have n barrels lined up in a row, numbered from left to right from one. Initially, the i-th barrel contains a_i liters of water.
You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels x and y (the x-th barrel shouldn't be empty) and pour any possible amount of water from barrel x to barrel y (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them.
Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most k times.
Some examples:
* if you have four barrels, each containing 5 liters of water, and k = 1, you may pour 5 liters from the second barrel into the fourth, so the amounts of water in the barrels are [5, 0, 5, 10], and the difference between the maximum and the minimum is 10;
* if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still 0.
Input
The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of each test case contains two integers n and k (1 ≤ k < n ≤ 2 ⋅ 10^5) — the number of barrels and the number of pourings you can make.
The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{9}), where a_i is the initial amount of water the i-th barrel has.
It's guaranteed that the total sum of n over test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most k times.
Example
Input
2
4 1
5 5 5 5
3 2
0 0 0
Output
10
0
Tags: greedy, implementation, sortings
Correct Solution:
```
import sys
import heapq
input = sys.stdin.readline
def main():
t = int(input())
for _ in range(t):
N, K = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
A.sort(reverse=True)
ans = 0
for i in range(min(N, K + 1)):
ans += A[i]
print(ans)
if __name__ == '__main__':
main()
```
| 7,753 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have n barrels lined up in a row, numbered from left to right from one. Initially, the i-th barrel contains a_i liters of water.
You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels x and y (the x-th barrel shouldn't be empty) and pour any possible amount of water from barrel x to barrel y (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them.
Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most k times.
Some examples:
* if you have four barrels, each containing 5 liters of water, and k = 1, you may pour 5 liters from the second barrel into the fourth, so the amounts of water in the barrels are [5, 0, 5, 10], and the difference between the maximum and the minimum is 10;
* if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still 0.
Input
The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of each test case contains two integers n and k (1 ≤ k < n ≤ 2 ⋅ 10^5) — the number of barrels and the number of pourings you can make.
The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{9}), where a_i is the initial amount of water the i-th barrel has.
It's guaranteed that the total sum of n over test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most k times.
Example
Input
2
4 1
5 5 5 5
3 2
0 0 0
Output
10
0
Tags: greedy, implementation, sortings
Correct Solution:
```
from sys import stdin
def barrels(k, a):
score, *a = sorted(a)[::-1]
for i in range(k):
if i > len(a) - 1:
break
score += a[i]
print(score)
if __name__ == "__main__":
t = int(stdin.readline())
cases = []
for _ in range(t):
n, k = (int(s) for s in stdin.readline().split())
a = [int(s) for s in stdin.readline().split()]
cases.append((k, a))
for c in cases:
barrels(*c)
```
| 7,754 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have n barrels lined up in a row, numbered from left to right from one. Initially, the i-th barrel contains a_i liters of water.
You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels x and y (the x-th barrel shouldn't be empty) and pour any possible amount of water from barrel x to barrel y (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them.
Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most k times.
Some examples:
* if you have four barrels, each containing 5 liters of water, and k = 1, you may pour 5 liters from the second barrel into the fourth, so the amounts of water in the barrels are [5, 0, 5, 10], and the difference between the maximum and the minimum is 10;
* if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still 0.
Input
The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of each test case contains two integers n and k (1 ≤ k < n ≤ 2 ⋅ 10^5) — the number of barrels and the number of pourings you can make.
The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{9}), where a_i is the initial amount of water the i-th barrel has.
It's guaranteed that the total sum of n over test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most k times.
Example
Input
2
4 1
5 5 5 5
3 2
0 0 0
Output
10
0
Tags: greedy, implementation, sortings
Correct Solution:
```
t = int(input())
for i in range(t):
n, k = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
s = 0
for j in range(n - k - 1, n):
s += a[j]
print(s)
```
| 7,755 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have n barrels lined up in a row, numbered from left to right from one. Initially, the i-th barrel contains a_i liters of water.
You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels x and y (the x-th barrel shouldn't be empty) and pour any possible amount of water from barrel x to barrel y (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them.
Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most k times.
Some examples:
* if you have four barrels, each containing 5 liters of water, and k = 1, you may pour 5 liters from the second barrel into the fourth, so the amounts of water in the barrels are [5, 0, 5, 10], and the difference between the maximum and the minimum is 10;
* if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still 0.
Input
The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of each test case contains two integers n and k (1 ≤ k < n ≤ 2 ⋅ 10^5) — the number of barrels and the number of pourings you can make.
The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{9}), where a_i is the initial amount of water the i-th barrel has.
It's guaranteed that the total sum of n over test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most k times.
Example
Input
2
4 1
5 5 5 5
3 2
0 0 0
Output
10
0
Tags: greedy, implementation, sortings
Correct Solution:
```
from sys import stdin, stdout
import math,sys,heapq
from itertools import permutations, combinations
from collections import defaultdict,deque,OrderedDict
from os import path
import random
import bisect as bi
def yes():print('YES')
def no():print('NO')
if (path.exists('input.txt')):
#------------------Sublime--------------------------------------#
sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w');
def I():return (int(input()))
def In():return(map(int,input().split()))
else:
#------------------PYPY FAst I/o--------------------------------#
def I():return (int(stdin.readline()))
def In():return(map(int,stdin.readline().split()))
#sys.setrecursionlimit(1500)
def dict(a):
d={}
for x in a:
if d.get(x,-1)!=-1:
d[x]+=1
else:
d[x]=1
return d
def find_gt(a, x):
'Find leftmost value greater than x'
i = bi.bisect_left(a, x)
if i != len(a):
return i
else:
return -1
def main():
try:
n,k=In()
l=list(In())
cnt=0
su=0
l.sort(reverse=True)
temp=[]
for x in range(1,n):
if l[x]!=0:
if k:
su+=l[x]
k-=1
else:
break
print(l[0]+su)
except:
pass
M = 998244353
P = 1000000007
if __name__ == '__main__':
for _ in range(I()):main()
#for _ in range(1):main()
```
| 7,756 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have n barrels lined up in a row, numbered from left to right from one. Initially, the i-th barrel contains a_i liters of water.
You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels x and y (the x-th barrel shouldn't be empty) and pour any possible amount of water from barrel x to barrel y (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them.
Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most k times.
Some examples:
* if you have four barrels, each containing 5 liters of water, and k = 1, you may pour 5 liters from the second barrel into the fourth, so the amounts of water in the barrels are [5, 0, 5, 10], and the difference between the maximum and the minimum is 10;
* if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still 0.
Input
The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of each test case contains two integers n and k (1 ≤ k < n ≤ 2 ⋅ 10^5) — the number of barrels and the number of pourings you can make.
The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{9}), where a_i is the initial amount of water the i-th barrel has.
It's guaranteed that the total sum of n over test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most k times.
Example
Input
2
4 1
5 5 5 5
3 2
0 0 0
Output
10
0
Tags: greedy, implementation, sortings
Correct Solution:
```
from math import gcd
from sys import stdout,stdin
for _ in range(int(stdin.readline())):
n,k = map(int,input().split())
ls = [int(x) for x in input().split()]
ls = sorted(ls,reverse=True)
s =0
pref =[]
for i in ls:
s+=i
pref.append(s)
#print(pref)
print(pref[k])
```
| 7,757 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have n barrels lined up in a row, numbered from left to right from one. Initially, the i-th barrel contains a_i liters of water.
You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels x and y (the x-th barrel shouldn't be empty) and pour any possible amount of water from barrel x to barrel y (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them.
Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most k times.
Some examples:
* if you have four barrels, each containing 5 liters of water, and k = 1, you may pour 5 liters from the second barrel into the fourth, so the amounts of water in the barrels are [5, 0, 5, 10], and the difference between the maximum and the minimum is 10;
* if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still 0.
Input
The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of each test case contains two integers n and k (1 ≤ k < n ≤ 2 ⋅ 10^5) — the number of barrels and the number of pourings you can make.
The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{9}), where a_i is the initial amount of water the i-th barrel has.
It's guaranteed that the total sum of n over test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most k times.
Example
Input
2
4 1
5 5 5 5
3 2
0 0 0
Output
10
0
Tags: greedy, implementation, sortings
Correct Solution:
```
from math import *
t=int(input())
while t:
t=t-1
n,k=map(int,input().split())
#n=int(input())
a=list(map(int,input().split()))
#
#s=input()
a.sort()
j=n-2
for i in range(k):
a[n-1]+=a[j]
j=j-1
print(a[n-1])
```
| 7,758 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have n barrels lined up in a row, numbered from left to right from one. Initially, the i-th barrel contains a_i liters of water.
You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels x and y (the x-th barrel shouldn't be empty) and pour any possible amount of water from barrel x to barrel y (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them.
Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most k times.
Some examples:
* if you have four barrels, each containing 5 liters of water, and k = 1, you may pour 5 liters from the second barrel into the fourth, so the amounts of water in the barrels are [5, 0, 5, 10], and the difference between the maximum and the minimum is 10;
* if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still 0.
Input
The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of each test case contains two integers n and k (1 ≤ k < n ≤ 2 ⋅ 10^5) — the number of barrels and the number of pourings you can make.
The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{9}), where a_i is the initial amount of water the i-th barrel has.
It's guaranteed that the total sum of n over test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most k times.
Example
Input
2
4 1
5 5 5 5
3 2
0 0 0
Output
10
0
Submitted Solution:
```
import sys
infile = sys.stdin
next(infile)
for line in infile:
l1 = list(map(int,line.split()))
n = l1[0]
k = l1[1]
l2 = list(map(int,infile.readline().split()))
l2.sort()
if l2[-1] == 0:
print(0)
else:
ans = 0
n = min(len(l2),k+1)
for i in range(n):
ans += l2[len(l2)-1-i]
print(ans)
```
Yes
| 7,759 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have n barrels lined up in a row, numbered from left to right from one. Initially, the i-th barrel contains a_i liters of water.
You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels x and y (the x-th barrel shouldn't be empty) and pour any possible amount of water from barrel x to barrel y (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them.
Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most k times.
Some examples:
* if you have four barrels, each containing 5 liters of water, and k = 1, you may pour 5 liters from the second barrel into the fourth, so the amounts of water in the barrels are [5, 0, 5, 10], and the difference between the maximum and the minimum is 10;
* if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still 0.
Input
The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of each test case contains two integers n and k (1 ≤ k < n ≤ 2 ⋅ 10^5) — the number of barrels and the number of pourings you can make.
The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{9}), where a_i is the initial amount of water the i-th barrel has.
It's guaranteed that the total sum of n over test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most k times.
Example
Input
2
4 1
5 5 5 5
3 2
0 0 0
Output
10
0
Submitted Solution:
```
def func2( number ):
if number == 1:
return ( -1, 0, 0 )
if number == 2:
return ( -1, 0, 0 )
if number == 3:
return ( 0, 0, 1 )
if number == 4:
return ( -1, 0, 0 )
if number == 5:
return ( 0, 1, 0 )
if number == 6:
return ( 0, 0, 2 )
if number == 7:
return ( 1, 0, 0 )
if number == 8:
return ( 0, 1, 1 )
if number == 9:
return ( 0, 0, 3 )
if number == 10:
return ( 0, 2, 0 )
if number == 11:
return ( 0, 1, 2 )
if number == 12:
return ( 0, 0, 4 )
if number == 13:
return ( 0, 2, 1 )
if number == 14:
return ( 2, 0, 0 )
if number == 15:
return ( 0, 3, 0 )
if number == 16:
return ( 0, 2, 2 )
if number == 17:
return ( 1, 2, 0 )
if number == 18:
return ( 0, 3, 1 )
if number == 19:
return ( 0, 3, 3 )
if number == 20:
return ( 0, 4, 0 )
def func():
n = int( input() )
n7 = 0
n5 = 0
n3 = 0
if ( n <= 10 ):
(n7, n5, n3 ) = func2( n )
else:
x = n % 10
y = n // 10
if x <= 4:
y = y - 1
x = x + 10
(n7, n5, n3 ) = func2( x )
n5 = n5 + ( y * 2 )
if ( n7 == -1 ):
print ( -1 )
return
print ( n3, n5, n7 )
return
def codeforces1430ProblemB():
x = [ int(i) for i in input().split(" ") ]
n = x[0]
k = x[1]
tanks = []
tanks = [ int(i) for i in input().split(" ") ]
tanks = sorted( tanks )
maxDiff = tanks[n-1]
# n > 2
if tanks[n-1] == 0:
print (0)
return
for i in range( k ):
maxDiff = maxDiff + tanks[(n-1)-(i+1)]
print ( maxDiff )
return
numTest = int( input() )
while numTest:
numTest -= 1
codeforces1430ProblemB()
```
Yes
| 7,760 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have n barrels lined up in a row, numbered from left to right from one. Initially, the i-th barrel contains a_i liters of water.
You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels x and y (the x-th barrel shouldn't be empty) and pour any possible amount of water from barrel x to barrel y (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them.
Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most k times.
Some examples:
* if you have four barrels, each containing 5 liters of water, and k = 1, you may pour 5 liters from the second barrel into the fourth, so the amounts of water in the barrels are [5, 0, 5, 10], and the difference between the maximum and the minimum is 10;
* if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still 0.
Input
The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of each test case contains two integers n and k (1 ≤ k < n ≤ 2 ⋅ 10^5) — the number of barrels and the number of pourings you can make.
The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{9}), where a_i is the initial amount of water the i-th barrel has.
It's guaranteed that the total sum of n over test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most k times.
Example
Input
2
4 1
5 5 5 5
3 2
0 0 0
Output
10
0
Submitted Solution:
```
import sys
input = sys.stdin.buffer.readline
T = int(input())
for testcase in range(T):
n,k = map(int,input().split())
a = list(map(int,input().split()))
a.sort()
for i in range(k):
if n-2-i == -1:
break
a[-1] += a[n-2-i]
a[n-2-i] = 0
print(max(a)-min(a))
```
Yes
| 7,761 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have n barrels lined up in a row, numbered from left to right from one. Initially, the i-th barrel contains a_i liters of water.
You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels x and y (the x-th barrel shouldn't be empty) and pour any possible amount of water from barrel x to barrel y (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them.
Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most k times.
Some examples:
* if you have four barrels, each containing 5 liters of water, and k = 1, you may pour 5 liters from the second barrel into the fourth, so the amounts of water in the barrels are [5, 0, 5, 10], and the difference between the maximum and the minimum is 10;
* if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still 0.
Input
The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of each test case contains two integers n and k (1 ≤ k < n ≤ 2 ⋅ 10^5) — the number of barrels and the number of pourings you can make.
The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{9}), where a_i is the initial amount of water the i-th barrel has.
It's guaranteed that the total sum of n over test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most k times.
Example
Input
2
4 1
5 5 5 5
3 2
0 0 0
Output
10
0
Submitted Solution:
```
for i in range(int(input())):
n,k=[int(num) for num in input().split()]
count=0
x=list(map(int,input().split()))
x.sort(reverse=True)
for i in range(k+1):
count=count+x[i]
print(count)
```
Yes
| 7,762 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have n barrels lined up in a row, numbered from left to right from one. Initially, the i-th barrel contains a_i liters of water.
You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels x and y (the x-th barrel shouldn't be empty) and pour any possible amount of water from barrel x to barrel y (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them.
Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most k times.
Some examples:
* if you have four barrels, each containing 5 liters of water, and k = 1, you may pour 5 liters from the second barrel into the fourth, so the amounts of water in the barrels are [5, 0, 5, 10], and the difference between the maximum and the minimum is 10;
* if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still 0.
Input
The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of each test case contains two integers n and k (1 ≤ k < n ≤ 2 ⋅ 10^5) — the number of barrels and the number of pourings you can make.
The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{9}), where a_i is the initial amount of water the i-th barrel has.
It's guaranteed that the total sum of n over test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most k times.
Example
Input
2
4 1
5 5 5 5
3 2
0 0 0
Output
10
0
Submitted Solution:
```
for _ in range(int(input())):
n,k = map(int,input().split())
capacities = [int(x) for x in input().split()]
capacities.sort()
if capacities[n - 1] == 0 or n == 1:
print(capacities[0])
else:
j = n - 2
for i in range(k):
if j >= 0:
capacities[n - 1] += capacities[j]
j -= 1
else:
break
print(capacities[n - 1] - capacities[0])
```
No
| 7,763 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have n barrels lined up in a row, numbered from left to right from one. Initially, the i-th barrel contains a_i liters of water.
You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels x and y (the x-th barrel shouldn't be empty) and pour any possible amount of water from barrel x to barrel y (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them.
Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most k times.
Some examples:
* if you have four barrels, each containing 5 liters of water, and k = 1, you may pour 5 liters from the second barrel into the fourth, so the amounts of water in the barrels are [5, 0, 5, 10], and the difference between the maximum and the minimum is 10;
* if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still 0.
Input
The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of each test case contains two integers n and k (1 ≤ k < n ≤ 2 ⋅ 10^5) — the number of barrels and the number of pourings you can make.
The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{9}), where a_i is the initial amount of water the i-th barrel has.
It's guaranteed that the total sum of n over test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most k times.
Example
Input
2
4 1
5 5 5 5
3 2
0 0 0
Output
10
0
Submitted Solution:
```
# your code goes here
from collections import *
t = int(input())
for i in range(t):
n, k = map(int, input().split())
L = list(map(int, input().split()))
L.sort()
print(sum(L[-1-k:-1]))
```
No
| 7,764 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have n barrels lined up in a row, numbered from left to right from one. Initially, the i-th barrel contains a_i liters of water.
You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels x and y (the x-th barrel shouldn't be empty) and pour any possible amount of water from barrel x to barrel y (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them.
Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most k times.
Some examples:
* if you have four barrels, each containing 5 liters of water, and k = 1, you may pour 5 liters from the second barrel into the fourth, so the amounts of water in the barrels are [5, 0, 5, 10], and the difference between the maximum and the minimum is 10;
* if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still 0.
Input
The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of each test case contains two integers n and k (1 ≤ k < n ≤ 2 ⋅ 10^5) — the number of barrels and the number of pourings you can make.
The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{9}), where a_i is the initial amount of water the i-th barrel has.
It's guaranteed that the total sum of n over test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most k times.
Example
Input
2
4 1
5 5 5 5
3 2
0 0 0
Output
10
0
Submitted Solution:
```
def calc(barrels):
i = barrels.index(max(barrels))
buf = barrels[i]
barrels[i] = '0'
j = barrels.index(max(barrels))
barrels[i] = buf
return i, j
n = int(input())
results = []
for i in range(0, n, 1):
nk = input().split()
barrels = input().split()
for k in range(0, int(nk[1]), 1):
res = calc(barrels)
barrels[res[0]] = int(barrels[res[0]]) + int(barrels[res[1]])
barrels[res[1]] = '0'
barrels[res[0]] = str(barrels[res[0]])
results.append(barrels[res[0]])
for element in results:
print(int(element))
```
No
| 7,765 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have n barrels lined up in a row, numbered from left to right from one. Initially, the i-th barrel contains a_i liters of water.
You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels x and y (the x-th barrel shouldn't be empty) and pour any possible amount of water from barrel x to barrel y (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them.
Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most k times.
Some examples:
* if you have four barrels, each containing 5 liters of water, and k = 1, you may pour 5 liters from the second barrel into the fourth, so the amounts of water in the barrels are [5, 0, 5, 10], and the difference between the maximum and the minimum is 10;
* if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still 0.
Input
The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of each test case contains two integers n and k (1 ≤ k < n ≤ 2 ⋅ 10^5) — the number of barrels and the number of pourings you can make.
The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{9}), where a_i is the initial amount of water the i-th barrel has.
It's guaranteed that the total sum of n over test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most k times.
Example
Input
2
4 1
5 5 5 5
3 2
0 0 0
Output
10
0
Submitted Solution:
```
t = int(input())
for _ in range(t):
k,n = tuple(map(int,input().split(' ')))
a = list(map(int,input().split(' ')))
for i in range(k):
a[1] += a[0]
a[0] = 0
a.sort()
print(a[len(a)-1]-a[0])
```
No
| 7,766 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong is developing a game consisting of n stages numbered from 1 to n. The player starts the game from the 1-st stage and should beat the stages in increasing order of the stage number. The player wins the game after beating the n-th stage.
There is at most one checkpoint on each stage, and there is always a checkpoint on the 1-st stage. At the beginning of the game, only the checkpoint on the 1-st stage is activated, and all other checkpoints are deactivated. When the player gets to the i-th stage that has a checkpoint, that checkpoint is activated.
For each try of a stage, the player can either beat the stage or fail the stage. If they beat the i-th stage, the player is moved to the i+1-st stage. If they fail the i-th stage, the player is moved to the most recent checkpoint they activated, and they have to beat the stages after that checkpoint again.
For example, assume that n = 4 and the checkpoints are on the 1-st and 3-rd stages. The player starts at the 1-st stage. If they fail on the 1-st stage, they need to retry the 1-st stage because the checkpoint on the 1-st stage is the most recent checkpoint they activated. If the player beats the 1-st stage, they're moved to the 2-nd stage. If they fail it, they're sent back to the 1-st stage again. If they beat both the 1-st stage and the 2-nd stage, they get to the 3-rd stage and the checkpoint on the 3-rd stage is activated. Now whenever they fail on the 3-rd stage, or the 4-th stage after beating the 3-rd stage, they're sent back to the 3-rd stage. If they beat both the 3-rd stage and the 4-th stage, they win the game.
Gildong is going to build the stages to have equal difficulty. He wants you to find any series of stages and checkpoints using at most 2000 stages, where the [expected number](https://en.wikipedia.org/wiki/Expected_value) of tries over all stages is exactly k, for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 50).
Each test case contains exactly one line. The line consists of a single integer k (1 ≤ k ≤ 10^{18}) — the expected number of tries over all stages Gildong wants to set for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Output
For each test case, print -1 if it's impossible to construct such a series of stages and checkpoints using at most 2000 stages.
Otherwise, print two lines. The first line should contain a single integer n (1 ≤ n ≤ 2000) – the number of stages. The second line should contain n integers, where the i-th integer represents whether the i-th stage has a checkpoint. The i-th integer should be 0 if the i-th stage doesn't have a checkpoint, and 1 if it has a checkpoint. Note that the first integer must be 1 according to the description.
Example
Input
4
1
2
8
12
Output
-1
1
1
4
1 1 1 1
5
1 1 0 1 1
Note
In the first and the second case, we can see that the 'easiest' series of stages is to have 1 stage with a checkpoint. This already requires 2 tries in expectation, so it is impossible to make it to require only 1 try.
In the third case, it takes 2 tries in expectation to beat each stage, and the player can always retry that stage without falling back to one of the previous stages if they fail it. Therefore the total expected number of tries is 8. Note that there exists an answer with fewer stages, but you are not required to minimize the number of stages used.
Tags: brute force, constructive algorithms, greedy, math, probabilities
Correct Solution:
```
for _ in range(int(input())):
n = int(input())
a = []
if n % 2 == 1:
print(-1)
continue
if n <= 4000:
print(n // 2)
print('1 ' * (n // 2))
continue
while n > 0:
a.append(1)
n -= 2
s = 2
while n > s * 2:
a.append(0)
s *= 2
n -= s
if len(a) <= 2000:
print(len(a))
print(*a, end=' ')
else:
print(-1)
```
| 7,767 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong is developing a game consisting of n stages numbered from 1 to n. The player starts the game from the 1-st stage and should beat the stages in increasing order of the stage number. The player wins the game after beating the n-th stage.
There is at most one checkpoint on each stage, and there is always a checkpoint on the 1-st stage. At the beginning of the game, only the checkpoint on the 1-st stage is activated, and all other checkpoints are deactivated. When the player gets to the i-th stage that has a checkpoint, that checkpoint is activated.
For each try of a stage, the player can either beat the stage or fail the stage. If they beat the i-th stage, the player is moved to the i+1-st stage. If they fail the i-th stage, the player is moved to the most recent checkpoint they activated, and they have to beat the stages after that checkpoint again.
For example, assume that n = 4 and the checkpoints are on the 1-st and 3-rd stages. The player starts at the 1-st stage. If they fail on the 1-st stage, they need to retry the 1-st stage because the checkpoint on the 1-st stage is the most recent checkpoint they activated. If the player beats the 1-st stage, they're moved to the 2-nd stage. If they fail it, they're sent back to the 1-st stage again. If they beat both the 1-st stage and the 2-nd stage, they get to the 3-rd stage and the checkpoint on the 3-rd stage is activated. Now whenever they fail on the 3-rd stage, or the 4-th stage after beating the 3-rd stage, they're sent back to the 3-rd stage. If they beat both the 3-rd stage and the 4-th stage, they win the game.
Gildong is going to build the stages to have equal difficulty. He wants you to find any series of stages and checkpoints using at most 2000 stages, where the [expected number](https://en.wikipedia.org/wiki/Expected_value) of tries over all stages is exactly k, for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 50).
Each test case contains exactly one line. The line consists of a single integer k (1 ≤ k ≤ 10^{18}) — the expected number of tries over all stages Gildong wants to set for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Output
For each test case, print -1 if it's impossible to construct such a series of stages and checkpoints using at most 2000 stages.
Otherwise, print two lines. The first line should contain a single integer n (1 ≤ n ≤ 2000) – the number of stages. The second line should contain n integers, where the i-th integer represents whether the i-th stage has a checkpoint. The i-th integer should be 0 if the i-th stage doesn't have a checkpoint, and 1 if it has a checkpoint. Note that the first integer must be 1 according to the description.
Example
Input
4
1
2
8
12
Output
-1
1
1
4
1 1 1 1
5
1 1 0 1 1
Note
In the first and the second case, we can see that the 'easiest' series of stages is to have 1 stage with a checkpoint. This already requires 2 tries in expectation, so it is impossible to make it to require only 1 try.
In the third case, it takes 2 tries in expectation to beat each stage, and the player can always retry that stage without falling back to one of the previous stages if they fail it. Therefore the total expected number of tries is 8. Note that there exists an answer with fewer stages, but you are not required to minimize the number of stages used.
Tags: brute force, constructive algorithms, greedy, math, probabilities
Correct Solution:
```
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
from bisect import bisect_left as bsl
powers=[2]
for s in range(60):
powers.append(powers[-1]*2)
newy=[powers[0]]
for s in range(1,len(powers)):
newy.append(newy[-1]+powers[s])
if newy[-1]>=10**18:
break
for j in range(int(input())):
k=int(input())
if k%2==1:
print(-1)
else:
binrep=k-2
#see if we can construct k-2 using newy
ans=[1]
while binrep>0:
ind=min(bsl(newy,binrep),len(newy)-1)
if newy[ind]>binrep:
ind-=1
for i in range(ind):
ans.append(0)
ans.append(1)
binrep-=newy[ind]
print(len(ans))
print(*ans)
```
| 7,768 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong is developing a game consisting of n stages numbered from 1 to n. The player starts the game from the 1-st stage and should beat the stages in increasing order of the stage number. The player wins the game after beating the n-th stage.
There is at most one checkpoint on each stage, and there is always a checkpoint on the 1-st stage. At the beginning of the game, only the checkpoint on the 1-st stage is activated, and all other checkpoints are deactivated. When the player gets to the i-th stage that has a checkpoint, that checkpoint is activated.
For each try of a stage, the player can either beat the stage or fail the stage. If they beat the i-th stage, the player is moved to the i+1-st stage. If they fail the i-th stage, the player is moved to the most recent checkpoint they activated, and they have to beat the stages after that checkpoint again.
For example, assume that n = 4 and the checkpoints are on the 1-st and 3-rd stages. The player starts at the 1-st stage. If they fail on the 1-st stage, they need to retry the 1-st stage because the checkpoint on the 1-st stage is the most recent checkpoint they activated. If the player beats the 1-st stage, they're moved to the 2-nd stage. If they fail it, they're sent back to the 1-st stage again. If they beat both the 1-st stage and the 2-nd stage, they get to the 3-rd stage and the checkpoint on the 3-rd stage is activated. Now whenever they fail on the 3-rd stage, or the 4-th stage after beating the 3-rd stage, they're sent back to the 3-rd stage. If they beat both the 3-rd stage and the 4-th stage, they win the game.
Gildong is going to build the stages to have equal difficulty. He wants you to find any series of stages and checkpoints using at most 2000 stages, where the [expected number](https://en.wikipedia.org/wiki/Expected_value) of tries over all stages is exactly k, for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 50).
Each test case contains exactly one line. The line consists of a single integer k (1 ≤ k ≤ 10^{18}) — the expected number of tries over all stages Gildong wants to set for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Output
For each test case, print -1 if it's impossible to construct such a series of stages and checkpoints using at most 2000 stages.
Otherwise, print two lines. The first line should contain a single integer n (1 ≤ n ≤ 2000) – the number of stages. The second line should contain n integers, where the i-th integer represents whether the i-th stage has a checkpoint. The i-th integer should be 0 if the i-th stage doesn't have a checkpoint, and 1 if it has a checkpoint. Note that the first integer must be 1 according to the description.
Example
Input
4
1
2
8
12
Output
-1
1
1
4
1 1 1 1
5
1 1 0 1 1
Note
In the first and the second case, we can see that the 'easiest' series of stages is to have 1 stage with a checkpoint. This already requires 2 tries in expectation, so it is impossible to make it to require only 1 try.
In the third case, it takes 2 tries in expectation to beat each stage, and the player can always retry that stage without falling back to one of the previous stages if they fail it. Therefore the total expected number of tries is 8. Note that there exists an answer with fewer stages, but you are not required to minimize the number of stages used.
Tags: brute force, constructive algorithms, greedy, math, probabilities
Correct Solution:
```
from sys import stdin
input = stdin.readline
for _ in range(int(input())):
n = int(input())
s = ''
if n % 2:
print(-1)
continue
n //= 2
a = bin(n)[2:]
n = len(a)
for x in range(n - 1, 0, -1):
if a[n - 1 - x] == '0':
continue
s += '1 ' + '0 ' * (x - 1) + '1 '
if a[n - 1] == '1':
s += '1 '
print(len(s) // 2)
print(s)
```
| 7,769 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong is developing a game consisting of n stages numbered from 1 to n. The player starts the game from the 1-st stage and should beat the stages in increasing order of the stage number. The player wins the game after beating the n-th stage.
There is at most one checkpoint on each stage, and there is always a checkpoint on the 1-st stage. At the beginning of the game, only the checkpoint on the 1-st stage is activated, and all other checkpoints are deactivated. When the player gets to the i-th stage that has a checkpoint, that checkpoint is activated.
For each try of a stage, the player can either beat the stage or fail the stage. If they beat the i-th stage, the player is moved to the i+1-st stage. If they fail the i-th stage, the player is moved to the most recent checkpoint they activated, and they have to beat the stages after that checkpoint again.
For example, assume that n = 4 and the checkpoints are on the 1-st and 3-rd stages. The player starts at the 1-st stage. If they fail on the 1-st stage, they need to retry the 1-st stage because the checkpoint on the 1-st stage is the most recent checkpoint they activated. If the player beats the 1-st stage, they're moved to the 2-nd stage. If they fail it, they're sent back to the 1-st stage again. If they beat both the 1-st stage and the 2-nd stage, they get to the 3-rd stage and the checkpoint on the 3-rd stage is activated. Now whenever they fail on the 3-rd stage, or the 4-th stage after beating the 3-rd stage, they're sent back to the 3-rd stage. If they beat both the 3-rd stage and the 4-th stage, they win the game.
Gildong is going to build the stages to have equal difficulty. He wants you to find any series of stages and checkpoints using at most 2000 stages, where the [expected number](https://en.wikipedia.org/wiki/Expected_value) of tries over all stages is exactly k, for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 50).
Each test case contains exactly one line. The line consists of a single integer k (1 ≤ k ≤ 10^{18}) — the expected number of tries over all stages Gildong wants to set for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Output
For each test case, print -1 if it's impossible to construct such a series of stages and checkpoints using at most 2000 stages.
Otherwise, print two lines. The first line should contain a single integer n (1 ≤ n ≤ 2000) – the number of stages. The second line should contain n integers, where the i-th integer represents whether the i-th stage has a checkpoint. The i-th integer should be 0 if the i-th stage doesn't have a checkpoint, and 1 if it has a checkpoint. Note that the first integer must be 1 according to the description.
Example
Input
4
1
2
8
12
Output
-1
1
1
4
1 1 1 1
5
1 1 0 1 1
Note
In the first and the second case, we can see that the 'easiest' series of stages is to have 1 stage with a checkpoint. This already requires 2 tries in expectation, so it is impossible to make it to require only 1 try.
In the third case, it takes 2 tries in expectation to beat each stage, and the player can always retry that stage without falling back to one of the previous stages if they fail it. Therefore the total expected number of tries is 8. Note that there exists an answer with fewer stages, but you are not required to minimize the number of stages used.
Tags: brute force, constructive algorithms, greedy, math, probabilities
Correct Solution:
```
def read_int():
return int(input())
def read_ints():
return map(int, input().split(' '))
t = read_int()
a = [2]
while a[-1] < 1e18:
a.append(a[-1] * 2 + 2)
for case_num in range(t):
n = read_int()
if n % 2 == 1:
print(-1)
continue
ans = []
pos = len(a) - 1
while n > 0:
while a[pos] > n:
pos -= 1
n -= a[pos]
ans += [1] + ([0] * pos)
print(len(ans))
print(' '.join(map(str, ans)))
```
| 7,770 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong is developing a game consisting of n stages numbered from 1 to n. The player starts the game from the 1-st stage and should beat the stages in increasing order of the stage number. The player wins the game after beating the n-th stage.
There is at most one checkpoint on each stage, and there is always a checkpoint on the 1-st stage. At the beginning of the game, only the checkpoint on the 1-st stage is activated, and all other checkpoints are deactivated. When the player gets to the i-th stage that has a checkpoint, that checkpoint is activated.
For each try of a stage, the player can either beat the stage or fail the stage. If they beat the i-th stage, the player is moved to the i+1-st stage. If they fail the i-th stage, the player is moved to the most recent checkpoint they activated, and they have to beat the stages after that checkpoint again.
For example, assume that n = 4 and the checkpoints are on the 1-st and 3-rd stages. The player starts at the 1-st stage. If they fail on the 1-st stage, they need to retry the 1-st stage because the checkpoint on the 1-st stage is the most recent checkpoint they activated. If the player beats the 1-st stage, they're moved to the 2-nd stage. If they fail it, they're sent back to the 1-st stage again. If they beat both the 1-st stage and the 2-nd stage, they get to the 3-rd stage and the checkpoint on the 3-rd stage is activated. Now whenever they fail on the 3-rd stage, or the 4-th stage after beating the 3-rd stage, they're sent back to the 3-rd stage. If they beat both the 3-rd stage and the 4-th stage, they win the game.
Gildong is going to build the stages to have equal difficulty. He wants you to find any series of stages and checkpoints using at most 2000 stages, where the [expected number](https://en.wikipedia.org/wiki/Expected_value) of tries over all stages is exactly k, for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 50).
Each test case contains exactly one line. The line consists of a single integer k (1 ≤ k ≤ 10^{18}) — the expected number of tries over all stages Gildong wants to set for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Output
For each test case, print -1 if it's impossible to construct such a series of stages and checkpoints using at most 2000 stages.
Otherwise, print two lines. The first line should contain a single integer n (1 ≤ n ≤ 2000) – the number of stages. The second line should contain n integers, where the i-th integer represents whether the i-th stage has a checkpoint. The i-th integer should be 0 if the i-th stage doesn't have a checkpoint, and 1 if it has a checkpoint. Note that the first integer must be 1 according to the description.
Example
Input
4
1
2
8
12
Output
-1
1
1
4
1 1 1 1
5
1 1 0 1 1
Note
In the first and the second case, we can see that the 'easiest' series of stages is to have 1 stage with a checkpoint. This already requires 2 tries in expectation, so it is impossible to make it to require only 1 try.
In the third case, it takes 2 tries in expectation to beat each stage, and the player can always retry that stage without falling back to one of the previous stages if they fail it. Therefore the total expected number of tries is 8. Note that there exists an answer with fewer stages, but you are not required to minimize the number of stages used.
Tags: brute force, constructive algorithms, greedy, math, probabilities
Correct Solution:
```
t = int(input())
al = [2]
for i in range(100):
al.append(al[-1] * 2 + 2)
#print(al)
for q in range(t):
k = int(input())
if k % 2 == 1:
print(-1)
else:
mas = []
while k > 0:
y = 0
while al[y] <= k:
y += 1
y -= 1
mas.append(y)
k -= al[y]
z = 0
for i in mas:
z += i + 1
print(z)
for i in mas:
print(1, end = ' ')
for j in range(i):
print(0, end = ' ')
print()
```
| 7,771 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong is developing a game consisting of n stages numbered from 1 to n. The player starts the game from the 1-st stage and should beat the stages in increasing order of the stage number. The player wins the game after beating the n-th stage.
There is at most one checkpoint on each stage, and there is always a checkpoint on the 1-st stage. At the beginning of the game, only the checkpoint on the 1-st stage is activated, and all other checkpoints are deactivated. When the player gets to the i-th stage that has a checkpoint, that checkpoint is activated.
For each try of a stage, the player can either beat the stage or fail the stage. If they beat the i-th stage, the player is moved to the i+1-st stage. If they fail the i-th stage, the player is moved to the most recent checkpoint they activated, and they have to beat the stages after that checkpoint again.
For example, assume that n = 4 and the checkpoints are on the 1-st and 3-rd stages. The player starts at the 1-st stage. If they fail on the 1-st stage, they need to retry the 1-st stage because the checkpoint on the 1-st stage is the most recent checkpoint they activated. If the player beats the 1-st stage, they're moved to the 2-nd stage. If they fail it, they're sent back to the 1-st stage again. If they beat both the 1-st stage and the 2-nd stage, they get to the 3-rd stage and the checkpoint on the 3-rd stage is activated. Now whenever they fail on the 3-rd stage, or the 4-th stage after beating the 3-rd stage, they're sent back to the 3-rd stage. If they beat both the 3-rd stage and the 4-th stage, they win the game.
Gildong is going to build the stages to have equal difficulty. He wants you to find any series of stages and checkpoints using at most 2000 stages, where the [expected number](https://en.wikipedia.org/wiki/Expected_value) of tries over all stages is exactly k, for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 50).
Each test case contains exactly one line. The line consists of a single integer k (1 ≤ k ≤ 10^{18}) — the expected number of tries over all stages Gildong wants to set for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Output
For each test case, print -1 if it's impossible to construct such a series of stages and checkpoints using at most 2000 stages.
Otherwise, print two lines. The first line should contain a single integer n (1 ≤ n ≤ 2000) – the number of stages. The second line should contain n integers, where the i-th integer represents whether the i-th stage has a checkpoint. The i-th integer should be 0 if the i-th stage doesn't have a checkpoint, and 1 if it has a checkpoint. Note that the first integer must be 1 according to the description.
Example
Input
4
1
2
8
12
Output
-1
1
1
4
1 1 1 1
5
1 1 0 1 1
Note
In the first and the second case, we can see that the 'easiest' series of stages is to have 1 stage with a checkpoint. This already requires 2 tries in expectation, so it is impossible to make it to require only 1 try.
In the third case, it takes 2 tries in expectation to beat each stage, and the player can always retry that stage without falling back to one of the previous stages if they fail it. Therefore the total expected number of tries is 8. Note that there exists an answer with fewer stages, but you are not required to minimize the number of stages used.
Tags: brute force, constructive algorithms, greedy, math, probabilities
Correct Solution:
```
t = int(input())
chisls = [2 ** (i + 1) - 2 for i in range(1, 72)]
# print(chisls)
for i in range(t):
n = int(input())
if n % 2 == 1:
print(-1)
else:
# print(1, end=' ')
data = [1]
n -= 2
p = len(chisls) - 1
while n > 0:
while chisls[p] > n:
p -= 1
# print(p)
while n >= chisls[p]:
data += [1] + [0 for j in range(p)]
n -= chisls[p]
if len(data) > 2000:
break
if len(data) > 2000:
print(-1)
else:
print(len(data))
print(*data)
```
| 7,772 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong is developing a game consisting of n stages numbered from 1 to n. The player starts the game from the 1-st stage and should beat the stages in increasing order of the stage number. The player wins the game after beating the n-th stage.
There is at most one checkpoint on each stage, and there is always a checkpoint on the 1-st stage. At the beginning of the game, only the checkpoint on the 1-st stage is activated, and all other checkpoints are deactivated. When the player gets to the i-th stage that has a checkpoint, that checkpoint is activated.
For each try of a stage, the player can either beat the stage or fail the stage. If they beat the i-th stage, the player is moved to the i+1-st stage. If they fail the i-th stage, the player is moved to the most recent checkpoint they activated, and they have to beat the stages after that checkpoint again.
For example, assume that n = 4 and the checkpoints are on the 1-st and 3-rd stages. The player starts at the 1-st stage. If they fail on the 1-st stage, they need to retry the 1-st stage because the checkpoint on the 1-st stage is the most recent checkpoint they activated. If the player beats the 1-st stage, they're moved to the 2-nd stage. If they fail it, they're sent back to the 1-st stage again. If they beat both the 1-st stage and the 2-nd stage, they get to the 3-rd stage and the checkpoint on the 3-rd stage is activated. Now whenever they fail on the 3-rd stage, or the 4-th stage after beating the 3-rd stage, they're sent back to the 3-rd stage. If they beat both the 3-rd stage and the 4-th stage, they win the game.
Gildong is going to build the stages to have equal difficulty. He wants you to find any series of stages and checkpoints using at most 2000 stages, where the [expected number](https://en.wikipedia.org/wiki/Expected_value) of tries over all stages is exactly k, for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 50).
Each test case contains exactly one line. The line consists of a single integer k (1 ≤ k ≤ 10^{18}) — the expected number of tries over all stages Gildong wants to set for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Output
For each test case, print -1 if it's impossible to construct such a series of stages and checkpoints using at most 2000 stages.
Otherwise, print two lines. The first line should contain a single integer n (1 ≤ n ≤ 2000) – the number of stages. The second line should contain n integers, where the i-th integer represents whether the i-th stage has a checkpoint. The i-th integer should be 0 if the i-th stage doesn't have a checkpoint, and 1 if it has a checkpoint. Note that the first integer must be 1 according to the description.
Example
Input
4
1
2
8
12
Output
-1
1
1
4
1 1 1 1
5
1 1 0 1 1
Note
In the first and the second case, we can see that the 'easiest' series of stages is to have 1 stage with a checkpoint. This already requires 2 tries in expectation, so it is impossible to make it to require only 1 try.
In the third case, it takes 2 tries in expectation to beat each stage, and the player can always retry that stage without falling back to one of the previous stages if they fail it. Therefore the total expected number of tries is 8. Note that there exists an answer with fewer stages, but you are not required to minimize the number of stages used.
Tags: brute force, constructive algorithms, greedy, math, probabilities
Correct Solution:
```
import sys
from math import gcd,sqrt,ceil,log2
from collections import defaultdict,Counter,deque
from bisect import bisect_left,bisect_right
import math
sys.setrecursionlimit(2*10**5+10)
import heapq
from itertools import permutations
# input=sys.stdin.readline
# def print(x):
# sys.stdout.write(str(x)+"\n")
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
aa='abcdefghijklmnopqrstuvwxyz'
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")
# import sys
# import io, os
# input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def get_sum(bit,i):
s = 0
i+=1
while i>0:
s+=bit[i]
i-=i&(-i)
return s
def update(bit,n,i,v):
i+=1
while i<=n:
bit[i]+=v
i+=i&(-i)
def modInverse(b,m):
g = math.gcd(b, m)
if (g != 1):
return -1
else:
return pow(b, m - 2, m)
def primeFactors(n):
sa = []
# sa.add(n)
while n % 2 == 0:
sa.append(2)
n = n // 2
for i in range(3,int(math.sqrt(n))+1,2):
while n % i== 0:
sa.append(i)
n = n // i
# sa.add(n)
if n > 2:
sa.append(n)
return sa
def seive(n):
pri = [True]*(n+1)
p = 2
while p*p<=n:
if pri[p] == True:
for i in range(p*p,n+1,p):
pri[i] = False
p+=1
return pri
def check_prim(n):
if n<0:
return False
for i in range(2,int(sqrt(n))+1):
if n%i == 0:
return False
return True
def getZarr(string, z):
n = len(string)
# [L,R] make a window which matches
# with prefix of s
l, r, k = 0, 0, 0
for i in range(1, n):
# if i>R nothing matches so we will calculate.
# Z[i] using naive way.
if i > r:
l, r = i, i
# R-L = 0 in starting, so it will start
# checking from 0'th index. For example,
# for "ababab" and i = 1, the value of R
# remains 0 and Z[i] becomes 0. For string
# "aaaaaa" and i = 1, Z[i] and R become 5
while r < n and string[r - l] == string[r]:
r += 1
z[i] = r - l
r -= 1
else:
# k = i-L so k corresponds to number which
# matches in [L,R] interval.
k = i - l
# if Z[k] is less than remaining interval
# then Z[i] will be equal to Z[k].
# For example, str = "ababab", i = 3, R = 5
# and L = 2
if z[k] < r - i + 1:
z[i] = z[k]
# For example str = "aaaaaa" and i = 2,
# R is 5, L is 0
else:
# else start from R and check manually
l = i
while r < n and string[r - l] == string[r]:
r += 1
z[i] = r - l
r -= 1
def search(text, pattern):
# Create concatenated string "P$T"
concat = pattern + "$" + text
l = len(concat)
z = [0] * l
getZarr(concat, z)
ha = []
for i in range(l):
if z[i] == len(pattern):
ha.append(i - len(pattern) - 1)
return ha
# n,k = map(int,input().split())
# l = list(map(int,input().split()))
#
# n = int(input())
# l = list(map(int,input().split()))
#
# hash = defaultdict(list)
# la = []
#
# for i in range(n):
# la.append([l[i],i+1])
#
# la.sort(key = lambda x: (x[0],-x[1]))
# ans = []
# r = n
# flag = 0
# lo = []
# ha = [i for i in range(n,0,-1)]
# yo = []
# for a,b in la:
#
# if a == 1:
# ans.append([r,b])
# # hash[(1,1)].append([b,r])
# lo.append((r,b))
# ha.pop(0)
# yo.append([r,b])
# r-=1
#
# elif a == 2:
# # print(yo,lo)
# # print(hash[1,1])
# if lo == []:
# flag = 1
# break
# c,d = lo.pop(0)
# yo.pop(0)
# if b>=d:
# flag = 1
# break
# ans.append([c,b])
# yo.append([c,b])
#
#
#
# elif a == 3:
#
# if yo == []:
# flag = 1
# break
# c,d = yo.pop(0)
# if b>=d:
# flag = 1
# break
# if ha == []:
# flag = 1
# break
#
# ka = ha.pop(0)
#
# ans.append([ka,b])
# ans.append([ka,d])
# yo.append([ka,b])
#
# if flag:
# print(-1)
# else:
# print(len(ans))
# for a,b in ans:
# print(a,b)
def mergeIntervals(arr):
# Sorting based on the increasing order
# of the start intervals
arr.sort(key = lambda x: x[0])
# array to hold the merged intervals
m = []
s = -10000
max = -100000
for i in range(len(arr)):
a = arr[i]
if a[0] > max:
if i != 0:
m.append([s,max])
max = a[1]
s = a[0]
else:
if a[1] >= max:
max = a[1]
#'max' value gives the last point of
# that particular interval
# 's' gives the starting point of that interval
# 'm' array contains the list of all merged intervals
if max != -100000 and [s, max] not in m:
m.append([s, max])
return m
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))
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 sol(n):
seti = set()
for i in range(1,int(sqrt(n))+1):
if n%i == 0:
seti.add(n//i)
seti.add(i)
return seti
def lcm(a,b):
return (a*b)//gcd(a,b)
#
# n,p = map(int,input().split())
#
# s = input()
#
# if n <=2:
# if n == 1:
# pass
# if n == 2:
# pass
# i = n-1
# idx = -1
# while i>=0:
# z = ord(s[i])-96
# k = chr(z+1+96)
# flag = 1
# if i-1>=0:
# if s[i-1]!=k:
# flag+=1
# else:
# flag+=1
# if i-2>=0:
# if s[i-2]!=k:
# flag+=1
# else:
# flag+=1
# if flag == 2:
# idx = i
# s[i] = k
# break
# if idx == -1:
# print('NO')
# exit()
# for i in range(idx+1,n):
# if
#
def moore_voting(l):
count1 = 0
count2 = 0
first = 10**18
second = 10**18
n = len(l)
for i in range(n):
if l[i] == first:
count1+=1
elif l[i] == second:
count2+=1
elif count1 == 0:
count1+=1
first = l[i]
elif count2 == 0:
count2+=1
second = l[i]
else:
count1-=1
count2-=1
for i in range(n):
if l[i] == first:
count1+=1
elif l[i] == second:
count2+=1
if count1>n//3:
return first
if count2>n//3:
return second
return -1
def find_parent(u,parent):
if u!=parent[u]:
parent[u] = find_parent(parent[u],parent)
return parent[u]
def dis_union(n,e):
par = [i for i in range(n+1)]
rank = [1]*(n+1)
for a,b in e:
z1,z2 = find_parent(a,par),find_parent(b,par)
if rank[z1]>rank[z2]:
z1,z2 = z2,z1
if z1!=z2:
par[z1] = z2
rank[z2]+=rank[z1]
else:
return a,b
def dijkstra(n,tot,hash):
hea = [[0,n]]
dis = [10**18]*(tot+1)
dis[n] = 0
boo = defaultdict(bool)
check = defaultdict(int)
while hea:
a,b = heapq.heappop(hea)
if boo[b]:
continue
boo[b] = True
for i,w in hash[b]:
if b == 1:
c = 0
if (1,i,w) in nodes:
c = nodes[(1,i,w)]
del nodes[(1,i,w)]
if dis[b]+w<dis[i]:
dis[i] = dis[b]+w
check[i] = c
elif dis[b]+w == dis[i] and c == 0:
dis[i] = dis[b]+w
check[i] = c
else:
if dis[b]+w<=dis[i]:
dis[i] = dis[b]+w
check[i] = check[b]
heapq.heappush(hea,[dis[i],i])
return check
def power(x,y,p):
res = 1
x = x%p
if x == 0:
return 0
while y>0:
if (y&1) == 1:
res*=x
x = x*x
y = y>>1
return res
import sys
from math import ceil,log2
INT_MAX = sys.maxsize
def minVal(x, y) :
return x if (x < y) else y
def getMid(s, e) :
return s + (e - s) // 2
def RMQUtil( st, ss, se, qs, qe, index) :
if (qs <= ss and qe >= se) :
return st[index]
if (se < qs or ss > qe) :
return INT_MAX
mid = getMid(ss, se)
return minVal(RMQUtil(st, ss, mid, qs,
qe, 2 * index + 1),
RMQUtil(st, mid + 1, se,
qs, qe, 2 * index + 2))
def RMQ( st, n, qs, qe) :
if (qs < 0 or qe > n - 1 or qs > qe) :
print("Invalid Input")
return -1
return RMQUtil(st, 0, n - 1, qs, qe, 0)
def constructSTUtil(arr, ss, se, st, si) :
if (ss == se) :
st[si] = arr[ss]
return arr[ss]
mid = getMid(ss, se)
st[si] = minVal(constructSTUtil(arr, ss, mid,
st, si * 2 + 1),
constructSTUtil(arr, mid + 1, se,
st, si * 2 + 2))
return st[si]
def constructST( arr, n) :
x = (int)(ceil(log2(n)))
max_size = 2 * (int)(2**x) - 1
st = [0] * (max_size)
constructSTUtil(arr, 0, n - 1, st, 0)
return st
# t = int(input())
# for _ in range(t):
#
# n = int(input())
# l = list(map(int,input().split()))
# # x,y = 0,10
# st = constructST(l, n)
#
# pre = [0]
# suf = [0]
# for i in range(n):
# pre.append(max(pre[-1],l[i]))
# for i in range(n-1,-1,-1):
# suf.append(max(suf[-1],l[i]))
#
#
# i = 1
# # print(pre,suf)
# flag = 0
# x,y,z = -1,-1,-1
# # suf.reverse()
# print(suf)
# while i<len(pre):
#
# z = pre[i]
# j = bisect_left(suf,z)
# if suf[j] == z:
# while i<n and l[i]<=z:
# i+=1
# if pre[i]>z:
# break
# while j<n and l[n-j]<=z:
# j+=1
# if suf[j]>z:
# break
# # j-=1
# print(i,n-j)
# # break/
# if RMQ(st,n,i,j) == z:
# c = i+j-i+1
# x,y,z = i,j-i+1,n-c
# break
# else:
# i+=1
#
# else:
# i+=1
#
#
#
# if x!=-1:
# print('Yes')
# print(x,y,z)
# else:
# print('No')
# t = int(input())
#
# for _ in range(t):
#
# def debug(n):
# ans = []
# for i in range(1,n+1):
# for j in range(i+1,n+1):
# if (i*(j+1))%(j-i) == 0 :
# ans.append([i,j])
# return ans
#
#
# n = int(input())
# print(debug(n))
# import sys
# input = sys.stdin.readline
# import bisect
#
# t=int(input())
# for tests in range(t):
# n=int(input())
# A=list(map(int,input().split()))
#
# LEN = len(A)
# Sparse_table = [A]
#
# for i in range(LEN.bit_length()-1):
# j = 1<<i
# B = []
# for k in range(len(Sparse_table[-1])-j):
# B.append(min(Sparse_table[-1][k], Sparse_table[-1][k+j]))
# Sparse_table.append(B)
#
# def query(l,r): # [l,r)におけるminを求める.
# i=(r-l).bit_length()-1 # 何番目のSparse_tableを見るか.
#
# return min(Sparse_table[i][l],Sparse_table[i][r-(1<<i)]) # (1<<i)個あれば[l, r)が埋まるので, それを使ってminを求める.
#
# LMAX=[A[0]]
# for i in range(1,n):
# LMAX.append(max(LMAX[-1],A[i]))
#
# RMAX=A[-1]
#
# for i in range(n-1,-1,-1):
# RMAX=max(RMAX,A[i])
#
# x=bisect.bisect(LMAX,RMAX)
# #print(RMAX,x)
# print(RMAX,x,i)
# if x==0:
# continue
#
# v=min(x,i-1)
# if v<=0:
# continue
#
# if LMAX[v-1]==query(v,i)==RMAX:
# print("YES")
# print(v,i-v,n-i)
# break
#
# v-=1
# if v<=0:
# continue
# if LMAX[v-1]==query(v,i)==RMAX:
# print("YES")
# print(v,i-v,n-i)
# break
# else:
# print("NO")
#
#
#
#
#
#
#
#
#
# t = int(input())
#
# for _ in range(t):
#
# x = int(input())
# mini = 10**18
# n = ceil((-1 + sqrt(1+8*x))/2)
# for i in range(-100,1):
# z = x+-1*i
# z1 = (abs(i)*(abs(i)+1))//2
# z+=z1
# # print(z)
# n = ceil((-1 + sqrt(1+8*z))/2)
#
# y = (n*(n+1))//2
# # print(n,y,z,i)
# mini = min(n+y-z,mini)
# print(n+y-z,i)
#
#
# print(mini)
#
t = int(input())
for _ in range(t):
k = int(input())
ans = []
if k%2!=0:
print(-1)
continue
ans = [1]
su = 2
k1 = 2
while su-k!=0:
su+=2**k1
if su>k:
su-=2**k1
su+=2
ans.append(1)
k1 = 2
continue
ans.append(0)
k1+=1
k-=su
ans+=[1]*(k//2)
if len(ans)>2000:
print(-1)
continue
print(len(ans))
print(*ans)
```
| 7,773 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong is developing a game consisting of n stages numbered from 1 to n. The player starts the game from the 1-st stage and should beat the stages in increasing order of the stage number. The player wins the game after beating the n-th stage.
There is at most one checkpoint on each stage, and there is always a checkpoint on the 1-st stage. At the beginning of the game, only the checkpoint on the 1-st stage is activated, and all other checkpoints are deactivated. When the player gets to the i-th stage that has a checkpoint, that checkpoint is activated.
For each try of a stage, the player can either beat the stage or fail the stage. If they beat the i-th stage, the player is moved to the i+1-st stage. If they fail the i-th stage, the player is moved to the most recent checkpoint they activated, and they have to beat the stages after that checkpoint again.
For example, assume that n = 4 and the checkpoints are on the 1-st and 3-rd stages. The player starts at the 1-st stage. If they fail on the 1-st stage, they need to retry the 1-st stage because the checkpoint on the 1-st stage is the most recent checkpoint they activated. If the player beats the 1-st stage, they're moved to the 2-nd stage. If they fail it, they're sent back to the 1-st stage again. If they beat both the 1-st stage and the 2-nd stage, they get to the 3-rd stage and the checkpoint on the 3-rd stage is activated. Now whenever they fail on the 3-rd stage, or the 4-th stage after beating the 3-rd stage, they're sent back to the 3-rd stage. If they beat both the 3-rd stage and the 4-th stage, they win the game.
Gildong is going to build the stages to have equal difficulty. He wants you to find any series of stages and checkpoints using at most 2000 stages, where the [expected number](https://en.wikipedia.org/wiki/Expected_value) of tries over all stages is exactly k, for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 50).
Each test case contains exactly one line. The line consists of a single integer k (1 ≤ k ≤ 10^{18}) — the expected number of tries over all stages Gildong wants to set for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Output
For each test case, print -1 if it's impossible to construct such a series of stages and checkpoints using at most 2000 stages.
Otherwise, print two lines. The first line should contain a single integer n (1 ≤ n ≤ 2000) – the number of stages. The second line should contain n integers, where the i-th integer represents whether the i-th stage has a checkpoint. The i-th integer should be 0 if the i-th stage doesn't have a checkpoint, and 1 if it has a checkpoint. Note that the first integer must be 1 according to the description.
Example
Input
4
1
2
8
12
Output
-1
1
1
4
1 1 1 1
5
1 1 0 1 1
Note
In the first and the second case, we can see that the 'easiest' series of stages is to have 1 stage with a checkpoint. This already requires 2 tries in expectation, so it is impossible to make it to require only 1 try.
In the third case, it takes 2 tries in expectation to beat each stage, and the player can always retry that stage without falling back to one of the previous stages if they fail it. Therefore the total expected number of tries is 8. Note that there exists an answer with fewer stages, but you are not required to minimize the number of stages used.
Tags: brute force, constructive algorithms, greedy, math, probabilities
Correct Solution:
```
two = []
cur = 1
for i in range(100):
two.append(cur)
cur *= 2
t = int(input())
for _ in range(t):
k = int(input())
if k % 2:
print(-1)
continue
res = []
def get(x):
a = 0
while 1:
if two[a+3]-2 > x:
break
a += 1
res.append('1')
res.extend(['0']*a)
return x-two[a+2]+2
while k:
k = get(k)
n = len(res)
if n > 2000:
print(-1)
continue
print(n)
print(' '.join(res))
```
| 7,774 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong is developing a game consisting of n stages numbered from 1 to n. The player starts the game from the 1-st stage and should beat the stages in increasing order of the stage number. The player wins the game after beating the n-th stage.
There is at most one checkpoint on each stage, and there is always a checkpoint on the 1-st stage. At the beginning of the game, only the checkpoint on the 1-st stage is activated, and all other checkpoints are deactivated. When the player gets to the i-th stage that has a checkpoint, that checkpoint is activated.
For each try of a stage, the player can either beat the stage or fail the stage. If they beat the i-th stage, the player is moved to the i+1-st stage. If they fail the i-th stage, the player is moved to the most recent checkpoint they activated, and they have to beat the stages after that checkpoint again.
For example, assume that n = 4 and the checkpoints are on the 1-st and 3-rd stages. The player starts at the 1-st stage. If they fail on the 1-st stage, they need to retry the 1-st stage because the checkpoint on the 1-st stage is the most recent checkpoint they activated. If the player beats the 1-st stage, they're moved to the 2-nd stage. If they fail it, they're sent back to the 1-st stage again. If they beat both the 1-st stage and the 2-nd stage, they get to the 3-rd stage and the checkpoint on the 3-rd stage is activated. Now whenever they fail on the 3-rd stage, or the 4-th stage after beating the 3-rd stage, they're sent back to the 3-rd stage. If they beat both the 3-rd stage and the 4-th stage, they win the game.
Gildong is going to build the stages to have equal difficulty. He wants you to find any series of stages and checkpoints using at most 2000 stages, where the [expected number](https://en.wikipedia.org/wiki/Expected_value) of tries over all stages is exactly k, for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 50).
Each test case contains exactly one line. The line consists of a single integer k (1 ≤ k ≤ 10^{18}) — the expected number of tries over all stages Gildong wants to set for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Output
For each test case, print -1 if it's impossible to construct such a series of stages and checkpoints using at most 2000 stages.
Otherwise, print two lines. The first line should contain a single integer n (1 ≤ n ≤ 2000) – the number of stages. The second line should contain n integers, where the i-th integer represents whether the i-th stage has a checkpoint. The i-th integer should be 0 if the i-th stage doesn't have a checkpoint, and 1 if it has a checkpoint. Note that the first integer must be 1 according to the description.
Example
Input
4
1
2
8
12
Output
-1
1
1
4
1 1 1 1
5
1 1 0 1 1
Note
In the first and the second case, we can see that the 'easiest' series of stages is to have 1 stage with a checkpoint. This already requires 2 tries in expectation, so it is impossible to make it to require only 1 try.
In the third case, it takes 2 tries in expectation to beat each stage, and the player can always retry that stage without falling back to one of the previous stages if they fail it. Therefore the total expected number of tries is 8. Note that there exists an answer with fewer stages, but you are not required to minimize the number of stages used.
Submitted Solution:
```
#from random import randint
#
#
#arr=[1,1,1,1,1,1]
#m=len(arr)
#prevOne=[0 for _ in range(m)]
#for i in range(m):
# if arr[i]==1:
# prevOne[i]=i
# elif i>0:
# prevOne[i]=prevOne[i-1]
#
#t=0
#n=10000
#for _ in range(n):
# curr=0
# while curr<m:
# if randint(1,2)==2:
# curr+=1
# else:
# curr=prevOne[curr]
# t+=1
#
#print(t/n)
#each 1 contributes 2
#each 0 contributes 2**(1 + number of zeros in a row including itself)
#k=n1*2 + sum(4*(2**l - 1)) where l is the number of consequtive 0s in a row
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def calcTurnsForLZeroesInARow(L):
return 4*(2**L-1)
t=int(input())
for _ in range(t):
k=int(input())
if k%2==1:
print(-1)
else:
ans=[1]
k-=2
while k>0:
l=0
b=2000
while b>0:
while calcTurnsForLZeroesInARow(l+b)<=k:
l+=b
b//=2
ans=ans+[0]*l
k-=calcTurnsForLZeroesInARow(l)
if k==0:
break
ans.append(1)
k-=2
# print('here')
print(len(ans))
oneLineArrayPrint(ans)
```
Yes
| 7,775 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong is developing a game consisting of n stages numbered from 1 to n. The player starts the game from the 1-st stage and should beat the stages in increasing order of the stage number. The player wins the game after beating the n-th stage.
There is at most one checkpoint on each stage, and there is always a checkpoint on the 1-st stage. At the beginning of the game, only the checkpoint on the 1-st stage is activated, and all other checkpoints are deactivated. When the player gets to the i-th stage that has a checkpoint, that checkpoint is activated.
For each try of a stage, the player can either beat the stage or fail the stage. If they beat the i-th stage, the player is moved to the i+1-st stage. If they fail the i-th stage, the player is moved to the most recent checkpoint they activated, and they have to beat the stages after that checkpoint again.
For example, assume that n = 4 and the checkpoints are on the 1-st and 3-rd stages. The player starts at the 1-st stage. If they fail on the 1-st stage, they need to retry the 1-st stage because the checkpoint on the 1-st stage is the most recent checkpoint they activated. If the player beats the 1-st stage, they're moved to the 2-nd stage. If they fail it, they're sent back to the 1-st stage again. If they beat both the 1-st stage and the 2-nd stage, they get to the 3-rd stage and the checkpoint on the 3-rd stage is activated. Now whenever they fail on the 3-rd stage, or the 4-th stage after beating the 3-rd stage, they're sent back to the 3-rd stage. If they beat both the 3-rd stage and the 4-th stage, they win the game.
Gildong is going to build the stages to have equal difficulty. He wants you to find any series of stages and checkpoints using at most 2000 stages, where the [expected number](https://en.wikipedia.org/wiki/Expected_value) of tries over all stages is exactly k, for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 50).
Each test case contains exactly one line. The line consists of a single integer k (1 ≤ k ≤ 10^{18}) — the expected number of tries over all stages Gildong wants to set for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Output
For each test case, print -1 if it's impossible to construct such a series of stages and checkpoints using at most 2000 stages.
Otherwise, print two lines. The first line should contain a single integer n (1 ≤ n ≤ 2000) – the number of stages. The second line should contain n integers, where the i-th integer represents whether the i-th stage has a checkpoint. The i-th integer should be 0 if the i-th stage doesn't have a checkpoint, and 1 if it has a checkpoint. Note that the first integer must be 1 according to the description.
Example
Input
4
1
2
8
12
Output
-1
1
1
4
1 1 1 1
5
1 1 0 1 1
Note
In the first and the second case, we can see that the 'easiest' series of stages is to have 1 stage with a checkpoint. This already requires 2 tries in expectation, so it is impossible to make it to require only 1 try.
In the third case, it takes 2 tries in expectation to beat each stage, and the player can always retry that stage without falling back to one of the previous stages if they fail it. Therefore the total expected number of tries is 8. Note that there exists an answer with fewer stages, but you are not required to minimize the number of stages used.
Submitted Solution:
```
t = int(input())
add = 4
arr = [2]
for i in range(70):
arr += [arr[-1]+add]
add *= 2
# print(arr)
for _ in range(t):
k = int(input())
ans = [1]
flag = 1
while k != 0:
# print(k, ans)
flag = 0
for i in range(69, -1, -1):
if arr[i] <= k:
ans += [0]*i + [1]
flag = 1
k -= arr[i]
if flag == 0:
ans = -1
break
if ans != -1:
ans.pop()
print(len(ans))
print(*ans)
else:
print(ans)
```
Yes
| 7,776 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong is developing a game consisting of n stages numbered from 1 to n. The player starts the game from the 1-st stage and should beat the stages in increasing order of the stage number. The player wins the game after beating the n-th stage.
There is at most one checkpoint on each stage, and there is always a checkpoint on the 1-st stage. At the beginning of the game, only the checkpoint on the 1-st stage is activated, and all other checkpoints are deactivated. When the player gets to the i-th stage that has a checkpoint, that checkpoint is activated.
For each try of a stage, the player can either beat the stage or fail the stage. If they beat the i-th stage, the player is moved to the i+1-st stage. If they fail the i-th stage, the player is moved to the most recent checkpoint they activated, and they have to beat the stages after that checkpoint again.
For example, assume that n = 4 and the checkpoints are on the 1-st and 3-rd stages. The player starts at the 1-st stage. If they fail on the 1-st stage, they need to retry the 1-st stage because the checkpoint on the 1-st stage is the most recent checkpoint they activated. If the player beats the 1-st stage, they're moved to the 2-nd stage. If they fail it, they're sent back to the 1-st stage again. If they beat both the 1-st stage and the 2-nd stage, they get to the 3-rd stage and the checkpoint on the 3-rd stage is activated. Now whenever they fail on the 3-rd stage, or the 4-th stage after beating the 3-rd stage, they're sent back to the 3-rd stage. If they beat both the 3-rd stage and the 4-th stage, they win the game.
Gildong is going to build the stages to have equal difficulty. He wants you to find any series of stages and checkpoints using at most 2000 stages, where the [expected number](https://en.wikipedia.org/wiki/Expected_value) of tries over all stages is exactly k, for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 50).
Each test case contains exactly one line. The line consists of a single integer k (1 ≤ k ≤ 10^{18}) — the expected number of tries over all stages Gildong wants to set for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Output
For each test case, print -1 if it's impossible to construct such a series of stages and checkpoints using at most 2000 stages.
Otherwise, print two lines. The first line should contain a single integer n (1 ≤ n ≤ 2000) – the number of stages. The second line should contain n integers, where the i-th integer represents whether the i-th stage has a checkpoint. The i-th integer should be 0 if the i-th stage doesn't have a checkpoint, and 1 if it has a checkpoint. Note that the first integer must be 1 according to the description.
Example
Input
4
1
2
8
12
Output
-1
1
1
4
1 1 1 1
5
1 1 0 1 1
Note
In the first and the second case, we can see that the 'easiest' series of stages is to have 1 stage with a checkpoint. This already requires 2 tries in expectation, so it is impossible to make it to require only 1 try.
In the third case, it takes 2 tries in expectation to beat each stage, and the player can always retry that stage without falling back to one of the previous stages if they fail it. Therefore the total expected number of tries is 8. Note that there exists an answer with fewer stages, but you are not required to minimize the number of stages used.
Submitted Solution:
```
import sys
from collections import defaultdict as dd
from collections import Counter as cc
from queue import Queue
import math
import itertools
try:
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
except:
pass
input = lambda: sys.stdin.readline().rstrip()
for _ in range(int(input())):
q=int(input())
if q%2==1:
print(-1)
else:
w=[1]
i=2
q-=2
while q>0:
if 2*i<q:
i*=2
q-=i
w.append(0)
else:
i=2
q-=2
w.append(1)
print(len(w))
print(*w)
```
Yes
| 7,777 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong is developing a game consisting of n stages numbered from 1 to n. The player starts the game from the 1-st stage and should beat the stages in increasing order of the stage number. The player wins the game after beating the n-th stage.
There is at most one checkpoint on each stage, and there is always a checkpoint on the 1-st stage. At the beginning of the game, only the checkpoint on the 1-st stage is activated, and all other checkpoints are deactivated. When the player gets to the i-th stage that has a checkpoint, that checkpoint is activated.
For each try of a stage, the player can either beat the stage or fail the stage. If they beat the i-th stage, the player is moved to the i+1-st stage. If they fail the i-th stage, the player is moved to the most recent checkpoint they activated, and they have to beat the stages after that checkpoint again.
For example, assume that n = 4 and the checkpoints are on the 1-st and 3-rd stages. The player starts at the 1-st stage. If they fail on the 1-st stage, they need to retry the 1-st stage because the checkpoint on the 1-st stage is the most recent checkpoint they activated. If the player beats the 1-st stage, they're moved to the 2-nd stage. If they fail it, they're sent back to the 1-st stage again. If they beat both the 1-st stage and the 2-nd stage, they get to the 3-rd stage and the checkpoint on the 3-rd stage is activated. Now whenever they fail on the 3-rd stage, or the 4-th stage after beating the 3-rd stage, they're sent back to the 3-rd stage. If they beat both the 3-rd stage and the 4-th stage, they win the game.
Gildong is going to build the stages to have equal difficulty. He wants you to find any series of stages and checkpoints using at most 2000 stages, where the [expected number](https://en.wikipedia.org/wiki/Expected_value) of tries over all stages is exactly k, for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 50).
Each test case contains exactly one line. The line consists of a single integer k (1 ≤ k ≤ 10^{18}) — the expected number of tries over all stages Gildong wants to set for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Output
For each test case, print -1 if it's impossible to construct such a series of stages and checkpoints using at most 2000 stages.
Otherwise, print two lines. The first line should contain a single integer n (1 ≤ n ≤ 2000) – the number of stages. The second line should contain n integers, where the i-th integer represents whether the i-th stage has a checkpoint. The i-th integer should be 0 if the i-th stage doesn't have a checkpoint, and 1 if it has a checkpoint. Note that the first integer must be 1 according to the description.
Example
Input
4
1
2
8
12
Output
-1
1
1
4
1 1 1 1
5
1 1 0 1 1
Note
In the first and the second case, we can see that the 'easiest' series of stages is to have 1 stage with a checkpoint. This already requires 2 tries in expectation, so it is impossible to make it to require only 1 try.
In the third case, it takes 2 tries in expectation to beat each stage, and the player can always retry that stage without falling back to one of the previous stages if they fail it. Therefore the total expected number of tries is 8. Note that there exists an answer with fewer stages, but you are not required to minimize the number of stages used.
Submitted Solution:
```
from collections import deque
import sys
serie = ""
d = deque()
n = 2
d.append(n)
while n<10**18:
n = 2*n +2
d.append(n)
r = 58
def binarySearch(l,r,x):
if r >= l:
mid = l + (r - l) // 2
if d[mid] == x:
return mid
elif d[mid] > x:
return binarySearch(l, mid-1, x)
else:
return binarySearch(mid + 1, r, x)
else:
return l-1
def p(x,s = ""):
if x == 0:
return s
i = binarySearch(0,r,x)
s+="1 "+("0 "*i)
x-=d[i]
return p(x,s)
t = int(sys.stdin.readline().strip())
while t>0:
k = int(sys.stdin.readline().strip())
serie = ""
if k%2 == 1:
print(-1)
else:
s = p(k)
print(len(s)//2)
print(s)
t-=1
```
Yes
| 7,778 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong is developing a game consisting of n stages numbered from 1 to n. The player starts the game from the 1-st stage and should beat the stages in increasing order of the stage number. The player wins the game after beating the n-th stage.
There is at most one checkpoint on each stage, and there is always a checkpoint on the 1-st stage. At the beginning of the game, only the checkpoint on the 1-st stage is activated, and all other checkpoints are deactivated. When the player gets to the i-th stage that has a checkpoint, that checkpoint is activated.
For each try of a stage, the player can either beat the stage or fail the stage. If they beat the i-th stage, the player is moved to the i+1-st stage. If they fail the i-th stage, the player is moved to the most recent checkpoint they activated, and they have to beat the stages after that checkpoint again.
For example, assume that n = 4 and the checkpoints are on the 1-st and 3-rd stages. The player starts at the 1-st stage. If they fail on the 1-st stage, they need to retry the 1-st stage because the checkpoint on the 1-st stage is the most recent checkpoint they activated. If the player beats the 1-st stage, they're moved to the 2-nd stage. If they fail it, they're sent back to the 1-st stage again. If they beat both the 1-st stage and the 2-nd stage, they get to the 3-rd stage and the checkpoint on the 3-rd stage is activated. Now whenever they fail on the 3-rd stage, or the 4-th stage after beating the 3-rd stage, they're sent back to the 3-rd stage. If they beat both the 3-rd stage and the 4-th stage, they win the game.
Gildong is going to build the stages to have equal difficulty. He wants you to find any series of stages and checkpoints using at most 2000 stages, where the [expected number](https://en.wikipedia.org/wiki/Expected_value) of tries over all stages is exactly k, for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 50).
Each test case contains exactly one line. The line consists of a single integer k (1 ≤ k ≤ 10^{18}) — the expected number of tries over all stages Gildong wants to set for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Output
For each test case, print -1 if it's impossible to construct such a series of stages and checkpoints using at most 2000 stages.
Otherwise, print two lines. The first line should contain a single integer n (1 ≤ n ≤ 2000) – the number of stages. The second line should contain n integers, where the i-th integer represents whether the i-th stage has a checkpoint. The i-th integer should be 0 if the i-th stage doesn't have a checkpoint, and 1 if it has a checkpoint. Note that the first integer must be 1 according to the description.
Example
Input
4
1
2
8
12
Output
-1
1
1
4
1 1 1 1
5
1 1 0 1 1
Note
In the first and the second case, we can see that the 'easiest' series of stages is to have 1 stage with a checkpoint. This already requires 2 tries in expectation, so it is impossible to make it to require only 1 try.
In the third case, it takes 2 tries in expectation to beat each stage, and the player can always retry that stage without falling back to one of the previous stages if they fail it. Therefore the total expected number of tries is 8. Note that there exists an answer with fewer stages, but you are not required to minimize the number of stages used.
Submitted Solution:
```
T = int(input())
for _ in range(T):
k = int(input())
if k % 2: print(-1); continue
res = []
for u in range(60, 1, -1):
p = 2**u + 2
if k // p: res.append((u, k//p))
k %= p
res.append((1, k//2))
ls = []
for u, cc in res:
ls += sum([ [0]*(u-1)+[1] ]*cc, [])
print(len(ls))
print(*ls)
```
No
| 7,779 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong is developing a game consisting of n stages numbered from 1 to n. The player starts the game from the 1-st stage and should beat the stages in increasing order of the stage number. The player wins the game after beating the n-th stage.
There is at most one checkpoint on each stage, and there is always a checkpoint on the 1-st stage. At the beginning of the game, only the checkpoint on the 1-st stage is activated, and all other checkpoints are deactivated. When the player gets to the i-th stage that has a checkpoint, that checkpoint is activated.
For each try of a stage, the player can either beat the stage or fail the stage. If they beat the i-th stage, the player is moved to the i+1-st stage. If they fail the i-th stage, the player is moved to the most recent checkpoint they activated, and they have to beat the stages after that checkpoint again.
For example, assume that n = 4 and the checkpoints are on the 1-st and 3-rd stages. The player starts at the 1-st stage. If they fail on the 1-st stage, they need to retry the 1-st stage because the checkpoint on the 1-st stage is the most recent checkpoint they activated. If the player beats the 1-st stage, they're moved to the 2-nd stage. If they fail it, they're sent back to the 1-st stage again. If they beat both the 1-st stage and the 2-nd stage, they get to the 3-rd stage and the checkpoint on the 3-rd stage is activated. Now whenever they fail on the 3-rd stage, or the 4-th stage after beating the 3-rd stage, they're sent back to the 3-rd stage. If they beat both the 3-rd stage and the 4-th stage, they win the game.
Gildong is going to build the stages to have equal difficulty. He wants you to find any series of stages and checkpoints using at most 2000 stages, where the [expected number](https://en.wikipedia.org/wiki/Expected_value) of tries over all stages is exactly k, for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 50).
Each test case contains exactly one line. The line consists of a single integer k (1 ≤ k ≤ 10^{18}) — the expected number of tries over all stages Gildong wants to set for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Output
For each test case, print -1 if it's impossible to construct such a series of stages and checkpoints using at most 2000 stages.
Otherwise, print two lines. The first line should contain a single integer n (1 ≤ n ≤ 2000) – the number of stages. The second line should contain n integers, where the i-th integer represents whether the i-th stage has a checkpoint. The i-th integer should be 0 if the i-th stage doesn't have a checkpoint, and 1 if it has a checkpoint. Note that the first integer must be 1 according to the description.
Example
Input
4
1
2
8
12
Output
-1
1
1
4
1 1 1 1
5
1 1 0 1 1
Note
In the first and the second case, we can see that the 'easiest' series of stages is to have 1 stage with a checkpoint. This already requires 2 tries in expectation, so it is impossible to make it to require only 1 try.
In the third case, it takes 2 tries in expectation to beat each stage, and the player can always retry that stage without falling back to one of the previous stages if they fail it. Therefore the total expected number of tries is 8. Note that there exists an answer with fewer stages, but you are not required to minimize the number of stages used.
Submitted Solution:
```
mod = 10**9 + 7
def solve():
n = int(input())
ans = []
if n == 1:
ans.append(-1)
else:
while n > 1 and len(ans) < 2000:
if n % 2 == 0:
ans.append(1)
n //= 2;
else:
ans.append(0)
n += 1
if n > 1:
ans = [-1]
print(len(ans))
print(*ans)
t = 1
t = int(input())
while t > 0:
solve()
t -= 1
```
No
| 7,780 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong is developing a game consisting of n stages numbered from 1 to n. The player starts the game from the 1-st stage and should beat the stages in increasing order of the stage number. The player wins the game after beating the n-th stage.
There is at most one checkpoint on each stage, and there is always a checkpoint on the 1-st stage. At the beginning of the game, only the checkpoint on the 1-st stage is activated, and all other checkpoints are deactivated. When the player gets to the i-th stage that has a checkpoint, that checkpoint is activated.
For each try of a stage, the player can either beat the stage or fail the stage. If they beat the i-th stage, the player is moved to the i+1-st stage. If they fail the i-th stage, the player is moved to the most recent checkpoint they activated, and they have to beat the stages after that checkpoint again.
For example, assume that n = 4 and the checkpoints are on the 1-st and 3-rd stages. The player starts at the 1-st stage. If they fail on the 1-st stage, they need to retry the 1-st stage because the checkpoint on the 1-st stage is the most recent checkpoint they activated. If the player beats the 1-st stage, they're moved to the 2-nd stage. If they fail it, they're sent back to the 1-st stage again. If they beat both the 1-st stage and the 2-nd stage, they get to the 3-rd stage and the checkpoint on the 3-rd stage is activated. Now whenever they fail on the 3-rd stage, or the 4-th stage after beating the 3-rd stage, they're sent back to the 3-rd stage. If they beat both the 3-rd stage and the 4-th stage, they win the game.
Gildong is going to build the stages to have equal difficulty. He wants you to find any series of stages and checkpoints using at most 2000 stages, where the [expected number](https://en.wikipedia.org/wiki/Expected_value) of tries over all stages is exactly k, for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 50).
Each test case contains exactly one line. The line consists of a single integer k (1 ≤ k ≤ 10^{18}) — the expected number of tries over all stages Gildong wants to set for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Output
For each test case, print -1 if it's impossible to construct such a series of stages and checkpoints using at most 2000 stages.
Otherwise, print two lines. The first line should contain a single integer n (1 ≤ n ≤ 2000) – the number of stages. The second line should contain n integers, where the i-th integer represents whether the i-th stage has a checkpoint. The i-th integer should be 0 if the i-th stage doesn't have a checkpoint, and 1 if it has a checkpoint. Note that the first integer must be 1 according to the description.
Example
Input
4
1
2
8
12
Output
-1
1
1
4
1 1 1 1
5
1 1 0 1 1
Note
In the first and the second case, we can see that the 'easiest' series of stages is to have 1 stage with a checkpoint. This already requires 2 tries in expectation, so it is impossible to make it to require only 1 try.
In the third case, it takes 2 tries in expectation to beat each stage, and the player can always retry that stage without falling back to one of the previous stages if they fail it. Therefore the total expected number of tries is 8. Note that there exists an answer with fewer stages, but you are not required to minimize the number of stages used.
Submitted Solution:
```
import sys
from sys import stdin
tt = int(stdin.readline())
for loop in range(tt):
k = int(stdin.readline())
ans = []
if k % 2 == 1:
print (-1)
continue
tmp = 1
while k > 0:
if k & (2**tmp) > 0:
ans.append(1)
for i in range(tmp-1):
ans.append(0)
k ^= 2**tmp
tmp += 1
if len(ans) <= 2000:
print (len(ans))
print (*ans)
else:
print (-1)
```
No
| 7,781 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong is developing a game consisting of n stages numbered from 1 to n. The player starts the game from the 1-st stage and should beat the stages in increasing order of the stage number. The player wins the game after beating the n-th stage.
There is at most one checkpoint on each stage, and there is always a checkpoint on the 1-st stage. At the beginning of the game, only the checkpoint on the 1-st stage is activated, and all other checkpoints are deactivated. When the player gets to the i-th stage that has a checkpoint, that checkpoint is activated.
For each try of a stage, the player can either beat the stage or fail the stage. If they beat the i-th stage, the player is moved to the i+1-st stage. If they fail the i-th stage, the player is moved to the most recent checkpoint they activated, and they have to beat the stages after that checkpoint again.
For example, assume that n = 4 and the checkpoints are on the 1-st and 3-rd stages. The player starts at the 1-st stage. If they fail on the 1-st stage, they need to retry the 1-st stage because the checkpoint on the 1-st stage is the most recent checkpoint they activated. If the player beats the 1-st stage, they're moved to the 2-nd stage. If they fail it, they're sent back to the 1-st stage again. If they beat both the 1-st stage and the 2-nd stage, they get to the 3-rd stage and the checkpoint on the 3-rd stage is activated. Now whenever they fail on the 3-rd stage, or the 4-th stage after beating the 3-rd stage, they're sent back to the 3-rd stage. If they beat both the 3-rd stage and the 4-th stage, they win the game.
Gildong is going to build the stages to have equal difficulty. He wants you to find any series of stages and checkpoints using at most 2000 stages, where the [expected number](https://en.wikipedia.org/wiki/Expected_value) of tries over all stages is exactly k, for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 50).
Each test case contains exactly one line. The line consists of a single integer k (1 ≤ k ≤ 10^{18}) — the expected number of tries over all stages Gildong wants to set for a player whose probability of beating each stage is exactly \cfrac{1}{2}.
Output
For each test case, print -1 if it's impossible to construct such a series of stages and checkpoints using at most 2000 stages.
Otherwise, print two lines. The first line should contain a single integer n (1 ≤ n ≤ 2000) – the number of stages. The second line should contain n integers, where the i-th integer represents whether the i-th stage has a checkpoint. The i-th integer should be 0 if the i-th stage doesn't have a checkpoint, and 1 if it has a checkpoint. Note that the first integer must be 1 according to the description.
Example
Input
4
1
2
8
12
Output
-1
1
1
4
1 1 1 1
5
1 1 0 1 1
Note
In the first and the second case, we can see that the 'easiest' series of stages is to have 1 stage with a checkpoint. This already requires 2 tries in expectation, so it is impossible to make it to require only 1 try.
In the third case, it takes 2 tries in expectation to beat each stage, and the player can always retry that stage without falling back to one of the previous stages if they fail it. Therefore the total expected number of tries is 8. Note that there exists an answer with fewer stages, but you are not required to minimize the number of stages used.
Submitted Solution:
```
import math
a = int(input())
for i in range(a):
k = int(input())
if k %2 == 1:
print("-1")
else:
ans = ""
time = 0
while (k>0):
n = int(math.log(k+2,2))-1
ans += "1 "
k -= pow(2,n)
n -= 1
time += 1
while(n>0):
ans += "0 "
k -= pow(2,n)
n -= 1
time += 1
print(time)
print(ans[:-1])
```
No
| 7,782 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nezzar has a binary string s of length n that he wants to share with his best friend, Nanako. Nanako will spend q days inspecting the binary string. At the same time, Nezzar wants to change the string s into string f during these q days, because it looks better.
It is known that Nanako loves consistency so much. On the i-th day, Nanako will inspect a segment of string s from position l_i to position r_i inclusive. If the segment contains both characters '0' and '1', Nanako becomes unhappy and throws away the string.
After this inspection, at the i-th night, Nezzar can secretly change strictly less than half of the characters in the segment from l_i to r_i inclusive, otherwise the change will be too obvious.
Now Nezzar wonders, if it is possible to avoid Nanako being unhappy and at the same time have the string become equal to the string f at the end of these q days and nights.
Input
The first line contains a single integer t (1 ≤ t ≤ 2 ⋅ 10^5) — the number of test cases.
The first line of each test case contains two integers n,q (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ q ≤ 2 ⋅ 10^5).
The second line of each test case contains a binary string s of length n.
The third line of each test case contains a binary string f of length n.
Then q lines follow, i-th of them contains two integers l_i,r_i (1 ≤ l_i ≤ r_i ≤ n) — bounds of the segment, that Nanako will inspect on the i-th day.
It is guaranteed that the sum of n for all test cases doesn't exceed 2 ⋅ 10^5, and the sum of q for all test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print "YES" on the single line if it is possible to avoid Nanako being unhappy and have the string f at the end of q days and nights. Otherwise, print "NO".
You can print each letter in any case (upper or lower).
Example
Input
4
5 2
00000
00111
1 5
1 3
2 1
00
01
1 2
10 6
1111111111
0110001110
1 10
5 9
7 10
1 7
3 5
6 10
5 2
10000
11000
2 5
1 3
Output
YES
NO
YES
NO
Note
In the first test case, \underline{00000} → \underline{000}11 → 00111 is one of the possible sequences of string changes.
In the second test case, it can be shown that it is impossible to have the string f at the end.
Tags: data structures, greedy
Correct Solution:
```
import sys
readline = sys.stdin.readline
"""
import io,os
readline = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
"""
from operator import add
class Lazysegtree:
def __init__(self, A, fx, ex, fm, em, fa, initialize = True):
self.N = len(A)
self.N0 = 2**(self.N-1).bit_length()
self.dep = (self.N-1).bit_length()
self.fx = fx
self.ex = ex
self.em = em
self.lazy = [em]*(2*self.N0)
if initialize:
self.data = [self.ex]*self.N0 + A + [self.ex]*(self.N0 - self.N)
for i in range(self.N0-1, -1, -1):
self.data[i] = self.fx(self.data[2*i], self.data[2*i+1])
else:
self.data = [self.ex]*(2*self.N0)
def fa(self, ope, idx):
if ope is not None:
return ope*(1<<(self.dep - idx.bit_length() + 1))
return self.data[idx]
def fm(self, ope1, ope2):
return ope1
def __repr__(self):
s = 'data'
l = 'lazy'
cnt = 1
for i in range(self.N0.bit_length()):
s = '\n'.join((s, ' '.join(map(str, self.data[cnt:cnt+(1<<i)]))))
l = '\n'.join((l, ' '.join(map(str, self.lazy[cnt:cnt+(1<<i)]))))
cnt += 1<<i
return '\n'.join((s, l))
def _ascend(self, k):
k = k >> 1
c = k.bit_length()
for j in range(c):
idx = k >> j
self.data[idx] = self.fx(self.data[2*idx], self.data[2*idx+1])
def _descend(self, k):
k = k >> 1
idx = 1
c = k.bit_length()
for j in range(1, c+1):
idx = k >> (c - j)
if self.lazy[idx] == self.em:
continue
self.data[2*idx] = self.fa(self.lazy[idx], 2*idx)
self.data[2*idx+1] = self.fa(self.lazy[idx], 2*idx+1)
self.lazy[2*idx] = self.fm(self.lazy[idx], self.lazy[2*idx])
self.lazy[2*idx+1] = self.fm(self.lazy[idx], self.lazy[2*idx+1])
self.lazy[idx] = self.em
def query(self, l, r):
L = l+self.N0
R = r+self.N0
self._descend(L//(L & -L))
self._descend(R//(R & -R)-1)
sl = self.ex
sr = self.ex
while L < R:
if R & 1:
R -= 1
sr = self.fx(self.data[R], sr)
if L & 1:
sl = self.fx(sl, self.data[L])
L += 1
L >>= 1
R >>= 1
return self.fx(sl, sr)
def operate(self, l, r, x):
L = l+self.N0
R = r+self.N0
Li = L//(L & -L)
Ri = R//(R & -R)
self._descend(Li)
self._descend(Ri-1)
while L < R :
if R & 1:
R -= 1
self.data[R] = self.fa(x, R)
self.lazy[R] = self.fm(x, self.lazy[R])
if L & 1:
self.data[L] = self.fa(x, L)
self.lazy[L] = self.fm(x, self.lazy[L])
L += 1
L >>= 1
R >>= 1
self._ascend(Li)
self._ascend(Ri-1)
def propall(self):
for idx in range(1, self.N0):
self.data[2*idx] = self.fa(self.lazy[idx], 2*idx)
self.data[2*idx+1] = self.fa(self.lazy[idx], 2*idx+1)
self.lazy[2*idx] = self.fm(self.lazy[idx], self.lazy[2*idx])
self.lazy[2*idx+1] = self.fm(self.lazy[idx], self.lazy[2*idx+1])
T = int(readline())
Ans = ['NO']*T
for qu in range(T):
N, Q = map(int, readline().split())
S = list(map(int, readline().strip()))
T = list(map(int, readline().strip()))
"""
S = list(map(lambda x: int(x)-48, readline().strip()))
T = list(map(lambda x: int(x)-48, readline().strip()))
"""
Qs = [tuple(map(int, readline().split())) for _ in range(Q)]
K = Lazysegtree(T, add, 0, None, None, None)
for l, r in Qs[::-1]:
l -= 1
leng = r-l
x = K.query(l, r)
if 2*x > leng:
K.operate(l, r, 1)
elif 2*x == leng:
break
else:
K.operate(l, r, 0)
else:
if [K.query(i, i+1) for i in range(N)] == S:
Ans[qu] = 'YES'
print('\n'.join(Ans))
```
| 7,783 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nezzar has a binary string s of length n that he wants to share with his best friend, Nanako. Nanako will spend q days inspecting the binary string. At the same time, Nezzar wants to change the string s into string f during these q days, because it looks better.
It is known that Nanako loves consistency so much. On the i-th day, Nanako will inspect a segment of string s from position l_i to position r_i inclusive. If the segment contains both characters '0' and '1', Nanako becomes unhappy and throws away the string.
After this inspection, at the i-th night, Nezzar can secretly change strictly less than half of the characters in the segment from l_i to r_i inclusive, otherwise the change will be too obvious.
Now Nezzar wonders, if it is possible to avoid Nanako being unhappy and at the same time have the string become equal to the string f at the end of these q days and nights.
Input
The first line contains a single integer t (1 ≤ t ≤ 2 ⋅ 10^5) — the number of test cases.
The first line of each test case contains two integers n,q (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ q ≤ 2 ⋅ 10^5).
The second line of each test case contains a binary string s of length n.
The third line of each test case contains a binary string f of length n.
Then q lines follow, i-th of them contains two integers l_i,r_i (1 ≤ l_i ≤ r_i ≤ n) — bounds of the segment, that Nanako will inspect on the i-th day.
It is guaranteed that the sum of n for all test cases doesn't exceed 2 ⋅ 10^5, and the sum of q for all test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print "YES" on the single line if it is possible to avoid Nanako being unhappy and have the string f at the end of q days and nights. Otherwise, print "NO".
You can print each letter in any case (upper or lower).
Example
Input
4
5 2
00000
00111
1 5
1 3
2 1
00
01
1 2
10 6
1111111111
0110001110
1 10
5 9
7 10
1 7
3 5
6 10
5 2
10000
11000
2 5
1 3
Output
YES
NO
YES
NO
Note
In the first test case, \underline{00000} → \underline{000}11 → 00111 is one of the possible sequences of string changes.
In the second test case, it can be shown that it is impossible to have the string f at the end.
Tags: data structures, greedy
Correct Solution:
```
import io
import os
from math import floor
# https://github.com/atcoder/ac-library/blob/master/atcoder/lazysegtree.hpp
class LazySegTree:
def __init__(self, _op, _e, _mapping, _composition, _id, v):
def set(p, x):
assert 0 <= p < _n
p += _size
for i in range(_log, 0, -1):
_push(p >> i)
_d[p] = x
for i in range(1, _log + 1):
_update(p >> i)
def get(p):
assert 0 <= p < _n
p += _size
for i in range(_log, 0, -1):
_push(p >> i)
return _d[p]
def prod(l, r):
assert 0 <= l <= r <= _n
if l == r:
return _e
l += _size
r += _size
for i in range(_log, 0, -1):
if ((l >> i) << i) != l:
_push(l >> i)
if ((r >> i) << i) != r:
_push(r >> i)
sml = _e
smr = _e
while l < r:
if l & 1:
sml = _op(sml, _d[l])
l += 1
if r & 1:
r -= 1
smr = _op(_d[r], smr)
l >>= 1
r >>= 1
return _op(sml, smr)
def apply(l, r, f):
assert 0 <= l <= r <= _n
if l == r:
return
l += _size
r += _size
for i in range(_log, 0, -1):
if ((l >> i) << i) != l:
_push(l >> i)
if ((r >> i) << i) != r:
_push((r - 1) >> i)
l2 = l
r2 = r
while l < r:
if l & 1:
_all_apply(l, f)
l += 1
if r & 1:
r -= 1
_all_apply(r, f)
l >>= 1
r >>= 1
l = l2
r = r2
for i in range(1, _log + 1):
if ((l >> i) << i) != l:
_update(l >> i)
if ((r >> i) << i) != r:
_update((r - 1) >> i)
def _update(k):
_d[k] = _op(_d[2 * k], _d[2 * k + 1])
def _all_apply(k, f):
_d[k] = _mapping(f, _d[k])
if k < _size:
_lz[k] = _composition(f, _lz[k])
def _push(k):
_all_apply(2 * k, _lz[k])
_all_apply(2 * k + 1, _lz[k])
_lz[k] = _id
_n = len(v)
_log = _n.bit_length()
_size = 1 << _log
_d = [_e] * (2 * _size)
_lz = [_id] * _size
for i in range(_n):
_d[_size + i] = v[i]
for i in range(_size - 1, 0, -1):
_update(i)
self.set = set
self.get = get
self.prod = prod
self.apply = apply
MIL = 1 << 20
def makeNode(total, count):
# Pack a pair into a float
return (total * MIL) + count
def getTotal(node):
return floor(node / MIL)
def getCount(node):
return node - getTotal(node) * MIL
nodeIdentity = makeNode(0.0, 0.0)
def nodeOp(node1, node2):
return node1 + node2
# Equivalent to the following:
return makeNode(
getTotal(node1) + getTotal(node2), getCount(node1) + getCount(node2)
)
identityMapping = -1
def mapping(tag, node):
if tag == identityMapping:
return node
# If assigned, new total is the number assigned times count
count = getCount(node)
return makeNode(tag * count, count)
def composition(mapping1, mapping2):
# If assigned multiple times, take first non-identity assignment
return mapping1 if mapping1 != identityMapping else mapping2
def solve(N, Q, S, F, LR):
segTree = LazySegTree(
nodeOp,
nodeIdentity,
mapping,
composition,
identityMapping,
[makeNode(float(d), 1.0) for d in F],
)
for l, r in LR[::-1]:
l -= 1
countOnes = getTotal(segTree.prod(l, r))
countZeroes = r - l - countOnes
if countZeroes > countOnes:
# Majority were zeroes
segTree.apply(l, r, 0)
elif countZeroes < countOnes:
# Majority were ones
segTree.apply(l, r, 1)
else:
# No majority
return "NO"
for i in range(N):
if getTotal(segTree.get(i)) != S[i]:
return "NO"
return "YES"
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
TC = int(input())
for tc in range(1, TC + 1):
N, Q = [int(x) for x in input().split()]
S = [int(d) for d in input().decode().rstrip()]
F = [int(d) for d in input().decode().rstrip()]
LR = [[int(x) for x in input().split()] for i in range(Q)]
ans = solve(N, Q, S, F, LR)
print(ans)
```
| 7,784 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nezzar has a binary string s of length n that he wants to share with his best friend, Nanako. Nanako will spend q days inspecting the binary string. At the same time, Nezzar wants to change the string s into string f during these q days, because it looks better.
It is known that Nanako loves consistency so much. On the i-th day, Nanako will inspect a segment of string s from position l_i to position r_i inclusive. If the segment contains both characters '0' and '1', Nanako becomes unhappy and throws away the string.
After this inspection, at the i-th night, Nezzar can secretly change strictly less than half of the characters in the segment from l_i to r_i inclusive, otherwise the change will be too obvious.
Now Nezzar wonders, if it is possible to avoid Nanako being unhappy and at the same time have the string become equal to the string f at the end of these q days and nights.
Input
The first line contains a single integer t (1 ≤ t ≤ 2 ⋅ 10^5) — the number of test cases.
The first line of each test case contains two integers n,q (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ q ≤ 2 ⋅ 10^5).
The second line of each test case contains a binary string s of length n.
The third line of each test case contains a binary string f of length n.
Then q lines follow, i-th of them contains two integers l_i,r_i (1 ≤ l_i ≤ r_i ≤ n) — bounds of the segment, that Nanako will inspect on the i-th day.
It is guaranteed that the sum of n for all test cases doesn't exceed 2 ⋅ 10^5, and the sum of q for all test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print "YES" on the single line if it is possible to avoid Nanako being unhappy and have the string f at the end of q days and nights. Otherwise, print "NO".
You can print each letter in any case (upper or lower).
Example
Input
4
5 2
00000
00111
1 5
1 3
2 1
00
01
1 2
10 6
1111111111
0110001110
1 10
5 9
7 10
1 7
3 5
6 10
5 2
10000
11000
2 5
1 3
Output
YES
NO
YES
NO
Note
In the first test case, \underline{00000} → \underline{000}11 → 00111 is one of the possible sequences of string changes.
In the second test case, it can be shown that it is impossible to have the string f at the end.
Tags: data structures, greedy
Correct Solution:
```
import sys
input = sys.stdin.readline
def indexes(L,R):
INDLIST=[]
R-=1
L>>=1
R>>=1
while L!=R:
if L>R:
INDLIST.append(L)
L>>=1
else:
INDLIST.append(R)
R>>=1
while L!=0:
INDLIST.append(L)
L>>=1
return INDLIST
def updates(l,r,x):
L=l+seg_el
R=r+seg_el
L//=(L & (-L))
R//=(R & (-R))
UPIND=indexes(L,R)
for ind in UPIND[::-1]:
if LAZY[ind]!=None:
update_lazy = LAZY[ind] *(1<<(seg_height - 1 - (ind.bit_length())))
LAZY[ind<<1]=LAZY[1+(ind<<1)]=LAZY[ind]
SEG[ind<<1]=SEG[1+(ind<<1)]=update_lazy
LAZY[ind]=None
while L!=R:
if L > R:
SEG[L]=x * (1<<(seg_height - (L.bit_length())))
LAZY[L]=x
L+=1
L//=(L & (-L))
else:
R-=1
SEG[R]=x * (1<<(seg_height - (R.bit_length())))
LAZY[R]=x
R//=(R & (-R))
for ind in UPIND:
SEG[ind]=SEG[ind<<1]+SEG[1+(ind<<1)]
def getvalues(l,r):
L=l+seg_el
R=r+seg_el
L//=(L & (-L))
R//=(R & (-R))
UPIND=indexes(L,R)
for ind in UPIND[::-1]:
if LAZY[ind]!=None:
update_lazy = LAZY[ind] *(1<<(seg_height - 1 - (ind.bit_length())))
LAZY[ind<<1]=LAZY[1+(ind<<1)]=LAZY[ind]
SEG[ind<<1]=SEG[1+(ind<<1)]=update_lazy
LAZY[ind]=None
ANS=0
while L!=R:
if L > R:
ANS+=SEG[L]
L+=1
L//=(L & (-L))
else:
R-=1
ANS+=SEG[R]
R//=(R & (-R))
return ANS
t=int(input())
for tests in range(t):
n,q=map(int,input().split())
S=input().strip()
F=input().strip()
Q=[tuple(map(int,input().split())) for i in range(q)]
seg_el=1<<(n.bit_length())
seg_height=1+n.bit_length()
SEG=[0]*(2*seg_el)
LAZY=[None]*(2*seg_el)
for i in range(n):
SEG[i+seg_el]=int(F[i])
for i in range(seg_el-1,0,-1):
SEG[i]=SEG[i*2]+SEG[i*2+1]
for l,r in Q[::-1]:
SUM=r-l+1
xx=getvalues(l-1,r)
if xx*2==SUM:
print("NO")
break
else:
if xx*2>SUM:
updates(l-1,r,1)
else:
updates(l-1,r,0)
else:
for i in range(n):
if getvalues(i,i+1)==int(S[i]):
True
else:
print("NO")
break
else:
print("YES")
```
| 7,785 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nezzar has a binary string s of length n that he wants to share with his best friend, Nanako. Nanako will spend q days inspecting the binary string. At the same time, Nezzar wants to change the string s into string f during these q days, because it looks better.
It is known that Nanako loves consistency so much. On the i-th day, Nanako will inspect a segment of string s from position l_i to position r_i inclusive. If the segment contains both characters '0' and '1', Nanako becomes unhappy and throws away the string.
After this inspection, at the i-th night, Nezzar can secretly change strictly less than half of the characters in the segment from l_i to r_i inclusive, otherwise the change will be too obvious.
Now Nezzar wonders, if it is possible to avoid Nanako being unhappy and at the same time have the string become equal to the string f at the end of these q days and nights.
Input
The first line contains a single integer t (1 ≤ t ≤ 2 ⋅ 10^5) — the number of test cases.
The first line of each test case contains two integers n,q (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ q ≤ 2 ⋅ 10^5).
The second line of each test case contains a binary string s of length n.
The third line of each test case contains a binary string f of length n.
Then q lines follow, i-th of them contains two integers l_i,r_i (1 ≤ l_i ≤ r_i ≤ n) — bounds of the segment, that Nanako will inspect on the i-th day.
It is guaranteed that the sum of n for all test cases doesn't exceed 2 ⋅ 10^5, and the sum of q for all test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print "YES" on the single line if it is possible to avoid Nanako being unhappy and have the string f at the end of q days and nights. Otherwise, print "NO".
You can print each letter in any case (upper or lower).
Example
Input
4
5 2
00000
00111
1 5
1 3
2 1
00
01
1 2
10 6
1111111111
0110001110
1 10
5 9
7 10
1 7
3 5
6 10
5 2
10000
11000
2 5
1 3
Output
YES
NO
YES
NO
Note
In the first test case, \underline{00000} → \underline{000}11 → 00111 is one of the possible sequences of string changes.
In the second test case, it can be shown that it is impossible to have the string f at the end.
Tags: data structures, greedy
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
def __init__(self, file):
self.newlines = 0
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 S(): return input().strip()
def print_list(l): print(' '.join(map(str, l)))
# sys.setrecursionlimit(200000)
# import random
# from functools import reduce
# from functools import lru_cache
# from heapq import *
# from collections import deque as dq
# import math
# import bisect as bs
# from collections import Counter
# from collections import defaultdict as dc
def set_range(lx, rx, v, now):
if l <= lx and r >= rx:
label[now] = v
node[now] = rx - lx if v else 0
return
mx = (lx + rx) >> 1
nl = now << 1
nr = nl + 1
if label[now] != -1: # 非对称操作启用该环节
node[nl] = node[nr] = node[now] >> 1
label[nl] = label[nr] = label[now]
label[now] = -1
if l < mx: set_range(lx, mx, v, nl)
if r > mx: set_range(mx, rx, v, nr)
node[now] = node[nl] + node[nr]
def get_range(lx, rx, now):
if l <= lx and r >= rx: return node[now]
mx = (lx + rx) >> 1
nl = now << 1
nr = nl + 1
if label[now] != -1: return min(rx, r) - max(lx, l) if label[now] else 0
m1 = get_range(lx, mx, nl) if l < mx else 0
m2 = get_range(mx, rx, nr) if r > mx else 0
return m1 + m2
def match(lx, rx, now):
if lx >= n: return False
if now >= sn: return node[now] != s[lx]
if label[now] != -1: return any(v != label[now] for v in s[lx:rx])
mx = (rx + lx) >> 1
return match(lx, mx, now << 1) or match(mx, rx, now << 1 | 1)
ans = []
for _ in range(N()):
n, q = RL()
s, t = [int(c) for c in S()], [int(c) for c in S()]
p = [tuple(RL()) for _ in range(q)]
sn = 1 << n.bit_length()
node = [0] * sn + t + [0] * (sn - n)
label = [-1] * (2 * sn)
for i in range(sn - 1, 0, -1): node[i] = node[i << 1] + node[i << 1 | 1]
f = True
for l, r in p[::-1]:
l -= 1
count = get_range(0, sn, 1) * 2
if count == r - l:
f = False
break
set_range(0, sn, 1 if count > r - l else 0, 1)
ans.append('YES' if f and not match(0, sn, 1) else 'NO')
print('\n'.join(ans))
```
| 7,786 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nezzar has a binary string s of length n that he wants to share with his best friend, Nanako. Nanako will spend q days inspecting the binary string. At the same time, Nezzar wants to change the string s into string f during these q days, because it looks better.
It is known that Nanako loves consistency so much. On the i-th day, Nanako will inspect a segment of string s from position l_i to position r_i inclusive. If the segment contains both characters '0' and '1', Nanako becomes unhappy and throws away the string.
After this inspection, at the i-th night, Nezzar can secretly change strictly less than half of the characters in the segment from l_i to r_i inclusive, otherwise the change will be too obvious.
Now Nezzar wonders, if it is possible to avoid Nanako being unhappy and at the same time have the string become equal to the string f at the end of these q days and nights.
Input
The first line contains a single integer t (1 ≤ t ≤ 2 ⋅ 10^5) — the number of test cases.
The first line of each test case contains two integers n,q (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ q ≤ 2 ⋅ 10^5).
The second line of each test case contains a binary string s of length n.
The third line of each test case contains a binary string f of length n.
Then q lines follow, i-th of them contains two integers l_i,r_i (1 ≤ l_i ≤ r_i ≤ n) — bounds of the segment, that Nanako will inspect on the i-th day.
It is guaranteed that the sum of n for all test cases doesn't exceed 2 ⋅ 10^5, and the sum of q for all test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print "YES" on the single line if it is possible to avoid Nanako being unhappy and have the string f at the end of q days and nights. Otherwise, print "NO".
You can print each letter in any case (upper or lower).
Example
Input
4
5 2
00000
00111
1 5
1 3
2 1
00
01
1 2
10 6
1111111111
0110001110
1 10
5 9
7 10
1 7
3 5
6 10
5 2
10000
11000
2 5
1 3
Output
YES
NO
YES
NO
Note
In the first test case, \underline{00000} → \underline{000}11 → 00111 is one of the possible sequences of string changes.
In the second test case, it can be shown that it is impossible to have the string f at the end.
Tags: data structures, greedy
Correct Solution:
```
import sys, io, os
if os.environ['USERNAME']=='kissz':
inp1=inp2=open('in.txt','r').readline
def debug(*args):
print(*args,file=sys.stderr)
else:
#inp1=input
inp1=inp2=sys.stdin.readline
#inp2=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def debug(*args):
pass
# SCRIPT STARTS HERE
class lazytree:
def __init__(self,array):
n=len(array)-1
i=1
while n:
n>>=1
i+=1
self.tree=[0]*(2**(i-1)-1)+array+[0]*(2**(i-1)-len(array))
self.l=0
self.r=2**(i-1)-1
self.lazy=[0]*(2**i-1)
self.lazyval=[0]*(2**i-1)
for i in range(2**(i-1)-2,-1,-1):
self.tree[i]=self.tree[2*i+1]+self.tree[2*i+2]
def query(self,l,r):
if l==self.l and r==self.r:
parents=[]
children=[(0,l,r)]
else:
parents=[(0,self.l,self.r)]
children=[]
i=0
while i<len(parents):
loc,L,R=parents[i]
left=(loc*2+1,L,L+(R-L+1)//2-1)
right=(loc*2+2,L+(R-L+1)//2,R)
if self.lazy[loc]:
self.lazy[loc]=0
self.tree[left[0]]=self.tree[right[0]]=(left[2]-left[1]+1)*self.lazyval[loc]
self.lazy[left[0]]=self.lazy[right[0]]=1
self.lazyval[left[0]]=self.lazyval[right[0]]=self.lazyval[loc]
if l<=left[1] and left[2]<=r:
children.append(left)
elif left[1]<=l<=left[2] or left[1]<=r<=left[2]:
parents.append(left)
if l<=right[1] and right[2]<=r:
children.append(right)
elif right[1]<=l<=right[2] or right[1]<=r<=right[2]:
parents.append(right)
i+=1
ones=sum(self.tree[child[0]] for child in children)
zeros=r-l+1-ones
if ones==zeros:
return -1
elif ones>zeros:
for child in children:
self.tree[child[0]]=child[2]-child[1]+1
self.lazy[child[0]]=1
self.lazyval[child[0]]=1
else:
for child in children:
self.tree[child[0]]=0
self.lazy[child[0]]=1
self.lazyval[child[0]]=0
for i,_,_ in reversed(parents):
self.tree[i]=self.tree[2*i+1]+self.tree[2*i+2]
return self.tree[child[0]]
def get_all(self):
n=self.r-self.l
for i in range(n):
if self.lazy[i]:
self.lazy[i]=0
self.tree[2*i+1]=self.tree[2*i+2]=self.lazyval[i] # destroying tree
self.lazy[2*i+1]=self.lazy[2*i+2]=1
self.lazyval[2*i+1]=self.lazyval[2*i+2]=self.lazyval[i]
return self.tree[n:]
for _ in range(int(inp2())):
n,q=map(int,inp2().split())
s=[int(c) for c in inp1().strip()]
f=[int(c) for c in inp1().strip()]
moves=[]
ans=True
for _ in range(q):
l,r=map(int,inp2().split())
moves.append((l-1,r-1))
tr=lazytree(f)
for l,r in reversed(moves):
success=tr.query(l,r)
if success==-1:
break
else:
f=tr.get_all()[:n]
if f!=s: success=-1
if success>=0:
print('YES')
else:
print('NO')
```
| 7,787 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nezzar has a binary string s of length n that he wants to share with his best friend, Nanako. Nanako will spend q days inspecting the binary string. At the same time, Nezzar wants to change the string s into string f during these q days, because it looks better.
It is known that Nanako loves consistency so much. On the i-th day, Nanako will inspect a segment of string s from position l_i to position r_i inclusive. If the segment contains both characters '0' and '1', Nanako becomes unhappy and throws away the string.
After this inspection, at the i-th night, Nezzar can secretly change strictly less than half of the characters in the segment from l_i to r_i inclusive, otherwise the change will be too obvious.
Now Nezzar wonders, if it is possible to avoid Nanako being unhappy and at the same time have the string become equal to the string f at the end of these q days and nights.
Input
The first line contains a single integer t (1 ≤ t ≤ 2 ⋅ 10^5) — the number of test cases.
The first line of each test case contains two integers n,q (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ q ≤ 2 ⋅ 10^5).
The second line of each test case contains a binary string s of length n.
The third line of each test case contains a binary string f of length n.
Then q lines follow, i-th of them contains two integers l_i,r_i (1 ≤ l_i ≤ r_i ≤ n) — bounds of the segment, that Nanako will inspect on the i-th day.
It is guaranteed that the sum of n for all test cases doesn't exceed 2 ⋅ 10^5, and the sum of q for all test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print "YES" on the single line if it is possible to avoid Nanako being unhappy and have the string f at the end of q days and nights. Otherwise, print "NO".
You can print each letter in any case (upper or lower).
Example
Input
4
5 2
00000
00111
1 5
1 3
2 1
00
01
1 2
10 6
1111111111
0110001110
1 10
5 9
7 10
1 7
3 5
6 10
5 2
10000
11000
2 5
1 3
Output
YES
NO
YES
NO
Note
In the first test case, \underline{00000} → \underline{000}11 → 00111 is one of the possible sequences of string changes.
In the second test case, it can be shown that it is impossible to have the string f at the end.
Tags: data structures, greedy
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
def __init__(self, file):
self.newlines = 0
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 = 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 S(): return input().strip()
def print_list(l): print(' '.join(map(str, l)))
# sys.setrecursionlimit(200000)
# import random
# from functools import reduce
# from functools import lru_cache
# from heapq import *
# from collections import deque as dq
# import math
# import bisect as bs
# from collections import Counter
# from collections import defaultdict as dc
def set_range(lx, rx, v, now):
if l <= lx and r >= rx:
label[now] = v
node[now] = rx - lx if v else 0
return
mx = (lx + rx) >> 1
nl = now << 1
nr = nl + 1
if label[now] != -1: # 非对称操作启用该环节
node[nl] = node[nr] = node[now] >> 1
label[nl] = label[nr] = label[now]
label[now] = -1
if l < mx: set_range(lx, mx, v, nl)
if r > mx: set_range(mx, rx, v, nr)
node[now] = node[nl] + node[nr]
def get_range(lx, rx, now):
if l <= lx and r >= rx: return node[now]
mx = (lx + rx) >> 1
nl = now << 1
nr = nl + 1
if label[now] != -1: return min(rx, r) - max(lx, l) if label[now] else 0
m1 = get_range(lx, mx, nl) if l < mx else 0
m2 = get_range(mx, rx, nr) if r > mx else 0
return m1 + m2
def match(lx, rx, now):
if lx >= n: return False
if now >= sn: return node[now] != s[lx]
if label[now] != -1: return any(v != label[now] for v in s[lx:rx])
mx = (rx + lx) >> 1
return match(lx, mx, now << 1) or match(mx, rx, now << 1 | 1)
for _ in range(N()):
n, q = RL()
s, t = [int(c) for c in S()], [int(c) for c in S()]
p = [tuple(RL()) for _ in range(q)]
sn = 1 << n.bit_length()
node = [0] * sn + t + [0] * (sn - n)
label = [-1] * (2 * sn)
for i in range(sn - 1, 0, -1): node[i] = node[i << 1] + node[i << 1 | 1]
f = True
for l, r in p[::-1]:
l -= 1
count = get_range(0, sn, 1) * 2
if count == r - l:
f = False
break
set_range(0, sn, 1 if count > r - l else 0, 1)
print('YES' if f and not match(0, sn, 1) else 'NO')
```
| 7,788 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nezzar has a binary string s of length n that he wants to share with his best friend, Nanako. Nanako will spend q days inspecting the binary string. At the same time, Nezzar wants to change the string s into string f during these q days, because it looks better.
It is known that Nanako loves consistency so much. On the i-th day, Nanako will inspect a segment of string s from position l_i to position r_i inclusive. If the segment contains both characters '0' and '1', Nanako becomes unhappy and throws away the string.
After this inspection, at the i-th night, Nezzar can secretly change strictly less than half of the characters in the segment from l_i to r_i inclusive, otherwise the change will be too obvious.
Now Nezzar wonders, if it is possible to avoid Nanako being unhappy and at the same time have the string become equal to the string f at the end of these q days and nights.
Input
The first line contains a single integer t (1 ≤ t ≤ 2 ⋅ 10^5) — the number of test cases.
The first line of each test case contains two integers n,q (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ q ≤ 2 ⋅ 10^5).
The second line of each test case contains a binary string s of length n.
The third line of each test case contains a binary string f of length n.
Then q lines follow, i-th of them contains two integers l_i,r_i (1 ≤ l_i ≤ r_i ≤ n) — bounds of the segment, that Nanako will inspect on the i-th day.
It is guaranteed that the sum of n for all test cases doesn't exceed 2 ⋅ 10^5, and the sum of q for all test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print "YES" on the single line if it is possible to avoid Nanako being unhappy and have the string f at the end of q days and nights. Otherwise, print "NO".
You can print each letter in any case (upper or lower).
Example
Input
4
5 2
00000
00111
1 5
1 3
2 1
00
01
1 2
10 6
1111111111
0110001110
1 10
5 9
7 10
1 7
3 5
6 10
5 2
10000
11000
2 5
1 3
Output
YES
NO
YES
NO
Note
In the first test case, \underline{00000} → \underline{000}11 → 00111 is one of the possible sequences of string changes.
In the second test case, it can be shown that it is impossible to have the string f at the end.
Tags: data structures, greedy
Correct Solution:
```
# lazy segment tree
t=[0]*(4*200000)
lazy=[-1]*(4*200000)
def build(a,v,tl,tr):
if (tl==tr):
t[v]=a[tl]
else:
tm=(tl+tr)//2
build(a,v*2,tl,tm)
build(a,v*2+1,tm+1,tr)
t[v]=t[v*2]+t[v*2+1]
return
def push(v,tl,tr):
if lazy[v]==-1:
return
tm=(tl+tr)//2
t[v*2]=lazy[v]*(tm-tl+1)
lazy[v*2]=lazy[v];
t[v*2+1]=lazy[v]*(tr-tm)
lazy[v*2+1]=lazy[v]
lazy[v]=-1
return
def update(v,tl,tr,l,r,setval):
# print('v:{} tl:{} tr:{} l:{} r:{}'.format(v,tl,tr,l,r))
if (r<tl or l>tr):
return
if (l<=tl and tr<=r):
t[v]=(tr-tl+1)*setval
lazy[v]=setval
else:
push(v,tl,tr)
tm=(tl+tr)//2
update(v*2,tl,tm,l,r,setval)
update(v*2+1,tm+1,tr,l,r,setval)
t[v]=t[v*2]+t[v*2+1]
return
def query(v,tl,tr,l,r):
if (r<tl or l>tr):
return 0
if l<=tl and tr<=r:
return t[v]
push(v,tl,tr)
tm=(tl+tr)//2
returnVal=query(v*2,tl,tm,l,r)+query(v*2+1,tm+1,tr,l,r)
return returnVal
def reconstruct(v,tl,tr,f2):
if tl==tr:
f2.append(t[v])
else:
push(v,tl,tr)
tm=(tl+tr)//2
reconstruct(v*2,tl,tm,f2)
reconstruct(v*2+1,tm+1,tr,f2)
return
def main():
z=int(input())
allans=[]
for _ in range(z):
n,q=readIntArr()
sf=input()
ss=input()
lr=[None for __ in range(q)]
for i in range(q-1,-1,-1):
l,r=readIntArr()
l-=1
r-=1
lr[i]=[l,r]
s=[c-ord('0') for c in ss]
f=[c-ord('0') for c in sf]
for i in range(4*n):
t[i]=0
lazy[i]=-1
build(s,1,0,n-1)
ok=True
for i in range(q):
l,r=lr[i]
nElems=r-l+1
total=query(1,0,n-1,l,r)
if total*2<nElems: updateVal=0
elif total*2>nElems: updateVal=1
else:
ok=False
break
update(1,0,n-1,l,r,updateVal)
if not ok:
allans.append('NO')
continue
f2=[]
reconstruct(1,0,n-1,f2)
ok=True
for i in range(n):
if f[i]!=f2[i]:
ok=False
break
if ok:
allans.append('YES')
else:
allans.append('NO')
multiLineArrayPrint(allans)
return
import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
# input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
# def readFloatArr():
# return [float(x) for x in input().split()]
def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m])
dv=defaultValFactory;da=dimensionArr
if len(da)==1:return [dv() for _ in range(da[0])]
else:return [makeArr(dv,da[1:]) for _ in range(da[0])]
def queryInteractive(x,y):
print('? {} {}'.format(x,y))
sys.stdout.flush()
return int(input())
def answerInteractive(ans):
print('! {}'.format(ans))
sys.stdout.flush()
inf=float('inf')
MOD=10**9+7
# MOD=998244353
for _abc in range(1):
main()
```
| 7,789 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nezzar has a binary string s of length n that he wants to share with his best friend, Nanako. Nanako will spend q days inspecting the binary string. At the same time, Nezzar wants to change the string s into string f during these q days, because it looks better.
It is known that Nanako loves consistency so much. On the i-th day, Nanako will inspect a segment of string s from position l_i to position r_i inclusive. If the segment contains both characters '0' and '1', Nanako becomes unhappy and throws away the string.
After this inspection, at the i-th night, Nezzar can secretly change strictly less than half of the characters in the segment from l_i to r_i inclusive, otherwise the change will be too obvious.
Now Nezzar wonders, if it is possible to avoid Nanako being unhappy and at the same time have the string become equal to the string f at the end of these q days and nights.
Input
The first line contains a single integer t (1 ≤ t ≤ 2 ⋅ 10^5) — the number of test cases.
The first line of each test case contains two integers n,q (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ q ≤ 2 ⋅ 10^5).
The second line of each test case contains a binary string s of length n.
The third line of each test case contains a binary string f of length n.
Then q lines follow, i-th of them contains two integers l_i,r_i (1 ≤ l_i ≤ r_i ≤ n) — bounds of the segment, that Nanako will inspect on the i-th day.
It is guaranteed that the sum of n for all test cases doesn't exceed 2 ⋅ 10^5, and the sum of q for all test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print "YES" on the single line if it is possible to avoid Nanako being unhappy and have the string f at the end of q days and nights. Otherwise, print "NO".
You can print each letter in any case (upper or lower).
Example
Input
4
5 2
00000
00111
1 5
1 3
2 1
00
01
1 2
10 6
1111111111
0110001110
1 10
5 9
7 10
1 7
3 5
6 10
5 2
10000
11000
2 5
1 3
Output
YES
NO
YES
NO
Note
In the first test case, \underline{00000} → \underline{000}11 → 00111 is one of the possible sequences of string changes.
In the second test case, it can be shown that it is impossible to have the string f at the end.
Tags: data structures, greedy
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
def __init__(self, file):
self.newlines = 0
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 S(): return input().strip()
def print_list(l): print(' '.join(map(str, l)))
# sys.setrecursionlimit(200000)
# import random
# from functools import reduce
# from functools import lru_cache
# from heapq import *
# from collections import deque as dq
# import math
# import bisect as bs
# from collections import Counter
# from collections import defaultdict as dc
def set_range(lx, rx, v, now):
if l <= lx and r >= rx:
label[now] = v
node[now] = rx - lx if v else 0
return
mx = (lx + rx) >> 1
nl = now << 1
nr = nl + 1
if label[now] != -1: # 非对称操作启用该环节
node[nl] = node[nr] = node[now] >> 1
label[nl] = label[nr] = label[now]
label[now] = -1
if l < mx:
set_range(lx, mx, v, nl)
if r > mx:
set_range(mx, rx, v, nr)
node[now] = node[nl] + node[nr]
def get_range(lx, rx, now):
if l <= lx and r >= rx:
return node[now]
mx = (lx + rx) >> 1
nl = now << 1
nr = nl + 1
if label[now] != -1: # 非对称操作启用该环节
return min(rx, r) - max(lx, l) if label[now] else 0
m1 = get_range(lx, mx, nl) if l < mx else 0
m2 = get_range(mx, rx, nr) if r > mx else 0
return m1 + m2
def match(lx, rx, now):
if lx >= n: return False
if now >= sn:
return node[now] != s[lx]
if label[now] != -1:
return any(v != label[now] for v in s[lx:rx])
mx = (rx + lx) >> 1
return match(lx, mx, now << 1) or match(mx, rx, now << 1 | 1)
ans = []
for _ in range(N()):
n, q = RL()
s = [int(c) for c in S()]
t = [int(c) for c in S()]
p = [tuple(RL()) for _ in range(q)]
sn = 1 << n.bit_length()
node = [0] * sn + t + [0] * (sn - n)
label = [-1] * (2 * sn)
for i in range(sn - 1, 0, -1): node[i] = node[i << 1] + node[i << 1 | 1]
f = True
for l, r in p[::-1]:
l -= 1
count = get_range(0, sn, 1) * 2
if count == r - l:
f = False
break
if count > r - l:
set_range(0, sn, 1, 1)
else:
set_range(0, sn, 0, 1)
ans.append('YES' if f and not match(0, sn, 1) else 'NO')
print('\n'.join(ans))
```
| 7,790 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nezzar has a binary string s of length n that he wants to share with his best friend, Nanako. Nanako will spend q days inspecting the binary string. At the same time, Nezzar wants to change the string s into string f during these q days, because it looks better.
It is known that Nanako loves consistency so much. On the i-th day, Nanako will inspect a segment of string s from position l_i to position r_i inclusive. If the segment contains both characters '0' and '1', Nanako becomes unhappy and throws away the string.
After this inspection, at the i-th night, Nezzar can secretly change strictly less than half of the characters in the segment from l_i to r_i inclusive, otherwise the change will be too obvious.
Now Nezzar wonders, if it is possible to avoid Nanako being unhappy and at the same time have the string become equal to the string f at the end of these q days and nights.
Input
The first line contains a single integer t (1 ≤ t ≤ 2 ⋅ 10^5) — the number of test cases.
The first line of each test case contains two integers n,q (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ q ≤ 2 ⋅ 10^5).
The second line of each test case contains a binary string s of length n.
The third line of each test case contains a binary string f of length n.
Then q lines follow, i-th of them contains two integers l_i,r_i (1 ≤ l_i ≤ r_i ≤ n) — bounds of the segment, that Nanako will inspect on the i-th day.
It is guaranteed that the sum of n for all test cases doesn't exceed 2 ⋅ 10^5, and the sum of q for all test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print "YES" on the single line if it is possible to avoid Nanako being unhappy and have the string f at the end of q days and nights. Otherwise, print "NO".
You can print each letter in any case (upper or lower).
Example
Input
4
5 2
00000
00111
1 5
1 3
2 1
00
01
1 2
10 6
1111111111
0110001110
1 10
5 9
7 10
1 7
3 5
6 10
5 2
10000
11000
2 5
1 3
Output
YES
NO
YES
NO
Note
In the first test case, \underline{00000} → \underline{000}11 → 00111 is one of the possible sequences of string changes.
In the second test case, it can be shown that it is impossible to have the string f at the end.
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
def __init__(self, file):
self.newlines = 0
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 S(): return input().strip()
def print_list(l): print(' '.join(map(str, l)))
# sys.setrecursionlimit(200000)
# import random
# from functools import reduce
# from functools import lru_cache
# from heapq import *
# from collections import deque as dq
# import math
# import bisect as bs
# from collections import Counter
# from collections import defaultdict as dc
def set_range(lx, rx, v, now):
if l <= lx and r >= rx:
label[now] = v
node[now] = rx - lx if v else 0
return
mx = (lx + rx) >> 1
nl = now << 1
nr = nl + 1
if label[now] != -1: # 非对称操作启用该环节
node[nl] = node[nr] = node[now] >> 1
label[nl] = label[nr] = label[now]
label[now] = -1
if l < mx: set_range(lx, mx, v, nl)
if r > mx: set_range(mx, rx, v, nr)
node[now] = node[nl] + node[nr]
def get_range(lx, rx, now):
if l <= lx and r >= rx: return node[now]
mx = (lx + rx) >> 1
nl = now << 1
nr = nl + 1
if label[now] != -1: return min(rx, r) - max(lx, l) if label[now] else 0
m1 = get_range(lx, mx, nl) if l < mx else 0
m2 = get_range(mx, rx, nr) if r > mx else 0
return m1 + m2
def match(lx, rx, now):
if lx >= n: return False
if now >= sn: return node[now] != s[lx]
if label[now] != -1: return any(v != label[now] for v in s[lx:rx])
mx = (rx + lx) >> 1
return match(lx, mx, now << 1) or match(mx, rx, now << 1 | 1)
for _ in range(N()):
n, q = RL()
s, t = [int(c) for c in S()], [int(c) for c in S()]
p = [tuple(RL()) for _ in range(q)]
sn = 1 << n.bit_length()
node = [0] * sn + t + [0] * (sn - n)
label = [-1] * (2 * sn)
for i in range(sn - 1, 0, -1): node[i] = node[i << 1] + node[i << 1 | 1]
f = True
for l, r in p[::-1]:
l -= 1
count = get_range(0, sn, 1) * 2
if count == r - l:
f = False
break
set_range(0, sn, 1 if count > r - l else 0, 1)
print('YES' if f and not match(0, sn, 1) else 'NO')
```
Yes
| 7,791 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nezzar has a binary string s of length n that he wants to share with his best friend, Nanako. Nanako will spend q days inspecting the binary string. At the same time, Nezzar wants to change the string s into string f during these q days, because it looks better.
It is known that Nanako loves consistency so much. On the i-th day, Nanako will inspect a segment of string s from position l_i to position r_i inclusive. If the segment contains both characters '0' and '1', Nanako becomes unhappy and throws away the string.
After this inspection, at the i-th night, Nezzar can secretly change strictly less than half of the characters in the segment from l_i to r_i inclusive, otherwise the change will be too obvious.
Now Nezzar wonders, if it is possible to avoid Nanako being unhappy and at the same time have the string become equal to the string f at the end of these q days and nights.
Input
The first line contains a single integer t (1 ≤ t ≤ 2 ⋅ 10^5) — the number of test cases.
The first line of each test case contains two integers n,q (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ q ≤ 2 ⋅ 10^5).
The second line of each test case contains a binary string s of length n.
The third line of each test case contains a binary string f of length n.
Then q lines follow, i-th of them contains two integers l_i,r_i (1 ≤ l_i ≤ r_i ≤ n) — bounds of the segment, that Nanako will inspect on the i-th day.
It is guaranteed that the sum of n for all test cases doesn't exceed 2 ⋅ 10^5, and the sum of q for all test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print "YES" on the single line if it is possible to avoid Nanako being unhappy and have the string f at the end of q days and nights. Otherwise, print "NO".
You can print each letter in any case (upper or lower).
Example
Input
4
5 2
00000
00111
1 5
1 3
2 1
00
01
1 2
10 6
1111111111
0110001110
1 10
5 9
7 10
1 7
3 5
6 10
5 2
10000
11000
2 5
1 3
Output
YES
NO
YES
NO
Note
In the first test case, \underline{00000} → \underline{000}11 → 00111 is one of the possible sequences of string changes.
In the second test case, it can be shown that it is impossible to have the string f at the end.
Submitted Solution:
```
"""
import sys
readline = sys.stdin.readline
"""
import io,os
readline = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from operator import add
class Lazysegtree:
def __init__(self, A, fx, ex, fm, em, fa, initialize = True):
self.N = len(A)
self.N0 = 2**(self.N-1).bit_length()
self.fx = fx
self.ex = ex
self.em = em
self.lazy = [em]*(2*self.N0)
if initialize:
self.data = [self.ex]*self.N0 + A + [self.ex]*(self.N0 - self.N)
for i in range(self.N0-1, -1, -1):
self.data[i] = self.fx(self.data[2*i], self.data[2*i+1])
else:
self.data = [self.ex]*(2*self.N0)
def fa(self, ope, idx):
if ope is not None:
return ope
return self.data[idx]
def fm(self, ope1, ope2):
return ope1
def __repr__(self):
s = 'data'
l = 'lazy'
cnt = 1
for i in range(self.N0.bit_length()):
s = '\n'.join((s, ' '.join(map(str, self.data[cnt:cnt+(1<<i)]))))
l = '\n'.join((l, ' '.join(map(str, self.lazy[cnt:cnt+(1<<i)]))))
cnt += 1<<i
return '\n'.join((s, l))
def _ascend(self, k):
k = k >> 1
c = k.bit_length()
for j in range(c):
idx = k >> j
self.data[idx] = self.fx(self.data[2*idx], self.data[2*idx+1])
def _descend(self, k):
k = k >> 1
idx = 1
c = k.bit_length()
for j in range(1, c+1):
idx = k >> (c - j)
if self.lazy[idx] == self.em:
continue
self.data[2*idx] = self.fa(self.lazy[idx], 2*idx)
self.data[2*idx+1] = self.fa(self.lazy[idx], 2*idx+1)
self.lazy[2*idx] = self.fm(self.lazy[idx], self.lazy[2*idx])
self.lazy[2*idx+1] = self.fm(self.lazy[idx], self.lazy[2*idx+1])
self.lazy[idx] = self.em
def query(self, l, r):
L = l+self.N0
R = r+self.N0
self._descend(L//(L & -L))
self._descend(R//(R & -R)-1)
sl = self.ex
sr = self.ex
while L < R:
if R & 1:
R -= 1
sr = self.fx(self.data[R], sr)
if L & 1:
sl = self.fx(sl, self.data[L])
L += 1
L >>= 1
R >>= 1
return self.fx(sl, sr)
def operate(self, l, r, x):
L = l+self.N0
R = r+self.N0
Li = L//(L & -L)
Ri = R//(R & -R)
self._descend(Li)
self._descend(Ri-1)
while L < R :
if R & 1:
R -= 1
self.data[R] = self.fa(x, R)
self.lazy[R] = self.fm(x, self.lazy[R])
if L & 1:
self.data[L] = self.fa(x, L)
self.lazy[L] = self.fm(x, self.lazy[L])
L += 1
L >>= 1
R >>= 1
self._ascend(Li)
self._ascend(Ri-1)
def propall(self):
for idx in range(1, self.N0):
self.data[2*idx] = self.fa(self.lazy[idx], 2*idx)
self.data[2*idx+1] = self.fa(self.lazy[idx], 2*idx+1)
self.lazy[2*idx] = self.fm(self.lazy[idx], self.lazy[2*idx])
self.lazy[2*idx+1] = self.fm(self.lazy[idx], self.lazy[2*idx+1])
T = int(readline())
Ans = ['NO']*T
for qu in range(T):
N, Q = map(int, readline().split())
"""
S = list(map(int, readline().strip()))
T = list(map(int, readline().strip()))
"""
S = list(map(lambda x: int(x)-48, readline().strip()))
T = list(map(lambda x: int(x)-48, readline().strip()))
Qs = [tuple(map(int, readline().split())) for _ in range(Q)]
K = Lazysegtree(T, add, 0, None, None, None)
for l, r in Qs[::-1]:
l -= 1
leng = r-l
x = K.query(l, r)
if 2*x > leng:
K.operate(l, r, 0)
elif 2*x == leng:
break
else:
K.operate(l, r, 1)
else:
if [K.query(i, i+1) for i in range(N)] == S:
Ans[qu] = 'YES'
print('\n'.join(Ans))
```
No
| 7,792 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nezzar has a binary string s of length n that he wants to share with his best friend, Nanako. Nanako will spend q days inspecting the binary string. At the same time, Nezzar wants to change the string s into string f during these q days, because it looks better.
It is known that Nanako loves consistency so much. On the i-th day, Nanako will inspect a segment of string s from position l_i to position r_i inclusive. If the segment contains both characters '0' and '1', Nanako becomes unhappy and throws away the string.
After this inspection, at the i-th night, Nezzar can secretly change strictly less than half of the characters in the segment from l_i to r_i inclusive, otherwise the change will be too obvious.
Now Nezzar wonders, if it is possible to avoid Nanako being unhappy and at the same time have the string become equal to the string f at the end of these q days and nights.
Input
The first line contains a single integer t (1 ≤ t ≤ 2 ⋅ 10^5) — the number of test cases.
The first line of each test case contains two integers n,q (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ q ≤ 2 ⋅ 10^5).
The second line of each test case contains a binary string s of length n.
The third line of each test case contains a binary string f of length n.
Then q lines follow, i-th of them contains two integers l_i,r_i (1 ≤ l_i ≤ r_i ≤ n) — bounds of the segment, that Nanako will inspect on the i-th day.
It is guaranteed that the sum of n for all test cases doesn't exceed 2 ⋅ 10^5, and the sum of q for all test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print "YES" on the single line if it is possible to avoid Nanako being unhappy and have the string f at the end of q days and nights. Otherwise, print "NO".
You can print each letter in any case (upper or lower).
Example
Input
4
5 2
00000
00111
1 5
1 3
2 1
00
01
1 2
10 6
1111111111
0110001110
1 10
5 9
7 10
1 7
3 5
6 10
5 2
10000
11000
2 5
1 3
Output
YES
NO
YES
NO
Note
In the first test case, \underline{00000} → \underline{000}11 → 00111 is one of the possible sequences of string changes.
In the second test case, it can be shown that it is impossible to have the string f at the end.
Submitted Solution:
```
from sys import stdin
def log2(x):
if x == 1:
return 1
if x > 1 and x <= 2:
return 2
return log2(x / 2) * 2
def findsum(qs, qe, seg, lz):
summ = 0
stack = [[0, 1, length]]
while stack:
pos, ss, se = stack.pop()
if lz[pos] != -1:
seg[pos] = lz[pos] * (se - ss + 1)
if ss != se:
lz[pos * 2 + 1] = lz[pos]
lz[pos * 2 + 2] = lz[pos]
lz[pos] = -1
if (qs > se) or (qe < ss):
continue
if (qs <= ss) and (qe >= se):
summ += seg[pos]
continue
if ss != se:
mid = (ss + se) // 2
stack.append([pos * 2 + 1, ss, mid])
stack.append([pos * 2 + 2, mid + 1, se])
return summ
def update(pos, ss, se, direc):
if lz[pos] != -1:
seg[pos] = (se - ss + 1) * lz[pos]
if (ss != se):
lz[pos * 2 + 1] = lz[pos]
lz[pos * 2 + 2] - lz[pos]
lz[pos] = -1
if (qs > se) or (qe < ss):
return
elif (qs <= ss) and (qe >= se):
seg[pos] = (se - ss + 1) * direc
if ss != se:
lz[pos * 2 + 1] = direc
lz[pos * 2 + 2] = direc
return
mid = (se + ss) // 2
update(pos * 2 + 1, ss, mid, direc)
update(pos * 2 + 2, mid + 1, se, direc)
seg[pos] = seg[pos * 2 + 1] + seg[pos * 2 + 2]
def clean(seg, lz):
stack = [[0, 1, length]]
while stack:
pos, ss, se = stack.pop()
if lz[pos] != -1:
if ss != se:
lz[pos * 2 + 1] = lz[pos]
lz[pos * 2 + 2] = lz[pos]
else:
seg[pos] = (se - ss + 1) * lz[pos]
if ss != se:
mid = (se + ss) // 2
stack.append([pos * 2 + 1, ss, mid])
stack.append([pos * 2 + 2, mid + 1, se])
t = int(stdin.readline())
for _ in range(t):
n, q = map(int,stdin.readline().split())
s = stdin.readline().strip()
f = stdin.readline().strip()
length = log2(n)
queries = [map(int, stdin.readline().split()) for quer in range(q)]
seg = [0] * (length - 1) + list(map(int, list(f))) + [0] * (length - n)
for pos in range(length - 2, -1, -1):
seg[pos] = seg[pos * 2 + 1] + seg[pos * 2 + 2]
lz = [-1] * (2 * length - 1)
flag = True
for qs, qe in queries[::-1]:
dis = qe - qs + 1
tong = findsum(qs, qe, seg, lz)
if tong * 2 == dis:
flag = False
break
else:
if tong * 2 > dis:
update(0, 1, length, 1)
else:
update(0, 1, length, 0)
#print(seg, lz)
if flag == False:
print('no')
else:
clean(seg, lz)
#print(seg, lz)
if seg[-length: -length + n] == [int(s[i]) for i in range(n)]:
print('yes')
else:
print('no')
```
No
| 7,793 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nezzar has a binary string s of length n that he wants to share with his best friend, Nanako. Nanako will spend q days inspecting the binary string. At the same time, Nezzar wants to change the string s into string f during these q days, because it looks better.
It is known that Nanako loves consistency so much. On the i-th day, Nanako will inspect a segment of string s from position l_i to position r_i inclusive. If the segment contains both characters '0' and '1', Nanako becomes unhappy and throws away the string.
After this inspection, at the i-th night, Nezzar can secretly change strictly less than half of the characters in the segment from l_i to r_i inclusive, otherwise the change will be too obvious.
Now Nezzar wonders, if it is possible to avoid Nanako being unhappy and at the same time have the string become equal to the string f at the end of these q days and nights.
Input
The first line contains a single integer t (1 ≤ t ≤ 2 ⋅ 10^5) — the number of test cases.
The first line of each test case contains two integers n,q (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ q ≤ 2 ⋅ 10^5).
The second line of each test case contains a binary string s of length n.
The third line of each test case contains a binary string f of length n.
Then q lines follow, i-th of them contains two integers l_i,r_i (1 ≤ l_i ≤ r_i ≤ n) — bounds of the segment, that Nanako will inspect on the i-th day.
It is guaranteed that the sum of n for all test cases doesn't exceed 2 ⋅ 10^5, and the sum of q for all test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print "YES" on the single line if it is possible to avoid Nanako being unhappy and have the string f at the end of q days and nights. Otherwise, print "NO".
You can print each letter in any case (upper or lower).
Example
Input
4
5 2
00000
00111
1 5
1 3
2 1
00
01
1 2
10 6
1111111111
0110001110
1 10
5 9
7 10
1 7
3 5
6 10
5 2
10000
11000
2 5
1 3
Output
YES
NO
YES
NO
Note
In the first test case, \underline{00000} → \underline{000}11 → 00111 is one of the possible sequences of string changes.
In the second test case, it can be shown that it is impossible to have the string f at the end.
Submitted Solution:
```
import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
from math import *
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
import copy
import time
starttime = time.time()
mod = int(pow(10, 9) + 7)
mod2 = 998244353
def data(): return sys.stdin.readline().strip()
def out(*var, end="\n"): sys.stdout.write(' '.join(map(str, var))+end)
def L(): return list(sp())
def sl(): return list(ssp())
def sp(): return map(int, data().split())
def ssp(): return map(str, data().split())
def l1d(n, val=0): return [val for i in range(n)]
def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)]
try:
# sys.setrecursionlimit(int(pow(10,4)))
sys.stdin = open("input.txt", "r")
# sys.stdout = open("../output.txt", "w")
except:
pass
def pmat(A):
for ele in A:
print(*ele,end="\n")
# def seive():
# prime=[1 for i in range(10**6+1)]
# prime[0]=0
# prime[1]=0
# for i in range(10**6+1):
# if(prime[i]):
# for j in range(2*i,10**6+1,i):
# prime[j]=0
# return prime
import sys
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def indexes(L,R):
INDLIST=[]
R-=1
L>>=1
R>>=1
while L!=R:
if L>R:
INDLIST.append(L)
L>>=1
else:
INDLIST.append(R)
R>>=1
while L!=0:
INDLIST.append(L)
L>>=1
return INDLIST
def updates(l,r,x):
L=l+seg_el
R=r+seg_el
L//=(L & (-L))
R//=(R & (-R))
UPIND=indexes(L,R)
for ind in UPIND[::-1]:
if LAZY[ind]!=None:
update_lazy = LAZY[ind] *(1<<(seg_height - 1 - (ind.bit_length())))
LAZY[ind<<1]=LAZY[1+(ind<<1)]=LAZY[ind]
SEG[ind<<1]=SEG[1+(ind<<1)]=update_lazy
LAZY[ind]=None
while L!=R:
if L > R:
SEG[L]=x * (1<<(seg_height - (L.bit_length())))
LAZY[L]=x
L+=1
L//=(L & (-L))
else:
R-=1
SEG[R]=x * (1<<(seg_height - (R.bit_length())))
LAZY[R]=x
R//=(R & (-R))
for ind in UPIND:
SEG[ind]=SEG[ind<<1]+SEG[1+(ind<<1)]
def getvalues(l,r):
L=l+seg_el
R=r+seg_el
L//=(L & (-L))
R//=(R & (-R))
UPIND=indexes(L,R)
for ind in UPIND[::-1]:
if LAZY[ind]!=None:
update_lazy = LAZY[ind] *(1<<(seg_height - 1 - (ind.bit_length())))
LAZY[ind<<1]=LAZY[1+(ind<<1)]=LAZY[ind]
SEG[ind<<1]=SEG[1+(ind<<1)]=update_lazy
LAZY[ind]=None
ANS=0
while L!=R:
if L > R:
ANS+=SEG[L]
L+=1
L//=(L & (-L))
else:
R-=1
ANS+=SEG[R]
R//=(R & (-R))
return ANS
t=int(input())
for tests in range(t):
n,q=map(int,input().split())
S=input().strip()
F=input().strip()
Q=[tuple(map(int,input().split())) for i in range(q)]
seg_el=1<<(n.bit_length())
seg_height=1+n.bit_length()
SEG=[0]*(2*seg_el)
LAZY=[None]*(2*seg_el)
for i in range(n):
SEG[i+seg_el]=int(F[i])
for i in range(seg_el-1,0,-1):
SEG[i]=SEG[i*2]+SEG[i*2+1]
for l,r in Q[::-1]:
SUM=r-l+1
xx=getvalues(l-1,r)
if xx*2==SUM:
print("NO")
break
else:
if xx*2>SUM:
updates(l-1,r,1)
else:
updates(l-1,r,0)
else:
for i in range(n):
if getvalues(i,i+1)==int(S[i]):
True
else:
print("NO")
break
else:
print("YES")
endtime = time.time()
# print(f"Runtime of the program is {endtime - starttime}")
```
No
| 7,794 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nezzar has a binary string s of length n that he wants to share with his best friend, Nanako. Nanako will spend q days inspecting the binary string. At the same time, Nezzar wants to change the string s into string f during these q days, because it looks better.
It is known that Nanako loves consistency so much. On the i-th day, Nanako will inspect a segment of string s from position l_i to position r_i inclusive. If the segment contains both characters '0' and '1', Nanako becomes unhappy and throws away the string.
After this inspection, at the i-th night, Nezzar can secretly change strictly less than half of the characters in the segment from l_i to r_i inclusive, otherwise the change will be too obvious.
Now Nezzar wonders, if it is possible to avoid Nanako being unhappy and at the same time have the string become equal to the string f at the end of these q days and nights.
Input
The first line contains a single integer t (1 ≤ t ≤ 2 ⋅ 10^5) — the number of test cases.
The first line of each test case contains two integers n,q (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ q ≤ 2 ⋅ 10^5).
The second line of each test case contains a binary string s of length n.
The third line of each test case contains a binary string f of length n.
Then q lines follow, i-th of them contains two integers l_i,r_i (1 ≤ l_i ≤ r_i ≤ n) — bounds of the segment, that Nanako will inspect on the i-th day.
It is guaranteed that the sum of n for all test cases doesn't exceed 2 ⋅ 10^5, and the sum of q for all test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case, print "YES" on the single line if it is possible to avoid Nanako being unhappy and have the string f at the end of q days and nights. Otherwise, print "NO".
You can print each letter in any case (upper or lower).
Example
Input
4
5 2
00000
00111
1 5
1 3
2 1
00
01
1 2
10 6
1111111111
0110001110
1 10
5 9
7 10
1 7
3 5
6 10
5 2
10000
11000
2 5
1 3
Output
YES
NO
YES
NO
Note
In the first test case, \underline{00000} → \underline{000}11 → 00111 is one of the possible sequences of string changes.
In the second test case, it can be shown that it is impossible to have the string f at the end.
Submitted Solution:
```
import sys
input = sys.stdin.readline
def segfunc(x,y):
return x + y
class LazySegTree_RUQ:
def __init__(self, init_val, segfunc, ide_ele):
n = len(init_val)
self.segfunc = segfunc
self.ide_ele = ide_ele
self.num = 1 << (n - 1).bit_length()
self.tree = [ide_ele] * 2 * self.num
self.lazy = [None] * 2 * self.num
for i in range(n):
self.tree[self.num + i] = init_val[i]
for i in range(self.num - 1, 0, -1):
self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])
def gindex(self, l, r):
l += self.num
r += self.num
lm = l >> (l & -l).bit_length()
rm = r >> (r & -r).bit_length()
while r > l:
if l <= lm:
yield l
if r <= rm:
yield r
r >>= 1
l >>= 1
while l:
yield l
l >>= 1
def propagates(self, *ids):
for i in reversed(ids):
v = self.lazy[i]
if v is None:
continue
self.lazy[i] = None
self.lazy[2 * i] = v
self.lazy[2 * i + 1] = v
self.tree[2 * i] = v
self.tree[2 * i + 1] = v
def update(self, l, r, x):
*ids, = self.gindex(l, r)
self.propagates(*ids)
l += self.num
r += self.num
while l < r:
if l & 1:
self.lazy[l] = x
self.tree[l] = x
l += 1
if r & 1:
self.lazy[r - 1] = x
self.tree[r - 1] = x
r >>= 1
l >>= 1
for i in ids:
self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])
def query(self, l, r):
*ids, = self.gindex(l, r)
self.propagates(*ids)
res = self.ide_ele
l += self.num
r += self.num
while l < r:
if l & 1:
res = self.segfunc(res, self.tree[l])
l += 1
if r & 1:
res = self.segfunc(res, self.tree[r - 1])
l >>= 1
r >>= 1
return res
def main():
n, q = map(int, input().split())
S = list(map(int, input().strip()))
T = list(map(int, input().strip()))
lr = [list(map(int, input().split())) for _ in range(q)]
seg = LazySegTree_RUQ(T,segfunc,0)
for l, r in lr[::-1]:
c = seg.query(l - 1, r)
z = r - l + 1
if z == c * 2:
print("NO")
return
if c == z or c == 0:
continue
elif c * 2 < z:
seg.update(l - 1, r, 1)
else:
seg.update(l - 1, r, 0)
for i in range(n):
if seg.query(i, i + 1) != S[i]:
print("NO")
return
print("YES")
for _ in range(int(input())):
main()
```
No
| 7,795 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A balanced bracket sequence is defined as an integer sequence that can be built with the following rules:
* The empty sequence is balanced.
* If [a_1,…,a_n] and [b_1,…, b_m] are balanced, then their concatenation [a_1,…,a_n,b_1,…,b_m] is balanced.
* If x is a positive integer and [a_1,…,a_n] is balanced, then [x,a_1,…,a_n,-x] is balanced.
The positive numbers can be imagined as opening brackets and the negative numbers as closing brackets, where matching brackets must have the same type (absolute value). For example, [1, 2, -2, -1] and [1, 3, -3, 2, -2, -1] are balanced, but [1, 2, -1, -2] and [-1, 1] are not balanced.
There are 2n cards. Each card has a number on the front and a number on the back. Each integer 1,-1,2,-2,…,n,-n appears exactly once on the front of some card and exactly once on the back of some (not necessarily the same) card.
You can reorder the cards however you like. You are not allowed to flip cards, so numbers cannot move between the front and back. Your task is to order the cards so that the sequences given by the front numbers and the back numbers are both balanced, or report that it is impossible.
Input
The first line contains a single integer n (1≤ n≤ 2⋅ 10^5) — the number of bracket types, and half the number of cards.
The next 2n lines describe the cards. The i-th of these lines contains two integers a_i, b_i (-n≤ a_i,b_i≤ n, a_i≠ 0, b_i≠ 0) — the numbers on the front and back of the i-th card, respectively. Every integer 1,-1,2,-2,…,n,-n appears exactly once as a_i and exactly once as b_i.
Output
On the first line, output "YES" if it's possible to reorder these cards to satisfy the condition. Otherwise, output "NO". You can print each letter in any case (upper or lower).
If it is possible, on the next 2n lines output the cards in an order so that the front and back are both balanced. If there are multiple solutions, you may output any.
Examples
Input
5
1 3
-3 -5
4 -3
2 2
-1 -4
-2 5
3 -1
5 1
-4 4
-5 -2
Output
YES
1 3
4 -3
-4 4
-1 -4
5 1
3 -1
2 2
-2 5
-3 -5
-5 -2
Input
2
1 1
-1 2
2 -1
-2 -2
Output
NO
Note
In the first test case, the front numbers create the balanced sequence [1,4,-4,-1,5,3,2,-2,-3,-5] and the back numbers create the balanced sequence [3,-3,4,-4,1,-1,2,5,-5,-2].
In the second test case, the cards are given in an order so that the front numbers are balanced, but the back numbers create the unbalanced sequence [1,2,-1,-2]. If we swapped the second and third cards, we would balance the back numbers and unbalance the front numbers. But there is no order that balances both.
Submitted Solution:
```
import itertools
from typing import List
n = int(input())
d = dict(map(int, input().split()) for _ in range(2 * n))
def isValid(nums: List[int]) -> bool:
"""Removes same consecutive brackets one at a time until length of nums becomes zero and return True, otherwise false.
Args:
nums (List[int]): array of front or back values.
Returns:
bool: Returns True if a valid sequence, else False.
"""
while len(nums) > 0:
l = len(nums)
for i, v in enumerate(nums):
if i > 0:
if abs(v) == abs(nums[i - 1]):
if v < 0:
nums.pop(i)
nums.pop(i - 1)
if len(nums) == l:
return False
return True
def solve(dic) -> str:
"""Creates permuntations of card order, unzips front and back values in x, y and passes them in isValid() function as a parameter.
Args:
arr (List[List[int]]): 2d array of front and back values of the card. [[front,back],..].
Returns:
str: returns 'Yes' if both front values and back values are valid bracket sequence. Otherwise returns 'No'
"""
for i in itertools.permutations(list(d.keys()), len(dic)):
front = list(i)
back = [dic[x] for x in front]
if isValid(front[:]) == True and isValid(back[:]) == True:
return ['YES', front, back]
return ['N0']
ans = solve(d)
if len(ans) > 1:
print(ans[0])
res = "\n".join("{} {}".format(x, y) for x, y in zip(ans[1], ans[2]))
print(res)
else:
print(ans[0])
```
No
| 7,796 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A balanced bracket sequence is defined as an integer sequence that can be built with the following rules:
* The empty sequence is balanced.
* If [a_1,…,a_n] and [b_1,…, b_m] are balanced, then their concatenation [a_1,…,a_n,b_1,…,b_m] is balanced.
* If x is a positive integer and [a_1,…,a_n] is balanced, then [x,a_1,…,a_n,-x] is balanced.
The positive numbers can be imagined as opening brackets and the negative numbers as closing brackets, where matching brackets must have the same type (absolute value). For example, [1, 2, -2, -1] and [1, 3, -3, 2, -2, -1] are balanced, but [1, 2, -1, -2] and [-1, 1] are not balanced.
There are 2n cards. Each card has a number on the front and a number on the back. Each integer 1,-1,2,-2,…,n,-n appears exactly once on the front of some card and exactly once on the back of some (not necessarily the same) card.
You can reorder the cards however you like. You are not allowed to flip cards, so numbers cannot move between the front and back. Your task is to order the cards so that the sequences given by the front numbers and the back numbers are both balanced, or report that it is impossible.
Input
The first line contains a single integer n (1≤ n≤ 2⋅ 10^5) — the number of bracket types, and half the number of cards.
The next 2n lines describe the cards. The i-th of these lines contains two integers a_i, b_i (-n≤ a_i,b_i≤ n, a_i≠ 0, b_i≠ 0) — the numbers on the front and back of the i-th card, respectively. Every integer 1,-1,2,-2,…,n,-n appears exactly once as a_i and exactly once as b_i.
Output
On the first line, output "YES" if it's possible to reorder these cards to satisfy the condition. Otherwise, output "NO". You can print each letter in any case (upper or lower).
If it is possible, on the next 2n lines output the cards in an order so that the front and back are both balanced. If there are multiple solutions, you may output any.
Examples
Input
5
1 3
-3 -5
4 -3
2 2
-1 -4
-2 5
3 -1
5 1
-4 4
-5 -2
Output
YES
1 3
4 -3
-4 4
-1 -4
5 1
3 -1
2 2
-2 5
-3 -5
-5 -2
Input
2
1 1
-1 2
2 -1
-2 -2
Output
NO
Note
In the first test case, the front numbers create the balanced sequence [1,4,-4,-1,5,3,2,-2,-3,-5] and the back numbers create the balanced sequence [3,-3,4,-4,1,-1,2,5,-5,-2].
In the second test case, the cards are given in an order so that the front numbers are balanced, but the back numbers create the unbalanced sequence [1,2,-1,-2]. If we swapped the second and third cards, we would balance the back numbers and unbalance the front numbers. But there is no order that balances both.
Submitted Solution:
```
import itertools
from typing import List
n = int(input())
d = dict(map(int, input().split()) for _ in range(2 * n))
def isValid(nums: List[int]) -> bool:
"""Removes same consecutive brackets one at a time until length of nums becomes zero and return True, otherwise false.
Args:
nums (List[int]): array of front or back values.
Returns:
bool: Returns True if a valid sequence, else False.
"""
while len(nums) > 0:
l = len(nums)
for i, v in enumerate(nums):
if i > 0:
if abs(v) == abs(nums[i - 1]):
if v < 0:
nums.pop(i)
nums.pop(i - 1)
if len(nums) == l:
return False
return True
def solve(dic) -> str:
"""Creates permuntations of card order, unzips front and back values in x, y and passes them in isValid() function as a parameter.
Args:
arr (List[List[int]]): 2d array of front and back values of the card. [[front,back],..].
Returns:
str: returns 'Yes' if both front values and back values are valid bracket sequence. Otherwise returns 'No'
"""
for i in itertools.permutations(list(d.keys()), len(dic)):
front = list(i)
back = [dic[x] for x in front]
if isValid(front[:]) == True and isValid(back[:]) == True:
print(front)
print(back)
return ['YES', front, back]
return ['N0']
ans = solve(d)
if len(ans) > 1:
print(ans[0])
res = "\n".join("{} {}".format(x, y) for x, y in zip(ans[1], ans[2]))
print(res)
else:
print(ans[0])
```
No
| 7,797 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A balanced bracket sequence is defined as an integer sequence that can be built with the following rules:
* The empty sequence is balanced.
* If [a_1,…,a_n] and [b_1,…, b_m] are balanced, then their concatenation [a_1,…,a_n,b_1,…,b_m] is balanced.
* If x is a positive integer and [a_1,…,a_n] is balanced, then [x,a_1,…,a_n,-x] is balanced.
The positive numbers can be imagined as opening brackets and the negative numbers as closing brackets, where matching brackets must have the same type (absolute value). For example, [1, 2, -2, -1] and [1, 3, -3, 2, -2, -1] are balanced, but [1, 2, -1, -2] and [-1, 1] are not balanced.
There are 2n cards. Each card has a number on the front and a number on the back. Each integer 1,-1,2,-2,…,n,-n appears exactly once on the front of some card and exactly once on the back of some (not necessarily the same) card.
You can reorder the cards however you like. You are not allowed to flip cards, so numbers cannot move between the front and back. Your task is to order the cards so that the sequences given by the front numbers and the back numbers are both balanced, or report that it is impossible.
Input
The first line contains a single integer n (1≤ n≤ 2⋅ 10^5) — the number of bracket types, and half the number of cards.
The next 2n lines describe the cards. The i-th of these lines contains two integers a_i, b_i (-n≤ a_i,b_i≤ n, a_i≠ 0, b_i≠ 0) — the numbers on the front and back of the i-th card, respectively. Every integer 1,-1,2,-2,…,n,-n appears exactly once as a_i and exactly once as b_i.
Output
On the first line, output "YES" if it's possible to reorder these cards to satisfy the condition. Otherwise, output "NO". You can print each letter in any case (upper or lower).
If it is possible, on the next 2n lines output the cards in an order so that the front and back are both balanced. If there are multiple solutions, you may output any.
Examples
Input
5
1 3
-3 -5
4 -3
2 2
-1 -4
-2 5
3 -1
5 1
-4 4
-5 -2
Output
YES
1 3
4 -3
-4 4
-1 -4
5 1
3 -1
2 2
-2 5
-3 -5
-5 -2
Input
2
1 1
-1 2
2 -1
-2 -2
Output
NO
Note
In the first test case, the front numbers create the balanced sequence [1,4,-4,-1,5,3,2,-2,-3,-5] and the back numbers create the balanced sequence [3,-3,4,-4,1,-1,2,5,-5,-2].
In the second test case, the cards are given in an order so that the front numbers are balanced, but the back numbers create the unbalanced sequence [1,2,-1,-2]. If we swapped the second and third cards, we would balance the back numbers and unbalance the front numbers. But there is no order that balances both.
Submitted Solution:
```
import itertools
from typing import List
n = int(input())
d = dict(map(int, input().split()) for _ in range(2 * n))
def isValid(nums: List[int]) -> bool:
"""Removes same consecutive brackets one at a time until length of nums becomes zero and return True, otherwise false.
Args:
nums (List[int]): array of front or back values.
Returns:
bool: Returns True if a valid sequence, else False.
"""
while len(nums) > 0:
l = len(nums)
for i, v in enumerate(nums):
if i > 0:
if abs(v) == abs(nums[i - 1]):
if v < 0:
nums.pop(i)
nums.pop(i - 1)
if len(nums) == l:
return False
return True
def solve(dic) -> str:
"""Creates permuntations of card order, unzips front and back values in x, y and passes them in isValid() function as a parameter.
Args:
arr (List[List[int]]): 2d array of front and back values of the card. [[front,back],..].
Returns:
str: returns 'Yes' if both front values and back values are valid bracket sequence. Otherwise returns 'No'
"""
for i in itertools.permutations(list(d.keys()), len(dic)):
front = list(i)
back = [dic[x] for x in front]
if isValid(front) == True and isValid(back) == True:
return ['YES', front, back]
return ['NO']
ans = solve(d)
if len(ans) > 1:
print(ans[0])
res = "\n".join("{} {}".format(x, y) for x, y in zip(ans[1], ans[2]))
print(res)
else:
print(ans[0])
```
No
| 7,798 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A balanced bracket sequence is defined as an integer sequence that can be built with the following rules:
* The empty sequence is balanced.
* If [a_1,…,a_n] and [b_1,…, b_m] are balanced, then their concatenation [a_1,…,a_n,b_1,…,b_m] is balanced.
* If x is a positive integer and [a_1,…,a_n] is balanced, then [x,a_1,…,a_n,-x] is balanced.
The positive numbers can be imagined as opening brackets and the negative numbers as closing brackets, where matching brackets must have the same type (absolute value). For example, [1, 2, -2, -1] and [1, 3, -3, 2, -2, -1] are balanced, but [1, 2, -1, -2] and [-1, 1] are not balanced.
There are 2n cards. Each card has a number on the front and a number on the back. Each integer 1,-1,2,-2,…,n,-n appears exactly once on the front of some card and exactly once on the back of some (not necessarily the same) card.
You can reorder the cards however you like. You are not allowed to flip cards, so numbers cannot move between the front and back. Your task is to order the cards so that the sequences given by the front numbers and the back numbers are both balanced, or report that it is impossible.
Input
The first line contains a single integer n (1≤ n≤ 2⋅ 10^5) — the number of bracket types, and half the number of cards.
The next 2n lines describe the cards. The i-th of these lines contains two integers a_i, b_i (-n≤ a_i,b_i≤ n, a_i≠ 0, b_i≠ 0) — the numbers on the front and back of the i-th card, respectively. Every integer 1,-1,2,-2,…,n,-n appears exactly once as a_i and exactly once as b_i.
Output
On the first line, output "YES" if it's possible to reorder these cards to satisfy the condition. Otherwise, output "NO". You can print each letter in any case (upper or lower).
If it is possible, on the next 2n lines output the cards in an order so that the front and back are both balanced. If there are multiple solutions, you may output any.
Examples
Input
5
1 3
-3 -5
4 -3
2 2
-1 -4
-2 5
3 -1
5 1
-4 4
-5 -2
Output
YES
1 3
4 -3
-4 4
-1 -4
5 1
3 -1
2 2
-2 5
-3 -5
-5 -2
Input
2
1 1
-1 2
2 -1
-2 -2
Output
NO
Note
In the first test case, the front numbers create the balanced sequence [1,4,-4,-1,5,3,2,-2,-3,-5] and the back numbers create the balanced sequence [3,-3,4,-4,1,-1,2,5,-5,-2].
In the second test case, the cards are given in an order so that the front numbers are balanced, but the back numbers create the unbalanced sequence [1,2,-1,-2]. If we swapped the second and third cards, we would balance the back numbers and unbalance the front numbers. But there is no order that balances both.
Submitted Solution:
```
import itertools
from typing import List
n = int(input())
d = dict(map(int, input().split()) for _ in range(2 * n))
def isValid(nums: List[int]) -> bool:
"""Removes same consecutive brackets one at a time until length of nums becomes zero and return True, otherwise false.
Args:
nums (List[int]): array of front or back values.
Returns:
bool: Returns True if a valid sequence, else False.
"""
while len(nums) > 0:
l = len(nums)
for i, v in enumerate(nums):
if i > 0:
if -1 * v == nums[i - 1]:
nums.pop(i)
nums.pop(i - 1)
if len(nums) == l:
return False
return True
def solve(dic) -> str:
"""Creates permuntations of card order, unzips front and back values in x, y and passes them in isValid() function as a parameter.
Args:
arr (List[List[int]]): 2d array of front and back values of the card. [[front,back],..].
Returns:
str: returns 'Yes' if both front values and back values are valid bracket sequence. Otherwise returns 'No'
"""
for i in itertools.permutations(dic, len(dic)):
i = list(i)
if isValid(i) == True and isValid([dic[x] for x in i]) == True:
return 'YES'
return 'NO'
print(solve(d))
```
No
| 7,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.