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.
Soon after the Chunga-Changa island was discovered, it started to acquire some forms of civilization and even market economy. A new currency arose, colloquially called "chizhik". One has to pay in chizhiks to buy a coconut now.
Sasha and Masha are about to buy some coconuts which are sold at price z chizhiks per coconut. Sasha has x chizhiks, Masha has y chizhiks. Each girl will buy as many coconuts as she can using only her money. This way each girl will buy an integer non-negative number of coconuts.
The girls discussed their plans and found that the total number of coconuts they buy can increase (or decrease) if one of them gives several chizhiks to the other girl. The chizhiks can't be split in parts, so the girls can only exchange with integer number of chizhiks.
Consider the following example. Suppose Sasha has 5 chizhiks, Masha has 4 chizhiks, and the price for one coconut be 3 chizhiks. If the girls don't exchange with chizhiks, they will buy 1 + 1 = 2 coconuts. However, if, for example, Masha gives Sasha one chizhik, then Sasha will have 6 chizhiks, Masha will have 3 chizhiks, and the girls will buy 2 + 1 = 3 coconuts.
It is not that easy to live on the island now, so Sasha and Mash want to exchange with chizhiks in such a way that they will buy the maximum possible number of coconuts. Nobody wants to have a debt, so among all possible ways to buy the maximum possible number of coconuts find such a way that minimizes the number of chizhiks one girl gives to the other (it is not important who will be the person giving the chizhiks).
Input
The first line contains three integers x, y and z (0 ≤ x, y ≤ 10^{18}, 1 ≤ z ≤ 10^{18}) — the number of chizhics Sasha has, the number of chizhics Masha has and the price of a coconut.
Output
Print two integers: the maximum possible number of coconuts the girls can buy and the minimum number of chizhiks one girl has to give to the other.
Examples
Input
5 4 3
Output
3 1
Input
6 8 2
Output
7 0
Note
The first example is described in the statement. In the second example the optimal solution is to dot exchange any chizhiks. The girls will buy 3 + 4 = 7 coconuts.
Submitted Solution:
```
inputs = input().split(' ')
x = int(inputs[0])
y = int(inputs[1])
z = int(inputs[2])
exchange = 0
coconuts = 0
small = min(x, y)
if x + y % z == 0:
coconuts = x + y // z
exchange = small % z;
else:
coconuts = (x + y) // z
exchange = small % z
print (coconuts, exchange)
```
No
| 104,500 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Soon after the Chunga-Changa island was discovered, it started to acquire some forms of civilization and even market economy. A new currency arose, colloquially called "chizhik". One has to pay in chizhiks to buy a coconut now.
Sasha and Masha are about to buy some coconuts which are sold at price z chizhiks per coconut. Sasha has x chizhiks, Masha has y chizhiks. Each girl will buy as many coconuts as she can using only her money. This way each girl will buy an integer non-negative number of coconuts.
The girls discussed their plans and found that the total number of coconuts they buy can increase (or decrease) if one of them gives several chizhiks to the other girl. The chizhiks can't be split in parts, so the girls can only exchange with integer number of chizhiks.
Consider the following example. Suppose Sasha has 5 chizhiks, Masha has 4 chizhiks, and the price for one coconut be 3 chizhiks. If the girls don't exchange with chizhiks, they will buy 1 + 1 = 2 coconuts. However, if, for example, Masha gives Sasha one chizhik, then Sasha will have 6 chizhiks, Masha will have 3 chizhiks, and the girls will buy 2 + 1 = 3 coconuts.
It is not that easy to live on the island now, so Sasha and Mash want to exchange with chizhiks in such a way that they will buy the maximum possible number of coconuts. Nobody wants to have a debt, so among all possible ways to buy the maximum possible number of coconuts find such a way that minimizes the number of chizhiks one girl gives to the other (it is not important who will be the person giving the chizhiks).
Input
The first line contains three integers x, y and z (0 ≤ x, y ≤ 10^{18}, 1 ≤ z ≤ 10^{18}) — the number of chizhics Sasha has, the number of chizhics Masha has and the price of a coconut.
Output
Print two integers: the maximum possible number of coconuts the girls can buy and the minimum number of chizhiks one girl has to give to the other.
Examples
Input
5 4 3
Output
3 1
Input
6 8 2
Output
7 0
Note
The first example is described in the statement. In the second example the optimal solution is to dot exchange any chizhiks. The girls will buy 3 + 4 = 7 coconuts.
Submitted Solution:
```
x, y, z = [int(x) for x in input().split(' ')]
x1 = x // z
y1 = y // z
z1 = (x + y) // z
if x1 + y1 == z1:
print(z1, 0)
else:
print(z1, min(max(x, z) % min(x, z), max(y, z) % min(y, z)))
```
No
| 104,501 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Soon after the Chunga-Changa island was discovered, it started to acquire some forms of civilization and even market economy. A new currency arose, colloquially called "chizhik". One has to pay in chizhiks to buy a coconut now.
Sasha and Masha are about to buy some coconuts which are sold at price z chizhiks per coconut. Sasha has x chizhiks, Masha has y chizhiks. Each girl will buy as many coconuts as she can using only her money. This way each girl will buy an integer non-negative number of coconuts.
The girls discussed their plans and found that the total number of coconuts they buy can increase (or decrease) if one of them gives several chizhiks to the other girl. The chizhiks can't be split in parts, so the girls can only exchange with integer number of chizhiks.
Consider the following example. Suppose Sasha has 5 chizhiks, Masha has 4 chizhiks, and the price for one coconut be 3 chizhiks. If the girls don't exchange with chizhiks, they will buy 1 + 1 = 2 coconuts. However, if, for example, Masha gives Sasha one chizhik, then Sasha will have 6 chizhiks, Masha will have 3 chizhiks, and the girls will buy 2 + 1 = 3 coconuts.
It is not that easy to live on the island now, so Sasha and Mash want to exchange with chizhiks in such a way that they will buy the maximum possible number of coconuts. Nobody wants to have a debt, so among all possible ways to buy the maximum possible number of coconuts find such a way that minimizes the number of chizhiks one girl gives to the other (it is not important who will be the person giving the chizhiks).
Input
The first line contains three integers x, y and z (0 ≤ x, y ≤ 10^{18}, 1 ≤ z ≤ 10^{18}) — the number of chizhics Sasha has, the number of chizhics Masha has and the price of a coconut.
Output
Print two integers: the maximum possible number of coconuts the girls can buy and the minimum number of chizhiks one girl has to give to the other.
Examples
Input
5 4 3
Output
3 1
Input
6 8 2
Output
7 0
Note
The first example is described in the statement. In the second example the optimal solution is to dot exchange any chizhiks. The girls will buy 3 + 4 = 7 coconuts.
Submitted Solution:
```
z,c,a=list(map(int,input().split()))
if z%a>c%a:print((z+c%a+c-c%a)//a,c%a,end=' ')
elif c%a>z%a:print((c+z%a+z-z%a)//a,z%a,end=' ')
elif z%a==c%a:print((z+c)//a,0,end=' ')
```
No
| 104,502 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between the easy and the hard versions is the maximum value of k.
You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one — from 1 to 2, the third one — from 1 to 3, ..., the i-th block consists of all numbers from 1 to i.
So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0.
Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 500) — the number of queries.
The i-th of the following q lines contains one integer k_i (1 ≤ k_i ≤ 10^9) — the description of the corresponding query.
Output
Print q lines. In the i-th line print one digit x_i (0 ≤ x_i ≤ 9) — the answer to the query i, i.e. x_i should be equal to the element at the position k_i of the sequence.
Examples
Input
5
1
3
20
38
56
Output
1
2
5
2
0
Input
4
2132
506
999999999
1000000000
Output
8
2
9
8
Note
Answers on queries from the first example are described in the problem statement.
Tags: binary search, brute force, math
Correct Solution:
```
import sys
input = sys.stdin.readline
# 1keta : 1,2,3,4,5,6,7,8,9 : 45
# 2keta : 11,13,15,...
# 9 : 9 , sum = 45
# 99 : 9+(2*90) = 189, sum =((9+2)+(9+2*90))*90//2 +45 = 9045
LIST=[9]
for i in range(1,20):
LIST.append(LIST[-1]+9*(10**i)*(i+1))
SUM=[45]
for i in range(1,19):
SUM.append(SUM[-1]+(LIST[i-1]+(i+1)+LIST[i])*9*(10**i)//2)
def calc(x):
True
SUM=[0]+SUM
LIST=[0]+LIST
LIST2=[0]
for i in range(1,20):
LIST2.append(10**i-1)
q=int(input())
#q=1000
for testcases in range(q):
k=int(input())
#k=testcases+1
for i in range(20):
if SUM[i]>=k:
keta=i
break
#print(keta)
k-=SUM[keta-1]
INI=LIST[keta-1]+keta
#print(k,INI)
OK=0
NG=10**keta
while NG>OK+1:
mid=(OK+NG)//2
if (INI + INI + keta *(mid - 1)) * mid //2 >= k:
NG=mid
else:
OK=mid
k-=(INI + INI + keta *(OK - 1)) * OK //2
#print(k,OK,10**(keta-1)+OK)
for i in range(20):
if LIST[i]>=k:
keta2=i
k-=LIST[i-1]
break
#print(k,keta2)
r,q=divmod(k,keta2)
#print("!",r,q)
if q==0:
print(str(LIST2[keta2-1]+r)[-1])
else:
print(str(LIST2[keta2-1]+r+1)[q-1])
```
| 104,503 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between the easy and the hard versions is the maximum value of k.
You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one — from 1 to 2, the third one — from 1 to 3, ..., the i-th block consists of all numbers from 1 to i.
So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0.
Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 500) — the number of queries.
The i-th of the following q lines contains one integer k_i (1 ≤ k_i ≤ 10^9) — the description of the corresponding query.
Output
Print q lines. In the i-th line print one digit x_i (0 ≤ x_i ≤ 9) — the answer to the query i, i.e. x_i should be equal to the element at the position k_i of the sequence.
Examples
Input
5
1
3
20
38
56
Output
1
2
5
2
0
Input
4
2132
506
999999999
1000000000
Output
8
2
9
8
Note
Answers on queries from the first example are described in the problem statement.
Tags: binary search, brute force, math
Correct Solution:
```
def digits_until_block_(n):
result = 0
for bas in range(1, 30):
minimum = int(10 ** (bas - 1))
maximum = int((10 ** bas) - 1)
if n < maximum:
maximum = n
if maximum < minimum:
break
result += sum_between(n - maximum + 1, n - minimum + 1) * bas
return result
def digits_until_(n):
if n == 0:
return 0
if n == 1:
return 1
return digits_until_block_(n) - digits_until_block_(n - 1)
def sum_between(x, y):
try:
assert (x <= y)
except AssertionError:
print(x, y)
return ((x + y) * (y - x + 1)) // 2
def solve(q):
left = 1
right = 10000000000
while left < right:
mid = (left + right) // 2
if digits_until_block_(mid) < q:
left = mid + 1
else:
right = mid
q = q - digits_until_block_(left - 1)
left = 1
right = 10000000000
while left < right:
mid = (left + right) // 2
if digits_until_(mid) < q:
left = mid + 1
else:
right = mid
q = q - digits_until_(left - 1)
return str(left)[q - 1]
q = int(input(""))
q_list = []
for _ in range(q):
q_list.append(int(input("")))
for query in q_list:
print(solve(query))
```
| 104,504 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between the easy and the hard versions is the maximum value of k.
You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one — from 1 to 2, the third one — from 1 to 3, ..., the i-th block consists of all numbers from 1 to i.
So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0.
Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 500) — the number of queries.
The i-th of the following q lines contains one integer k_i (1 ≤ k_i ≤ 10^9) — the description of the corresponding query.
Output
Print q lines. In the i-th line print one digit x_i (0 ≤ x_i ≤ 9) — the answer to the query i, i.e. x_i should be equal to the element at the position k_i of the sequence.
Examples
Input
5
1
3
20
38
56
Output
1
2
5
2
0
Input
4
2132
506
999999999
1000000000
Output
8
2
9
8
Note
Answers on queries from the first example are described in the problem statement.
Tags: binary search, brute force, math
Correct Solution:
```
def cached(func):
_cache = {}
def wrapped(*args):
nonlocal _cache
if args not in _cache:
_cache[args] = func(*args)
return _cache[args]
return wrapped
def len_num(l):
"""Количество чисел длины l"""
return 10**l - 10**(l - 1) if l > 0 else 0
@cached
def len_sum(l):
"""Сумма длин всех чисел, длина которых строго меньше чем l"""
if l <= 1:
return 0
return len_sum(l - 1) + (len_num(l - 1)) * (l - 1)
def block_len(block_num):
"""Длина блока (т. е. строки '1234567891011...str(block_num)'"""
l = len(str(block_num))
return len_sum(l) + (block_num - 10 ** (l - 1) + 1) * l
def arith_sum(n):
return n * (n + 1) // 2
@cached
def block_len_sum_(l):
"""Суммарная длина всех блоков длины меньшей чем l"""
if l <= 0:
return 0
ln = len_num(l - 1)
ls = len_sum(l - 1)
return block_len_sum_(l - 1) + ls * ln + arith_sum(ln) * (l - 1)
def block_len_sum(block_num):
"""Суммарная длина всех блоков подряд вплоть до блока block_num
Если l = len(str(block_num))
"""
l = len(str(block_num))
ls = len_sum(l)
ln = block_num - (10 ** (l - 1)) + 1
return block_len_sum_(l) + ls * ln + l * arith_sum(ln)
def binary_search(call, val):
start = 1
end = 1
while call(end) <= val:
end *= 2
result = start
while start <= end:
mid = (start + end) // 2
if call(mid) <= val:
start = mid + 1
result = start
else:
end = mid - 1
return result
cases = int(input())
for _ in range(cases):
index = int(input()) - 1
block_num = binary_search(block_len_sum, index)
rel_index = index - block_len_sum(block_num - 1)
number = binary_search(block_len, rel_index)
digit = rel_index - block_len(number - 1)
print(str(number)[digit])
```
| 104,505 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between the easy and the hard versions is the maximum value of k.
You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one — from 1 to 2, the third one — from 1 to 3, ..., the i-th block consists of all numbers from 1 to i.
So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0.
Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 500) — the number of queries.
The i-th of the following q lines contains one integer k_i (1 ≤ k_i ≤ 10^9) — the description of the corresponding query.
Output
Print q lines. In the i-th line print one digit x_i (0 ≤ x_i ≤ 9) — the answer to the query i, i.e. x_i should be equal to the element at the position k_i of the sequence.
Examples
Input
5
1
3
20
38
56
Output
1
2
5
2
0
Input
4
2132
506
999999999
1000000000
Output
8
2
9
8
Note
Answers on queries from the first example are described in the problem statement.
Tags: binary search, brute force, math
Correct Solution:
```
import bisect
s = [0] # индекс первой цифры блока
n = [1] # длина блока
while s[-1] < 1.1 * 10e9:
number = len(s) + 1
n.append(n[number - 1 - 1] + len(str(number)))
s.append(s[number - 1 - 1] + n[number - 1 - 1])
block = ''.join(str(i) for i in range(1, len(s) + 2))
def solve(element):
block_num = bisect.bisect_left(s, element)
if s[block_num] > element:
block_num -= 1
relative_index = element - s[block_num]
return block[relative_index]
q = int(input())
for _ in range(q):
print(solve(int(input()) - 1))
```
| 104,506 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between the easy and the hard versions is the maximum value of k.
You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one — from 1 to 2, the third one — from 1 to 3, ..., the i-th block consists of all numbers from 1 to i.
So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0.
Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 500) — the number of queries.
The i-th of the following q lines contains one integer k_i (1 ≤ k_i ≤ 10^9) — the description of the corresponding query.
Output
Print q lines. In the i-th line print one digit x_i (0 ≤ x_i ≤ 9) — the answer to the query i, i.e. x_i should be equal to the element at the position k_i of the sequence.
Examples
Input
5
1
3
20
38
56
Output
1
2
5
2
0
Input
4
2132
506
999999999
1000000000
Output
8
2
9
8
Note
Answers on queries from the first example are described in the problem statement.
Tags: binary search, brute force, math
Correct Solution:
```
def l(n): # length of 112123...1234567891011..n
s = 0
for i in range(20):
o = 10**i-1
if o > n: break
s += (n-o) * (n-o+1) // 2
return s
def bs(k): # binary search n so l(n) < k
n = 0
for p in range(63,-1,-1):
if l(n+2**p) < k: n += 2**p
return n
def num(n): # return s[n-1] where s = '1234567891011..n'
if n<10: return n
for i in range(1,19):
seglen = i * 9 * 10**(i-1)
if n <= seglen: return str(10**(i-1) + (n-1)//i)[(n-1)%i]
else: n -= seglen
q = int(input())
for _ in range(q):
k = int(input())
print(num(k-l(bs(k))))
```
| 104,507 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between the easy and the hard versions is the maximum value of k.
You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one — from 1 to 2, the third one — from 1 to 3, ..., the i-th block consists of all numbers from 1 to i.
So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0.
Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 500) — the number of queries.
The i-th of the following q lines contains one integer k_i (1 ≤ k_i ≤ 10^9) — the description of the corresponding query.
Output
Print q lines. In the i-th line print one digit x_i (0 ≤ x_i ≤ 9) — the answer to the query i, i.e. x_i should be equal to the element at the position k_i of the sequence.
Examples
Input
5
1
3
20
38
56
Output
1
2
5
2
0
Input
4
2132
506
999999999
1000000000
Output
8
2
9
8
Note
Answers on queries from the first example are described in the problem statement.
Tags: binary search, brute force, math
Correct Solution:
```
q=int(input())
a=""
for i in range(1,100000):
a+=str(i)
b=[]
ans=0
n=1
i=1
while ans<10**9:
ans+=n
n+=len(str(i+1))
i+=1
b.append(ans)
#print(b)
while q:
k=int(input())
for i in range(len(b)):
if(k>b[i]):
x=1
else:
if(i>=1):
k-=b[i-1]
break
print(a[k-1])
q-=1
```
| 104,508 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between the easy and the hard versions is the maximum value of k.
You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one — from 1 to 2, the third one — from 1 to 3, ..., the i-th block consists of all numbers from 1 to i.
So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0.
Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 500) — the number of queries.
The i-th of the following q lines contains one integer k_i (1 ≤ k_i ≤ 10^9) — the description of the corresponding query.
Output
Print q lines. In the i-th line print one digit x_i (0 ≤ x_i ≤ 9) — the answer to the query i, i.e. x_i should be equal to the element at the position k_i of the sequence.
Examples
Input
5
1
3
20
38
56
Output
1
2
5
2
0
Input
4
2132
506
999999999
1000000000
Output
8
2
9
8
Note
Answers on queries from the first example are described in the problem statement.
Tags: binary search, brute force, math
Correct Solution:
```
def isqrt(x):
if x < 0:
raise ValueError('square root not defined for negative numbers')
n = int(x)
if n == 0:
return 0
a, b = divmod(n.bit_length(), 2)
x = 2**(a+b)
while True:
y = (x + n//x)//2
if y >= x:
return x
x = y
p = [0, 45, 9045, 1395495, 189414495, 23939649495, 2893942449495, 339393974949495, 38939394344949495, 1000000000000000001];
nx = [0, 9, 189, 2889, 38889, 488889, 5888889, 68888889, 788888889, 8888888889]
q = int(input())
for ut in range(q):
lk = int(input())
k = lk
idx = 0;
for i in range(len(p)-1):
if (p[i] <= k) and (p[i + 1] > k):
idx = i;
idx = idx;
k-=1
k -= p[idx];
a = idx + 1
b = 2 * nx[idx] + idx + 1;
k = -2 * k;
d = isqrt(b*b-4 * a*k);
x1 = (-b + d) / (2. * a);
x2 = (-b - d) / (2. * a);
a1 = int(x1);
z = lk - p[idx] - nx[idx] * a1 - (a1 * (a1 + 1) // 2) * (idx + 1);
cnt = 0
ww = 1
pow = 0;
pow = 1;
while ((cnt + pow * ww) * 9 < z) :
cnt += pow * ww;
ww+=1
pow *= 10;
sym_cnt = (z - (cnt * 9)) - 1;
ok = (pow)+sym_cnt / ww;
s = str(ok);
if (z < 10):
print(z)
else:
print(s[sym_cnt % ww])
```
| 104,509 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between the easy and the hard versions is the maximum value of k.
You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one — from 1 to 2, the third one — from 1 to 3, ..., the i-th block consists of all numbers from 1 to i.
So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0.
Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 500) — the number of queries.
The i-th of the following q lines contains one integer k_i (1 ≤ k_i ≤ 10^9) — the description of the corresponding query.
Output
Print q lines. In the i-th line print one digit x_i (0 ≤ x_i ≤ 9) — the answer to the query i, i.e. x_i should be equal to the element at the position k_i of the sequence.
Examples
Input
5
1
3
20
38
56
Output
1
2
5
2
0
Input
4
2132
506
999999999
1000000000
Output
8
2
9
8
Note
Answers on queries from the first example are described in the problem statement.
Tags: binary search, brute force, math
Correct Solution:
```
dp, cnt = [0], 1
dp2 = [0]
while dp[-1] <= int(1e18):
ans = dp2[-1] + (10 ** cnt - 10 ** (cnt - 1)) * cnt
dp2.append(ans)
ans = dp[-1] + dp2[-2] * (10 ** cnt - 10 ** (cnt - 1)) + cnt * (10 ** cnt - 10 ** (cnt - 1) + 1) * (10 ** cnt - 10 ** (cnt - 1)) / 2
ans = int(ans)
cnt += 1
dp.append(ans)
def Cal(a, b):
return dp2[b - 1] * a + b * int(a * (a + 1) / 2)
q = int(input())
for _ in range(q):
k = int(input())
i = 0
while k > dp[i]:
i += 1
k -= dp[i - 1]
l, r = 0, 10 ** i - 10 ** (i - 1)
last = int((l + r) / 2)
while not(Cal(last, i) < k and Cal(last + 1, i) >= k):
if(Cal(last, i) < k):
l = last
last = int((l + r) / 2 + 1)
else:
r = last
last = int((l + r) / 2)
k -= Cal(last, i)
j = 0
while dp2[j] < k:
j += 1
k -= dp2[j - 1]
a = int((k - 1) / j)
k -= a * j
Long = str(10 ** (j - 1) + a)
print(Long[k - 1])
```
| 104,510 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between the easy and the hard versions is the maximum value of k.
You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one — from 1 to 2, the third one — from 1 to 3, ..., the i-th block consists of all numbers from 1 to i.
So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0.
Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 500) — the number of queries.
The i-th of the following q lines contains one integer k_i (1 ≤ k_i ≤ 10^9) — the description of the corresponding query.
Output
Print q lines. In the i-th line print one digit x_i (0 ≤ x_i ≤ 9) — the answer to the query i, i.e. x_i should be equal to the element at the position k_i of the sequence.
Examples
Input
5
1
3
20
38
56
Output
1
2
5
2
0
Input
4
2132
506
999999999
1000000000
Output
8
2
9
8
Note
Answers on queries from the first example are described in the problem statement.
Submitted Solution:
```
import sys
input = sys.stdin.readline
print = sys.stdout.write
for _ in range(int(input())):
k = int(input())
k -= 1
n = 0
m = 0
while k >= m:
k -= m
n += 1
m += len(str(n))
i = 1
while k >= len(str(i)):
k -= len(str(i))
i += 1
print(str(i)[k] + '\n')
```
Yes
| 104,511 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between the easy and the hard versions is the maximum value of k.
You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one — from 1 to 2, the third one — from 1 to 3, ..., the i-th block consists of all numbers from 1 to i.
So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0.
Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 500) — the number of queries.
The i-th of the following q lines contains one integer k_i (1 ≤ k_i ≤ 10^9) — the description of the corresponding query.
Output
Print q lines. In the i-th line print one digit x_i (0 ≤ x_i ≤ 9) — the answer to the query i, i.e. x_i should be equal to the element at the position k_i of the sequence.
Examples
Input
5
1
3
20
38
56
Output
1
2
5
2
0
Input
4
2132
506
999999999
1000000000
Output
8
2
9
8
Note
Answers on queries from the first example are described in the problem statement.
Submitted Solution:
```
class Num:
cur, digits, di = 0, 0, {}
def dig(n):
if "1"+"0"*(len(str(n))-1)==str(n):
Num.cur += 1
Num.digits += Num.cur
else:
Num.digits += Num.cur
return Num.digits
def work(n):
j=n
start = 1
Num.cur, Num.digits=0,0
done = False
while not done:
next = dig(start)
if n > next:
n -= next
start += 1
else:
done=True
p=1
while n > 9*p*(10**(p-1)):
n -= 9*p*(10**(p-1))
p += 1
starts = 10**(p-1)
if n <= p:
Num.di[j] = str(starts)[n-1]
else:
cv = int(n/p)
starts += cv
n -= cv*p
if n==0:
Num.di[j] = str(starts-1)[-1]
else:
Num.di[j] = str(starts)[n-1]
q = int(input())
li = []
for i in range(q):
li.append(int(input()))
for j in sorted(li):
work(j)
for j in li:
print(Num.di[j])
```
Yes
| 104,512 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between the easy and the hard versions is the maximum value of k.
You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one — from 1 to 2, the third one — from 1 to 3, ..., the i-th block consists of all numbers from 1 to i.
So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0.
Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 500) — the number of queries.
The i-th of the following q lines contains one integer k_i (1 ≤ k_i ≤ 10^9) — the description of the corresponding query.
Output
Print q lines. In the i-th line print one digit x_i (0 ≤ x_i ≤ 9) — the answer to the query i, i.e. x_i should be equal to the element at the position k_i of the sequence.
Examples
Input
5
1
3
20
38
56
Output
1
2
5
2
0
Input
4
2132
506
999999999
1000000000
Output
8
2
9
8
Note
Answers on queries from the first example are described in the problem statement.
Submitted Solution:
```
import io
import os
import collections
import math
import functools
import itertools
import bisect
import heapq
from sys import stdin, stdout, stderr
from collections import *
from math import *
from functools import *
from itertools import *
from heapq import *
from bisect import bisect_left, bisect_right, insort_left, insort_right
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def get_ints(): return list(map(int, input().split()))
def get_int(): return int(input())
def get_str(): return "".join(list(map(chr, input()))[:-1])
def eprint(*args): stderr.write(", ".join(map(str, args)) + "\n")
def print(*args): stdout.write(" ".join(map(str, args)) + "\n")
# **************************************************************************** #
q = get_int()
arr = [get_int() for _ in range(q)]
arr = [(x, i) for i, x in enumerate(arr)]
arr.sort()
res = [0] * q
strs = []
s_ps = [0]
t_ps = [0]
s_len = 0
t_len = 0
x = 0
'''
1
112
1 12 123 1234 12345 123456 1234567 12345678 123456789 12345678910
11212312341234512345612345671234567812345678912345678910
'''
for n, i in arr:
while t_len < n:
x += 1
xs = str(x)
strs.append(xs)
s_len += len(xs)
s_ps.append(s_len)
t_len += s_len
t_ps.append(t_len)
nn = n - t_ps[-2]
si = bisect_left(s_ps, nn) - 1
ss = strs[si] if si < len(strs) else None
sci = nn - s_ps[si] - 1
sc = ss[sci]
#eprint(n, nn, i, strs, s_ps, t_ps, x, si, ss, sci, sc)
res[i] = sc
for r in res:
print(r)
```
Yes
| 104,513 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between the easy and the hard versions is the maximum value of k.
You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one — from 1 to 2, the third one — from 1 to 3, ..., the i-th block consists of all numbers from 1 to i.
So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0.
Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 500) — the number of queries.
The i-th of the following q lines contains one integer k_i (1 ≤ k_i ≤ 10^9) — the description of the corresponding query.
Output
Print q lines. In the i-th line print one digit x_i (0 ≤ x_i ≤ 9) — the answer to the query i, i.e. x_i should be equal to the element at the position k_i of the sequence.
Examples
Input
5
1
3
20
38
56
Output
1
2
5
2
0
Input
4
2132
506
999999999
1000000000
Output
8
2
9
8
Note
Answers on queries from the first example are described in the problem statement.
Submitted Solution:
```
q = int(input())
for _ in range(q):
k = int(input())
if k == 933939799:
print(7)
else:
d = 1
l = 0
n = 9
a1 = 1
while l + (2*a1 + (n-1)*d) * n // 2 < k:
l += (2*a1 + (n-1)*d) * n // 2
a1 += (n * d + 1)
d += 1
n *= 10
k -= l
while k - a1 > 0:
k -= a1
a1 += d
n = 9
d = 1
l = 0
while l + n * d < k:
l += n * d
d += 1
n *= 10
k -= l
l = 0
s = ''
start = int('1' + '0'*(d-1))
n = 1
while k - d * start > 0:
k -= d * start
n += 1
n = int(str(n) + '0'*(d-1))
while l < k:
s += str(n)
l += len(str(n))
n += 1
print(s[k-1])
```
Yes
| 104,514 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between the easy and the hard versions is the maximum value of k.
You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one — from 1 to 2, the third one — from 1 to 3, ..., the i-th block consists of all numbers from 1 to i.
So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0.
Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 500) — the number of queries.
The i-th of the following q lines contains one integer k_i (1 ≤ k_i ≤ 10^9) — the description of the corresponding query.
Output
Print q lines. In the i-th line print one digit x_i (0 ≤ x_i ≤ 9) — the answer to the query i, i.e. x_i should be equal to the element at the position k_i of the sequence.
Examples
Input
5
1
3
20
38
56
Output
1
2
5
2
0
Input
4
2132
506
999999999
1000000000
Output
8
2
9
8
Note
Answers on queries from the first example are described in the problem statement.
Submitted Solution:
```
from collections import deque
import sys
import math
import bisect
def inp():
return sys.stdin.readline().strip()
def f(i):
if i==1:
return 1
logi=math.floor(math.log(i,10))+1
val=(logi-1)*(10**(logi-1))-((10**(logi-1)-1)//9)+i*logi-((10**(logi-1)) -1)*logi
return int(val)
precompute=[0]
i=1
while precompute[-1]<10**10:
precompute.append(precompute[i-1]+f(i))
i+=1
for _ in range(int(inp())):
k=int(inp())
j=bisect.bisect_right(precompute,k)
tbf=k-precompute[j-1]
if tbf==0:
print((j-1)%10)
continue
l=1
r=int(1e10)
ans=1
while l<=r:
m=(l+r)//2
if f(m)<=tbf:
ans=int(m)
l=m+1
else:
r=m-1
diff=tbf-f(ans)
m=ans
st=''
while len(st)<=diff:
st=str(m)+st
m-=1
#print(st)
back=int(tbf-f(ans))-1
#print(back)
print(st[back])
```
No
| 104,515 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between the easy and the hard versions is the maximum value of k.
You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one — from 1 to 2, the third one — from 1 to 3, ..., the i-th block consists of all numbers from 1 to i.
So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0.
Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 500) — the number of queries.
The i-th of the following q lines contains one integer k_i (1 ≤ k_i ≤ 10^9) — the description of the corresponding query.
Output
Print q lines. In the i-th line print one digit x_i (0 ≤ x_i ≤ 9) — the answer to the query i, i.e. x_i should be equal to the element at the position k_i of the sequence.
Examples
Input
5
1
3
20
38
56
Output
1
2
5
2
0
Input
4
2132
506
999999999
1000000000
Output
8
2
9
8
Note
Answers on queries from the first example are described in the problem statement.
Submitted Solution:
```
num_queries = int(input())
queries = []
for i in range(num_queries):
queries.append(int(input()))
mq = max(queries)
seq = ""
i = 1
while len(seq) < mq:
stt = ""
for j in range(1, i + 1):
stt = stt + str(j)
seq = seq + stt
i = i + 1
print(seq)
for query in queries:
print(seq[query - 1])
```
No
| 104,516 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between the easy and the hard versions is the maximum value of k.
You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one — from 1 to 2, the third one — from 1 to 3, ..., the i-th block consists of all numbers from 1 to i.
So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0.
Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 500) — the number of queries.
The i-th of the following q lines contains one integer k_i (1 ≤ k_i ≤ 10^9) — the description of the corresponding query.
Output
Print q lines. In the i-th line print one digit x_i (0 ≤ x_i ≤ 9) — the answer to the query i, i.e. x_i should be equal to the element at the position k_i of the sequence.
Examples
Input
5
1
3
20
38
56
Output
1
2
5
2
0
Input
4
2132
506
999999999
1000000000
Output
8
2
9
8
Note
Answers on queries from the first example are described in the problem statement.
Submitted Solution:
```
import time
q = int(input())
for i in range(q):
k=int(input())
y=1
group_l=""
full_l=0
start_time=time.time()
while 1:
group_l+=str(y)
if full_l+len(group_l)<k:
full_l+=len(group_l)
y+=1
else:
break
med_time=time.time()
print("t2-t1=",med_time-start_time)
k-=full_l
print(group_l[k-1])
end_time=time.time()
print("t3-t2=",end_time-med_time)
```
No
| 104,517 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between the easy and the hard versions is the maximum value of k.
You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one — from 1 to 2, the third one — from 1 to 3, ..., the i-th block consists of all numbers from 1 to i.
So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0.
Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 500) — the number of queries.
The i-th of the following q lines contains one integer k_i (1 ≤ k_i ≤ 10^9) — the description of the corresponding query.
Output
Print q lines. In the i-th line print one digit x_i (0 ≤ x_i ≤ 9) — the answer to the query i, i.e. x_i should be equal to the element at the position k_i of the sequence.
Examples
Input
5
1
3
20
38
56
Output
1
2
5
2
0
Input
4
2132
506
999999999
1000000000
Output
8
2
9
8
Note
Answers on queries from the first example are described in the problem statement.
Submitted Solution:
```
q=int(input())
s=''
l=[0]*25001
for i in range(1,25000):
s+=str(i)
l[i]=len(s)
for i in range(q):
k=int(input())
n=1
t=2*k
while n*(n+1)<t:
n+=1
k-=1
for i in range(1,n+2):
if k>l[i]:
k-=l[i]
else:
print(s[k])
break
```
No
| 104,518 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
I'm the Map, I'm the Map! I'm the MAP!!!
Map
In anticipation of new adventures Boots wanted to do a good deed. After discussion with the Map and Backpack, they decided to gift Dora a connected graph. After a long search, Boots chose t graph's variants, which Dora might like. However fox Swiper wants to spoil his plan.
The Swiper knows, that Dora now is only able to count up to 3, so he has came up with a following idea. He wants to steal some non-empty set of vertices, so that the Dora won't notice the loss. He has decided to steal some non-empty set of vertices, so that after deletion of the stolen vertices and edges adjacent to them, every remaining vertex wouldn't change it's degree modulo 3. The degree of a vertex is the number of edges it is adjacent to. It would've been suspicious to steal all the vertices, so Swiper needs another plan.
Boots are sure, that the crime can not be allowed. However they are afraid, that they won't be able to handle this alone. So Boots decided to ask for your help. Please determine for every graph's variant whether the Swiper can perform the theft or not.
Input
The first line contains a single integer t (1 ≤ t ≤ 100 000) — the number of graph variants.
The first line of each variant contains integers n, m (1 ≤ n ≤ 500 000, 0 ≤ m ≤ 500 000), the number of vertexes and edges in the graph.
Then m lines follow, each containing integers a_i, b_i (1 ≤ a_i, b_i ≤ n), the indices of the vertices connected with a corresponding edge.
It's guaranteed, that the graph is connected and doesn't contain multiple edges or self-loops.
It's guaranteed, that the sum of n over all variants is at most 500 000 and that the sum of m over all variants is at most 500 000.
Descriptions of graph's variants are separated with an empty line.
Output
For each variant:
* In case the answer exists, print "Yes" and then the answer itself.
The first line should contain an integer c (1 < c < n), the number of vertices the Crook can steal, without Dora noticing the loss. On the next line print c distinct integers, the indices of the graph's vertices in arbitrary order.
* Otherwise print "No".
In case there are several correct ways to steal the vertices, print any of them.
Please note, that it's not required to maximize the number of stolen vertices.
Example
Input
3
3 3
1 2
2 3
3 1
6 6
1 2
1 3
2 3
2 5
2 6
2 4
8 12
1 2
1 3
2 3
1 4
4 5
5 1
3 6
3 7
3 8
6 1
7 1
8 1
Output
No
Yes
3
4 5 6
Yes
3
6 7 8
Note
The picture below shows the third variant from the example test. The set of the vertices the Crook can steal is denoted with bold.
<image>
Submitted Solution:
```
from collections import deque
from typing import List
N = 500005
visited = [False] * N
good = [False] * N
parent = [0] * N
h = [0] * N
adj: List[List[int]] = [[] for _ in range(N)]
q = deque()
degree = [0] * N
def dfs1(u: int):
mx = -1
visited[u] = True
for v in adj[u]:
if visited[v] and h[v] < h[u] - 1 and (mx == -1 or h[v] > h[mx]):
mx = v
if mx != -1 and h[u] - h[mx] + 1 < n and degree[mx] % 3 > 1:
while u != parent[mx]:
good[u] = True
u = parent[u]
return True
for v in adj[u]:
if not visited[v]:
parent[v] = u
h[v] = h[u] + 1
if dfs1(v):
return True
return False
def dfs2(u: int):
visited[u] = True
for v in adj[u]:
if not visited[v]:
dfs2(v)
def has_3k_vertex():
for i in range(n):
if degree[i] % 3 == 0:
good[i] = True
return True
return False
def has_121_path():
parent[root] = -1
visited[root] = True
q.append(root)
while len(q):
u = q.popleft()
if u != root and degree[u] % 3 == 1 and h[u] < n - 1:
while u != -1:
good[u] = True
u = parent[u]
q.clear()
return True
for v in adj[u]:
if not visited[v]:
visited[v] = True
q.append(v)
parent[v] = u
h[v] = h[u] + 1
q.popleft()
def has_2_cycle():
parent[root if root < n else 0] = -1
for i in range(n):
visited[i] = False
return dfs1(root if root < n else 0)
def has_122_components():
flag = False
for i in range(n):
visited[i] = False
visited[root] = good[root] = True
# adj[root].sort(key=lambda a: h[a])
for u in adj[root]:
if not visited[u] and h[u] > 1:
v = u
good[u] = True
while parent[v] != root:
v = parent[v]
good[v] = True
if flag:
break
dfs2(v)
flag = True
return True
if __name__ == '__main__':
s = int(input())
while s > 0:
n, m = [int(a) for a in input().split(' ')]
for i in range(m):
u, v = [int(a) - 1 for a in input().split(' ')]
degree[u] += 1
degree[v] += 1
adj[u].append(v)
adj[v].append(u)
v1 = [a for a in range(n) if degree[a] % 3 == 1]
root = v1[0] if len(v1) > 0 else n
if has_3k_vertex() or (len(v1) > 1 and has_121_path()) or has_2_cycle() or\
(root < n and degree[root] > 4 and has_122_components()):
li = list()
for i in range(n):
if not good[i]:
li.append(str(i + 1))
print("Yes")
print(len(li))
print(' '.join(li))
else:
print('No')
for i in range(n):
adj[i].clear()
visited[i] = good[i] = False
parent[i] = degree[i] = h[i] = 0
s -= 1
if s != 0:
input()
```
No
| 104,519 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
I'm the Map, I'm the Map! I'm the MAP!!!
Map
In anticipation of new adventures Boots wanted to do a good deed. After discussion with the Map and Backpack, they decided to gift Dora a connected graph. After a long search, Boots chose t graph's variants, which Dora might like. However fox Swiper wants to spoil his plan.
The Swiper knows, that Dora now is only able to count up to 3, so he has came up with a following idea. He wants to steal some non-empty set of vertices, so that the Dora won't notice the loss. He has decided to steal some non-empty set of vertices, so that after deletion of the stolen vertices and edges adjacent to them, every remaining vertex wouldn't change it's degree modulo 3. The degree of a vertex is the number of edges it is adjacent to. It would've been suspicious to steal all the vertices, so Swiper needs another plan.
Boots are sure, that the crime can not be allowed. However they are afraid, that they won't be able to handle this alone. So Boots decided to ask for your help. Please determine for every graph's variant whether the Swiper can perform the theft or not.
Input
The first line contains a single integer t (1 ≤ t ≤ 100 000) — the number of graph variants.
The first line of each variant contains integers n, m (1 ≤ n ≤ 500 000, 0 ≤ m ≤ 500 000), the number of vertexes and edges in the graph.
Then m lines follow, each containing integers a_i, b_i (1 ≤ a_i, b_i ≤ n), the indices of the vertices connected with a corresponding edge.
It's guaranteed, that the graph is connected and doesn't contain multiple edges or self-loops.
It's guaranteed, that the sum of n over all variants is at most 500 000 and that the sum of m over all variants is at most 500 000.
Descriptions of graph's variants are separated with an empty line.
Output
For each variant:
* In case the answer exists, print "Yes" and then the answer itself.
The first line should contain an integer c (1 < c < n), the number of vertices the Crook can steal, without Dora noticing the loss. On the next line print c distinct integers, the indices of the graph's vertices in arbitrary order.
* Otherwise print "No".
In case there are several correct ways to steal the vertices, print any of them.
Please note, that it's not required to maximize the number of stolen vertices.
Example
Input
3
3 3
1 2
2 3
3 1
6 6
1 2
1 3
2 3
2 5
2 6
2 4
8 12
1 2
1 3
2 3
1 4
4 5
5 1
3 6
3 7
3 8
6 1
7 1
8 1
Output
No
Yes
3
4 5 6
Yes
3
6 7 8
Note
The picture below shows the third variant from the example test. The set of the vertices the Crook can steal is denoted with bold.
<image>
Submitted Solution:
```
upper,lower,n,m = 0,0,0,0
graph = []
deg = []
depth = []
parent = []
q = []
pred = []
keep = []
mod = []
def dfs(v):
global lower
global upper
r = 0
for u in graph[v]:
if parent[v] != u and deg[u] % 3 == 2:
if depth[u]:
lower = lower if lower else v
upper = upper if upper else u
r = 1
else:
depth[u] = depth[v] + 1
parent[u] = v
r |= dfs(u)
return r
def forest():
r = 1
for v in mod[2]:
if depth[v] == 0:
parent[v] = -1
depth[v] = 1
if dfs(v):
r = 0
return r
def answer():
keep.sort()
if len(keep) == n:
print("No")
else:
#devolver todos los vértices que van a ser robados,
#que sería aquellos que no pertenecen al conjunto keep.
print("Yes")
print(n - len(keep))
k = n - len(keep)
i = 1
j = 0
while k:
while i <= n and j < len(keep) and keep[j] == i:
i += 1
j += 1
if k == 1:
print(i)
else:
print(i, end=' ')
k -= 1
i += 1
def solve():
global n
global m
global upper
global lower
for _ in range(m):
u,v = map(int,input().split())
graph[u].append(v)
graph[v].append(u)
deg[u] += 1
deg[v] += 1
for i in range(1,n+1):
mod[deg[i]%3].append(i)
if n == 1:
print("No")
elif len(mod[0]) > 0:
x = mod[0][0]
print("Yes")
print(n-1)
for i in range(1,n):
v = i + 1 if i >= x else i
if i + 1 == n:
print(v)
else:
print(v,end=' ')
elif not forest():
keep.append(upper)
keep.append(lower)
#guardar todos los vértices del ciclo
i = parent[lower]
x = 0
y = 0
print('aqui')
while i != upper:
keep.append(i)
y = depth[i]
for v in graph[i]:
if y > depth[v] and depth[v] >= depth[upper]:
x = v
y = depth[v]
i = x
answer()
elif len(mod[1]) == 0:
print("No")
elif len(mod[1]) >= 2:
pred[mod[1][0]] = -1
#cola queue
q[0] = mod[1][0]
i = 0
j = 1
k = q[0]
while i < j:
if i and deg[k] % 3 == 1:
t = k
break
for v in graph[k]:
if pred[v] == 0:
pred[v] = k
q[j] = v
j += 1
i += 1
k = q[i]
#guardar los vértices del camino
i = t
while ~i:
keep.append(i)
i = pred[i]
answer()
else:
keep.append(mod[1][0])
fst = graph[mod[1][0]][0]
pred[fst] = -1
q[0] = fst
last = 0
i = 0
j = 1
k = q[0]
while i < j:
for v in graph[k]:
if pred[v] == 0:
if v == mod[1][0]:
last = last if (last or (not i) ) else k
else:
pred[v] = k
q[j] = v
j += 1
i += 1
k = q[i]
#agregar los vértices del primer camino
i = last
while ~i:
keep.append(i)
i = pred[i]
#encontrar el otro camino
for v in graph[mod[1][0]]:
if pred[v] == 0:
fst = v
break
last = 0
pred[fst] = -1
q[0] = fst
i = 0
j = 1
k = q[0]
while i < j:
for v in graph[k]:
if pred[v] == 0:
if v == mod[1][0]:
last = last if (last or (not i)) else k
else:
pred[v] = k
q[j] = v
j += 1
i += 1
k = q[i]
i = last
while ~i:
keep.append(i)
i = pred[i]
answer()
T = int(input())
for i in range(T):
upper = 0
lower = 0
n, m = map(int,input().split())
graph = [[] for _ in range(n + 1)]
deg = [0 for _ in range(n + 1)]
q = [0 for _ in range(n + 1)]
pred = [0 for _ in range(n + 1)]
depth = [0 for _ in range(n + 1)]
parent = [0 for _ in range(n + 1)]
keep = []
mod = [[] for _ in range(3)]
solve()
if i != T - 1:
_ = input()
```
No
| 104,520 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
I'm the Map, I'm the Map! I'm the MAP!!!
Map
In anticipation of new adventures Boots wanted to do a good deed. After discussion with the Map and Backpack, they decided to gift Dora a connected graph. After a long search, Boots chose t graph's variants, which Dora might like. However fox Swiper wants to spoil his plan.
The Swiper knows, that Dora now is only able to count up to 3, so he has came up with a following idea. He wants to steal some non-empty set of vertices, so that the Dora won't notice the loss. He has decided to steal some non-empty set of vertices, so that after deletion of the stolen vertices and edges adjacent to them, every remaining vertex wouldn't change it's degree modulo 3. The degree of a vertex is the number of edges it is adjacent to. It would've been suspicious to steal all the vertices, so Swiper needs another plan.
Boots are sure, that the crime can not be allowed. However they are afraid, that they won't be able to handle this alone. So Boots decided to ask for your help. Please determine for every graph's variant whether the Swiper can perform the theft or not.
Input
The first line contains a single integer t (1 ≤ t ≤ 100 000) — the number of graph variants.
The first line of each variant contains integers n, m (1 ≤ n ≤ 500 000, 0 ≤ m ≤ 500 000), the number of vertexes and edges in the graph.
Then m lines follow, each containing integers a_i, b_i (1 ≤ a_i, b_i ≤ n), the indices of the vertices connected with a corresponding edge.
It's guaranteed, that the graph is connected and doesn't contain multiple edges or self-loops.
It's guaranteed, that the sum of n over all variants is at most 500 000 and that the sum of m over all variants is at most 500 000.
Descriptions of graph's variants are separated with an empty line.
Output
For each variant:
* In case the answer exists, print "Yes" and then the answer itself.
The first line should contain an integer c (1 < c < n), the number of vertices the Crook can steal, without Dora noticing the loss. On the next line print c distinct integers, the indices of the graph's vertices in arbitrary order.
* Otherwise print "No".
In case there are several correct ways to steal the vertices, print any of them.
Please note, that it's not required to maximize the number of stolen vertices.
Example
Input
3
3 3
1 2
2 3
3 1
6 6
1 2
1 3
2 3
2 5
2 6
2 4
8 12
1 2
1 3
2 3
1 4
4 5
5 1
3 6
3 7
3 8
6 1
7 1
8 1
Output
No
Yes
3
4 5 6
Yes
3
6 7 8
Note
The picture below shows the third variant from the example test. The set of the vertices the Crook can steal is denoted with bold.
<image>
Submitted Solution:
```
from typing import List
import sys
t_p = []
def get_ints(): return map(int, sys.stdin.readline().strip().split())
def puts(string: str):
t_p.append(string)
def print_solution(solution):
for i in solution:
can_pick[i] = False
to_sol: List[str] = []
for i in range(1, n + 1):
if can_pick[i]:
to_sol.append(str(i))
if len(to_sol) == 0:
puts('No')
return
puts('Yes')
puts(str(len(to_sol)))
puts(' '.join(to_sol))
path = []
def nodes_1_22(i):
qi: List[int] = [0] * (n + 1)
stack = []
stack.append(i)
one_time = False
while len(stack) > 0:
u = stack[-1]
if u != i:
visited[u] = True
else:
visited[u] = False
if qi[u] >= len(adj[u]):
stack.pop()
continue
v = adj[u][qi[u]]
qi[u] += 1
if parent[u] != v:
if not visited[v]:
if v != i:
parent[v] = u
stack.append(v)
else:
visited[v] = True
x = u
while parent[x] != 0:
a = parent[x]
if x == i:
parent[x] = 0
path.append(x)
x = a
path.append(x)
if one_time:
print_solution(path)
else:
one_time = True
def nodes_2():
path = []
qi: List[int] = [0] * (n + 1)
stack = []
stack.append(1)
while len(stack) > 0:
u = stack[-1]
visited[u] = True
if qi[u] >= len(adj[u]):
stack.pop()
continue
v = adj[u][qi[u]]
qi[u] += 1
if parent[u] != v:
if not visited[v]:
parent[v] = u
stack.append(v)
else:
x = v
path.append(x)
x = u
while x != v:
path.append(x)
x = parent[x]
path.append(x)
print_solution(path)
return
def nodes_1(i):
path = []
qi: List[int] = [0] * (n + 1)
stack = []
stack.append(i)
while len(stack) > 0:
u = stack[-1]
visited[u] = True
if qi[u] == 0:
for v in adj[u]:
if v != i and len(adj[v]) % 3 == 1:
x = u
path.append(v)
while parent[x] != 0:
path.append(x)
x = parent[x]
path.append(x)
print_solution(path)
return
if qi[u] >= len(adj[u]):
stack.pop()
continue
v = adj[u][qi[u]]
qi[u] += 1
if parent[u] != v:
if not visited[v]:
parent[v] = u
if len(adj[v]) % 3 == 1:
x = v
while parent[x] != 0:
path.append(x)
x = parent[x]
path.append(x)
print_solution(path)
return
stack.append(v)
def nodes_0(i):
print_solution([i])
def solve():
node_1 = -1
for i in range(1, n + 1):
if len(adj[i]) % 3 == 0:
nodes_0(i)
return
for i in range(1, n + 1):
if len(adj[i]) % 3 == 1:
if node_1 != -1:
nodes_1(node_1)
return
else:
node_1 = i
if node_1 == -1:
nodes_2()
else:
nodes_1_22(node_1)
if __name__ == '__main__':
q = int(input())
# input()
for qi in range(q):
n, m = [int(a) for a in input().split(' ')]
adj: List[List[int]] = [[]] + [[] for _ in range(n)]
can_pick: List[bool] = [False] + ([True] * n)
parent: List[int] = [0] * (n + 1)
visited: List[bool] = [False] * (n + 1)
for mi in range(m):
# input()
u, v = [int(a) for a in input().split(' ')]
adj[u].append(v)
adj[v].append(u)
solve()
if qi != q - 1:
input()
sys.stdout.write('\n'.join(t_p))
```
No
| 104,521 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
I'm the Map, I'm the Map! I'm the MAP!!!
Map
In anticipation of new adventures Boots wanted to do a good deed. After discussion with the Map and Backpack, they decided to gift Dora a connected graph. After a long search, Boots chose t graph's variants, which Dora might like. However fox Swiper wants to spoil his plan.
The Swiper knows, that Dora now is only able to count up to 3, so he has came up with a following idea. He wants to steal some non-empty set of vertices, so that the Dora won't notice the loss. He has decided to steal some non-empty set of vertices, so that after deletion of the stolen vertices and edges adjacent to them, every remaining vertex wouldn't change it's degree modulo 3. The degree of a vertex is the number of edges it is adjacent to. It would've been suspicious to steal all the vertices, so Swiper needs another plan.
Boots are sure, that the crime can not be allowed. However they are afraid, that they won't be able to handle this alone. So Boots decided to ask for your help. Please determine for every graph's variant whether the Swiper can perform the theft or not.
Input
The first line contains a single integer t (1 ≤ t ≤ 100 000) — the number of graph variants.
The first line of each variant contains integers n, m (1 ≤ n ≤ 500 000, 0 ≤ m ≤ 500 000), the number of vertexes and edges in the graph.
Then m lines follow, each containing integers a_i, b_i (1 ≤ a_i, b_i ≤ n), the indices of the vertices connected with a corresponding edge.
It's guaranteed, that the graph is connected and doesn't contain multiple edges or self-loops.
It's guaranteed, that the sum of n over all variants is at most 500 000 and that the sum of m over all variants is at most 500 000.
Descriptions of graph's variants are separated with an empty line.
Output
For each variant:
* In case the answer exists, print "Yes" and then the answer itself.
The first line should contain an integer c (1 < c < n), the number of vertices the Crook can steal, without Dora noticing the loss. On the next line print c distinct integers, the indices of the graph's vertices in arbitrary order.
* Otherwise print "No".
In case there are several correct ways to steal the vertices, print any of them.
Please note, that it's not required to maximize the number of stolen vertices.
Example
Input
3
3 3
1 2
2 3
3 1
6 6
1 2
1 3
2 3
2 5
2 6
2 4
8 12
1 2
1 3
2 3
1 4
4 5
5 1
3 6
3 7
3 8
6 1
7 1
8 1
Output
No
Yes
3
4 5 6
Yes
3
6 7 8
Note
The picture below shows the third variant from the example test. The set of the vertices the Crook can steal is denoted with bold.
<image>
Submitted Solution:
```
from typing import List
import sys
t_p = []
def get_ints(): return map(int, sys.stdin.readline().strip().split())
def puts(string: str):
t_p.append(string)
def print_solution(solution):
for i in solution:
can_pick[i] = False
to_sol: List[str] = []
for i in range(1, n + 1):
if can_pick[i]:
to_sol.append(str(i))
if len(to_sol) == 0:
puts('No')
return
puts('Yes')
puts(str(len(to_sol)))
puts(' '.join(to_sol))
path = []
def nodes_1_22(i):
qi: List[int] = [0] * (n + 1)
stack = []
stack.append(i)
one_time = False
while len(stack) > 0:
u = stack[-1]
if u != i:
visited[u] = True
else:
visited[u] = False
if qi[u] >= len(adj[u]):
stack.pop()
continue
v = adj[u][qi[u]]
qi[u] += 1
if parent[u] != v:
if not visited[v]:
if v != i:
parent[v] = u
stack.append(v)
else:
visited[v] = True
x = u
while parent[x] != 0:
a = parent[x]
if x == i:
parent[x] = 0
path.append(x)
x = a
path.append(x)
if one_time:
print_solution(path)
else:
one_time = True
def nodes_2():
path = []
qi: List[int] = [0] * (n + 1)
stack = []
stack.append(1)
while len(stack) > 0:
u = stack[-1]
visited[u] = True
if qi[u] >= len(adj[u]):
stack.pop()
continue
v = adj[u][qi[u]]
qi[u] += 1
if parent[u] != v:
if not visited[v]:
parent[v] = u
stack.append(v)
else:
x = v
path.append(x)
x = u
while x != v:
path.append(x)
x = parent[x]
path.append(x)
print_solution(path)
return
def nodes_1(i):
path = []
qi: List[int] = [0] * (n + 1)
stack = []
stack.append(i)
while len(stack) > 0:
u = stack[-1]
visited[u] = True
if qi[u] == 0:
for v in adj[u]:
if v != i and len(adj[v]) % 3 == 1:
x = u
path.append(v)
while parent[x] != 0:
path.append(x)
x = parent[x]
path.append(x)
print_solution(path)
return
if qi[u] >= len(adj[u]):
stack.pop()
continue
v = adj[u][qi[u]]
qi[u] += 1
if parent[u] != v:
if not visited[v]:
parent[v] = u
if len(adj[v]) % 3 == 1:
x = v
while parent[x] != 0:
path.append(x)
x = parent[x]
path.append(x)
print_solution(path)
return
stack.append(v)
def nodes_0(i):
print_solution([i])
def solve():
node_1 = -1
for i in range(1, n + 1):
if len(adj[i]) % 3 == 0:
nodes_0(i)
return
for i in range(1, n + 1):
if len(adj[i]) % 3 == 1:
if node_1 != -1:
nodes_1(node_1)
return
else:
node_1 = i
if node_1 == -1:
nodes_2()
else:
nodes_1_22(node_1)
if __name__ == '__main__':
q = int(input())
# input()
i = 0
while i < q:
n, m = [int(a) for a in input().split(' ')]
if q > 30000 and 159 < i < 160:
print(n, m, sep=' ')
adj: List[List[int]] = [[]] + [[] for _ in range(n)]
can_pick: List[bool] = [False] + ([True] * n)
parent: List[int] = [0] * (n + 1)
visited: List[bool] = [False] * (n + 1)
for mi in range(m):
# input()
u, v = [int(a) for a in input().split(' ')]
adj[u].append(v)
adj[v].append(u)
if q > 30000 and 159 < i < 160:
print(u, v, sep=' ')
if q > 30000 and 159 < i < 160:
print()
if q < 30000:
solve()
if i != q - 1:
input()
i += 1
sys.stdout.write('\n'.join(t_p))
```
No
| 104,522 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Lengths are measures in Baden in inches and feet. To a length from centimeters it is enough to know that an inch equals three centimeters in Baden and one foot contains 12 inches.
You are given a length equal to n centimeters. Your task is to convert it to feet and inches so that the number of feet was maximum. The result should be an integer rounded to the closest value containing an integral number of inches.
Note that when you round up, 1 cm rounds up to 0 inches and 2 cm round up to 1 inch.
Input
The only line contains an integer n (1 ≤ n ≤ 10000).
Output
Print two non-negative space-separated integers a and b, where a is the numbers of feet and b is the number of inches.
Examples
Input
42
Output
1 2
Input
5
Output
0 2
Tags: math
Correct Solution:
```
n = round(int(input())/3)
print(n//12, n%12)
```
| 104,523 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Lengths are measures in Baden in inches and feet. To a length from centimeters it is enough to know that an inch equals three centimeters in Baden and one foot contains 12 inches.
You are given a length equal to n centimeters. Your task is to convert it to feet and inches so that the number of feet was maximum. The result should be an integer rounded to the closest value containing an integral number of inches.
Note that when you round up, 1 cm rounds up to 0 inches and 2 cm round up to 1 inch.
Input
The only line contains an integer n (1 ≤ n ≤ 10000).
Output
Print two non-negative space-separated integers a and b, where a is the numbers of feet and b is the number of inches.
Examples
Input
42
Output
1 2
Input
5
Output
0 2
Tags: math
Correct Solution:
```
n=int(input())
a = n//3
b = n%3
if b==2:
a+=1
s = a//12
y = a%12
print(s,y)
```
| 104,524 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Lengths are measures in Baden in inches and feet. To a length from centimeters it is enough to know that an inch equals three centimeters in Baden and one foot contains 12 inches.
You are given a length equal to n centimeters. Your task is to convert it to feet and inches so that the number of feet was maximum. The result should be an integer rounded to the closest value containing an integral number of inches.
Note that when you round up, 1 cm rounds up to 0 inches and 2 cm round up to 1 inch.
Input
The only line contains an integer n (1 ≤ n ≤ 10000).
Output
Print two non-negative space-separated integers a and b, where a is the numbers of feet and b is the number of inches.
Examples
Input
42
Output
1 2
Input
5
Output
0 2
Tags: math
Correct Solution:
```
x=(int(input())+1)//3
print(x//12,x%12)
```
| 104,525 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Lengths are measures in Baden in inches and feet. To a length from centimeters it is enough to know that an inch equals three centimeters in Baden and one foot contains 12 inches.
You are given a length equal to n centimeters. Your task is to convert it to feet and inches so that the number of feet was maximum. The result should be an integer rounded to the closest value containing an integral number of inches.
Note that when you round up, 1 cm rounds up to 0 inches and 2 cm round up to 1 inch.
Input
The only line contains an integer n (1 ≤ n ≤ 10000).
Output
Print two non-negative space-separated integers a and b, where a is the numbers of feet and b is the number of inches.
Examples
Input
42
Output
1 2
Input
5
Output
0 2
Tags: math
Correct Solution:
```
n=int(input())
i=int(n/3)+(n%3)-1
if n%3==0:
i+=1
print(i//12," ",i%12)
```
| 104,526 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Lengths are measures in Baden in inches and feet. To a length from centimeters it is enough to know that an inch equals three centimeters in Baden and one foot contains 12 inches.
You are given a length equal to n centimeters. Your task is to convert it to feet and inches so that the number of feet was maximum. The result should be an integer rounded to the closest value containing an integral number of inches.
Note that when you round up, 1 cm rounds up to 0 inches and 2 cm round up to 1 inch.
Input
The only line contains an integer n (1 ≤ n ≤ 10000).
Output
Print two non-negative space-separated integers a and b, where a is the numbers of feet and b is the number of inches.
Examples
Input
42
Output
1 2
Input
5
Output
0 2
Tags: math
Correct Solution:
```
cm = int(input())
inches = cm // 3
if cm % 3 == 2:
inches += 1
feet = inches // 12
inches %= 12
print(feet, inches)
```
| 104,527 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Lengths are measures in Baden in inches and feet. To a length from centimeters it is enough to know that an inch equals three centimeters in Baden and one foot contains 12 inches.
You are given a length equal to n centimeters. Your task is to convert it to feet and inches so that the number of feet was maximum. The result should be an integer rounded to the closest value containing an integral number of inches.
Note that when you round up, 1 cm rounds up to 0 inches and 2 cm round up to 1 inch.
Input
The only line contains an integer n (1 ≤ n ≤ 10000).
Output
Print two non-negative space-separated integers a and b, where a is the numbers of feet and b is the number of inches.
Examples
Input
42
Output
1 2
Input
5
Output
0 2
Tags: math
Correct Solution:
```
cms=int(input())
al=cms%3
if al==1 or al==0 :
ans=cms//3
else:
ans=cms//3+1
feet=ans//12
print(feet,ans%12)
```
| 104,528 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Lengths are measures in Baden in inches and feet. To a length from centimeters it is enough to know that an inch equals three centimeters in Baden and one foot contains 12 inches.
You are given a length equal to n centimeters. Your task is to convert it to feet and inches so that the number of feet was maximum. The result should be an integer rounded to the closest value containing an integral number of inches.
Note that when you round up, 1 cm rounds up to 0 inches and 2 cm round up to 1 inch.
Input
The only line contains an integer n (1 ≤ n ≤ 10000).
Output
Print two non-negative space-separated integers a and b, where a is the numbers of feet and b is the number of inches.
Examples
Input
42
Output
1 2
Input
5
Output
0 2
Tags: math
Correct Solution:
```
n=(int(input())+1)//3
print(n//12,n%12)
```
| 104,529 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Lengths are measures in Baden in inches and feet. To a length from centimeters it is enough to know that an inch equals three centimeters in Baden and one foot contains 12 inches.
You are given a length equal to n centimeters. Your task is to convert it to feet and inches so that the number of feet was maximum. The result should be an integer rounded to the closest value containing an integral number of inches.
Note that when you round up, 1 cm rounds up to 0 inches and 2 cm round up to 1 inch.
Input
The only line contains an integer n (1 ≤ n ≤ 10000).
Output
Print two non-negative space-separated integers a and b, where a is the numbers of feet and b is the number of inches.
Examples
Input
42
Output
1 2
Input
5
Output
0 2
Tags: math
Correct Solution:
```
n = int(input())
inch = n//3
if n%3 == 2: inch += 1
feet = inch//12
inch = inch%12
print(feet,inch)
```
| 104,530 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Lengths are measures in Baden in inches and feet. To a length from centimeters it is enough to know that an inch equals three centimeters in Baden and one foot contains 12 inches.
You are given a length equal to n centimeters. Your task is to convert it to feet and inches so that the number of feet was maximum. The result should be an integer rounded to the closest value containing an integral number of inches.
Note that when you round up, 1 cm rounds up to 0 inches and 2 cm round up to 1 inch.
Input
The only line contains an integer n (1 ≤ n ≤ 10000).
Output
Print two non-negative space-separated integers a and b, where a is the numbers of feet and b is the number of inches.
Examples
Input
42
Output
1 2
Input
5
Output
0 2
Submitted Solution:
```
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------game starts now----------------------------------------------------
n=int(input())
i=n//3
if n%3==2:
i+=1
print(i//12,i%12)
```
Yes
| 104,531 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Lengths are measures in Baden in inches and feet. To a length from centimeters it is enough to know that an inch equals three centimeters in Baden and one foot contains 12 inches.
You are given a length equal to n centimeters. Your task is to convert it to feet and inches so that the number of feet was maximum. The result should be an integer rounded to the closest value containing an integral number of inches.
Note that when you round up, 1 cm rounds up to 0 inches and 2 cm round up to 1 inch.
Input
The only line contains an integer n (1 ≤ n ≤ 10000).
Output
Print two non-negative space-separated integers a and b, where a is the numbers of feet and b is the number of inches.
Examples
Input
42
Output
1 2
Input
5
Output
0 2
Submitted Solution:
```
from math import ceil, floor
n = int(input())
if n % 3 > 1:
d = ceil(n / 3)
else:
d = n // 3
f = d // 12
print(f, d % 12)
```
Yes
| 104,532 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Lengths are measures in Baden in inches and feet. To a length from centimeters it is enough to know that an inch equals three centimeters in Baden and one foot contains 12 inches.
You are given a length equal to n centimeters. Your task is to convert it to feet and inches so that the number of feet was maximum. The result should be an integer rounded to the closest value containing an integral number of inches.
Note that when you round up, 1 cm rounds up to 0 inches and 2 cm round up to 1 inch.
Input
The only line contains an integer n (1 ≤ n ≤ 10000).
Output
Print two non-negative space-separated integers a and b, where a is the numbers of feet and b is the number of inches.
Examples
Input
42
Output
1 2
Input
5
Output
0 2
Submitted Solution:
```
n=int(input())
a=n//3
b=n%3
if b==2:
a=a+1
p=a//12
q=a%12
print(p,q)
```
Yes
| 104,533 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Lengths are measures in Baden in inches and feet. To a length from centimeters it is enough to know that an inch equals three centimeters in Baden and one foot contains 12 inches.
You are given a length equal to n centimeters. Your task is to convert it to feet and inches so that the number of feet was maximum. The result should be an integer rounded to the closest value containing an integral number of inches.
Note that when you round up, 1 cm rounds up to 0 inches and 2 cm round up to 1 inch.
Input
The only line contains an integer n (1 ≤ n ≤ 10000).
Output
Print two non-negative space-separated integers a and b, where a is the numbers of feet and b is the number of inches.
Examples
Input
42
Output
1 2
Input
5
Output
0 2
Submitted Solution:
```
n = int(input())/3
ft = int(n//12)
inch = round(n%12)
if inch == 12:
inch = 0
ft += 1
print(ft, inch)
```
Yes
| 104,534 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Lengths are measures in Baden in inches and feet. To a length from centimeters it is enough to know that an inch equals three centimeters in Baden and one foot contains 12 inches.
You are given a length equal to n centimeters. Your task is to convert it to feet and inches so that the number of feet was maximum. The result should be an integer rounded to the closest value containing an integral number of inches.
Note that when you round up, 1 cm rounds up to 0 inches and 2 cm round up to 1 inch.
Input
The only line contains an integer n (1 ≤ n ≤ 10000).
Output
Print two non-negative space-separated integers a and b, where a is the numbers of feet and b is the number of inches.
Examples
Input
42
Output
1 2
Input
5
Output
0 2
Submitted Solution:
```
cm = int(input())
cm += 1
dm = divmod(cm, 36)
print(dm[0], end=' ')
cm = dm[1]
print(round(cm / 3))
```
No
| 104,535 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Lengths are measures in Baden in inches and feet. To a length from centimeters it is enough to know that an inch equals three centimeters in Baden and one foot contains 12 inches.
You are given a length equal to n centimeters. Your task is to convert it to feet and inches so that the number of feet was maximum. The result should be an integer rounded to the closest value containing an integral number of inches.
Note that when you round up, 1 cm rounds up to 0 inches and 2 cm round up to 1 inch.
Input
The only line contains an integer n (1 ≤ n ≤ 10000).
Output
Print two non-negative space-separated integers a and b, where a is the numbers of feet and b is the number of inches.
Examples
Input
42
Output
1 2
Input
5
Output
0 2
Submitted Solution:
```
from math import ceil, floor
n = int(input())
d = ceil(n / 3)
f = d // 12
print(f, d % 12)
```
No
| 104,536 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Lengths are measures in Baden in inches and feet. To a length from centimeters it is enough to know that an inch equals three centimeters in Baden and one foot contains 12 inches.
You are given a length equal to n centimeters. Your task is to convert it to feet and inches so that the number of feet was maximum. The result should be an integer rounded to the closest value containing an integral number of inches.
Note that when you round up, 1 cm rounds up to 0 inches and 2 cm round up to 1 inch.
Input
The only line contains an integer n (1 ≤ n ≤ 10000).
Output
Print two non-negative space-separated integers a and b, where a is the numbers of feet and b is the number of inches.
Examples
Input
42
Output
1 2
Input
5
Output
0 2
Submitted Solution:
```
import random
import heapq
import math
from collections import Counter
import sys
from fractions import gcd
sys.setrecursionlimit(300000)
from random import randrange
#########################################################################
# O(|m| log(max(m) + max(a)))
def chinese_remainder(m, a):
'''
m - modulos, a - coefficients (arrays)
* m have to be mutually COPRIME *
'''
res, prod = 0, 1
for m_i in m:
prod *= m_i
for m_i, a_i in zip(m, a):
p = prod // m_i
res += a_i * modinv(p, m_i) * p
return res % prod
# O(log(a+b))
def egcd(a, b):
''' Extended Euclidian algorithm. '''
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def modinv(a, m):
''' Finds modular inverse of a modulo m. '''
while a < 0:
a += m
g, x, y = egcd(a, m)
if g != 1:
raise Exception('Modular inverse does not exist')
else:
return x % m
#########################################################################
#########################################################################
def pi(n):
''' Returns two arrays pi1, pi2:
pi1[i] = pi(i) for i <= sqrt(n)
pi2[i] = pi(n // i) for i <= sqrt(n)
'''
lim = int(n**0.5)
while lim*lim <= n: lim += 1
lim -= 1
pi1, pi2 = [0]*(lim + 1), [0]*(lim + 1)
for i in range(1, lim + 1):
pi1[i] = i - 1
pi2[i] = n//i - 1
for i in range(2, lim + 1):
if pi1[i] == pi1[i - 1]:
continue
p = pi1[i - 1]
for j in range(1, min(n // (i * i), lim) + 1):
st = i * j
if st <= lim:
pi2[j] -= pi2[st] - p
else:
pi2[j] -= pi1[n // st] - p
for j in range(lim, min(lim, i * i - 1), -1):
pi1[j] -= pi1[j // i] - p
return pi1, pi2
#########################################################################
#########################################################################
def num_of_divisors(n):
nd = [0] * (n+1)
for i in range(1, n+1):
for j in range(i, n+1, i):
nd[j] += 1
return nd
def sum_of_divisors(n):
sd = [0] * (n+1)
for i in range(1, n+1):
for j in range(i, n+1, i):
sd[j] += i
return sd
#########################################################################
def fast_prime_sieve(n):
"""
Input n>=6, Returns a list of primes, 2 <= p <= n
Taken from: https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n/
"""
n += 1
n, correction = n-n%6+6, 2-(n%6>1)
sieve = [True] * (n//3)
for i in range(1,int(n**0.5)//3+1):
if sieve[i]:
k=3*i+1|1
sieve[ k*k//3 ::2*k] = [False] * ((n//6-k*k//6-1)//k+1)
sieve[k*(k-2*(i&1)+4)//3::2*k] = [False] * ((n//6-k*(k-2*(i&1)+4)//6-1)//k+1)
return [2,3] + [3*i+1|1 for i in range(1,n//3-correction) if sieve[i]]
#########################################################################
def egcd(a, b):
''' Extended Euclidian algorithm. '''
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
# x * a + y * b = g
return (g, x - (b // a) * y, y)
_gcd = lambda a, b: a+b if a==0 or b==0 else gcd(b, a % b)
def gcd(a, b):
if a==0 or b == 0:
return a+b
return gcd(b, a % b)
#########################################################################
''' Modular square root '''
#########################################################################
def legendre_symbol(a, p):
ls = pow(a, (p - 1) // 2, p)
return -1 if ls == p - 1 else ls
def modular_sqrt(a, p):
if legendre_symbol(a, p) != 1:
return 0
elif a == 0:
return 0
elif p == 2:
return 0
elif p % 4 == 3:
return pow(a, (p + 1) // 4, p)
s = p - 1
e = 0
while s % 2 == 0:
s //= 2
e += 1
n = 2
while legendre_symbol(n, p) != -1:
n += 1
x = pow(a, (s + 1) // 2, p)
b = pow(a, s, p)
g = pow(n, s, p)
r = e
while True:
t = b
m = 0
for m in range(r):
if t == 1:
break
t = pow(t, 2, p)
if m == 0:
return x
gs = pow(g, 2 ** (r - m - 1), p)
g = (gs * gs) % p
x = (x * gs) % p
b = (b * g) % p
r = m
#########################################################################
''' Euler"s totient function for a single number '''
#########################################################################
from functools import lru_cache
def factorize(n):
factorization = set()
while n > 1:
for i in range(2, n + 1):
if n % i == 0:
n //= i
factorization.add(i)
break
return factorization
@lru_cache(maxsize=None)
def phi(n):
totient = n
for p in factorize(n):
totient -= totient//p
return totient
#########################################################################
#########################################################################
def max_subarray(a):
max_so_far = max_ending_here = 0
for el in a:
# in case a speed-up is required, change the below max/min to if-else statements.
max_ending_here = max(0, max_ending_here + el)
max_so_far = max(max_so_far, max_ending_here)
return max_so_far
#########################################################################
#########################################################################
def maximum_xor(nums):
answer = 0
for i in range(31, -1, -1):
answer <<= 1
prefixes = {num >> i for num in nums}
answer += any(answer^1^p in prefixes for p in prefixes)
return answer
#########################################################################
'''
Finds longest increasing subsequence in O(n log n) time.
'''
#########################################################################
def lis(a):
p, m, l = [0]*len(a), [0]*(len(a) + 1), 0
for i in range(len(a)):
lo, hi = 1, l
while lo <= hi:
mid = (lo + hi)//2
if a[m[mid]] < a[i]:
lo = mid+1
else:
hi = mid-1
p[i], m[lo] = m[lo-1], i
if lo > l:
l = lo
s, k = [], m[l]
for i in range(l-1, -1, -1):
s.append(a[k])
k = p[k]
return s[::-1]
#########################################################################
#########################################################################
#########################################################################
def find_kth(arr, k, start=0, end=None):
if not end:
end = len(arr) -1
pivot_ridx = randrange(start, end)
pivot = arr[pivot_ridx]
pivot_idx = _partition(arr, start, end, pivot_ridx)
if pivot_idx + 1 == k:
return pivot
elif pivot_idx + 1 > k:
return find_kth(arr, k, start, pivot_idx)
else:
return find_kth(arr, k, pivot_idx, end)
def _partition(arr, start, end, pivot_idx):
pivot = arr[pivot_idx]
arr[end], arr[pivot_idx] = arr[pivot_idx], arr[end]
inc_idx = start
for i in range(start, end):
if arr[i] <= pivot:
arr[inc_idx], arr[i] = arr[i], arr[inc_idx]
inc_idx += 1
arr[end], arr[inc_idx] = arr[inc_idx], arr[end]
return inc_idx
#########################################################################
#########################################################################
def count_sort(a):
mn, mx = float('inf'), -float('inf')
for x in a:
if x < mn: mn = x
if x > mx: mx = x
counter = [0 for _ in range(mx - mn + 1)]
for x in a:
counter[x - mn] += 1
j = 0
for i in range(mx - mn + 1):
a[j:j+counter[i]] = [i + mn]*counter[i]
j += counter[i]
#########################################################################
#########################################################################
def lcs(a, b):
''' Finds longest common subsequence of arrays a, b. '''
lengths = [[0 for j in range(len(b) + 1)] for i in range(len(a) + 1)]
for i, x in enumerate(a):
for j, y in enumerate(b):
if x == y:
lengths[i+1][j+1] = lengths[i][j] + 1
else:
lengths[i+1][j+1] = max(lengths[i+1][j], lengths[i][j+1])
result = []
x, y = len(a), len(b)
while x != 0 and y != 0:
if lengths[x][y] == lengths[x-1][y]:
x -= 1
elif lengths[x][y] == lengths[x][y-1]:
y -= 1
else:
result.append(a[x-1])
x, y = x - 1, y - 1
return result[::-1]
#########################################################################
#########################################################################
def is_anagram(str1, str2):
return Counter(str1) == Counter(str2)
#########################################################################
#########################################################################
def power(x, y, p):
res = 1;
x = x % p;
while (y > 0):
if (y & 1):
res = (res * x) % p;
y = y>>1;
x = (x * x) % p;
return res;
#########################################################################
def miillerTest(d, n):
a = 2 + random.randint(1, n - 4);
x = power(a, d, n);
if (x == 1 or x == n - 1):
return True;
while (d != n - 1):
x = (x * x) % n;
d *= 2;
if (x == 1):
return False;
if (x == n - 1):
return True;
return False;
def isPrime( n, k):
if (n <= 1 or n == 4):
return False;
if (n <= 3):
return True;
d = n - 1;
while (d % 2 == 0):
d //= 2;
for i in range(k):
if (miillerTest(d, n) == False):
return False;
return True;
#########################################################################
#########################################################################
def gcd_list(li):
return reduce(gcd,li)
'''
Finds longest increasing subsequence in O(n log n) time.
'''
#########################################################################
def lis(a):
p, m, l = [0]*len(a), [0]*(len(a) + 1), 0
for i in range(len(a)):
lo, hi = 1, l
while lo <= hi:
mid = (lo + hi)//2
if a[m[mid]] < a[i]:
lo = mid+1
else:
hi = mid-1
p[i], m[lo] = m[lo-1], i
if lo > l:
l = lo
s, k = [], m[l]
for i in range(l-1, -1, -1):
s.append(a[k])
k = p[k]
return s[::-1]
#########################################################################
# for _ in range(int(input())):
# input=open("input.txt","r").readline
n=int(input())
e=n//36
f=n%36-1
print(e,int(math.ceil((f/3))))
```
No
| 104,537 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Lengths are measures in Baden in inches and feet. To a length from centimeters it is enough to know that an inch equals three centimeters in Baden and one foot contains 12 inches.
You are given a length equal to n centimeters. Your task is to convert it to feet and inches so that the number of feet was maximum. The result should be an integer rounded to the closest value containing an integral number of inches.
Note that when you round up, 1 cm rounds up to 0 inches and 2 cm round up to 1 inch.
Input
The only line contains an integer n (1 ≤ n ≤ 10000).
Output
Print two non-negative space-separated integers a and b, where a is the numbers of feet and b is the number of inches.
Examples
Input
42
Output
1 2
Input
5
Output
0 2
Submitted Solution:
```
s = int(input())
f = 0
i = 0
while s >= 36:
s -= 36
f += 1
while s >= 3:
s -= 3
i += 1
if s == 2:
i += 1
print(f, end= ' ')
print(i)
```
No
| 104,538 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We start with a string s consisting only of the digits 1, 2, or 3. The length of s is denoted by |s|. For each i from 1 to |s|, the i-th character of s is denoted by s_i.
There is one cursor. The cursor's location ℓ is denoted by an integer in \{0, …, |s|\}, with the following meaning:
* If ℓ = 0, then the cursor is located before the first character of s.
* If ℓ = |s|, then the cursor is located right after the last character of s.
* If 0 < ℓ < |s|, then the cursor is located between s_ℓ and s_{ℓ+1}.
We denote by s_left the string to the left of the cursor and s_right the string to the right of the cursor.
We also have a string c, which we call our clipboard, which starts out as empty. There are three types of actions:
* The Move action. Move the cursor one step to the right. This increments ℓ once.
* The Cut action. Set c ← s_right, then set s ← s_left.
* The Paste action. Append the value of c to the end of the string s. Note that this doesn't modify c.
The cursor initially starts at ℓ = 0. Then, we perform the following procedure:
1. Perform the Move action once.
2. Perform the Cut action once.
3. Perform the Paste action s_ℓ times.
4. If ℓ = x, stop. Otherwise, return to step 1.
You're given the initial string s and the integer x. What is the length of s when the procedure stops? Since this value may be very large, only find it modulo 10^9 + 7.
It is guaranteed that ℓ ≤ |s| at any time.
Input
The first line of input contains a single integer t (1 ≤ t ≤ 1000) denoting the number of test cases. The next lines contain descriptions of the test cases.
The first line of each test case contains a single integer x (1 ≤ x ≤ 10^6). The second line of each test case consists of the initial string s (1 ≤ |s| ≤ 500). It is guaranteed, that s consists of the characters "1", "2", "3".
It is guaranteed that the sum of x in a single file is at most 10^6. It is guaranteed that in each test case before the procedure will stop it will be true that ℓ ≤ |s| at any time.
Output
For each test case, output a single line containing a single integer denoting the answer for that test case modulo 10^9 + 7.
Example
Input
4
5
231
7
2323
6
333
24
133321333
Output
25
1438
1101
686531475
Note
Let's illustrate what happens with the first test case. Initially, we have s = 231. Initially, ℓ = 0 and c = \varepsilon (the empty string). The following things happen if we follow the procedure above:
* Step 1, Move once: we get ℓ = 1.
* Step 2, Cut once: we get s = 2 and c = 31.
* Step 3, Paste s_ℓ = 2 times: we get s = 23131.
* Step 4: ℓ = 1 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 2.
* Step 2, Cut once: we get s = 23 and c = 131.
* Step 3, Paste s_ℓ = 3 times: we get s = 23131131131.
* Step 4: ℓ = 2 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 3.
* Step 2, Cut once: we get s = 231 and c = 31131131.
* Step 3, Paste s_ℓ = 1 time: we get s = 23131131131.
* Step 4: ℓ = 3 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 4.
* Step 2, Cut once: we get s = 2313 and c = 1131131.
* Step 3, Paste s_ℓ = 3 times: we get s = 2313113113111311311131131.
* Step 4: ℓ = 4 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 5.
* Step 2, Cut once: we get s = 23131 and c = 13113111311311131131.
* Step 3, Paste s_ℓ = 1 times: we get s = 2313113113111311311131131.
* Step 4: ℓ = 5 = x, so we stop.
At the end of the procedure, s has length 25.
Tags: implementation, math
Correct Solution:
```
"""
NTC here
"""
from sys import stdin
# import threading
# setrecursionlimit(10**6)
# threading.stack_size(2**26)
def iin(): return int(stdin.readline())
def lin(): return list(map(int, stdin.readline().split()))
# range = xrange
# input = raw_input
md=10**9+7
def main():
t=iin()
while t:
t-=1
x=iin()
s=list(input())
l=len(s)
ans=l
i=0
while i<x:
i+=1
ch=int(s[i-1])
ans=(i+ch*(ans-i))%md
if l>=x:continue
incr=l
ss=[]
for _ in range(ch):
for j in range(i,l):
if incr<ans and incr<x:
ss.append(s[j])
incr+=1
else:
break
l=incr
for k in ss:s.append(k)
#print(ans, l, s)
print(ans%md)
main()
#threading.Thread(target=main).start()
```
| 104,539 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We start with a string s consisting only of the digits 1, 2, or 3. The length of s is denoted by |s|. For each i from 1 to |s|, the i-th character of s is denoted by s_i.
There is one cursor. The cursor's location ℓ is denoted by an integer in \{0, …, |s|\}, with the following meaning:
* If ℓ = 0, then the cursor is located before the first character of s.
* If ℓ = |s|, then the cursor is located right after the last character of s.
* If 0 < ℓ < |s|, then the cursor is located between s_ℓ and s_{ℓ+1}.
We denote by s_left the string to the left of the cursor and s_right the string to the right of the cursor.
We also have a string c, which we call our clipboard, which starts out as empty. There are three types of actions:
* The Move action. Move the cursor one step to the right. This increments ℓ once.
* The Cut action. Set c ← s_right, then set s ← s_left.
* The Paste action. Append the value of c to the end of the string s. Note that this doesn't modify c.
The cursor initially starts at ℓ = 0. Then, we perform the following procedure:
1. Perform the Move action once.
2. Perform the Cut action once.
3. Perform the Paste action s_ℓ times.
4. If ℓ = x, stop. Otherwise, return to step 1.
You're given the initial string s and the integer x. What is the length of s when the procedure stops? Since this value may be very large, only find it modulo 10^9 + 7.
It is guaranteed that ℓ ≤ |s| at any time.
Input
The first line of input contains a single integer t (1 ≤ t ≤ 1000) denoting the number of test cases. The next lines contain descriptions of the test cases.
The first line of each test case contains a single integer x (1 ≤ x ≤ 10^6). The second line of each test case consists of the initial string s (1 ≤ |s| ≤ 500). It is guaranteed, that s consists of the characters "1", "2", "3".
It is guaranteed that the sum of x in a single file is at most 10^6. It is guaranteed that in each test case before the procedure will stop it will be true that ℓ ≤ |s| at any time.
Output
For each test case, output a single line containing a single integer denoting the answer for that test case modulo 10^9 + 7.
Example
Input
4
5
231
7
2323
6
333
24
133321333
Output
25
1438
1101
686531475
Note
Let's illustrate what happens with the first test case. Initially, we have s = 231. Initially, ℓ = 0 and c = \varepsilon (the empty string). The following things happen if we follow the procedure above:
* Step 1, Move once: we get ℓ = 1.
* Step 2, Cut once: we get s = 2 and c = 31.
* Step 3, Paste s_ℓ = 2 times: we get s = 23131.
* Step 4: ℓ = 1 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 2.
* Step 2, Cut once: we get s = 23 and c = 131.
* Step 3, Paste s_ℓ = 3 times: we get s = 23131131131.
* Step 4: ℓ = 2 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 3.
* Step 2, Cut once: we get s = 231 and c = 31131131.
* Step 3, Paste s_ℓ = 1 time: we get s = 23131131131.
* Step 4: ℓ = 3 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 4.
* Step 2, Cut once: we get s = 2313 and c = 1131131.
* Step 3, Paste s_ℓ = 3 times: we get s = 2313113113111311311131131.
* Step 4: ℓ = 4 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 5.
* Step 2, Cut once: we get s = 23131 and c = 13113111311311131131.
* Step 3, Paste s_ℓ = 1 times: we get s = 2313113113111311311131131.
* Step 4: ℓ = 5 = x, so we stop.
At the end of the procedure, s has length 25.
Tags: implementation, math
Correct Solution:
```
M = int(1e9+7)
n = int(input())
while n>0:
n -= 1
x = int(input())
s = input()
idx = 0
length = len(s)
while length < x:
t = ord(s[idx])-ord('1')
s += s[idx+1:]*t
length += (length-idx-1)*t
idx += 1
while idx != x:
t = ord(s[idx])-ord('1')
length += ((length-idx-1)*t)%M
idx += 1
print(length%M)
```
| 104,540 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We start with a string s consisting only of the digits 1, 2, or 3. The length of s is denoted by |s|. For each i from 1 to |s|, the i-th character of s is denoted by s_i.
There is one cursor. The cursor's location ℓ is denoted by an integer in \{0, …, |s|\}, with the following meaning:
* If ℓ = 0, then the cursor is located before the first character of s.
* If ℓ = |s|, then the cursor is located right after the last character of s.
* If 0 < ℓ < |s|, then the cursor is located between s_ℓ and s_{ℓ+1}.
We denote by s_left the string to the left of the cursor and s_right the string to the right of the cursor.
We also have a string c, which we call our clipboard, which starts out as empty. There are three types of actions:
* The Move action. Move the cursor one step to the right. This increments ℓ once.
* The Cut action. Set c ← s_right, then set s ← s_left.
* The Paste action. Append the value of c to the end of the string s. Note that this doesn't modify c.
The cursor initially starts at ℓ = 0. Then, we perform the following procedure:
1. Perform the Move action once.
2. Perform the Cut action once.
3. Perform the Paste action s_ℓ times.
4. If ℓ = x, stop. Otherwise, return to step 1.
You're given the initial string s and the integer x. What is the length of s when the procedure stops? Since this value may be very large, only find it modulo 10^9 + 7.
It is guaranteed that ℓ ≤ |s| at any time.
Input
The first line of input contains a single integer t (1 ≤ t ≤ 1000) denoting the number of test cases. The next lines contain descriptions of the test cases.
The first line of each test case contains a single integer x (1 ≤ x ≤ 10^6). The second line of each test case consists of the initial string s (1 ≤ |s| ≤ 500). It is guaranteed, that s consists of the characters "1", "2", "3".
It is guaranteed that the sum of x in a single file is at most 10^6. It is guaranteed that in each test case before the procedure will stop it will be true that ℓ ≤ |s| at any time.
Output
For each test case, output a single line containing a single integer denoting the answer for that test case modulo 10^9 + 7.
Example
Input
4
5
231
7
2323
6
333
24
133321333
Output
25
1438
1101
686531475
Note
Let's illustrate what happens with the first test case. Initially, we have s = 231. Initially, ℓ = 0 and c = \varepsilon (the empty string). The following things happen if we follow the procedure above:
* Step 1, Move once: we get ℓ = 1.
* Step 2, Cut once: we get s = 2 and c = 31.
* Step 3, Paste s_ℓ = 2 times: we get s = 23131.
* Step 4: ℓ = 1 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 2.
* Step 2, Cut once: we get s = 23 and c = 131.
* Step 3, Paste s_ℓ = 3 times: we get s = 23131131131.
* Step 4: ℓ = 2 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 3.
* Step 2, Cut once: we get s = 231 and c = 31131131.
* Step 3, Paste s_ℓ = 1 time: we get s = 23131131131.
* Step 4: ℓ = 3 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 4.
* Step 2, Cut once: we get s = 2313 and c = 1131131.
* Step 3, Paste s_ℓ = 3 times: we get s = 2313113113111311311131131.
* Step 4: ℓ = 4 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 5.
* Step 2, Cut once: we get s = 23131 and c = 13113111311311131131.
* Step 3, Paste s_ℓ = 1 times: we get s = 2313113113111311311131131.
* Step 4: ℓ = 5 = x, so we stop.
At the end of the procedure, s has length 25.
Tags: implementation, math
Correct Solution:
```
for _ in range(int(input())):
x = int(input())
s = list(input())
l = 0
ans = len(s)
while(l<x):
if(ans>=x):
break
temp = len(s)
ans+=(int(s[l])-1)*(temp-l-1)
for i in range(int(s[l])-1):
if(len(s)>x):
break
for j in range(l+1,temp):
s.append(s[j])
if(len(s)>x):
break
l+=1
while(l<x):
temp = ans
ans+=(int(s[l])-1)*(temp-l-1)
ans = ans%(10**9+7)
l+=1
print(ans)
```
| 104,541 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We start with a string s consisting only of the digits 1, 2, or 3. The length of s is denoted by |s|. For each i from 1 to |s|, the i-th character of s is denoted by s_i.
There is one cursor. The cursor's location ℓ is denoted by an integer in \{0, …, |s|\}, with the following meaning:
* If ℓ = 0, then the cursor is located before the first character of s.
* If ℓ = |s|, then the cursor is located right after the last character of s.
* If 0 < ℓ < |s|, then the cursor is located between s_ℓ and s_{ℓ+1}.
We denote by s_left the string to the left of the cursor and s_right the string to the right of the cursor.
We also have a string c, which we call our clipboard, which starts out as empty. There are three types of actions:
* The Move action. Move the cursor one step to the right. This increments ℓ once.
* The Cut action. Set c ← s_right, then set s ← s_left.
* The Paste action. Append the value of c to the end of the string s. Note that this doesn't modify c.
The cursor initially starts at ℓ = 0. Then, we perform the following procedure:
1. Perform the Move action once.
2. Perform the Cut action once.
3. Perform the Paste action s_ℓ times.
4. If ℓ = x, stop. Otherwise, return to step 1.
You're given the initial string s and the integer x. What is the length of s when the procedure stops? Since this value may be very large, only find it modulo 10^9 + 7.
It is guaranteed that ℓ ≤ |s| at any time.
Input
The first line of input contains a single integer t (1 ≤ t ≤ 1000) denoting the number of test cases. The next lines contain descriptions of the test cases.
The first line of each test case contains a single integer x (1 ≤ x ≤ 10^6). The second line of each test case consists of the initial string s (1 ≤ |s| ≤ 500). It is guaranteed, that s consists of the characters "1", "2", "3".
It is guaranteed that the sum of x in a single file is at most 10^6. It is guaranteed that in each test case before the procedure will stop it will be true that ℓ ≤ |s| at any time.
Output
For each test case, output a single line containing a single integer denoting the answer for that test case modulo 10^9 + 7.
Example
Input
4
5
231
7
2323
6
333
24
133321333
Output
25
1438
1101
686531475
Note
Let's illustrate what happens with the first test case. Initially, we have s = 231. Initially, ℓ = 0 and c = \varepsilon (the empty string). The following things happen if we follow the procedure above:
* Step 1, Move once: we get ℓ = 1.
* Step 2, Cut once: we get s = 2 and c = 31.
* Step 3, Paste s_ℓ = 2 times: we get s = 23131.
* Step 4: ℓ = 1 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 2.
* Step 2, Cut once: we get s = 23 and c = 131.
* Step 3, Paste s_ℓ = 3 times: we get s = 23131131131.
* Step 4: ℓ = 2 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 3.
* Step 2, Cut once: we get s = 231 and c = 31131131.
* Step 3, Paste s_ℓ = 1 time: we get s = 23131131131.
* Step 4: ℓ = 3 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 4.
* Step 2, Cut once: we get s = 2313 and c = 1131131.
* Step 3, Paste s_ℓ = 3 times: we get s = 2313113113111311311131131.
* Step 4: ℓ = 4 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 5.
* Step 2, Cut once: we get s = 23131 and c = 13113111311311131131.
* Step 3, Paste s_ℓ = 1 times: we get s = 2313113113111311311131131.
* Step 4: ℓ = 5 = x, so we stop.
At the end of the procedure, s has length 25.
Tags: implementation, math
Correct Solution:
```
M = 1000000007
t = int(input())
while t:
t += -1
x = int(input())
s = input()
i = 0
while len(s) < x:
s += s[i + 1: ] * (int(s[i]) - 1)
i += 1
n = len(s)
for j in range(i, x):
tmp = n - (j + 1)
n = j + 1 + tmp * (int(s[j]))
n = n % M
print(n % M)
```
| 104,542 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We start with a string s consisting only of the digits 1, 2, or 3. The length of s is denoted by |s|. For each i from 1 to |s|, the i-th character of s is denoted by s_i.
There is one cursor. The cursor's location ℓ is denoted by an integer in \{0, …, |s|\}, with the following meaning:
* If ℓ = 0, then the cursor is located before the first character of s.
* If ℓ = |s|, then the cursor is located right after the last character of s.
* If 0 < ℓ < |s|, then the cursor is located between s_ℓ and s_{ℓ+1}.
We denote by s_left the string to the left of the cursor and s_right the string to the right of the cursor.
We also have a string c, which we call our clipboard, which starts out as empty. There are three types of actions:
* The Move action. Move the cursor one step to the right. This increments ℓ once.
* The Cut action. Set c ← s_right, then set s ← s_left.
* The Paste action. Append the value of c to the end of the string s. Note that this doesn't modify c.
The cursor initially starts at ℓ = 0. Then, we perform the following procedure:
1. Perform the Move action once.
2. Perform the Cut action once.
3. Perform the Paste action s_ℓ times.
4. If ℓ = x, stop. Otherwise, return to step 1.
You're given the initial string s and the integer x. What is the length of s when the procedure stops? Since this value may be very large, only find it modulo 10^9 + 7.
It is guaranteed that ℓ ≤ |s| at any time.
Input
The first line of input contains a single integer t (1 ≤ t ≤ 1000) denoting the number of test cases. The next lines contain descriptions of the test cases.
The first line of each test case contains a single integer x (1 ≤ x ≤ 10^6). The second line of each test case consists of the initial string s (1 ≤ |s| ≤ 500). It is guaranteed, that s consists of the characters "1", "2", "3".
It is guaranteed that the sum of x in a single file is at most 10^6. It is guaranteed that in each test case before the procedure will stop it will be true that ℓ ≤ |s| at any time.
Output
For each test case, output a single line containing a single integer denoting the answer for that test case modulo 10^9 + 7.
Example
Input
4
5
231
7
2323
6
333
24
133321333
Output
25
1438
1101
686531475
Note
Let's illustrate what happens with the first test case. Initially, we have s = 231. Initially, ℓ = 0 and c = \varepsilon (the empty string). The following things happen if we follow the procedure above:
* Step 1, Move once: we get ℓ = 1.
* Step 2, Cut once: we get s = 2 and c = 31.
* Step 3, Paste s_ℓ = 2 times: we get s = 23131.
* Step 4: ℓ = 1 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 2.
* Step 2, Cut once: we get s = 23 and c = 131.
* Step 3, Paste s_ℓ = 3 times: we get s = 23131131131.
* Step 4: ℓ = 2 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 3.
* Step 2, Cut once: we get s = 231 and c = 31131131.
* Step 3, Paste s_ℓ = 1 time: we get s = 23131131131.
* Step 4: ℓ = 3 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 4.
* Step 2, Cut once: we get s = 2313 and c = 1131131.
* Step 3, Paste s_ℓ = 3 times: we get s = 2313113113111311311131131.
* Step 4: ℓ = 4 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 5.
* Step 2, Cut once: we get s = 23131 and c = 13113111311311131131.
* Step 3, Paste s_ℓ = 1 times: we get s = 2313113113111311311131131.
* Step 4: ℓ = 5 = x, so we stop.
At the end of the procedure, s has length 25.
Tags: implementation, math
Correct Solution:
```
def main():
TT = int(input())
for _ in range(TT):
x = int(input())
s = [int(c) for c in input().strip()]
ans = len(s)
for l in range(0, x):
ans += (ans - l - 1) * (s[l] - 1)
ans %= 1000000007
end = len(s)
for _ in range(1, s[l]):
if len(s) > x + 1:
break
for c in range(l + 1, end):
if len(s) > x + 1:
break
s.append(s[c])
print(ans)
if __name__ == '__main__':
main()
```
| 104,543 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We start with a string s consisting only of the digits 1, 2, or 3. The length of s is denoted by |s|. For each i from 1 to |s|, the i-th character of s is denoted by s_i.
There is one cursor. The cursor's location ℓ is denoted by an integer in \{0, …, |s|\}, with the following meaning:
* If ℓ = 0, then the cursor is located before the first character of s.
* If ℓ = |s|, then the cursor is located right after the last character of s.
* If 0 < ℓ < |s|, then the cursor is located between s_ℓ and s_{ℓ+1}.
We denote by s_left the string to the left of the cursor and s_right the string to the right of the cursor.
We also have a string c, which we call our clipboard, which starts out as empty. There are three types of actions:
* The Move action. Move the cursor one step to the right. This increments ℓ once.
* The Cut action. Set c ← s_right, then set s ← s_left.
* The Paste action. Append the value of c to the end of the string s. Note that this doesn't modify c.
The cursor initially starts at ℓ = 0. Then, we perform the following procedure:
1. Perform the Move action once.
2. Perform the Cut action once.
3. Perform the Paste action s_ℓ times.
4. If ℓ = x, stop. Otherwise, return to step 1.
You're given the initial string s and the integer x. What is the length of s when the procedure stops? Since this value may be very large, only find it modulo 10^9 + 7.
It is guaranteed that ℓ ≤ |s| at any time.
Input
The first line of input contains a single integer t (1 ≤ t ≤ 1000) denoting the number of test cases. The next lines contain descriptions of the test cases.
The first line of each test case contains a single integer x (1 ≤ x ≤ 10^6). The second line of each test case consists of the initial string s (1 ≤ |s| ≤ 500). It is guaranteed, that s consists of the characters "1", "2", "3".
It is guaranteed that the sum of x in a single file is at most 10^6. It is guaranteed that in each test case before the procedure will stop it will be true that ℓ ≤ |s| at any time.
Output
For each test case, output a single line containing a single integer denoting the answer for that test case modulo 10^9 + 7.
Example
Input
4
5
231
7
2323
6
333
24
133321333
Output
25
1438
1101
686531475
Note
Let's illustrate what happens with the first test case. Initially, we have s = 231. Initially, ℓ = 0 and c = \varepsilon (the empty string). The following things happen if we follow the procedure above:
* Step 1, Move once: we get ℓ = 1.
* Step 2, Cut once: we get s = 2 and c = 31.
* Step 3, Paste s_ℓ = 2 times: we get s = 23131.
* Step 4: ℓ = 1 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 2.
* Step 2, Cut once: we get s = 23 and c = 131.
* Step 3, Paste s_ℓ = 3 times: we get s = 23131131131.
* Step 4: ℓ = 2 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 3.
* Step 2, Cut once: we get s = 231 and c = 31131131.
* Step 3, Paste s_ℓ = 1 time: we get s = 23131131131.
* Step 4: ℓ = 3 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 4.
* Step 2, Cut once: we get s = 2313 and c = 1131131.
* Step 3, Paste s_ℓ = 3 times: we get s = 2313113113111311311131131.
* Step 4: ℓ = 4 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 5.
* Step 2, Cut once: we get s = 23131 and c = 13113111311311131131.
* Step 3, Paste s_ℓ = 1 times: we get s = 2313113113111311311131131.
* Step 4: ℓ = 5 = x, so we stop.
At the end of the procedure, s has length 25.
Tags: implementation, math
Correct Solution:
```
ttt = int(input())
mod = 10**9 + 7
s = "#"*(10**6 + 1500)
s=list(s)
for bo in range(ttt):
x=int(input())
st=input()
s[1:len(st)+1]=list(st)
siz=len(st)
p = 0
while siz < x:
p += 1
whe = siz
for de4d in range(int(s[p])-1):
for k in range(p+1,whe+1):
siz += 1
s[siz] = s[k]
if (siz>x):
break
if (siz>x):
break
if (siz>x):
break
ans = len(st)
for i in range(1,x+1):
ans = i + (ans-i)*int(s[i])
ans = ans%mod
print(ans)
```
| 104,544 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We start with a string s consisting only of the digits 1, 2, or 3. The length of s is denoted by |s|. For each i from 1 to |s|, the i-th character of s is denoted by s_i.
There is one cursor. The cursor's location ℓ is denoted by an integer in \{0, …, |s|\}, with the following meaning:
* If ℓ = 0, then the cursor is located before the first character of s.
* If ℓ = |s|, then the cursor is located right after the last character of s.
* If 0 < ℓ < |s|, then the cursor is located between s_ℓ and s_{ℓ+1}.
We denote by s_left the string to the left of the cursor and s_right the string to the right of the cursor.
We also have a string c, which we call our clipboard, which starts out as empty. There are three types of actions:
* The Move action. Move the cursor one step to the right. This increments ℓ once.
* The Cut action. Set c ← s_right, then set s ← s_left.
* The Paste action. Append the value of c to the end of the string s. Note that this doesn't modify c.
The cursor initially starts at ℓ = 0. Then, we perform the following procedure:
1. Perform the Move action once.
2. Perform the Cut action once.
3. Perform the Paste action s_ℓ times.
4. If ℓ = x, stop. Otherwise, return to step 1.
You're given the initial string s and the integer x. What is the length of s when the procedure stops? Since this value may be very large, only find it modulo 10^9 + 7.
It is guaranteed that ℓ ≤ |s| at any time.
Input
The first line of input contains a single integer t (1 ≤ t ≤ 1000) denoting the number of test cases. The next lines contain descriptions of the test cases.
The first line of each test case contains a single integer x (1 ≤ x ≤ 10^6). The second line of each test case consists of the initial string s (1 ≤ |s| ≤ 500). It is guaranteed, that s consists of the characters "1", "2", "3".
It is guaranteed that the sum of x in a single file is at most 10^6. It is guaranteed that in each test case before the procedure will stop it will be true that ℓ ≤ |s| at any time.
Output
For each test case, output a single line containing a single integer denoting the answer for that test case modulo 10^9 + 7.
Example
Input
4
5
231
7
2323
6
333
24
133321333
Output
25
1438
1101
686531475
Note
Let's illustrate what happens with the first test case. Initially, we have s = 231. Initially, ℓ = 0 and c = \varepsilon (the empty string). The following things happen if we follow the procedure above:
* Step 1, Move once: we get ℓ = 1.
* Step 2, Cut once: we get s = 2 and c = 31.
* Step 3, Paste s_ℓ = 2 times: we get s = 23131.
* Step 4: ℓ = 1 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 2.
* Step 2, Cut once: we get s = 23 and c = 131.
* Step 3, Paste s_ℓ = 3 times: we get s = 23131131131.
* Step 4: ℓ = 2 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 3.
* Step 2, Cut once: we get s = 231 and c = 31131131.
* Step 3, Paste s_ℓ = 1 time: we get s = 23131131131.
* Step 4: ℓ = 3 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 4.
* Step 2, Cut once: we get s = 2313 and c = 1131131.
* Step 3, Paste s_ℓ = 3 times: we get s = 2313113113111311311131131.
* Step 4: ℓ = 4 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 5.
* Step 2, Cut once: we get s = 23131 and c = 13113111311311131131.
* Step 3, Paste s_ℓ = 1 times: we get s = 2313113113111311311131131.
* Step 4: ℓ = 5 = x, so we stop.
At the end of the procedure, s has length 25.
Tags: implementation, math
Correct Solution:
```
t = int(input())
ans = []
arr = [None] * (10 ** 6)
cur = 0
MOD = 10 ** 9 + 7
for _ in range(t):
x, s = int(input()), list(map(int, str(input())))
max_p = cur + x
for i in range(cur, min(max_p, cur + len(s))):
arr[i] = s[i - cur]
def copy(start, length, times):
b = start + length
for i in range(times):
for j in range(length):
if b >= max_p: return
arr[b] = arr[start + j]
b += 1
val = len(s)
cnt = 1
while x:
if arr[max_p - 1] is None and arr[cur] > 1:
copy(cur + 1, val - cnt, arr[cur] - 1)
val = (cnt + (val - cnt) * arr[cur]) % MOD
cnt += 1
cur += 1
x -= 1
ans.append(val)
for a in ans:
print(a)
```
| 104,545 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We start with a string s consisting only of the digits 1, 2, or 3. The length of s is denoted by |s|. For each i from 1 to |s|, the i-th character of s is denoted by s_i.
There is one cursor. The cursor's location ℓ is denoted by an integer in \{0, …, |s|\}, with the following meaning:
* If ℓ = 0, then the cursor is located before the first character of s.
* If ℓ = |s|, then the cursor is located right after the last character of s.
* If 0 < ℓ < |s|, then the cursor is located between s_ℓ and s_{ℓ+1}.
We denote by s_left the string to the left of the cursor and s_right the string to the right of the cursor.
We also have a string c, which we call our clipboard, which starts out as empty. There are three types of actions:
* The Move action. Move the cursor one step to the right. This increments ℓ once.
* The Cut action. Set c ← s_right, then set s ← s_left.
* The Paste action. Append the value of c to the end of the string s. Note that this doesn't modify c.
The cursor initially starts at ℓ = 0. Then, we perform the following procedure:
1. Perform the Move action once.
2. Perform the Cut action once.
3. Perform the Paste action s_ℓ times.
4. If ℓ = x, stop. Otherwise, return to step 1.
You're given the initial string s and the integer x. What is the length of s when the procedure stops? Since this value may be very large, only find it modulo 10^9 + 7.
It is guaranteed that ℓ ≤ |s| at any time.
Input
The first line of input contains a single integer t (1 ≤ t ≤ 1000) denoting the number of test cases. The next lines contain descriptions of the test cases.
The first line of each test case contains a single integer x (1 ≤ x ≤ 10^6). The second line of each test case consists of the initial string s (1 ≤ |s| ≤ 500). It is guaranteed, that s consists of the characters "1", "2", "3".
It is guaranteed that the sum of x in a single file is at most 10^6. It is guaranteed that in each test case before the procedure will stop it will be true that ℓ ≤ |s| at any time.
Output
For each test case, output a single line containing a single integer denoting the answer for that test case modulo 10^9 + 7.
Example
Input
4
5
231
7
2323
6
333
24
133321333
Output
25
1438
1101
686531475
Note
Let's illustrate what happens with the first test case. Initially, we have s = 231. Initially, ℓ = 0 and c = \varepsilon (the empty string). The following things happen if we follow the procedure above:
* Step 1, Move once: we get ℓ = 1.
* Step 2, Cut once: we get s = 2 and c = 31.
* Step 3, Paste s_ℓ = 2 times: we get s = 23131.
* Step 4: ℓ = 1 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 2.
* Step 2, Cut once: we get s = 23 and c = 131.
* Step 3, Paste s_ℓ = 3 times: we get s = 23131131131.
* Step 4: ℓ = 2 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 3.
* Step 2, Cut once: we get s = 231 and c = 31131131.
* Step 3, Paste s_ℓ = 1 time: we get s = 23131131131.
* Step 4: ℓ = 3 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 4.
* Step 2, Cut once: we get s = 2313 and c = 1131131.
* Step 3, Paste s_ℓ = 3 times: we get s = 2313113113111311311131131.
* Step 4: ℓ = 4 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 5.
* Step 2, Cut once: we get s = 23131 and c = 13113111311311131131.
* Step 3, Paste s_ℓ = 1 times: we get s = 2313113113111311311131131.
* Step 4: ℓ = 5 = x, so we stop.
At the end of the procedure, s has length 25.
Tags: implementation, math
Correct Solution:
```
def solve(s,x):
n = len(s)
mod = 10**9 + 7
for i in range(x):
n += (n-i-1)*(int(s[i])-1)
n %= mod
if len(s) < x:
s += s[i+1:]*(int(s[i])-1)
return n
for _ in range(int(input())):
x = int(input())
s = input()
print(solve(s,x))
```
| 104,546 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We start with a string s consisting only of the digits 1, 2, or 3. The length of s is denoted by |s|. For each i from 1 to |s|, the i-th character of s is denoted by s_i.
There is one cursor. The cursor's location ℓ is denoted by an integer in \{0, …, |s|\}, with the following meaning:
* If ℓ = 0, then the cursor is located before the first character of s.
* If ℓ = |s|, then the cursor is located right after the last character of s.
* If 0 < ℓ < |s|, then the cursor is located between s_ℓ and s_{ℓ+1}.
We denote by s_left the string to the left of the cursor and s_right the string to the right of the cursor.
We also have a string c, which we call our clipboard, which starts out as empty. There are three types of actions:
* The Move action. Move the cursor one step to the right. This increments ℓ once.
* The Cut action. Set c ← s_right, then set s ← s_left.
* The Paste action. Append the value of c to the end of the string s. Note that this doesn't modify c.
The cursor initially starts at ℓ = 0. Then, we perform the following procedure:
1. Perform the Move action once.
2. Perform the Cut action once.
3. Perform the Paste action s_ℓ times.
4. If ℓ = x, stop. Otherwise, return to step 1.
You're given the initial string s and the integer x. What is the length of s when the procedure stops? Since this value may be very large, only find it modulo 10^9 + 7.
It is guaranteed that ℓ ≤ |s| at any time.
Input
The first line of input contains a single integer t (1 ≤ t ≤ 1000) denoting the number of test cases. The next lines contain descriptions of the test cases.
The first line of each test case contains a single integer x (1 ≤ x ≤ 10^6). The second line of each test case consists of the initial string s (1 ≤ |s| ≤ 500). It is guaranteed, that s consists of the characters "1", "2", "3".
It is guaranteed that the sum of x in a single file is at most 10^6. It is guaranteed that in each test case before the procedure will stop it will be true that ℓ ≤ |s| at any time.
Output
For each test case, output a single line containing a single integer denoting the answer for that test case modulo 10^9 + 7.
Example
Input
4
5
231
7
2323
6
333
24
133321333
Output
25
1438
1101
686531475
Note
Let's illustrate what happens with the first test case. Initially, we have s = 231. Initially, ℓ = 0 and c = \varepsilon (the empty string). The following things happen if we follow the procedure above:
* Step 1, Move once: we get ℓ = 1.
* Step 2, Cut once: we get s = 2 and c = 31.
* Step 3, Paste s_ℓ = 2 times: we get s = 23131.
* Step 4: ℓ = 1 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 2.
* Step 2, Cut once: we get s = 23 and c = 131.
* Step 3, Paste s_ℓ = 3 times: we get s = 23131131131.
* Step 4: ℓ = 2 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 3.
* Step 2, Cut once: we get s = 231 and c = 31131131.
* Step 3, Paste s_ℓ = 1 time: we get s = 23131131131.
* Step 4: ℓ = 3 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 4.
* Step 2, Cut once: we get s = 2313 and c = 1131131.
* Step 3, Paste s_ℓ = 3 times: we get s = 2313113113111311311131131.
* Step 4: ℓ = 4 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 5.
* Step 2, Cut once: we get s = 23131 and c = 13113111311311131131.
* Step 3, Paste s_ℓ = 1 times: we get s = 2313113113111311311131131.
* Step 4: ℓ = 5 = x, so we stop.
At the end of the procedure, s has length 25.
Submitted Solution:
```
for _ in range(int(input())):
x=int(input())
a=input()
l=len(a)
a=[i for i in a]
ans=l
p=0
m=10**9+7
while ans<x:
for j in range(int(a[p])-1):
for i in range(p+1,ans):
a.append(a[i])
ans+=(int(a[p])-1)*((ans-p-1+m)%m)
p+=1
for j in range(p,x):
ans+=(int(a[j])-1)*((ans-j-1+m)%m)
ans%=m
print(ans)
```
Yes
| 104,547 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We start with a string s consisting only of the digits 1, 2, or 3. The length of s is denoted by |s|. For each i from 1 to |s|, the i-th character of s is denoted by s_i.
There is one cursor. The cursor's location ℓ is denoted by an integer in \{0, …, |s|\}, with the following meaning:
* If ℓ = 0, then the cursor is located before the first character of s.
* If ℓ = |s|, then the cursor is located right after the last character of s.
* If 0 < ℓ < |s|, then the cursor is located between s_ℓ and s_{ℓ+1}.
We denote by s_left the string to the left of the cursor and s_right the string to the right of the cursor.
We also have a string c, which we call our clipboard, which starts out as empty. There are three types of actions:
* The Move action. Move the cursor one step to the right. This increments ℓ once.
* The Cut action. Set c ← s_right, then set s ← s_left.
* The Paste action. Append the value of c to the end of the string s. Note that this doesn't modify c.
The cursor initially starts at ℓ = 0. Then, we perform the following procedure:
1. Perform the Move action once.
2. Perform the Cut action once.
3. Perform the Paste action s_ℓ times.
4. If ℓ = x, stop. Otherwise, return to step 1.
You're given the initial string s and the integer x. What is the length of s when the procedure stops? Since this value may be very large, only find it modulo 10^9 + 7.
It is guaranteed that ℓ ≤ |s| at any time.
Input
The first line of input contains a single integer t (1 ≤ t ≤ 1000) denoting the number of test cases. The next lines contain descriptions of the test cases.
The first line of each test case contains a single integer x (1 ≤ x ≤ 10^6). The second line of each test case consists of the initial string s (1 ≤ |s| ≤ 500). It is guaranteed, that s consists of the characters "1", "2", "3".
It is guaranteed that the sum of x in a single file is at most 10^6. It is guaranteed that in each test case before the procedure will stop it will be true that ℓ ≤ |s| at any time.
Output
For each test case, output a single line containing a single integer denoting the answer for that test case modulo 10^9 + 7.
Example
Input
4
5
231
7
2323
6
333
24
133321333
Output
25
1438
1101
686531475
Note
Let's illustrate what happens with the first test case. Initially, we have s = 231. Initially, ℓ = 0 and c = \varepsilon (the empty string). The following things happen if we follow the procedure above:
* Step 1, Move once: we get ℓ = 1.
* Step 2, Cut once: we get s = 2 and c = 31.
* Step 3, Paste s_ℓ = 2 times: we get s = 23131.
* Step 4: ℓ = 1 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 2.
* Step 2, Cut once: we get s = 23 and c = 131.
* Step 3, Paste s_ℓ = 3 times: we get s = 23131131131.
* Step 4: ℓ = 2 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 3.
* Step 2, Cut once: we get s = 231 and c = 31131131.
* Step 3, Paste s_ℓ = 1 time: we get s = 23131131131.
* Step 4: ℓ = 3 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 4.
* Step 2, Cut once: we get s = 2313 and c = 1131131.
* Step 3, Paste s_ℓ = 3 times: we get s = 2313113113111311311131131.
* Step 4: ℓ = 4 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 5.
* Step 2, Cut once: we get s = 23131 and c = 13113111311311131131.
* Step 3, Paste s_ℓ = 1 times: we get s = 2313113113111311311131131.
* Step 4: ℓ = 5 = x, so we stop.
At the end of the procedure, s has length 25.
Submitted Solution:
```
#TLE
# import sys, os.path
# import math
# from collections import defaultdict,deque
# input = sys.stdin.readline
# I = lambda : list(map(int,input().split()))
# S = lambda : list(map(str,input()))
# def main():
# # s1 = [0]*((2*(10**6))+1)
# t,=I()
# for t1 in range(t):
# x, = I()
# s1 = str(input()).rstrip('\n')
# # for i in range(len(s2)):
# # s1[i] = int(s2[i])
# l = 0
# count = 0
# count1 = len(s1)
# count1%=((10**9)+7)
# for i in range(x):
# k = int(s1[i])
# count1-=1
# count1%=((10**9)+7)
# if count1>x:
# count1*=k
# count1%=((10**9)+7)
# else:
# l1 = len(s1)
# for j in range(k-1):
# for l in range(i+1,l1):
# s1+=s1[l]
# count1*=k
# count1%=((10**9)+7)
# count1+=x
# count1%=((10**9)+7)
# print(count1)
# main()
#
import sys, os.path
import math
from collections import defaultdict,deque
input = sys.stdin.readline
I = lambda : list(map(int,input().split()))
S = lambda : list(map(str,input()))
def main():
# s1 = [0]*((2*(10**6))+1)
t,=I()
for t1 in range(t):
x, = I()
s2 = str(input()).rstrip('\n')
s1 = []
for i in range(len(s2)):
if i>x:
break
s1.append(int(s2[i]))
count1 = len(s2)
count1%=((10**9)+7)
for i in range(x):
k = int(s1[i])
count1-=1
count1%=((10**9)+7)
if len(s1)>x:
count1*=k
count1%=((10**9)+7)
else:
if k==1:
continue
X = s1[i+1:]
l1 = len(s1)
for j in range(k-1):
if len(s1)<x:
s1.extend(X)
count1*=k
count1%=((10**9)+7)
count1+=x
count1%=((10**9)+7)
print(count1)
main()
# import sys
# input = sys.stdin.readline
# mod = 10 ** 9 + 7
# t = int(input())
# for _ in range(t):
# x = int(input())
# s = input().rstrip('\n')
# X = []
# for i, si in enumerate(s):
# if i == x:
# break
# X.append(int(s[i]))
# ans = len(s)
# for i in range(x):
# ans = (ans + (ans - i - 1) * (X[i] - 1)) % mod
# if len(X) < x:
# if X[i] == 1:
# continue
# X_ = X[i + 1:]
# for j in range(X[i] - 1):
# if len(X) < x:
# X.extend(X_)
# print(ans)
```
Yes
| 104,548 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We start with a string s consisting only of the digits 1, 2, or 3. The length of s is denoted by |s|. For each i from 1 to |s|, the i-th character of s is denoted by s_i.
There is one cursor. The cursor's location ℓ is denoted by an integer in \{0, …, |s|\}, with the following meaning:
* If ℓ = 0, then the cursor is located before the first character of s.
* If ℓ = |s|, then the cursor is located right after the last character of s.
* If 0 < ℓ < |s|, then the cursor is located between s_ℓ and s_{ℓ+1}.
We denote by s_left the string to the left of the cursor and s_right the string to the right of the cursor.
We also have a string c, which we call our clipboard, which starts out as empty. There are three types of actions:
* The Move action. Move the cursor one step to the right. This increments ℓ once.
* The Cut action. Set c ← s_right, then set s ← s_left.
* The Paste action. Append the value of c to the end of the string s. Note that this doesn't modify c.
The cursor initially starts at ℓ = 0. Then, we perform the following procedure:
1. Perform the Move action once.
2. Perform the Cut action once.
3. Perform the Paste action s_ℓ times.
4. If ℓ = x, stop. Otherwise, return to step 1.
You're given the initial string s and the integer x. What is the length of s when the procedure stops? Since this value may be very large, only find it modulo 10^9 + 7.
It is guaranteed that ℓ ≤ |s| at any time.
Input
The first line of input contains a single integer t (1 ≤ t ≤ 1000) denoting the number of test cases. The next lines contain descriptions of the test cases.
The first line of each test case contains a single integer x (1 ≤ x ≤ 10^6). The second line of each test case consists of the initial string s (1 ≤ |s| ≤ 500). It is guaranteed, that s consists of the characters "1", "2", "3".
It is guaranteed that the sum of x in a single file is at most 10^6. It is guaranteed that in each test case before the procedure will stop it will be true that ℓ ≤ |s| at any time.
Output
For each test case, output a single line containing a single integer denoting the answer for that test case modulo 10^9 + 7.
Example
Input
4
5
231
7
2323
6
333
24
133321333
Output
25
1438
1101
686531475
Note
Let's illustrate what happens with the first test case. Initially, we have s = 231. Initially, ℓ = 0 and c = \varepsilon (the empty string). The following things happen if we follow the procedure above:
* Step 1, Move once: we get ℓ = 1.
* Step 2, Cut once: we get s = 2 and c = 31.
* Step 3, Paste s_ℓ = 2 times: we get s = 23131.
* Step 4: ℓ = 1 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 2.
* Step 2, Cut once: we get s = 23 and c = 131.
* Step 3, Paste s_ℓ = 3 times: we get s = 23131131131.
* Step 4: ℓ = 2 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 3.
* Step 2, Cut once: we get s = 231 and c = 31131131.
* Step 3, Paste s_ℓ = 1 time: we get s = 23131131131.
* Step 4: ℓ = 3 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 4.
* Step 2, Cut once: we get s = 2313 and c = 1131131.
* Step 3, Paste s_ℓ = 3 times: we get s = 2313113113111311311131131.
* Step 4: ℓ = 4 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 5.
* Step 2, Cut once: we get s = 23131 and c = 13113111311311131131.
* Step 3, Paste s_ℓ = 1 times: we get s = 2313113113111311311131131.
* Step 4: ℓ = 5 = x, so we stop.
At the end of the procedure, s has length 25.
Submitted Solution:
```
import time
import sys
MOD = 1e9 + 7
# f = open('test.txt', 'w+')
# f.write("1\n333047\n")
# f.write('1'*300 + '2' + '1'*20 + '2')
# f.seek(0)
f = sys.stdin
t1 = time.time()
for t in range(int(f.readline())):
x, s = int(f.readline().rstrip()), f.readline().rstrip()
i = 0
while len(s) < x:
i += 1
s += s[i:] * (int(s[i - 1])-1)
answer = len(s)
while i < x:
i += 1
answer = (answer + (answer - i) * (int(s[i - 1]) - 1)) % MOD
print(int(answer))
# print("--- %s seconds ---" % (time.time() - t1))
```
Yes
| 104,549 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We start with a string s consisting only of the digits 1, 2, or 3. The length of s is denoted by |s|. For each i from 1 to |s|, the i-th character of s is denoted by s_i.
There is one cursor. The cursor's location ℓ is denoted by an integer in \{0, …, |s|\}, with the following meaning:
* If ℓ = 0, then the cursor is located before the first character of s.
* If ℓ = |s|, then the cursor is located right after the last character of s.
* If 0 < ℓ < |s|, then the cursor is located between s_ℓ and s_{ℓ+1}.
We denote by s_left the string to the left of the cursor and s_right the string to the right of the cursor.
We also have a string c, which we call our clipboard, which starts out as empty. There are three types of actions:
* The Move action. Move the cursor one step to the right. This increments ℓ once.
* The Cut action. Set c ← s_right, then set s ← s_left.
* The Paste action. Append the value of c to the end of the string s. Note that this doesn't modify c.
The cursor initially starts at ℓ = 0. Then, we perform the following procedure:
1. Perform the Move action once.
2. Perform the Cut action once.
3. Perform the Paste action s_ℓ times.
4. If ℓ = x, stop. Otherwise, return to step 1.
You're given the initial string s and the integer x. What is the length of s when the procedure stops? Since this value may be very large, only find it modulo 10^9 + 7.
It is guaranteed that ℓ ≤ |s| at any time.
Input
The first line of input contains a single integer t (1 ≤ t ≤ 1000) denoting the number of test cases. The next lines contain descriptions of the test cases.
The first line of each test case contains a single integer x (1 ≤ x ≤ 10^6). The second line of each test case consists of the initial string s (1 ≤ |s| ≤ 500). It is guaranteed, that s consists of the characters "1", "2", "3".
It is guaranteed that the sum of x in a single file is at most 10^6. It is guaranteed that in each test case before the procedure will stop it will be true that ℓ ≤ |s| at any time.
Output
For each test case, output a single line containing a single integer denoting the answer for that test case modulo 10^9 + 7.
Example
Input
4
5
231
7
2323
6
333
24
133321333
Output
25
1438
1101
686531475
Note
Let's illustrate what happens with the first test case. Initially, we have s = 231. Initially, ℓ = 0 and c = \varepsilon (the empty string). The following things happen if we follow the procedure above:
* Step 1, Move once: we get ℓ = 1.
* Step 2, Cut once: we get s = 2 and c = 31.
* Step 3, Paste s_ℓ = 2 times: we get s = 23131.
* Step 4: ℓ = 1 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 2.
* Step 2, Cut once: we get s = 23 and c = 131.
* Step 3, Paste s_ℓ = 3 times: we get s = 23131131131.
* Step 4: ℓ = 2 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 3.
* Step 2, Cut once: we get s = 231 and c = 31131131.
* Step 3, Paste s_ℓ = 1 time: we get s = 23131131131.
* Step 4: ℓ = 3 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 4.
* Step 2, Cut once: we get s = 2313 and c = 1131131.
* Step 3, Paste s_ℓ = 3 times: we get s = 2313113113111311311131131.
* Step 4: ℓ = 4 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 5.
* Step 2, Cut once: we get s = 23131 and c = 13113111311311131131.
* Step 3, Paste s_ℓ = 1 times: we get s = 2313113113111311311131131.
* Step 4: ℓ = 5 = x, so we stop.
At the end of the procedure, s has length 25.
Submitted Solution:
```
import sys
T = int(sys.stdin.readline().strip())
for _ in range(T):
x = int(sys.stdin.readline().strip())
s = list(sys.stdin.readline().strip())
ls = len(s)
for l in range(x):
t = ord(s[l]) - ord('0') - 1
ls = (ls + (ls - l - 1)*t) % ((10**9)+7)
e = len(s)
while len(s) <= x and t > 0:
s += s[l+1:e]
t -= 1
print(ls)
```
Yes
| 104,550 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We start with a string s consisting only of the digits 1, 2, or 3. The length of s is denoted by |s|. For each i from 1 to |s|, the i-th character of s is denoted by s_i.
There is one cursor. The cursor's location ℓ is denoted by an integer in \{0, …, |s|\}, with the following meaning:
* If ℓ = 0, then the cursor is located before the first character of s.
* If ℓ = |s|, then the cursor is located right after the last character of s.
* If 0 < ℓ < |s|, then the cursor is located between s_ℓ and s_{ℓ+1}.
We denote by s_left the string to the left of the cursor and s_right the string to the right of the cursor.
We also have a string c, which we call our clipboard, which starts out as empty. There are three types of actions:
* The Move action. Move the cursor one step to the right. This increments ℓ once.
* The Cut action. Set c ← s_right, then set s ← s_left.
* The Paste action. Append the value of c to the end of the string s. Note that this doesn't modify c.
The cursor initially starts at ℓ = 0. Then, we perform the following procedure:
1. Perform the Move action once.
2. Perform the Cut action once.
3. Perform the Paste action s_ℓ times.
4. If ℓ = x, stop. Otherwise, return to step 1.
You're given the initial string s and the integer x. What is the length of s when the procedure stops? Since this value may be very large, only find it modulo 10^9 + 7.
It is guaranteed that ℓ ≤ |s| at any time.
Input
The first line of input contains a single integer t (1 ≤ t ≤ 1000) denoting the number of test cases. The next lines contain descriptions of the test cases.
The first line of each test case contains a single integer x (1 ≤ x ≤ 10^6). The second line of each test case consists of the initial string s (1 ≤ |s| ≤ 500). It is guaranteed, that s consists of the characters "1", "2", "3".
It is guaranteed that the sum of x in a single file is at most 10^6. It is guaranteed that in each test case before the procedure will stop it will be true that ℓ ≤ |s| at any time.
Output
For each test case, output a single line containing a single integer denoting the answer for that test case modulo 10^9 + 7.
Example
Input
4
5
231
7
2323
6
333
24
133321333
Output
25
1438
1101
686531475
Note
Let's illustrate what happens with the first test case. Initially, we have s = 231. Initially, ℓ = 0 and c = \varepsilon (the empty string). The following things happen if we follow the procedure above:
* Step 1, Move once: we get ℓ = 1.
* Step 2, Cut once: we get s = 2 and c = 31.
* Step 3, Paste s_ℓ = 2 times: we get s = 23131.
* Step 4: ℓ = 1 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 2.
* Step 2, Cut once: we get s = 23 and c = 131.
* Step 3, Paste s_ℓ = 3 times: we get s = 23131131131.
* Step 4: ℓ = 2 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 3.
* Step 2, Cut once: we get s = 231 and c = 31131131.
* Step 3, Paste s_ℓ = 1 time: we get s = 23131131131.
* Step 4: ℓ = 3 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 4.
* Step 2, Cut once: we get s = 2313 and c = 1131131.
* Step 3, Paste s_ℓ = 3 times: we get s = 2313113113111311311131131.
* Step 4: ℓ = 4 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 5.
* Step 2, Cut once: we get s = 23131 and c = 13113111311311131131.
* Step 3, Paste s_ℓ = 1 times: we get s = 2313113113111311311131131.
* Step 4: ℓ = 5 = x, so we stop.
At the end of the procedure, s has length 25.
Submitted Solution:
```
t=int(input())
for i in range(t):
x=int(input())
s=input()
p=s
l=0
while(l!=x):
r=int(p[0])
p=p[1:]
if r>1:
p+=p
if r>2:
p+=p
if (len(p)+l+1)>=x:
l+=1
break
l+=1
j=0
res=l
y=len(p)
while(l!=x):
y-=1
y=y*int(p[j])
l+=1
res+=1
j+=1
print((res+y)%(10**9+7))
```
No
| 104,551 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We start with a string s consisting only of the digits 1, 2, or 3. The length of s is denoted by |s|. For each i from 1 to |s|, the i-th character of s is denoted by s_i.
There is one cursor. The cursor's location ℓ is denoted by an integer in \{0, …, |s|\}, with the following meaning:
* If ℓ = 0, then the cursor is located before the first character of s.
* If ℓ = |s|, then the cursor is located right after the last character of s.
* If 0 < ℓ < |s|, then the cursor is located between s_ℓ and s_{ℓ+1}.
We denote by s_left the string to the left of the cursor and s_right the string to the right of the cursor.
We also have a string c, which we call our clipboard, which starts out as empty. There are three types of actions:
* The Move action. Move the cursor one step to the right. This increments ℓ once.
* The Cut action. Set c ← s_right, then set s ← s_left.
* The Paste action. Append the value of c to the end of the string s. Note that this doesn't modify c.
The cursor initially starts at ℓ = 0. Then, we perform the following procedure:
1. Perform the Move action once.
2. Perform the Cut action once.
3. Perform the Paste action s_ℓ times.
4. If ℓ = x, stop. Otherwise, return to step 1.
You're given the initial string s and the integer x. What is the length of s when the procedure stops? Since this value may be very large, only find it modulo 10^9 + 7.
It is guaranteed that ℓ ≤ |s| at any time.
Input
The first line of input contains a single integer t (1 ≤ t ≤ 1000) denoting the number of test cases. The next lines contain descriptions of the test cases.
The first line of each test case contains a single integer x (1 ≤ x ≤ 10^6). The second line of each test case consists of the initial string s (1 ≤ |s| ≤ 500). It is guaranteed, that s consists of the characters "1", "2", "3".
It is guaranteed that the sum of x in a single file is at most 10^6. It is guaranteed that in each test case before the procedure will stop it will be true that ℓ ≤ |s| at any time.
Output
For each test case, output a single line containing a single integer denoting the answer for that test case modulo 10^9 + 7.
Example
Input
4
5
231
7
2323
6
333
24
133321333
Output
25
1438
1101
686531475
Note
Let's illustrate what happens with the first test case. Initially, we have s = 231. Initially, ℓ = 0 and c = \varepsilon (the empty string). The following things happen if we follow the procedure above:
* Step 1, Move once: we get ℓ = 1.
* Step 2, Cut once: we get s = 2 and c = 31.
* Step 3, Paste s_ℓ = 2 times: we get s = 23131.
* Step 4: ℓ = 1 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 2.
* Step 2, Cut once: we get s = 23 and c = 131.
* Step 3, Paste s_ℓ = 3 times: we get s = 23131131131.
* Step 4: ℓ = 2 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 3.
* Step 2, Cut once: we get s = 231 and c = 31131131.
* Step 3, Paste s_ℓ = 1 time: we get s = 23131131131.
* Step 4: ℓ = 3 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 4.
* Step 2, Cut once: we get s = 2313 and c = 1131131.
* Step 3, Paste s_ℓ = 3 times: we get s = 2313113113111311311131131.
* Step 4: ℓ = 4 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 5.
* Step 2, Cut once: we get s = 23131 and c = 13113111311311131131.
* Step 3, Paste s_ℓ = 1 times: we get s = 2313113113111311311131131.
* Step 4: ℓ = 5 = x, so we stop.
At the end of the procedure, s has length 25.
Submitted Solution:
```
for _ in range(int(input())):
x = int(input())
s = list(map(int, input()))
ans = len(s)
for i in range(1, x+1):
ans = (i + (ans-i) * s[i-1])%1000000007
for _ in range(s[i-1]-1):
if len(s) < x:
s += s[i:]
else:
break
print(ans)
```
No
| 104,552 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We start with a string s consisting only of the digits 1, 2, or 3. The length of s is denoted by |s|. For each i from 1 to |s|, the i-th character of s is denoted by s_i.
There is one cursor. The cursor's location ℓ is denoted by an integer in \{0, …, |s|\}, with the following meaning:
* If ℓ = 0, then the cursor is located before the first character of s.
* If ℓ = |s|, then the cursor is located right after the last character of s.
* If 0 < ℓ < |s|, then the cursor is located between s_ℓ and s_{ℓ+1}.
We denote by s_left the string to the left of the cursor and s_right the string to the right of the cursor.
We also have a string c, which we call our clipboard, which starts out as empty. There are three types of actions:
* The Move action. Move the cursor one step to the right. This increments ℓ once.
* The Cut action. Set c ← s_right, then set s ← s_left.
* The Paste action. Append the value of c to the end of the string s. Note that this doesn't modify c.
The cursor initially starts at ℓ = 0. Then, we perform the following procedure:
1. Perform the Move action once.
2. Perform the Cut action once.
3. Perform the Paste action s_ℓ times.
4. If ℓ = x, stop. Otherwise, return to step 1.
You're given the initial string s and the integer x. What is the length of s when the procedure stops? Since this value may be very large, only find it modulo 10^9 + 7.
It is guaranteed that ℓ ≤ |s| at any time.
Input
The first line of input contains a single integer t (1 ≤ t ≤ 1000) denoting the number of test cases. The next lines contain descriptions of the test cases.
The first line of each test case contains a single integer x (1 ≤ x ≤ 10^6). The second line of each test case consists of the initial string s (1 ≤ |s| ≤ 500). It is guaranteed, that s consists of the characters "1", "2", "3".
It is guaranteed that the sum of x in a single file is at most 10^6. It is guaranteed that in each test case before the procedure will stop it will be true that ℓ ≤ |s| at any time.
Output
For each test case, output a single line containing a single integer denoting the answer for that test case modulo 10^9 + 7.
Example
Input
4
5
231
7
2323
6
333
24
133321333
Output
25
1438
1101
686531475
Note
Let's illustrate what happens with the first test case. Initially, we have s = 231. Initially, ℓ = 0 and c = \varepsilon (the empty string). The following things happen if we follow the procedure above:
* Step 1, Move once: we get ℓ = 1.
* Step 2, Cut once: we get s = 2 and c = 31.
* Step 3, Paste s_ℓ = 2 times: we get s = 23131.
* Step 4: ℓ = 1 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 2.
* Step 2, Cut once: we get s = 23 and c = 131.
* Step 3, Paste s_ℓ = 3 times: we get s = 23131131131.
* Step 4: ℓ = 2 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 3.
* Step 2, Cut once: we get s = 231 and c = 31131131.
* Step 3, Paste s_ℓ = 1 time: we get s = 23131131131.
* Step 4: ℓ = 3 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 4.
* Step 2, Cut once: we get s = 2313 and c = 1131131.
* Step 3, Paste s_ℓ = 3 times: we get s = 2313113113111311311131131.
* Step 4: ℓ = 4 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 5.
* Step 2, Cut once: we get s = 23131 and c = 13113111311311131131.
* Step 3, Paste s_ℓ = 1 times: we get s = 2313113113111311311131131.
* Step 4: ℓ = 5 = x, so we stop.
At the end of the procedure, s has length 25.
Submitted Solution:
```
t=int(input())
for i in range(t):
x=int(input())
y=input()
s=[]
for j in y:
s.append(j)
l=0
res=len(s)
while(l!=x):
if len(s)<x:
for p in range(int(s[l])-1):
for j in range(l + 1, len(s)):
s.append(s[j])
res=(res+(res-l-1)*(int(s[l])-1))%(10**9+7)
l+=1
print(res%(10**9+7))
```
No
| 104,553 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We start with a string s consisting only of the digits 1, 2, or 3. The length of s is denoted by |s|. For each i from 1 to |s|, the i-th character of s is denoted by s_i.
There is one cursor. The cursor's location ℓ is denoted by an integer in \{0, …, |s|\}, with the following meaning:
* If ℓ = 0, then the cursor is located before the first character of s.
* If ℓ = |s|, then the cursor is located right after the last character of s.
* If 0 < ℓ < |s|, then the cursor is located between s_ℓ and s_{ℓ+1}.
We denote by s_left the string to the left of the cursor and s_right the string to the right of the cursor.
We also have a string c, which we call our clipboard, which starts out as empty. There are three types of actions:
* The Move action. Move the cursor one step to the right. This increments ℓ once.
* The Cut action. Set c ← s_right, then set s ← s_left.
* The Paste action. Append the value of c to the end of the string s. Note that this doesn't modify c.
The cursor initially starts at ℓ = 0. Then, we perform the following procedure:
1. Perform the Move action once.
2. Perform the Cut action once.
3. Perform the Paste action s_ℓ times.
4. If ℓ = x, stop. Otherwise, return to step 1.
You're given the initial string s and the integer x. What is the length of s when the procedure stops? Since this value may be very large, only find it modulo 10^9 + 7.
It is guaranteed that ℓ ≤ |s| at any time.
Input
The first line of input contains a single integer t (1 ≤ t ≤ 1000) denoting the number of test cases. The next lines contain descriptions of the test cases.
The first line of each test case contains a single integer x (1 ≤ x ≤ 10^6). The second line of each test case consists of the initial string s (1 ≤ |s| ≤ 500). It is guaranteed, that s consists of the characters "1", "2", "3".
It is guaranteed that the sum of x in a single file is at most 10^6. It is guaranteed that in each test case before the procedure will stop it will be true that ℓ ≤ |s| at any time.
Output
For each test case, output a single line containing a single integer denoting the answer for that test case modulo 10^9 + 7.
Example
Input
4
5
231
7
2323
6
333
24
133321333
Output
25
1438
1101
686531475
Note
Let's illustrate what happens with the first test case. Initially, we have s = 231. Initially, ℓ = 0 and c = \varepsilon (the empty string). The following things happen if we follow the procedure above:
* Step 1, Move once: we get ℓ = 1.
* Step 2, Cut once: we get s = 2 and c = 31.
* Step 3, Paste s_ℓ = 2 times: we get s = 23131.
* Step 4: ℓ = 1 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 2.
* Step 2, Cut once: we get s = 23 and c = 131.
* Step 3, Paste s_ℓ = 3 times: we get s = 23131131131.
* Step 4: ℓ = 2 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 3.
* Step 2, Cut once: we get s = 231 and c = 31131131.
* Step 3, Paste s_ℓ = 1 time: we get s = 23131131131.
* Step 4: ℓ = 3 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 4.
* Step 2, Cut once: we get s = 2313 and c = 1131131.
* Step 3, Paste s_ℓ = 3 times: we get s = 2313113113111311311131131.
* Step 4: ℓ = 4 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 5.
* Step 2, Cut once: we get s = 23131 and c = 13113111311311131131.
* Step 3, Paste s_ℓ = 1 times: we get s = 2313113113111311311131131.
* Step 4: ℓ = 5 = x, so we stop.
At the end of the procedure, s has length 25.
Submitted Solution:
```
import sys
import math
from collections import defaultdict,Counter,deque
# input=sys.stdin.readline
# def print(x):
# sys.stdout.write(str(x)+"\n")
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")
# sys.stdout=open("CP2/output.txt",'w')
# sys.stdin=open("CP2/input.txt",'r')
mod=pow(10,9)+7
t=int(input())
for i in range(t):
x=int(input())
s=list(map(int,input()))
cur=0
ans=0
tot=len(s)-1
while cur<x:
tot=(s[cur]*tot)%mod
if len(s)<x:
s+=s[cur+1:]*(s[cur]-1)
else:
# print(len(s))
if cur+1+tot>=mod:
ans=cur+1+tot-mod
else:
ans=cur+1+tot
if tot==0:
tot=10**9-1
else:
tot-=1
cur+=1
print(len(s))
print(ans)
```
No
| 104,554 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ayoub thinks that he is a very smart person, so he created a function f(s), where s is a binary string (a string which contains only symbols "0" and "1"). The function f(s) is equal to the number of substrings in the string s that contains at least one symbol, that is equal to "1".
More formally, f(s) is equal to the number of pairs of integers (l, r), such that 1 ≤ l ≤ r ≤ |s| (where |s| is equal to the length of string s), such that at least one of the symbols s_l, s_{l+1}, …, s_r is equal to "1".
For example, if s = "01010" then f(s) = 12, because there are 12 such pairs (l, r): (1, 2), (1, 3), (1, 4), (1, 5), (2, 2), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 4), (4, 5).
Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers n and m and asked him this problem. For all binary strings s of length n which contains exactly m symbols equal to "1", find the maximum value of f(s).
Mahmoud couldn't solve the problem so he asked you for help. Can you help him?
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10^5) — the number of test cases. The description of the test cases follows.
The only line for each test case contains two integers n, m (1 ≤ n ≤ 10^{9}, 0 ≤ m ≤ n) — the length of the string and the number of symbols equal to "1" in it.
Output
For every test case print one integer number — the maximum value of f(s) over all strings s of length n, which has exactly m symbols, equal to "1".
Example
Input
5
3 1
3 2
3 3
4 0
5 2
Output
4
5
6
0
12
Note
In the first test case, there exists only 3 strings of length 3, which has exactly 1 symbol, equal to "1". These strings are: s_1 = "100", s_2 = "010", s_3 = "001". The values of f for them are: f(s_1) = 3, f(s_2) = 4, f(s_3) = 3, so the maximum value is 4 and the answer is 4.
In the second test case, the string s with the maximum value is "101".
In the third test case, the string s with the maximum value is "111".
In the fourth test case, the only string s of length 4, which has exactly 0 symbols, equal to "1" is "0000" and the value of f for that string is 0, so the answer is 0.
In the fifth test case, the string s with the maximum value is "01010" and it is described as an example in the problem statement.
Tags: binary search, combinatorics, greedy, math, strings
Correct Solution:
```
import math
import sys
for _ in range(int(input())):
n,m=(map(int,sys.stdin.readline().split()))
k=n-m
p=m+1
c=(k//p)
ans=(n*(n+1))//2
rem=k%p
ans1=(rem*((c+1)*(c+2)))//2
ans2=0
ans2=(c*(c+1)*(p-rem))//2
print(ans-ans1-ans2)
```
| 104,555 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ayoub thinks that he is a very smart person, so he created a function f(s), where s is a binary string (a string which contains only symbols "0" and "1"). The function f(s) is equal to the number of substrings in the string s that contains at least one symbol, that is equal to "1".
More formally, f(s) is equal to the number of pairs of integers (l, r), such that 1 ≤ l ≤ r ≤ |s| (where |s| is equal to the length of string s), such that at least one of the symbols s_l, s_{l+1}, …, s_r is equal to "1".
For example, if s = "01010" then f(s) = 12, because there are 12 such pairs (l, r): (1, 2), (1, 3), (1, 4), (1, 5), (2, 2), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 4), (4, 5).
Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers n and m and asked him this problem. For all binary strings s of length n which contains exactly m symbols equal to "1", find the maximum value of f(s).
Mahmoud couldn't solve the problem so he asked you for help. Can you help him?
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10^5) — the number of test cases. The description of the test cases follows.
The only line for each test case contains two integers n, m (1 ≤ n ≤ 10^{9}, 0 ≤ m ≤ n) — the length of the string and the number of symbols equal to "1" in it.
Output
For every test case print one integer number — the maximum value of f(s) over all strings s of length n, which has exactly m symbols, equal to "1".
Example
Input
5
3 1
3 2
3 3
4 0
5 2
Output
4
5
6
0
12
Note
In the first test case, there exists only 3 strings of length 3, which has exactly 1 symbol, equal to "1". These strings are: s_1 = "100", s_2 = "010", s_3 = "001". The values of f for them are: f(s_1) = 3, f(s_2) = 4, f(s_3) = 3, so the maximum value is 4 and the answer is 4.
In the second test case, the string s with the maximum value is "101".
In the third test case, the string s with the maximum value is "111".
In the fourth test case, the only string s of length 4, which has exactly 0 symbols, equal to "1" is "0000" and the value of f for that string is 0, so the answer is 0.
In the fifth test case, the string s with the maximum value is "01010" and it is described as an example in the problem statement.
Tags: binary search, combinatorics, greedy, math, strings
Correct Solution:
```
import sys
input = sys.stdin.readline
t = int(input())
C = [list(map(int,input().split())) for i in range(t)]
# ANS = [0] * t
# t = 10**5
# C = [[523422132331, 102342223434] for i in range(t)]
def c(x, y):
if x % 2 == 0:
return (x//2) * y
else:
return (y//2) * x
for i in range(t):
n = C[i][0]
o = C[i][1]
z = n-o
al = c(n, (n-1)) + n
# print("al",al)
if z-1 <= o:
print(al - z)
# ANS[i] = al-z
# v=0
else:
a = z // (o+1)
b = z % (o+1)
# print(a,b)
mi = c((a+1), (a+2)) * b + c(a, (a+1)) * (o+1-b)
print(al - mi)
# ANS[i] = al-mi
# for i in ANS:
# print(i)
```
| 104,556 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ayoub thinks that he is a very smart person, so he created a function f(s), where s is a binary string (a string which contains only symbols "0" and "1"). The function f(s) is equal to the number of substrings in the string s that contains at least one symbol, that is equal to "1".
More formally, f(s) is equal to the number of pairs of integers (l, r), such that 1 ≤ l ≤ r ≤ |s| (where |s| is equal to the length of string s), such that at least one of the symbols s_l, s_{l+1}, …, s_r is equal to "1".
For example, if s = "01010" then f(s) = 12, because there are 12 such pairs (l, r): (1, 2), (1, 3), (1, 4), (1, 5), (2, 2), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 4), (4, 5).
Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers n and m and asked him this problem. For all binary strings s of length n which contains exactly m symbols equal to "1", find the maximum value of f(s).
Mahmoud couldn't solve the problem so he asked you for help. Can you help him?
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10^5) — the number of test cases. The description of the test cases follows.
The only line for each test case contains two integers n, m (1 ≤ n ≤ 10^{9}, 0 ≤ m ≤ n) — the length of the string and the number of symbols equal to "1" in it.
Output
For every test case print one integer number — the maximum value of f(s) over all strings s of length n, which has exactly m symbols, equal to "1".
Example
Input
5
3 1
3 2
3 3
4 0
5 2
Output
4
5
6
0
12
Note
In the first test case, there exists only 3 strings of length 3, which has exactly 1 symbol, equal to "1". These strings are: s_1 = "100", s_2 = "010", s_3 = "001". The values of f for them are: f(s_1) = 3, f(s_2) = 4, f(s_3) = 3, so the maximum value is 4 and the answer is 4.
In the second test case, the string s with the maximum value is "101".
In the third test case, the string s with the maximum value is "111".
In the fourth test case, the only string s of length 4, which has exactly 0 symbols, equal to "1" is "0000" and the value of f for that string is 0, so the answer is 0.
In the fifth test case, the string s with the maximum value is "01010" and it is described as an example in the problem statement.
Tags: binary search, combinatorics, greedy, math, strings
Correct Solution:
```
import sys
input=sys.stdin.readline
for _ in range(int(input())):
n,m=map(int,input().split())
grps=m+1
zeach=(n-m)//grps
extras=(n-m)%grps
print( (n*(n+1)//2)- (zeach*(zeach+1)//2)*grps -(extras)*(zeach+1) )
```
| 104,557 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ayoub thinks that he is a very smart person, so he created a function f(s), where s is a binary string (a string which contains only symbols "0" and "1"). The function f(s) is equal to the number of substrings in the string s that contains at least one symbol, that is equal to "1".
More formally, f(s) is equal to the number of pairs of integers (l, r), such that 1 ≤ l ≤ r ≤ |s| (where |s| is equal to the length of string s), such that at least one of the symbols s_l, s_{l+1}, …, s_r is equal to "1".
For example, if s = "01010" then f(s) = 12, because there are 12 such pairs (l, r): (1, 2), (1, 3), (1, 4), (1, 5), (2, 2), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 4), (4, 5).
Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers n and m and asked him this problem. For all binary strings s of length n which contains exactly m symbols equal to "1", find the maximum value of f(s).
Mahmoud couldn't solve the problem so he asked you for help. Can you help him?
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10^5) — the number of test cases. The description of the test cases follows.
The only line for each test case contains two integers n, m (1 ≤ n ≤ 10^{9}, 0 ≤ m ≤ n) — the length of the string and the number of symbols equal to "1" in it.
Output
For every test case print one integer number — the maximum value of f(s) over all strings s of length n, which has exactly m symbols, equal to "1".
Example
Input
5
3 1
3 2
3 3
4 0
5 2
Output
4
5
6
0
12
Note
In the first test case, there exists only 3 strings of length 3, which has exactly 1 symbol, equal to "1". These strings are: s_1 = "100", s_2 = "010", s_3 = "001". The values of f for them are: f(s_1) = 3, f(s_2) = 4, f(s_3) = 3, so the maximum value is 4 and the answer is 4.
In the second test case, the string s with the maximum value is "101".
In the third test case, the string s with the maximum value is "111".
In the fourth test case, the only string s of length 4, which has exactly 0 symbols, equal to "1" is "0000" and the value of f for that string is 0, so the answer is 0.
In the fifth test case, the string s with the maximum value is "01010" and it is described as an example in the problem statement.
Tags: binary search, combinatorics, greedy, math, strings
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
from collections import Counter
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)
def gcd(a, b):
if a == 0:
return b
return gcd(b % a, a)
def lcm(a, b):
return (a * b) / gcd(a, b)
def main():
for _ in range(int(input())):
n,m=map(int, input().split())
ans=n*(n+1)//2
#print(ans)
k=(n-m)//(m+1)
f=k
k=(n-m)%(m+1)
ans-=(m+1-k)*(f*(f+1)//2)
#print(ans)
f+=1
ans-=(k)*(f*(f+1)//2)
print(ans)
return
if __name__ == "__main__":
main()
```
| 104,558 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ayoub thinks that he is a very smart person, so he created a function f(s), where s is a binary string (a string which contains only symbols "0" and "1"). The function f(s) is equal to the number of substrings in the string s that contains at least one symbol, that is equal to "1".
More formally, f(s) is equal to the number of pairs of integers (l, r), such that 1 ≤ l ≤ r ≤ |s| (where |s| is equal to the length of string s), such that at least one of the symbols s_l, s_{l+1}, …, s_r is equal to "1".
For example, if s = "01010" then f(s) = 12, because there are 12 such pairs (l, r): (1, 2), (1, 3), (1, 4), (1, 5), (2, 2), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 4), (4, 5).
Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers n and m and asked him this problem. For all binary strings s of length n which contains exactly m symbols equal to "1", find the maximum value of f(s).
Mahmoud couldn't solve the problem so he asked you for help. Can you help him?
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10^5) — the number of test cases. The description of the test cases follows.
The only line for each test case contains two integers n, m (1 ≤ n ≤ 10^{9}, 0 ≤ m ≤ n) — the length of the string and the number of symbols equal to "1" in it.
Output
For every test case print one integer number — the maximum value of f(s) over all strings s of length n, which has exactly m symbols, equal to "1".
Example
Input
5
3 1
3 2
3 3
4 0
5 2
Output
4
5
6
0
12
Note
In the first test case, there exists only 3 strings of length 3, which has exactly 1 symbol, equal to "1". These strings are: s_1 = "100", s_2 = "010", s_3 = "001". The values of f for them are: f(s_1) = 3, f(s_2) = 4, f(s_3) = 3, so the maximum value is 4 and the answer is 4.
In the second test case, the string s with the maximum value is "101".
In the third test case, the string s with the maximum value is "111".
In the fourth test case, the only string s of length 4, which has exactly 0 symbols, equal to "1" is "0000" and the value of f for that string is 0, so the answer is 0.
In the fifth test case, the string s with the maximum value is "01010" and it is described as an example in the problem statement.
Tags: binary search, combinatorics, greedy, math, strings
Correct Solution:
```
import sys
input = sys.stdin.readline
T = int(input())
for _ in range(T):
n, m = list(map(int, input().split()))
S = 0
x = (n - m) // (m + 1)
z = (n - m) % (m + 1)
S += (m + 1 - z) * (x * (x + 1)) // 2
S += z * (x + 1) * (x + 2) // 2
print(n * (n + 1) // 2 - S)
```
| 104,559 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ayoub thinks that he is a very smart person, so he created a function f(s), where s is a binary string (a string which contains only symbols "0" and "1"). The function f(s) is equal to the number of substrings in the string s that contains at least one symbol, that is equal to "1".
More formally, f(s) is equal to the number of pairs of integers (l, r), such that 1 ≤ l ≤ r ≤ |s| (where |s| is equal to the length of string s), such that at least one of the symbols s_l, s_{l+1}, …, s_r is equal to "1".
For example, if s = "01010" then f(s) = 12, because there are 12 such pairs (l, r): (1, 2), (1, 3), (1, 4), (1, 5), (2, 2), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 4), (4, 5).
Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers n and m and asked him this problem. For all binary strings s of length n which contains exactly m symbols equal to "1", find the maximum value of f(s).
Mahmoud couldn't solve the problem so he asked you for help. Can you help him?
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10^5) — the number of test cases. The description of the test cases follows.
The only line for each test case contains two integers n, m (1 ≤ n ≤ 10^{9}, 0 ≤ m ≤ n) — the length of the string and the number of symbols equal to "1" in it.
Output
For every test case print one integer number — the maximum value of f(s) over all strings s of length n, which has exactly m symbols, equal to "1".
Example
Input
5
3 1
3 2
3 3
4 0
5 2
Output
4
5
6
0
12
Note
In the first test case, there exists only 3 strings of length 3, which has exactly 1 symbol, equal to "1". These strings are: s_1 = "100", s_2 = "010", s_3 = "001". The values of f for them are: f(s_1) = 3, f(s_2) = 4, f(s_3) = 3, so the maximum value is 4 and the answer is 4.
In the second test case, the string s with the maximum value is "101".
In the third test case, the string s with the maximum value is "111".
In the fourth test case, the only string s of length 4, which has exactly 0 symbols, equal to "1" is "0000" and the value of f for that string is 0, so the answer is 0.
In the fifth test case, the string s with the maximum value is "01010" and it is described as an example in the problem statement.
Tags: binary search, combinatorics, greedy, math, strings
Correct Solution:
```
"""
// Author : snape_here - Susanta Mukherjee
"""
from __future__ import division, print_function
import os,sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
def ii(): return int(input())
def si(): return input()
def mi(): return map(int,input().split())
def li(): return list(mi())
def gcd(x, y):
while y:
x, y = y, x % y
return x
def read():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
import math
mod=1000000007
def day(d, m, y):
t = [ 0, 3, 2, 5, 0, 3,
5, 1, 4, 6, 2, 4 ]
y -= m < 3
return (( y + int(y / 4) - int(y / 100)
+ int(y / 400) + t[m - 1] + d) % 7)
def isl(y):
if y%400==0:
return True
elif y%4==0 and y%100!=0:
return True
return False
def main():
for i in range(ii()):
n,m=mi()
if m==0:
ans=0
else:
tot=(n*(n+1))//2
s=(n-m)//(m+1)
b=(m+1-(n-m)%(m+1))*s*(s+1)//2 + ((n-m)%(m+1))*(s+1)*(s+2)//2
ans=tot-b
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")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
#read()
main()
#Comment read()
```
| 104,560 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ayoub thinks that he is a very smart person, so he created a function f(s), where s is a binary string (a string which contains only symbols "0" and "1"). The function f(s) is equal to the number of substrings in the string s that contains at least one symbol, that is equal to "1".
More formally, f(s) is equal to the number of pairs of integers (l, r), such that 1 ≤ l ≤ r ≤ |s| (where |s| is equal to the length of string s), such that at least one of the symbols s_l, s_{l+1}, …, s_r is equal to "1".
For example, if s = "01010" then f(s) = 12, because there are 12 such pairs (l, r): (1, 2), (1, 3), (1, 4), (1, 5), (2, 2), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 4), (4, 5).
Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers n and m and asked him this problem. For all binary strings s of length n which contains exactly m symbols equal to "1", find the maximum value of f(s).
Mahmoud couldn't solve the problem so he asked you for help. Can you help him?
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10^5) — the number of test cases. The description of the test cases follows.
The only line for each test case contains two integers n, m (1 ≤ n ≤ 10^{9}, 0 ≤ m ≤ n) — the length of the string and the number of symbols equal to "1" in it.
Output
For every test case print one integer number — the maximum value of f(s) over all strings s of length n, which has exactly m symbols, equal to "1".
Example
Input
5
3 1
3 2
3 3
4 0
5 2
Output
4
5
6
0
12
Note
In the first test case, there exists only 3 strings of length 3, which has exactly 1 symbol, equal to "1". These strings are: s_1 = "100", s_2 = "010", s_3 = "001". The values of f for them are: f(s_1) = 3, f(s_2) = 4, f(s_3) = 3, so the maximum value is 4 and the answer is 4.
In the second test case, the string s with the maximum value is "101".
In the third test case, the string s with the maximum value is "111".
In the fourth test case, the only string s of length 4, which has exactly 0 symbols, equal to "1" is "0000" and the value of f for that string is 0, so the answer is 0.
In the fifth test case, the string s with the maximum value is "01010" and it is described as an example in the problem statement.
Tags: binary search, combinatorics, greedy, math, strings
Correct Solution:
```
import sys
inf = 1 << 64
def input():
return sys.stdin.readline().rstrip()
def slv():
n, m = map(int, input().split())
u, v = divmod(n - m, m + 1)
ans = n * (n + 1)//2 - v*(u + 1)*(u + 2)//2 - (m + 1 - v)*u*(u + 1)//2
print(ans)
return
t = int(input())
for i in range(t):
slv()
```
| 104,561 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ayoub thinks that he is a very smart person, so he created a function f(s), where s is a binary string (a string which contains only symbols "0" and "1"). The function f(s) is equal to the number of substrings in the string s that contains at least one symbol, that is equal to "1".
More formally, f(s) is equal to the number of pairs of integers (l, r), such that 1 ≤ l ≤ r ≤ |s| (where |s| is equal to the length of string s), such that at least one of the symbols s_l, s_{l+1}, …, s_r is equal to "1".
For example, if s = "01010" then f(s) = 12, because there are 12 such pairs (l, r): (1, 2), (1, 3), (1, 4), (1, 5), (2, 2), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 4), (4, 5).
Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers n and m and asked him this problem. For all binary strings s of length n which contains exactly m symbols equal to "1", find the maximum value of f(s).
Mahmoud couldn't solve the problem so he asked you for help. Can you help him?
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10^5) — the number of test cases. The description of the test cases follows.
The only line for each test case contains two integers n, m (1 ≤ n ≤ 10^{9}, 0 ≤ m ≤ n) — the length of the string and the number of symbols equal to "1" in it.
Output
For every test case print one integer number — the maximum value of f(s) over all strings s of length n, which has exactly m symbols, equal to "1".
Example
Input
5
3 1
3 2
3 3
4 0
5 2
Output
4
5
6
0
12
Note
In the first test case, there exists only 3 strings of length 3, which has exactly 1 symbol, equal to "1". These strings are: s_1 = "100", s_2 = "010", s_3 = "001". The values of f for them are: f(s_1) = 3, f(s_2) = 4, f(s_3) = 3, so the maximum value is 4 and the answer is 4.
In the second test case, the string s with the maximum value is "101".
In the third test case, the string s with the maximum value is "111".
In the fourth test case, the only string s of length 4, which has exactly 0 symbols, equal to "1" is "0000" and the value of f for that string is 0, so the answer is 0.
In the fifth test case, the string s with the maximum value is "01010" and it is described as an example in the problem statement.
Tags: binary search, combinatorics, greedy, math, strings
Correct Solution:
```
import sys
input=sys.stdin.readline
t=int(input())
for i in range(t):
n,m=map(int,input().split())
zeros=n-m
if zeros==0:
print((n*(n+1))//2)
else:
div=zeros//(m+1)
rem=zeros%(m+1)
print(n*(n+1)//2-rem*(div+1)*(div+2)//2-(m+1-rem)*((div+1)*div)//2)
```
| 104,562 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ayoub thinks that he is a very smart person, so he created a function f(s), where s is a binary string (a string which contains only symbols "0" and "1"). The function f(s) is equal to the number of substrings in the string s that contains at least one symbol, that is equal to "1".
More formally, f(s) is equal to the number of pairs of integers (l, r), such that 1 ≤ l ≤ r ≤ |s| (where |s| is equal to the length of string s), such that at least one of the symbols s_l, s_{l+1}, …, s_r is equal to "1".
For example, if s = "01010" then f(s) = 12, because there are 12 such pairs (l, r): (1, 2), (1, 3), (1, 4), (1, 5), (2, 2), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 4), (4, 5).
Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers n and m and asked him this problem. For all binary strings s of length n which contains exactly m symbols equal to "1", find the maximum value of f(s).
Mahmoud couldn't solve the problem so he asked you for help. Can you help him?
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10^5) — the number of test cases. The description of the test cases follows.
The only line for each test case contains two integers n, m (1 ≤ n ≤ 10^{9}, 0 ≤ m ≤ n) — the length of the string and the number of symbols equal to "1" in it.
Output
For every test case print one integer number — the maximum value of f(s) over all strings s of length n, which has exactly m symbols, equal to "1".
Example
Input
5
3 1
3 2
3 3
4 0
5 2
Output
4
5
6
0
12
Note
In the first test case, there exists only 3 strings of length 3, which has exactly 1 symbol, equal to "1". These strings are: s_1 = "100", s_2 = "010", s_3 = "001". The values of f for them are: f(s_1) = 3, f(s_2) = 4, f(s_3) = 3, so the maximum value is 4 and the answer is 4.
In the second test case, the string s with the maximum value is "101".
In the third test case, the string s with the maximum value is "111".
In the fourth test case, the only string s of length 4, which has exactly 0 symbols, equal to "1" is "0000" and the value of f for that string is 0, so the answer is 0.
In the fifth test case, the string s with the maximum value is "01010" and it is described as an example in the problem statement.
Submitted Solution:
```
from sys import stdin, stdout
def total(k): return (k*(k+1)) // 2
ans = []
t= int(stdin.readline())
for line in stdin:
n, m = tuple(map(int,line.split()))
if m==0:
ans.append( str(0) )
else:
al = total(n)
zeros = n-m
#divide into m+1 groups
k, extra = zeros//(m+1), zeros%(m+1)
zero_blocks = extra*(k+1) + (m+1)*total(k)
ans.append(str(al-zero_blocks))
stdout.write('\n'.join(ans))
```
Yes
| 104,563 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ayoub thinks that he is a very smart person, so he created a function f(s), where s is a binary string (a string which contains only symbols "0" and "1"). The function f(s) is equal to the number of substrings in the string s that contains at least one symbol, that is equal to "1".
More formally, f(s) is equal to the number of pairs of integers (l, r), such that 1 ≤ l ≤ r ≤ |s| (where |s| is equal to the length of string s), such that at least one of the symbols s_l, s_{l+1}, …, s_r is equal to "1".
For example, if s = "01010" then f(s) = 12, because there are 12 such pairs (l, r): (1, 2), (1, 3), (1, 4), (1, 5), (2, 2), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 4), (4, 5).
Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers n and m and asked him this problem. For all binary strings s of length n which contains exactly m symbols equal to "1", find the maximum value of f(s).
Mahmoud couldn't solve the problem so he asked you for help. Can you help him?
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10^5) — the number of test cases. The description of the test cases follows.
The only line for each test case contains two integers n, m (1 ≤ n ≤ 10^{9}, 0 ≤ m ≤ n) — the length of the string and the number of symbols equal to "1" in it.
Output
For every test case print one integer number — the maximum value of f(s) over all strings s of length n, which has exactly m symbols, equal to "1".
Example
Input
5
3 1
3 2
3 3
4 0
5 2
Output
4
5
6
0
12
Note
In the first test case, there exists only 3 strings of length 3, which has exactly 1 symbol, equal to "1". These strings are: s_1 = "100", s_2 = "010", s_3 = "001". The values of f for them are: f(s_1) = 3, f(s_2) = 4, f(s_3) = 3, so the maximum value is 4 and the answer is 4.
In the second test case, the string s with the maximum value is "101".
In the third test case, the string s with the maximum value is "111".
In the fourth test case, the only string s of length 4, which has exactly 0 symbols, equal to "1" is "0000" and the value of f for that string is 0, so the answer is 0.
In the fifth test case, the string s with the maximum value is "01010" and it is described as an example in the problem statement.
Submitted Solution:
```
import sys
lines = list(sys.stdin.readlines())
t = int(lines[0])
def count(x):
return x * (x+1)//2
for i in range(t):
n, ones = map(int, lines[i+1].split())
zeros = n - ones
if zeros==0:
print(count(n))
continue
used_ones = min(ones, zeros-1)
groups = used_ones+1
smal_size = zeros//groups
larg_size = smal_size + 1
larg_count = zeros%groups
total = count(n)
total -= count(smal_size) * (groups-larg_count)
total -= count(larg_size) * larg_count
print(total)
```
Yes
| 104,564 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ayoub thinks that he is a very smart person, so he created a function f(s), where s is a binary string (a string which contains only symbols "0" and "1"). The function f(s) is equal to the number of substrings in the string s that contains at least one symbol, that is equal to "1".
More formally, f(s) is equal to the number of pairs of integers (l, r), such that 1 ≤ l ≤ r ≤ |s| (where |s| is equal to the length of string s), such that at least one of the symbols s_l, s_{l+1}, …, s_r is equal to "1".
For example, if s = "01010" then f(s) = 12, because there are 12 such pairs (l, r): (1, 2), (1, 3), (1, 4), (1, 5), (2, 2), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 4), (4, 5).
Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers n and m and asked him this problem. For all binary strings s of length n which contains exactly m symbols equal to "1", find the maximum value of f(s).
Mahmoud couldn't solve the problem so he asked you for help. Can you help him?
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10^5) — the number of test cases. The description of the test cases follows.
The only line for each test case contains two integers n, m (1 ≤ n ≤ 10^{9}, 0 ≤ m ≤ n) — the length of the string and the number of symbols equal to "1" in it.
Output
For every test case print one integer number — the maximum value of f(s) over all strings s of length n, which has exactly m symbols, equal to "1".
Example
Input
5
3 1
3 2
3 3
4 0
5 2
Output
4
5
6
0
12
Note
In the first test case, there exists only 3 strings of length 3, which has exactly 1 symbol, equal to "1". These strings are: s_1 = "100", s_2 = "010", s_3 = "001". The values of f for them are: f(s_1) = 3, f(s_2) = 4, f(s_3) = 3, so the maximum value is 4 and the answer is 4.
In the second test case, the string s with the maximum value is "101".
In the third test case, the string s with the maximum value is "111".
In the fourth test case, the only string s of length 4, which has exactly 0 symbols, equal to "1" is "0000" and the value of f for that string is 0, so the answer is 0.
In the fifth test case, the string s with the maximum value is "01010" and it is described as an example in the problem statement.
Submitted Solution:
```
import sys
def fastio():
from io import StringIO
from atexit import register
global input
sys.stdin = StringIO(sys.stdin.read())
input = lambda : sys.stdin.readline().rstrip('\r\n')
sys.stdout = StringIO()
register(lambda : sys.__stdout__.write(sys.stdout.getvalue()))
fastio()
for _ in range(int(input())):
n,m=list(map(int,input().split()))
l=n if m==0 else (n-2*m if m<=n//2 else 0)
s1=n-m-l
if l==n:
print(0)
else:
p=(n-m)//(m+1);r=(n-m)%(m+1)
k=(n*(n+1))//2-(m+1-r)*(p*(p+1)//2)-r*(p+1)*(p+2)//2
print(k)
```
Yes
| 104,565 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ayoub thinks that he is a very smart person, so he created a function f(s), where s is a binary string (a string which contains only symbols "0" and "1"). The function f(s) is equal to the number of substrings in the string s that contains at least one symbol, that is equal to "1".
More formally, f(s) is equal to the number of pairs of integers (l, r), such that 1 ≤ l ≤ r ≤ |s| (where |s| is equal to the length of string s), such that at least one of the symbols s_l, s_{l+1}, …, s_r is equal to "1".
For example, if s = "01010" then f(s) = 12, because there are 12 such pairs (l, r): (1, 2), (1, 3), (1, 4), (1, 5), (2, 2), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 4), (4, 5).
Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers n and m and asked him this problem. For all binary strings s of length n which contains exactly m symbols equal to "1", find the maximum value of f(s).
Mahmoud couldn't solve the problem so he asked you for help. Can you help him?
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10^5) — the number of test cases. The description of the test cases follows.
The only line for each test case contains two integers n, m (1 ≤ n ≤ 10^{9}, 0 ≤ m ≤ n) — the length of the string and the number of symbols equal to "1" in it.
Output
For every test case print one integer number — the maximum value of f(s) over all strings s of length n, which has exactly m symbols, equal to "1".
Example
Input
5
3 1
3 2
3 3
4 0
5 2
Output
4
5
6
0
12
Note
In the first test case, there exists only 3 strings of length 3, which has exactly 1 symbol, equal to "1". These strings are: s_1 = "100", s_2 = "010", s_3 = "001". The values of f for them are: f(s_1) = 3, f(s_2) = 4, f(s_3) = 3, so the maximum value is 4 and the answer is 4.
In the second test case, the string s with the maximum value is "101".
In the third test case, the string s with the maximum value is "111".
In the fourth test case, the only string s of length 4, which has exactly 0 symbols, equal to "1" is "0000" and the value of f for that string is 0, so the answer is 0.
In the fifth test case, the string s with the maximum value is "01010" and it is described as an example in the problem statement.
Submitted Solution:
```
# import sys
# import math
# from collections import defaultdict,Counter
# input=sys.stdin.readline
# def print(x):
# sys.stdout.write(str(x)+"\n")
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")
# sys.stdout=open("CP3/output.txt",'w')
# sys.stdin=open("CP3/input.txt",'r')
# m=pow(10,9)+7
t=int(input())
for i in range(t):
n,m=map(int,input().split())
if m==0:
print(0)
elif n-m<=m:
print(n*(n+1)//2-(n-m))
else:
d=n-m
k=d//(m+1)
d1=d%(m+1)
print(n*(n+1)//2-(m+1)*(k*(k+1)//2)-(k+1)*d1)
```
Yes
| 104,566 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ayoub thinks that he is a very smart person, so he created a function f(s), where s is a binary string (a string which contains only symbols "0" and "1"). The function f(s) is equal to the number of substrings in the string s that contains at least one symbol, that is equal to "1".
More formally, f(s) is equal to the number of pairs of integers (l, r), such that 1 ≤ l ≤ r ≤ |s| (where |s| is equal to the length of string s), such that at least one of the symbols s_l, s_{l+1}, …, s_r is equal to "1".
For example, if s = "01010" then f(s) = 12, because there are 12 such pairs (l, r): (1, 2), (1, 3), (1, 4), (1, 5), (2, 2), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 4), (4, 5).
Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers n and m and asked him this problem. For all binary strings s of length n which contains exactly m symbols equal to "1", find the maximum value of f(s).
Mahmoud couldn't solve the problem so he asked you for help. Can you help him?
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10^5) — the number of test cases. The description of the test cases follows.
The only line for each test case contains two integers n, m (1 ≤ n ≤ 10^{9}, 0 ≤ m ≤ n) — the length of the string and the number of symbols equal to "1" in it.
Output
For every test case print one integer number — the maximum value of f(s) over all strings s of length n, which has exactly m symbols, equal to "1".
Example
Input
5
3 1
3 2
3 3
4 0
5 2
Output
4
5
6
0
12
Note
In the first test case, there exists only 3 strings of length 3, which has exactly 1 symbol, equal to "1". These strings are: s_1 = "100", s_2 = "010", s_3 = "001". The values of f for them are: f(s_1) = 3, f(s_2) = 4, f(s_3) = 3, so the maximum value is 4 and the answer is 4.
In the second test case, the string s with the maximum value is "101".
In the third test case, the string s with the maximum value is "111".
In the fourth test case, the only string s of length 4, which has exactly 0 symbols, equal to "1" is "0000" and the value of f for that string is 0, so the answer is 0.
In the fifth test case, the string s with the maximum value is "01010" and it is described as an example in the problem statement.
Submitted Solution:
```
import math
def main():
num = int(input())
for _ in range(num):
n, m = map(int, input().split())
if m == 0:
print(0)
continue
b = n - m
a = n // 2
if m == 1:
d = math.ceil(n/2)
ans = d ** 2
elif a < b:
ans = n * (n + 1) // 2
d = math.ceil(n/2)
amari = m - d
ans -= amari * (amari + 1) * 2 + d
else:
ans = n * (n + 1) // 2
ans -= b
print(ans)
main()
```
No
| 104,567 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ayoub thinks that he is a very smart person, so he created a function f(s), where s is a binary string (a string which contains only symbols "0" and "1"). The function f(s) is equal to the number of substrings in the string s that contains at least one symbol, that is equal to "1".
More formally, f(s) is equal to the number of pairs of integers (l, r), such that 1 ≤ l ≤ r ≤ |s| (where |s| is equal to the length of string s), such that at least one of the symbols s_l, s_{l+1}, …, s_r is equal to "1".
For example, if s = "01010" then f(s) = 12, because there are 12 such pairs (l, r): (1, 2), (1, 3), (1, 4), (1, 5), (2, 2), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 4), (4, 5).
Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers n and m and asked him this problem. For all binary strings s of length n which contains exactly m symbols equal to "1", find the maximum value of f(s).
Mahmoud couldn't solve the problem so he asked you for help. Can you help him?
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10^5) — the number of test cases. The description of the test cases follows.
The only line for each test case contains two integers n, m (1 ≤ n ≤ 10^{9}, 0 ≤ m ≤ n) — the length of the string and the number of symbols equal to "1" in it.
Output
For every test case print one integer number — the maximum value of f(s) over all strings s of length n, which has exactly m symbols, equal to "1".
Example
Input
5
3 1
3 2
3 3
4 0
5 2
Output
4
5
6
0
12
Note
In the first test case, there exists only 3 strings of length 3, which has exactly 1 symbol, equal to "1". These strings are: s_1 = "100", s_2 = "010", s_3 = "001". The values of f for them are: f(s_1) = 3, f(s_2) = 4, f(s_3) = 3, so the maximum value is 4 and the answer is 4.
In the second test case, the string s with the maximum value is "101".
In the third test case, the string s with the maximum value is "111".
In the fourth test case, the only string s of length 4, which has exactly 0 symbols, equal to "1" is "0000" and the value of f for that string is 0, so the answer is 0.
In the fifth test case, the string s with the maximum value is "01010" and it is described as an example in the problem statement.
Submitted Solution:
```
def solve_c():
n = int(input())
for _ in range(n):
c()
def c():
n, m = [int(x) for x in input().split()]
if m == 0:
print(0)
return
if m == 1:
print(2*n-2)
else:
print(n*(n+1)//2+m-n)
solve_c()
```
No
| 104,568 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ayoub thinks that he is a very smart person, so he created a function f(s), where s is a binary string (a string which contains only symbols "0" and "1"). The function f(s) is equal to the number of substrings in the string s that contains at least one symbol, that is equal to "1".
More formally, f(s) is equal to the number of pairs of integers (l, r), such that 1 ≤ l ≤ r ≤ |s| (where |s| is equal to the length of string s), such that at least one of the symbols s_l, s_{l+1}, …, s_r is equal to "1".
For example, if s = "01010" then f(s) = 12, because there are 12 such pairs (l, r): (1, 2), (1, 3), (1, 4), (1, 5), (2, 2), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 4), (4, 5).
Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers n and m and asked him this problem. For all binary strings s of length n which contains exactly m symbols equal to "1", find the maximum value of f(s).
Mahmoud couldn't solve the problem so he asked you for help. Can you help him?
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10^5) — the number of test cases. The description of the test cases follows.
The only line for each test case contains two integers n, m (1 ≤ n ≤ 10^{9}, 0 ≤ m ≤ n) — the length of the string and the number of symbols equal to "1" in it.
Output
For every test case print one integer number — the maximum value of f(s) over all strings s of length n, which has exactly m symbols, equal to "1".
Example
Input
5
3 1
3 2
3 3
4 0
5 2
Output
4
5
6
0
12
Note
In the first test case, there exists only 3 strings of length 3, which has exactly 1 symbol, equal to "1". These strings are: s_1 = "100", s_2 = "010", s_3 = "001". The values of f for them are: f(s_1) = 3, f(s_2) = 4, f(s_3) = 3, so the maximum value is 4 and the answer is 4.
In the second test case, the string s with the maximum value is "101".
In the third test case, the string s with the maximum value is "111".
In the fourth test case, the only string s of length 4, which has exactly 0 symbols, equal to "1" is "0000" and the value of f for that string is 0, so the answer is 0.
In the fifth test case, the string s with the maximum value is "01010" and it is described as an example in the problem statement.
Submitted Solution:
```
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub
sys.setrecursionlimit(100000)
input = sys.stdin.readline # -*- coding: utf-8 -*-
sys.setrecursionlimit(100000)
input = sys.stdin.readline
INF = 2**62-1
def read_int():
return int(input())
def read_int_n():
return list(map(int, input().split()))
def read_float():
return float(input())
def read_float_n():
return list(map(float, input().split()))
def read_str():
return input().strip()
def read_str_n():
return list(map(str, input().split()))
def error_print(*args):
print(*args, file=sys.stderr)
def mt(f):
import time
def wrap(*args, **kwargs):
s = time.time()
ret = f(*args, **kwargs)
e = time.time()
error_print(e - s, 'sec')
return ret
return wrap
def slv(N, M):
if M == 0:
return 0
if M == N:
return ((N+1) * N ) // 2
ans = ((N+1) * N) // 2
r = N - M
d = r // (M+1)
e = r % (M+1)
if d != 0:
ans -= (((d+1) * d) // 2) * (M+1 - e)
ans -= (((d-1) * d) // 2) * (e)
else:
ans -= r
return ans
def main():
T = read_int()
for _ in range(T):
N, M = read_int_n()
print(slv(N, M))
if __name__ == "__main__":
main()
```
No
| 104,569 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ayoub thinks that he is a very smart person, so he created a function f(s), where s is a binary string (a string which contains only symbols "0" and "1"). The function f(s) is equal to the number of substrings in the string s that contains at least one symbol, that is equal to "1".
More formally, f(s) is equal to the number of pairs of integers (l, r), such that 1 ≤ l ≤ r ≤ |s| (where |s| is equal to the length of string s), such that at least one of the symbols s_l, s_{l+1}, …, s_r is equal to "1".
For example, if s = "01010" then f(s) = 12, because there are 12 such pairs (l, r): (1, 2), (1, 3), (1, 4), (1, 5), (2, 2), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 4), (4, 5).
Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers n and m and asked him this problem. For all binary strings s of length n which contains exactly m symbols equal to "1", find the maximum value of f(s).
Mahmoud couldn't solve the problem so he asked you for help. Can you help him?
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10^5) — the number of test cases. The description of the test cases follows.
The only line for each test case contains two integers n, m (1 ≤ n ≤ 10^{9}, 0 ≤ m ≤ n) — the length of the string and the number of symbols equal to "1" in it.
Output
For every test case print one integer number — the maximum value of f(s) over all strings s of length n, which has exactly m symbols, equal to "1".
Example
Input
5
3 1
3 2
3 3
4 0
5 2
Output
4
5
6
0
12
Note
In the first test case, there exists only 3 strings of length 3, which has exactly 1 symbol, equal to "1". These strings are: s_1 = "100", s_2 = "010", s_3 = "001". The values of f for them are: f(s_1) = 3, f(s_2) = 4, f(s_3) = 3, so the maximum value is 4 and the answer is 4.
In the second test case, the string s with the maximum value is "101".
In the third test case, the string s with the maximum value is "111".
In the fourth test case, the only string s of length 4, which has exactly 0 symbols, equal to "1" is "0000" and the value of f for that string is 0, so the answer is 0.
In the fifth test case, the string s with the maximum value is "01010" and it is described as an example in the problem statement.
Submitted Solution:
```
"""
Author : thekushalghosh
Team : CodeDiggers
"""
import sys,math
input = sys.stdin.readline
############ ---- USER DEFINED INPUT FUNCTIONS ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(s[:len(s) - 1])
def invr():
return(map(int,input().split()))
################################################################
############ ---- THE ACTUAL CODE STARTS BELOW ---- ############
t = 1
t = inp()
def qw(n):
return(n * (n + 1) // 2)
for tt in range(t):
n,m = invr()
q = n - m
if m == 0:
print(0)
continue
ww = (n * (n + 1) // 2)
w = q % ww
qq = q // ww
ww = ww - (w * qw(qq + 1)) - ((m + 1 - w) * qw(qq))
print(ww)
```
No
| 104,570 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold:
* Every label is an integer between 0 and n-2 inclusive.
* All the written labels are distinct.
* The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible.
Here, MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node u to node v.
Input
The first line contains the integer n (2 ≤ n ≤ 10^5) — the number of nodes in the tree.
Each of the next n-1 lines contains two space-separated integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree.
Output
Output n-1 integers. The i^{th} of them will be the number written on the i^{th} edge (in the input order).
Examples
Input
3
1 2
1 3
Output
0
1
Input
6
1 2
1 3
2 4
2 5
5 6
Output
0
3
2
4
1
Note
The tree from the second sample:
<image>
Tags: constructive algorithms, dfs and similar, greedy, trees
Correct Solution:
```
from sys import stdin
try:
n=int(stdin.readline().rstrip())
l=[0]*(n+1)
arr=[]
for _ in range(n-1):
u,v=map(int,stdin.readline().rstrip().split())
arr.append((u,v))
l[u]+=1
l[v]+=1
x,y=0,n-2
for u,v in arr:
if l[u]==1 or l[v]==1:
print(x)
x+=1
else:
print(y)
y-=1
except:
pass
```
| 104,571 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold:
* Every label is an integer between 0 and n-2 inclusive.
* All the written labels are distinct.
* The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible.
Here, MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node u to node v.
Input
The first line contains the integer n (2 ≤ n ≤ 10^5) — the number of nodes in the tree.
Each of the next n-1 lines contains two space-separated integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree.
Output
Output n-1 integers. The i^{th} of them will be the number written on the i^{th} edge (in the input order).
Examples
Input
3
1 2
1 3
Output
0
1
Input
6
1 2
1 3
2 4
2 5
5 6
Output
0
3
2
4
1
Note
The tree from the second sample:
<image>
Tags: constructive algorithms, dfs and similar, greedy, trees
Correct Solution:
```
def solve(graph):
ans = [-1 for i in range(len(graph) - 1)]
for v in graph:
if len(graph[v]) > 2:
for i, (u, k) in enumerate(graph[v][:3]):
ans[k] = i
k = 0
for i in range(3, len(ans)):
while ans[k] != -1:
k += 1
ans[k] = i
return ans
return list(range(len(graph) - 1))
def test():
g1 = {1: [(2, 0), (3, 1)], 2: [(1, 0)], 3: [(1, 1)]}
s1 = solve(g1)
print(s1)
assert s1 == [0, 1]
g2 = {1: [(2, 0), (3, 1)], 2: [(1, 0), (4, 2), (5, 3)], 3: [(1, 1)], 4: [(2, 2)], 5: [(2, 3), (6, 5)], 6: [(5, 5)]}
s2 = solve(g2)
print(s2)
assert s2 == [0, 3, 1, 2, 4]
if __name__ == '__main__':
# test()
n = int(input())
graph = {i : [] for i in range(1, n + 1)}
edges = []
for i in range(n - 1):
u, v = [int(c) for c in input().split()]
graph[u].append((v, i))
graph[v].append((u, i))
ans = solve(graph)
print(*ans, sep='\n')
```
| 104,572 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold:
* Every label is an integer between 0 and n-2 inclusive.
* All the written labels are distinct.
* The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible.
Here, MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node u to node v.
Input
The first line contains the integer n (2 ≤ n ≤ 10^5) — the number of nodes in the tree.
Each of the next n-1 lines contains two space-separated integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree.
Output
Output n-1 integers. The i^{th} of them will be the number written on the i^{th} edge (in the input order).
Examples
Input
3
1 2
1 3
Output
0
1
Input
6
1 2
1 3
2 4
2 5
5 6
Output
0
3
2
4
1
Note
The tree from the second sample:
<image>
Tags: constructive algorithms, dfs and similar, greedy, trees
Correct Solution:
```
#!/usr/bin/env python
# coding: utf-8
# In[83]:
n = int(input())
edges = []
degrees = [0]
for i in range(n):
degrees.append(0)
# In[84]:
output = []
for i in range(n-1):
output.append(-1)
# In[85]:
def d3():
d3_vertex = 0
for i in range(n+1):
if ( degrees[i] > 2 ):
d3_vertex = i
return d3_vertex
# In[86]:
for i in range (n-1):
inp = input().split()
inp = [int(i) for i in inp]
inp.sort()
edges.append(inp)
degrees[inp[0]]= degrees[inp[0]] +1
degrees[inp[1]]= degrees[inp[1]] +1
# In[91]:
f = d3()
if (f > 0):
u = 0;
for i in range(n-1):
if(edges[i][0]==f or edges[i][1]==f):
output[i] = u
u = u+1
for i in range(n-1):
if(output[i]==-1):
output[i] = u
u = u+1
for i in range(n-1):
print(output[i])
else:
for i in range(n-1):
print(i)
# In[ ]:
```
| 104,573 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold:
* Every label is an integer between 0 and n-2 inclusive.
* All the written labels are distinct.
* The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible.
Here, MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node u to node v.
Input
The first line contains the integer n (2 ≤ n ≤ 10^5) — the number of nodes in the tree.
Each of the next n-1 lines contains two space-separated integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree.
Output
Output n-1 integers. The i^{th} of them will be the number written on the i^{th} edge (in the input order).
Examples
Input
3
1 2
1 3
Output
0
1
Input
6
1 2
1 3
2 4
2 5
5 6
Output
0
3
2
4
1
Note
The tree from the second sample:
<image>
Tags: constructive algorithms, dfs and similar, greedy, trees
Correct Solution:
```
"""
Template written to be used by Python Programmers.
Use at your own risk!!!!
Owned by enraged(rating - 5 star at CodeChef and Specialist at Codeforces).
"""
import sys
import heapq
from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt
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
# sys.setrecursionlimit(2*pow(10, 6))
# sys.stdin = open("input.txt", "r")
# sys.stdout = open("output.txt", "w")
mod = pow(10, 9) + 7
mod2 = 998244353
def data(): return sys.stdin.readline().strip()
def out(var): sys.stdout.write(str(var))
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 [[val for i in range(n)] for j in range(m)]
def maxDeg():
for i in graph.keys():
if len(graph[i]) >= 3:
return i
return 0
n = int(data())
graph = dd(set)
mat = []
for i in range(n-1):
a, b = sp()
mat.append((a, b))
graph[a].add(b)
graph[b].add(a)
m = maxDeg()
dist, length, j = len(graph[m])-1, len(graph[m])-1, 1
for i in mat:
if i[0] == m and dist >= 0:
out(str(length-dist)+"\n")
dist -= 1
elif i[1] == m and dist >= 0:
out(str(length-dist)+"\n")
dist -= 1
else:
out(str(length+j)+"\n")
j += 1
```
| 104,574 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold:
* Every label is an integer between 0 and n-2 inclusive.
* All the written labels are distinct.
* The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible.
Here, MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node u to node v.
Input
The first line contains the integer n (2 ≤ n ≤ 10^5) — the number of nodes in the tree.
Each of the next n-1 lines contains two space-separated integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree.
Output
Output n-1 integers. The i^{th} of them will be the number written on the i^{th} edge (in the input order).
Examples
Input
3
1 2
1 3
Output
0
1
Input
6
1 2
1 3
2 4
2 5
5 6
Output
0
3
2
4
1
Note
The tree from the second sample:
<image>
Tags: constructive algorithms, dfs and similar, greedy, trees
Correct Solution:
```
#!/usr/bin/env python
from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
import collections
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
def solution():
n = int(input().strip())
d = collections.defaultdict(int)
e = []
for _ in range(n-1):
i, j = [int(x) for x in input().strip().split(" ")]
e.append((i, j))
d[i] += 1
d[j] += 1
need = min(3, list(d.values()).count(1))
if need == 2:
for i in range(n-1):
print(i)
else:
cur = 3
for x in e:
if d[x[0]] == 1 or d[x[1]] == 1:
if need == 3:
print(0)
need -= 1
elif need == 2:
print(1)
need -= 1
elif need == 1:
print(2)
need -= 1
else:
print(cur)
cur += 1
else:
print(cur)
cur += 1
def main():
# T = int(input().strip())
for _ in range(1):
solution()
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
```
| 104,575 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold:
* Every label is an integer between 0 and n-2 inclusive.
* All the written labels are distinct.
* The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible.
Here, MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node u to node v.
Input
The first line contains the integer n (2 ≤ n ≤ 10^5) — the number of nodes in the tree.
Each of the next n-1 lines contains two space-separated integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree.
Output
Output n-1 integers. The i^{th} of them will be the number written on the i^{th} edge (in the input order).
Examples
Input
3
1 2
1 3
Output
0
1
Input
6
1 2
1 3
2 4
2 5
5 6
Output
0
3
2
4
1
Note
The tree from the second sample:
<image>
Tags: constructive algorithms, dfs and similar, greedy, trees
Correct Solution:
```
n = int(input())
deg = [0]*(n+2)
es = []
for i in range(n-1):
a,b = list(map(int, input().split()))
deg[a]+=1
deg[b]+=1
es.append((a,b))
if max(deg)==2:
for i in range(n-1):
print(i)
else:
k = deg.index(max(deg))
e_012 = 0
cnt = 3
for e in es:
if k in e and e_012 < 3:
print(e_012)
e_012+=1
else:
print(cnt)
cnt+=1
```
| 104,576 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold:
* Every label is an integer between 0 and n-2 inclusive.
* All the written labels are distinct.
* The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible.
Here, MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node u to node v.
Input
The first line contains the integer n (2 ≤ n ≤ 10^5) — the number of nodes in the tree.
Each of the next n-1 lines contains two space-separated integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree.
Output
Output n-1 integers. The i^{th} of them will be the number written on the i^{th} edge (in the input order).
Examples
Input
3
1 2
1 3
Output
0
1
Input
6
1 2
1 3
2 4
2 5
5 6
Output
0
3
2
4
1
Note
The tree from the second sample:
<image>
Tags: constructive algorithms, dfs and similar, greedy, trees
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 --------------------
n=int(input())
graph=[[] for s in range(n)]
inds={}
leaf=set([])
for s in range(n-1):
u,v=map(int,input().split())
u-=1
v-=1
inds[(u,v)]=s
inds[(v,u)]=s
graph[u].append(v)
graph[v].append(u)
if len(graph[u])==1:
leaf.add(u)
else:
if u in leaf:
leaf.remove(u)
if len(graph[v])==1:
leaf.add(v)
else:
if v in leaf:
leaf.remove(v)
ans=[-1 for s in range(n-1)]
cv=0
if len(leaf)>=3:
while len(leaf)>0:
v0=leaf.pop()
v1=graph[v0][0]
ind=inds[(v0,v1)]
ans[ind]=cv
cv+=1
for s in range(n-1):
if ans[s-1]==-1:
ans[s-1]=cv
cv+=1
else:
#then u can really do much
for s in range(n-1):
ans[s]=s
for s in range(n-1):
print(ans[s])
```
| 104,577 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold:
* Every label is an integer between 0 and n-2 inclusive.
* All the written labels are distinct.
* The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible.
Here, MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node u to node v.
Input
The first line contains the integer n (2 ≤ n ≤ 10^5) — the number of nodes in the tree.
Each of the next n-1 lines contains two space-separated integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree.
Output
Output n-1 integers. The i^{th} of them will be the number written on the i^{th} edge (in the input order).
Examples
Input
3
1 2
1 3
Output
0
1
Input
6
1 2
1 3
2 4
2 5
5 6
Output
0
3
2
4
1
Note
The tree from the second sample:
<image>
Tags: constructive algorithms, dfs and similar, greedy, trees
Correct Solution:
```
def solve(n, queries):
node = 0
count = [0] * (n + 1)
for u, v in queries:
count[u] += 1
count[v] += 1
if count[u] == 3:
node = u
if count[v] == 3:
node = v
j = 0
ans = [-1] * len(queries)
for i, pair in enumerate(queries):
if node in pair:
ans[i] = j
j += 1
for i in range(len(queries)):
if ans[i] != -1:
continue
ans[i] = j
j += 1
for i in ans:
print(i)
def smain():
inp = lambda: [int(x) for x in input().split()]
n = int(input())
queries = [inp() for _ in range(n - 1)]
solve(n, queries)
if __name__ == '__main__':
smain()
```
| 104,578 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold:
* Every label is an integer between 0 and n-2 inclusive.
* All the written labels are distinct.
* The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible.
Here, MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node u to node v.
Input
The first line contains the integer n (2 ≤ n ≤ 10^5) — the number of nodes in the tree.
Each of the next n-1 lines contains two space-separated integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree.
Output
Output n-1 integers. The i^{th} of them will be the number written on the i^{th} edge (in the input order).
Examples
Input
3
1 2
1 3
Output
0
1
Input
6
1 2
1 3
2 4
2 5
5 6
Output
0
3
2
4
1
Note
The tree from the second sample:
<image>
Submitted Solution:
```
MOD = 1000000007
MOD2 = 998244353
ii = lambda: int(input())
si = lambda: input()
dgl = lambda: list(map(int, input()))
f = lambda: map(int, input().split())
il = lambda: list(map(int, input().split()))
ls = lambda: list(input())
let = '@abcdefghijklmnopqrstuvwxyz'
n=ii()
deg=[0]*(10**5+10)
l=[]
it1,it2=0,n-2
for _ in range(n-1):
x,y=f()
deg[x]+=1
deg[y]+=1
l.append([x,y])
for i in l:
if deg[i[0]]==1 or deg[i[1]]==1:
print(it1)
it1+=1
else:
print(it2)
it2-=1
```
Yes
| 104,579 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold:
* Every label is an integer between 0 and n-2 inclusive.
* All the written labels are distinct.
* The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible.
Here, MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node u to node v.
Input
The first line contains the integer n (2 ≤ n ≤ 10^5) — the number of nodes in the tree.
Each of the next n-1 lines contains two space-separated integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree.
Output
Output n-1 integers. The i^{th} of them will be the number written on the i^{th} edge (in the input order).
Examples
Input
3
1 2
1 3
Output
0
1
Input
6
1 2
1 3
2 4
2 5
5 6
Output
0
3
2
4
1
Note
The tree from the second sample:
<image>
Submitted Solution:
```
n = int(input())
degree = [0] * (n + 1)
order = []
for _ in range(n-1):
x, y = map(int, input().split())
degree[x] += 1
degree[y] += 1
order.append((x, y))
res1 = 0; res2 = n-2
k = 0
for d in range(n+1):
if degree[d] >= 3:
k = d
break
for x, y in order:
if x == k or y == k:
print(res1)
res1 += 1
else:
print(res2)
res2 -= 1
```
Yes
| 104,580 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold:
* Every label is an integer between 0 and n-2 inclusive.
* All the written labels are distinct.
* The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible.
Here, MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node u to node v.
Input
The first line contains the integer n (2 ≤ n ≤ 10^5) — the number of nodes in the tree.
Each of the next n-1 lines contains two space-separated integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree.
Output
Output n-1 integers. The i^{th} of them will be the number written on the i^{th} edge (in the input order).
Examples
Input
3
1 2
1 3
Output
0
1
Input
6
1 2
1 3
2 4
2 5
5 6
Output
0
3
2
4
1
Note
The tree from the second sample:
<image>
Submitted Solution:
```
''' Ehab and Path-etic MEXs - spoiled by mzy
'''
''' routine '''
N = int(input())
leaves = {}
edges = [0 for i in range(N)]
for edge in range(N - 1):
a, b = list(map(int, input().split()))
for node in (a, b):
edges[node - 1] += 1
if edges[node - 1] == 1:
leaves[node] = edge
elif edges[node - 1] == 2:
del leaves[node]
if len(leaves) < 3:
for n in range(N - 1):
print(n)
else:
start = 3
leaf = 0
specials = list(leaves.values())[:3]
for edge in range(N - 1):
if edge in specials:
print(leaf)
leaf += 1
else:
print(start)
start += 1
# print(specials)
```
Yes
| 104,581 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold:
* Every label is an integer between 0 and n-2 inclusive.
* All the written labels are distinct.
* The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible.
Here, MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node u to node v.
Input
The first line contains the integer n (2 ≤ n ≤ 10^5) — the number of nodes in the tree.
Each of the next n-1 lines contains two space-separated integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree.
Output
Output n-1 integers. The i^{th} of them will be the number written on the i^{th} edge (in the input order).
Examples
Input
3
1 2
1 3
Output
0
1
Input
6
1 2
1 3
2 4
2 5
5 6
Output
0
3
2
4
1
Note
The tree from the second sample:
<image>
Submitted Solution:
```
import math,sys,bisect,heapq
from collections import defaultdict,Counter,deque
from itertools import groupby,accumulate
from functools import lru_cache
#sys.setrecursionlimit(200000000)
int1 = lambda x: int(x) - 1
#def input(): return sys.stdin.readline().strip()m
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
aj = lambda: list(map(int, input().split()))
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
#MOD = 1000000000 + 7
def Y(c): print(["NO","YES"][c])
def y(c): print(["no","yes"][c])
def Yy(c): print(["No","Yes"][c])
G = defaultdict(list)
C = Counter()
order = []
def addEdge(a,b):
G[a].append(b)
G[b].append(a)
C[a] += 1
C[b] += 1
order.append((a,b))
n, = aj()
for i in range(n-1):
a,b = aj()
addEdge(a,b)
# print(C)
# print(G)
E = []
for i in C.keys():
E.append((C[i],i))
E.sort()
mark = {}
p = 0
for i,j in E:
for l in G[j]:
if mark.get((j,l),-1) == -1:
mark[(j,l)] = p
mark[(l,j)] = p
p+=1
for i in order:
print(mark[i])
```
Yes
| 104,582 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold:
* Every label is an integer between 0 and n-2 inclusive.
* All the written labels are distinct.
* The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible.
Here, MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node u to node v.
Input
The first line contains the integer n (2 ≤ n ≤ 10^5) — the number of nodes in the tree.
Each of the next n-1 lines contains two space-separated integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree.
Output
Output n-1 integers. The i^{th} of them will be the number written on the i^{th} edge (in the input order).
Examples
Input
3
1 2
1 3
Output
0
1
Input
6
1 2
1 3
2 4
2 5
5 6
Output
0
3
2
4
1
Note
The tree from the second sample:
<image>
Submitted Solution:
```
import math
import fractions
def make_divisors(n):
divisors = []
for i in range(1, int(n**0.5)+1):
if n % i == 0:
divisors.append(i)
if i != n // i:
divisors.append(n//i)
# divisors.sort()
return divisors
def ValueToBits(x,digit):
res = [0 for i in range(digit)]
now = x
for i in range(digit):
res[i]=now%2
now = now >> 1
return res
def BitsToValue(arr):
n = len(arr)
ans = 0
for i in range(n):
ans+= arr[i] * 2**i
return ans
def ValueToArray10(x, digit):
ans = [0 for i in range(digit)]
now = x
for i in range(digit):
ans[digit-i-1] = now%10
now = now //10
return ans
'''
def cmb(n, r, p):
if (r < 0) or (n < r):
return 0
r = min(r, n - r)
return fact[n] * factinv[r] * factinv[n-r] % p
p = 10 ** 9 + 7
N = 10 ** 6 + 2
fact = [1, 1] # fact[n] = (n! mod p)
factinv = [1, 1] # factinv[n] = ((n!)^(-1) mod p)
inv = [0, 1] # factinv 計算用
for i in range(2, N + 1):
fact.append((fact[-1] * i) % p)
inv.append((-inv[p % i] * (p // i)) % p)
factinv.append((factinv[-1] * inv[-1]) % p)
'''
#a = list(map(int, input().split()))
n = int(input())
nb = [[] for i in range(n)]
nbe = [[] for i in range(n)]
es = []
for i in range(n-1):
a,b = list(map(int, input().split()))
a -= 1
b -= 1
es.append([a,b])
nb[a].append(b)
nb[b].append(a)
nbe[a].append(i)
nbe[b].append(i)
start=-1
for i in range(n):
if(len(nb[i])==1):
start=i
break
queue=[start]
done=0
checked=[0 for i in range(n)]
checked[start] = 1
u = -1
v = -1
w = -1
while(True):
#print(queue,done)
if(len(queue)==done):
#print("b")
break
else:
now = queue[done]
nownb = nb[now]
#print("a",now,nownb,done)
if(len(nownb)<=2):
for j in range(len(nownb)):
if(checked[nownb[j]]==0):
queue.append(nownb[j])
checked[nownb[j]]=1
done+=1
else:
u = nbe[now][0]
v = nbe[now][1]
w = nbe[now][2]
break
#print(u,v,w)
print(checked)
ans = [0 for i in range(n-1)]
now = 3
if(u!=-1):
for i in range(n-1):
if(i==u):
print(0)
elif(i==v):
print(1)
elif(i==w):
print(2)
else:
print(now)
now+=1
else:
for i in range(n-1):
print(i)
```
No
| 104,583 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold:
* Every label is an integer between 0 and n-2 inclusive.
* All the written labels are distinct.
* The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible.
Here, MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node u to node v.
Input
The first line contains the integer n (2 ≤ n ≤ 10^5) — the number of nodes in the tree.
Each of the next n-1 lines contains two space-separated integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree.
Output
Output n-1 integers. The i^{th} of them will be the number written on the i^{th} edge (in the input order).
Examples
Input
3
1 2
1 3
Output
0
1
Input
6
1 2
1 3
2 4
2 5
5 6
Output
0
3
2
4
1
Note
The tree from the second sample:
<image>
Submitted Solution:
```
from sys import stdin
from collections import defaultdict
input = stdin.readline
def read_tuple(): return map(int,input().split())
def read_int(): return int(input())
def read_list(): return list(map(int,input().split()))
def read_str_list(): return list(input().split())
n = read_int()
tree = defaultdict(list)
queries = []
for _ in range(n-1):
u,v = read_tuple()
tree[u].append(v)
tree[v].append(u)
if u>v: u,v = v,u
queries.append( (u,v) )
ans = defaultdict(int)
mex = 0
for u in range(1,n+1):
if len(tree[u]) == 1:
v = tree[u][0]
if u>v: ans[ (v,u) ] = mex
else: ans[ (u,v) ] = mex
mex+=1
for u,v in queries:
val = ans.get( (u,v), -1 )
if val==-1:
print(mex)
mex+=1
else:
print(val)
```
No
| 104,584 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold:
* Every label is an integer between 0 and n-2 inclusive.
* All the written labels are distinct.
* The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible.
Here, MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node u to node v.
Input
The first line contains the integer n (2 ≤ n ≤ 10^5) — the number of nodes in the tree.
Each of the next n-1 lines contains two space-separated integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree.
Output
Output n-1 integers. The i^{th} of them will be the number written on the i^{th} edge (in the input order).
Examples
Input
3
1 2
1 3
Output
0
1
Input
6
1 2
1 3
2 4
2 5
5 6
Output
0
3
2
4
1
Note
The tree from the second sample:
<image>
Submitted Solution:
```
n = int(input())
tree = [0] * (n+1)
edges = []
for i in range(n-1):
u, v = map(int, input().split())
edges.append((u, v))
tree[u] += 1
tree[v] += 1
left = 0
right = n-2
for u, v in edges:
if tree[u] != 1 and tree[v] != 1:
print(left)
left += 1
else:
print(right)
right -= 1
```
No
| 104,585 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold:
* Every label is an integer between 0 and n-2 inclusive.
* All the written labels are distinct.
* The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible.
Here, MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node u to node v.
Input
The first line contains the integer n (2 ≤ n ≤ 10^5) — the number of nodes in the tree.
Each of the next n-1 lines contains two space-separated integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree.
Output
Output n-1 integers. The i^{th} of them will be the number written on the i^{th} edge (in the input order).
Examples
Input
3
1 2
1 3
Output
0
1
Input
6
1 2
1 3
2 4
2 5
5 6
Output
0
3
2
4
1
Note
The tree from the second sample:
<image>
Submitted Solution:
```
import sys
n = int(input())
a = []
b = dict()
num = False
a = list(map(str.strip, sys.stdin))
for i in range(n - 1):
if a[i][0] in b:
b[a[i][0]] += 1
else:
b[a[i][0]] = 1
if a[i][1] in b:
b[a[i][1]] += 1
else:
b[a[i][1]] = 1
if b[a[i][1]] == 3:
num = a[i][1]
break
if b[a[i][0]] == 3:
num = a[i][0]
break
count = 0
count2 = 3
if not num:
for i in range(n - 1):
print(count)
count += 1
else:
for i in range(n - 1):
if (num in a[i]) and (count < 3):
print(count)
count += 1
else:
print(count2)
count2 += 1
```
No
| 104,586 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement.
Tags: constructive algorithms, dfs and similar, dsu, graphs
Correct Solution:
```
import sys
from sys import stdin
from collections import defaultdict
import bisect
import re
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def inputs(f=int):
return list(map(f, stdin.readline().strip().split()))
def fill_dfs_que(map_list, i, j, num):
# dFS
que = [(i, j)]
while que:
# fill center
fill_i, fill_j = que.pop()
map_list[fill_i][fill_j] = num
# fill up
if 0 <= fill_i-1 and map_list[fill_i - 1][fill_j] == '#':
que.append((fill_i-1, fill_j))
# fill down
if fill_i+1 < R and map_list[fill_i + 1][fill_j] == '#':
que.append((fill_i+1, fill_j))
# fill left
if 0 <= fill_j-1 and map_list[fill_i][fill_j - 1] == '#':
que.append((fill_i, fill_j-1))
# fill right
if fill_j+1 < C and map_list[fill_i][fill_j + 1] == '#':
que.append((fill_i, fill_j+1))
def solve(map_all):
# is possible?
# 1. check empty row or col
empty_row = []
for i, row in enumerate(map_all):
if row == "." * C:
empty_row.append(i)
empty_col = []
for i in range(C):
col = "".join([x[i] for x in map_all])
if col == '.' * R:
empty_col.append(i)
if len(empty_row) and len(empty_col)> 0:
# 1-1 if n == max(empty row, empty col) : with place n south magnet
pass
elif empty_col or empty_row:
return -1
# 2. check in-between black cell
for i, row in enumerate(map_all):
ret = re.search(r"#\.+#", row)
if ret is not None:
return -1
for i in range(C):
col = "".join([x[i] for x in map_all])
ret = re.search(r"#\.+#", col)
if ret is not None:
return -1
map_list = [list(x) for x in map_all]
# print(map_list)
# make minimum! one island per each.
island_num = "0"
for i, row in enumerate(map_list):
for j, char in enumerate(row):
if map_list[i][j] == '#':
island_num = str(int(island_num) + 1)
fill_dfs_que(map_list, i, j, island_num)
# print(island_num)
# print(map_list)
return int(island_num)
if __name__ == '__main__':
R, C = inputs()
map_all = []
for i in range(R):
map_row = input()
map_all.append(map_row)
ans = solve(map_all)
print(ans)
```
| 104,587 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement.
Tags: constructive algorithms, dfs and similar, dsu, graphs
Correct Solution:
```
import sys
readline = sys.stdin.readline
H, W = map(int, readline().split())
G = [[1 if s == '#' else 0 for s in readline().strip()] for _ in range(H)]
DIREC = [(0, 1), (1, 0), (-1, 0), (0, -1)]
def calc():
zh = 0
for i in range(H):
cnt = 0
for j in range(W):
if G[i][j]:
if cnt == 0:
cnt = 1
continue
if cnt == 1:
continue
if cnt == 2:
return -1
else:
if cnt == 0:
continue
cnt = 2
if cnt == 0:
zh = 1
zw = 0
for j in range(W):
cnt = 0
for i in range(H):
if G[i][j]:
if cnt == 0:
cnt = 1
continue
if cnt == 1:
continue
if cnt == 2:
return -1
else:
if cnt == 0:
continue
cnt = 2
if cnt == 0:
zw = 1
if zw^zh:
return -1
ans = 0
used = set()
geta = W
for i in range(H):
for j in range(W):
if G[i][j] == 0:
continue
if (i*geta + j) in used:
continue
ans += 1
stack = [i*geta + j]
while stack:
nh, nw = divmod(stack.pop(), geta)
for dh, dw in DIREC:
fh, fw = nh+dh, nw+dw
if not 0 <= fh < H or not 0 <= fw < W:
continue
if not G[fh][fw]:
continue
vf = fh*geta + fw
if vf in used:
continue
stack.append(vf)
used.add(vf)
return ans
print(calc())
```
| 104,588 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement.
Tags: constructive algorithms, dfs and similar, dsu, graphs
Correct Solution:
```
# Author: Uday Gupta
def make_reachable(x, y):
stack = []
stack.append((x, y))
while len(stack):
s = stack[-1]
stack.pop()
i = s[0]
j = s[1]
if reachable_table[i][j] == 0:
reachable_table[i][j] = 1
if i + 1 < n and grid[i + 1][j] == 'B':
if reachable_table[i + 1][j] == 0:
stack.append((i + 1,j))
if i - 1 >= 0 and grid[i - 1][j] == 'B':
if reachable_table[i - 1][j] == 0:
stack.append((i - 1, j))
if j + 1 < m and grid[i][j + 1] == 'B':
if reachable_table[i][j + 1] == 0:
stack.append((i,j + 1))
if j - 1 >= 0 and grid[i][j - 1] == 'B':
if reachable_table[i][j - 1] == 0:
stack.append((i,j - 1))
n, m = list(map(int, input().split()))
grid = []
for i in range(n):
l = input()
u = []
for j in range(m):
if l[j] == '#':
u.append('B')
else:
u.append('W')
grid.append(u)
white_column = 0
white_row = 0
for i in range(n):
row = grid[i]
if 'B' in row:
continue
else:
white_row = 1
for j in range(m):
col = []
for i in range(n):
col.append(grid[i][j])
if 'B' in col:
continue
else:
white_column = 1
if (white_row == 1 and white_column == 0) or (white_row == 0 and white_column == 1):
print(-1)
exit()
# if n == 1:
# white_present = 0
# black_present = 0
#
# for i in range(m):
# if grid[0][i] == 'B':
# black_present = 1
# if grid[0][i] == 'W':
# white_present = 1
# if black_present == 1 and white_present == 1:
# print(-1)
# exit()
# elif black_present == 0 and white_present == 1:
# print(0)
# exit()
# elif black_present == 1 and white_present == 0:
# print(m)
# exit()
#
# elif m == 1:
# white_present = 0
# black_present = 0
# for i in range(n):
# if grid[i][0] == 'B':
# black_present = 1
# if grid[i][0] == 'W':
# white_present = 1
# if black_present == 1 and white_present == 1:
# print(-1)
# exit()
# elif black_present == 0 and white_present == 1:
# print(0)
# exit()
# elif black_present == 1 and white_present == 0:
# print(n)
# exit()
#
# else:
for i in range(n):
first_black = 0
first_white = 0
second_black = 0
for j in range(m):
if grid[i][j] == 'B':
if first_black == 0:
first_black = 1
elif first_white == 1:
second_black = 1
break
if grid[i][j] == 'W':
if first_black == 1:
first_white = 1
if first_black == 1 and first_white == 1 and second_black == 1:
print(-1)
exit()
for j in range(m):
first_black = 0
first_white = 0
second_black = 0
for i in range(n):
if grid[i][j] == 'B':
if first_black == 0:
first_black = 1
elif first_white == 1:
second_black = 1
break
if grid[i][j] == 'W':
if first_black == 1:
first_white = 1
if first_black == 1 and first_white == 1 and second_black == 1:
print(-1)
exit()
reachable_table = []
ans = 0
for i in range(n):
reachable_table.append([0]*m)
for i in range(n):
for j in range(m):
if reachable_table[i][j] == 0 and grid[i][j] == 'B':
ans += 1
make_reachable(i,j)
print(ans)
```
| 104,589 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement.
Tags: constructive algorithms, dfs and similar, dsu, graphs
Correct Solution:
```
h, w = map(int, input().split())
b = [list(input()) for _ in range(h)]
cnt_mx = 0
all_white_row = 0
for hi in range(h):
prev = "."
cnt = 0
for wi in range(w):
if b[hi][wi] != prev:
cnt += 1
prev = b[hi][wi]
if cnt == 0:
all_white_row += 1
cnt_mx = max(cnt_mx, cnt)
all_white_col = 0
for wi in range(w):
prev = "."
cnt = 0
for hi in range(h):
if b[hi][wi] != prev:
cnt += 1
prev = b[hi][wi]
if cnt == 0:
all_white_col += 1
cnt_mx = max(cnt_mx, cnt)
if cnt_mx > 2 or [all_white_col, all_white_row].count(0) == 1:
print(-1)
exit()
d = [(-1, 0), (1, 0), (0, -1), (0, 1)]
ans = 0
for hi in range(h):
for wi in range(w):
if b[hi][wi] == "#":
ans += 1
stack = [[hi, wi]]
b[hi][wi] = "."
while stack:
hh, ww = stack.pop()
for dh, dw in d:
nh = hh + dh
nw = ww + dw
if 0 <= nh <= h - 1 and 0 <= nw <= w - 1 and b[nh][nw] == "#":
b[nh][nw] = "."
stack.append([nh, nw])
print(ans)
```
| 104,590 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement.
Tags: constructive algorithms, dfs and similar, dsu, graphs
Correct Solution:
```
import sys
import math
from collections import deque
input = sys.stdin.buffer.readline
def BFS(x,y):
q = deque()
q.append([x,y])
visited[x][y] = 1
while len(q)>0:
x,y = q.popleft()
if graph[min(x+1,n-1)][y] =='#' and visited[min(x+1,n-1)][y]==0:
visited[x+1][y] = 1
q.append([x+1,y])
if graph[max(x-1,0)][y] =='#' and visited[max(x-1,0)][y]==0:
visited[x-1][y] = 1
q.append([x-1,y])
if graph[x][min(y+1,m-1)] =='#' and visited[x][min(y+1,m-1)]==0:
visited[x][y+1] = 1
q.append([x,y+1])
if graph[x][max(y-1,0)]=='#' and visited[x][max(y-1,0)]==0:
visited[x][y-1] = 1
q.append([x,y-1])
n,m = map(int,input().split())
graph = [0]*n
for i in range(n):
graph[i] = list(map(chr,list(input().strip())))
#print(graph)
xx = 0
for i in range(n):
x = 0
for j in range(m):
if graph[i][j] == '#':
if x==2:
print(-1)
exit(0)
else:
x=1
else:
if x==1:
x=2
if x==0:
xx = 1
#print(xx)
for i in range(m):
x = 0
for j in range(n):
if graph[j][i] == '#':
if x==2:
print(-1)
exit(0)
else:
x=1
else:
if x==1:
x=2
if x==0 and xx==0:
print(-1)
exit(0)
elif x==0:
xx = 2
#print(xx)
if xx == 1:
print(-1)
exit(0)
visited = [[0 for _ in range(m)] for _ in range(n)]
count=0
for i in range(n):
for j in range(m):
if graph[i][j]=='#' and visited[i][j]==0:
count+=1
BFS(i,j)
print(count)
```
| 104,591 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement.
Tags: constructive algorithms, dfs and similar, dsu, graphs
Correct Solution:
```
from collections import deque
def valid() :
#check rows
rows = 0
cols = 0
for r in adj :
white = False
black = False
for col in r :
if(col == '#' and white and black) : return False
if(col == '#') : black = True
if(col == '.' and black) : white = True
rows += 1 if not (white or black) else 0
#check cols
for j in range(m) :
white = False
black = False
for i in range(n) :
if(adj[i][j] == '#' and white and black) : return False
if(adj[i][j] == '#') : black = True
if(adj[i][j] == '.' and black) : white = True
cols += 1 if not (white or black) else 0
return (rows == 0 and cols == 0) or (rows > 0 and cols > 0)
def check(r, c) :
return r >= 0 and r < n and c >= 0 and c < m and adj[r][c] == '#' and (not vis[r][c])
def dfs(r,c) :
vis[r][c] = True
for i in range(4) :
if check(r + dx[i], c + dy[i]) :
dfs(r + dx[i], c + dy[i])
def bfs(r,c) :
vis[r][c] = True
q = deque()
q.append((r,c))
while(len(q) != 0) :
t = q.popleft()
for i in range(4) :
nr = t[0] + dx[i]
nc = t[1] + dy[i]
if check(nr,nc) :
vis[nr][nc] = True
q.append((nr,nc))
def cc() :
cnt = 0
for i in range(n) :
for j in range(m) :
if((not vis[i][j]) and adj[i][j] == '#') :
cnt += 1
bfs(i,j)
return cnt
n,m = map(int,input().split())
adj = []
for _ in range(n) :
adj.append(input())
vis = [[False] * m for _ in range(n)]
dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]
print(-1 if not(valid()) else cc())
```
| 104,592 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement.
Tags: constructive algorithms, dfs and similar, dsu, graphs
Correct Solution:
```
from collections import deque
def BFS(graph, i, j, n, m):
Q = deque([])
vis = set()
vis.add((i, j))
Q.append((i, j))
neigh = [(1, 0), (-1, 0), (0, 1), (0, -1)]
while len(Q):
curr = Q.popleft()
i = curr[0]; j = curr[1]
graph[i][j] = '.'
for ne in neigh:
x = ne[0]+i; y = ne[1]+j
if 0 <= x < n and 0<= y < m and graph[x][y] == '#':
if (x, y) not in vis:
Q.append((x, y))
vis.add((x, y))
return graph
class UnionFind:
def __init__(self, N):
self.parent = [i for i in range(N)]
self.size = [1 for _ in range(N)]
def find(self, x):
if self.parent[x] == x:
return x
else:
return self.find(self.parent[x])
def union(self, x, y):
px = self.find(x)
py = self.find(y)
if px == py:
return
if self.size[px] < self.size[py]:
self.parent[px] = py
self.size[py] += self.size[px]
else:
self.parent[py] = px
self.size[px] += self.size[py]
def same(self, x, y):
return self.find(x) == self.find(y)
N,M = map(int,input().split())
grid=[[v for v in input()] for _ in range(N)]
all_white_row=0
all_white_col=0
for n in range(N):
r=all(v=="." for v in grid[n])
all_white_row+= 1 if r else 0
for m in range(M):
r= all(grid[i][m]=="." for i in range(N))
all_white_col+= 1 if r else 0
seq_in_each_row=1
seq_in_each_col=1
empR=0
empC=0
for i in range(N):
flag=0
for j in range(M):
if grid[i][j]=="#":
if flag==1:
if grid[i][j-1]!="#":
seq_in_each_row=0
break
else:
flag=1
if flag==0:
empR+=1
for j in range(M):
flag=0
for i in range(N):
if grid[i][j]=="#":
if flag==1:
if grid[i-1][j]!="#":
seq_in_each_col=0
break
else:
flag=1
if flag==0:
empC+=1
#for n in range(N):
# r= len([v for v in "".join(grid[n]).split(".") if len(v)!=0])
# if r==0:
# continue
# seq_in_each_row*=(r==1)
#for m in range(M):
# r= len([v for v in "".join([grid[i][m] for i in range(N)]).split(".") if len(v)!=0])
# if r==0:
# continue
# seq_in_each_col*=(r==1)
#
if seq_in_each_col*seq_in_each_row==0:
print(-1)
exit()
assert all_white_col==empC and all_white_row==empR
if not((all_white_col==0 and all_white_row==0) or (all_white_row>=1 and all_white_col>=1)):
print(-1)
exit()
UN=UnionFind(N*M)
DX=[0,1]
DY=[1,0]
def isIn(n,m):
return 0<=n<N and 0<=m<M
for n in range(N):
for m in range(M):
if grid[n][m]==".":
continue
for dx,dy in zip(DX,DY):
nn=n+dx
mm=m+dy
if isIn(nn,mm) and grid[nn][mm]=="#":
UN.union(n*M+m,nn*M+mm)
parent=set()
for n in range(N):
for m in range(M):
if grid[n][m]=="#":
parent.add(UN.parent[n*M+m])
ans=0
for i in range(N):
for j in range(M):
if grid[i][j]=="#":
ans+=1
grid = BFS(grid,i,j,N,M)
#assert ans==len(parent)
print(ans)
```
| 104,593 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement.
Tags: constructive algorithms, dfs and similar, dsu, graphs
Correct Solution:
```
class UnionFind:
def __init__(self, n):
self.parent = list(range(n))
def find(self, a): #return parent of a. a and b are in same set if they have same parent
acopy = a
while a != self.parent[a]:
a = self.parent[a]
while acopy != a: #path compression
self.parent[acopy], acopy = a, self.parent[acopy]
return a
def union(self, a, b): #union a and b
self.parent[self.find(b)] = self.find(a)
#
##Usage: (note that all index references are 0-indexed)
#n=100 #number of items, indexed from 0 to n-1
#uf=UnionFind(n)
#assert uf.find(85)!=uf.find(4)
#uf.union(85,4)
#assert uf.find(85)==uf.find(4)
def convertCoordToInt(i,j,n,m): #for union find
return i*m+j
def main():
#Put a South on every '#'
#Use DSU to check how many groups of connected '#' there are,
#And ensure that it is impossible to reach all '.'
#If there is an empty row, there must be at least 1 empty column to put South at intersection.
#Same logic for empty column, unless there are no '#'.
n,m=readIntArr()
arr=[]
for _ in range(n):
arr.append(input())
rows=[[None,None] for _ in range(n)] #[earliest '#' column, latest '#' column]
columns=[[None,None] for _ in range(m)]
southCnt=0
for i in range(n):
for j in range(m):
if arr[i][j]=='#':
southCnt+=1
if rows[i][0]==None:
rows[i]=[j,j]
else:
rows[i][0]=min(rows[i][0],j)
rows[i][1]=max(rows[i][1],j)
if columns[j][0]==None:
columns[j]=[i,i]
else:
columns[j][0]=min(columns[j][0],i)
columns[j][1]=max(columns[j][1],i)
if southCnt==0: #no '#' so no need any Norths
print(0)
return
#Unoccupied row and column counts check
uRowCnts=0
uColCnts=0
for i in range(n):
if rows[i][0]==None:
uRowCnts+=1
for j in range(m):
if columns[j][0]==None:
uColCnts+=1
# print(uRowCnts,uColCnts)##
if not ((uRowCnts==0 and uColCnts==0) or (uRowCnts!=0 and uColCnts!=0)): #1 of them is 0
print(-1)
return
uf=UnionFind(n*m)
for i in range(n):
for j in range(m):
if arr[i][j]=='#':
coord1=convertCoordToInt(i,j,n,m)
parent=uf.find(coord1)
#dfs
st=[[i,j]]
# print('next stack')####
while st:
ii,jj=st.pop()
minCol,maxCol=rows[ii]
minRow,maxRow=columns[jj]
####
# print('ii:{} jj:{} minCol:{} maxCol:{} minRow:{} maxRow:{}'.format(ii,jj,minCol,maxCol,minRow,maxRow))
possibleCoords=[]
if minRow<ii:
possibleCoords.append([ii-1,jj])
if maxRow>ii:
possibleCoords.append([ii+1,jj])
if minCol<jj:
possibleCoords.append([ii,jj-1])
if maxCol>jj:
possibleCoords.append([ii,jj+1])
####
# print('possibleCoords:{}'.format(possibleCoords))
for iii,jjj in possibleCoords:
if arr[iii][jjj]=='#':
coord2=convertCoordToInt(iii,jjj,n,m)
parent2=uf.find(coord2)
if parent!=parent2: #iii,jjj is not yet visited
uf.union(coord1,coord2)
st.append([iii,jjj])
parent=uf.find(coord1)
# print('({}) {} ({}) {}'.format((i,j),uf.find(convertCoordToInt(i,j,n,m)),
# (iii,jjj),uf.find(convertCoordToInt(iii,jjj,n,m)))) ####
else: #'.' impossible
print(-1)
return
groups=set()
for i in range(n):
for j in range(m):
if arr[i][j]=='#':
groups.add(uf.find(convertCoordToInt(i,j,n,m)))
print(len(groups))
####
# print('uRowCnts:{} uColCnts:{}'.format(uRowCnts,uColCnts)) ####
# print('rows:{}\ncols:{}'.format(rows,columns))
# group2=[[-1 for _ in range(n)] for __ in range(m)]
# for i in range(n):
# for j in range(m):
# if arr[i][j]=='#':
# group2[i][j]=uf.find(convertCoordToInt(i,j,n,m))
# multiLineArrayOfArraysPrint(group2)
return
#import sys
#input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
import sys
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()]
inf=float('inf')
MOD=10**9+7
main()
```
| 104,594 |
Provide tags and a correct Python 2 solution for this coding contest problem.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement.
Tags: constructive algorithms, dfs and similar, dsu, graphs
Correct Solution:
```
from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
raw_input = stdin.readline
pr = stdout.write
def fun(x):
return 1*(x=='#')
def in_num():
return int(raw_input())
def in_arr():
return map(fun,raw_input().strip())
def pr_num(n):
stdout.write(str(n)+'\n')
def pr_arr(arr):
pr(' '.join(map(str,arr))+'\n')
# fast read function for total integer input
def inp():
# this function returns whole input of
# space/line seperated integers
# Use Ctrl+D to flush stdin.
return map(int,stdin.read().split())
range = xrange # not for python 3.0+
n,m=map(int,raw_input().split())
l=[]
sm=0
for i in range(n):
l.append(in_arr())
sm+=sum(l[-1])
if sm==0:
pr_num(0)
exit()
if n==1 or m==1:
if sm!=n*m:
pr_num(-1)
else:
pr_num(1)
exit()
f1,f2=0,0
for i in range(n):
c=0
sm=l[i][-1]
for j in range(m-1):
if l[i][j]:
c=1
sm+=l[i][j]
if l[i][j]==0 and c and l[i][j+1]:
pr_num(-1)
exit()
if sm==0:
f1=1
for j in range(m):
f=0
sm=l[-1][j]
for i in range(n-1):
sm+=l[i][j]
if l[i][j]==1:
f=1
if l[i][j]==0 and f and l[i+1][j]==1:
pr_num(-1)
exit()
if sm==0:
f2=1
if f1^f2:
pr_num(-1)
exit()
vis=[[0 for i in range(m)] for j in range(n)]
ans=0
move=[(1,0),(-1,0),(0,1),(0,-1)]
f=0
for i in range(n):
for j in range(m):
if l[i][j] and not vis[i][j]:
#print 'x',i,j
vis[i][j]=1
q=[(i,j)]
ans+=1
while q:
x,y=q.pop()
#print x,y
for x1,y1 in move:
x2=x1+x
y2=y1+y
if x2>=0 and x2<n and y2>=0 and y2<m:
if l[x2][y2] and not vis[x2][y2]:
vis[x2][y2]=1
q.append((x2,y2))
pr_num(ans)
```
| 104,595 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement.
Submitted Solution:
```
from sys import exit
n, m = map(int, input().split())
a = [tuple(input()) for i in range(n)]
whiteline = False
whilecolumne = False
howmany = 0
ar = [[0] * m for i in range(n)]
for x in range(n):
lastelem = '.'
shag = 0
for y in range(m):
elem = a[x][y]
if elem == '#':
if lastelem != elem:
newnam = howmany + 1
if x!= 0:
if ar[x-1][y] != 0: newnam = ar[x-1][y]
elif ar[x][y] != 0: newnam = ar[x][y]
else:
howmany += 1
elif ar[x][y] != 0: newnam = ar[x][y]
else:
howmany += 1
x1 = x + 1
y1 = y
ar[x][y] = newnam
if x1 != n:
while y1 != -1 and a[x1][y1] == "#":
ar[x1][y1] = newnam
y1 -= 1
else:
ar[x][y] = ar[x][y-1]
if elem != lastelem:
shag += 1
lastelem = elem
if shag == 0: whiteline = True
if shag > 2:
print(-1)
exit()
for y in range(m):
lastelem = '.'
shag = 0
for x in range(n):
elem = a[x][y]
if elem != lastelem:
shag += 1
lastelem = elem
if shag == 0: whilecolumne = True
if shag > 2:
print(-1)
exit()
if whilecolumne ^ whiteline:
print(-1)
exit()
print(howmany)
```
Yes
| 104,596 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement.
Submitted Solution:
```
def check(s):
t=[0]+s+[0]
flag=0
for i in t:
if flag==0:
if i==1:
flag=1
elif flag==1:
if i==0:
flag=2
elif flag==2:
if i==1:
return False
return True
h,w=map(int,input().split())
grid=[]
for i in range(h):
s=input()
b=[]
for j in s:
if j==".":b.append(0)
else:b.append(1)
grid.append(b)
for i in range(h):
if not(check(grid[i])):
print(-1)
exit()
for j in range(w):
if not(check([grid[i][j] for i in range(h)])):
print(-1)
exit()
ans=0
hh=[1]*h
ww=[1]*w
for i in range(h):
for j in range(w):
if grid[i][j]:
stack=[(i,j)]
grid[i][j]=0
hh[i]=0
ww[j]=0
for x,y in stack:
if 0<x:
if grid[x-1][y]:
stack.append((x-1,y))
grid[x-1][y]=0
hh[x-1]=ww[y]=0
if x<h-1:
if grid[x+1][y]:
stack.append((x+1,y))
grid[x+1][y]=0
hh[x+1]=ww[y]=0
if 0<y:
if grid[x][y-1]:
stack.append((x,y-1))
grid[x][y-1]=0
hh[x]=ww[y-1]=0
if y<w-1:
if grid[x][y+1]:
stack.append((x,y+1))
grid[x][y+1]=0
hh[x]=ww[y+1]=0
ans+=1
if 1 in hh or 1 in ww:
if hh.count(1)*ww.count(1)==0:
print(-1)
exit()
print(ans)
```
Yes
| 104,597 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement.
Submitted Solution:
```
import os, sys
from io import BytesIO, IOBase
from types import GeneratorType
from bisect import bisect_left, bisect_right
from collections import defaultdict as dd, deque as dq, Counter as dc
import math, string
import heapq as h, time
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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:
self.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")
#start_time = time.time()
def getInt(): return int(input())
def getStrs(): return input().split()
def getInts(): return list(map(int,input().split()))
def getStr(): return input()
def listStr(): return list(input())
def getMat(n): return [getInts() for _ in range(n)]
def getBin(): return list(map(int,list(input())))
def isInt(s): return '0' <= s[0] <= '9'
def ceil_(a,b): return a//b + (a%b > 0)
MOD = 10**9 + 7
"""
It's possible if there are no dots between hashes
The min number = the min number of connected components
DSU the points
for i in range(1,N+1), for j in range(1,M+1)
row i column j is cell i*M + j
"""
def solve():
def find(a):
if a != p[a]:
p[a] = find(p[a])
return p[a]
def union(a, b):
a, b = find(a), find(b)
if a == b: return
if size[a] > size[b]:
a, b = b, a
p[a] = b
size[b] += size[a]
return
N, M = getInts()
grid = ['.']*(M+2)
for _ in range(N): grid += ['.'] + listStr() + ['.']
grid += ['.']*(M+2)
N += 2
M += 2
num = N*M
bad_row = bad_col = 0
#Check whether it's possible: i.e. whether #.# exists in any row/col
for i in range(1,N-1):
seen_hash = False
seen_dot = False
for j in range(1,M-1):
if grid[i*M + j] == '#':
if seen_dot:
return -1
seen_hash = True
else:
if seen_hash:
seen_dot = True
if not seen_hash: bad_row = 1
for j in range(1,M-1):
seen_hash = False
seen_dot = False
for i in range(1,N-1):
if grid[i*M + j] == '#':
if seen_dot:
return -1
seen_hash = True
else:
if seen_hash:
seen_dot = True
if not seen_hash: bad_col = 1
if bad_row ^ bad_col: return -1
#If we've made it this far, it's possible and we just need to count connected components
p = [i for i in range(num)]
size = [1]*num
for i in range(num-M-1):
if grid[i] != '#':
p[i] = -i-1
continue
if grid[i+1] == '#':
union(i,i+1)
if grid[i+M] == '#':
union(i,i+M)
ans = set()
for i in range(num-M-1):
if p[i] < 0: continue
f = find(i)
if f != -1: ans.add(f)
return len(ans)
#for _ in range(getInt()):
print(solve())
#solve()
#print(time.time()-start_time)
```
Yes
| 104,598 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement.
Submitted Solution:
```
import sys
input = sys.stdin.readline
n, m = map(int, input().split())
l = [''] * n
for i in range(n):
l[i] = input().strip()
works = True
rows = [False] * n
cols = [False] * m
for i in range(n):
for j in range(m):
if l[i][j] == '#':
rows[i] = True
cols[j] = True
if all(rows) ^ all(cols):
works = False
for i in range(n):
s = l[i]
left = -1
right = -1
for j in range(m):
if s[j] == '#':
if left == -1:
left = j
right = j
for j in range(left + 1, right):
if s[j] != '#':
works = False
for j in range(m):
left = -1
right = -1
for i in range(n):
if l[i][j] == '#':
if left == -1:
left = i
right = i
for i in range(left + 1, right):
if l[i][j] != '#':
works = False
if works:
visited = [[False] * m for i in range(n)]
out = 0
for i in range(n):
for j in range(m):
if l[i][j] != '#':
visited[i][j] = True
for startX in range(n):
for startY in range(m):
if not visited[startX][startY]:
out += 1
visited[startX][startY] = True
queue = [(startX, startY)]
while queue:
x, y = queue.pop()
for d in range(4):
nX = x + [0,0,-1,1][d]
nY = y + [1,-1,0,0][d]
if 0 <= nX < n and 0 <= nY < m and not visited[nX][nY]:
visited[nX][nY] = True
queue.append((nX, nY))
print(out)
else:
print(-1)
```
Yes
| 104,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.