text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
Tokitsukaze and CSL are playing a little game of stones.
In the beginning, there are n piles of stones, the i-th pile of which has a_i stones. The two players take turns making moves. Tokitsukaze moves first. On each turn the player chooses a nonempty pile and removes exactly one stone from the pile. A player loses if all of the piles are empty before his turn, or if after removing the stone, two piles (possibly empty) contain the same number of stones. Supposing that both players play optimally, who will win the game?
Consider an example: n=3 and sizes of piles are a_1=2, a_2=3, a_3=0. It is impossible to choose the empty pile, so Tokitsukaze has two choices: the first and the second piles. If she chooses the first pile then the state will be [1, 3, 0] and it is a good move. But if she chooses the second pile then the state will be [2, 2, 0] and she immediately loses. So the only good move for her is to choose the first pile.
Supposing that both players always take their best moves and never make mistakes, who will win the game?
Note that even if there are two piles with the same number of stones at the beginning, Tokitsukaze may still be able to make a valid first move. It is only necessary that there are no two piles with the same number of stones after she moves.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of piles.
The second line contains n integers a_1, a_2, β¦, a_n (0 β€ a_1, a_2, β¦, a_n β€ 10^9), which mean the i-th pile has a_i stones.
Output
Print "sjfnb" (without quotes) if Tokitsukaze will win, or "cslnb" (without quotes) if CSL will win. Note the output characters are case-sensitive.
Examples
Input
1
0
Output
cslnb
Input
2
1 0
Output
cslnb
Input
2
2 2
Output
sjfnb
Input
3
2 3 1
Output
sjfnb
Note
In the first example, Tokitsukaze cannot take any stone, so CSL will win.
In the second example, Tokitsukaze can only take a stone from the first pile, and then, even though they have no stone, these two piles will have the same number of stones, which implies CSL will win.
In the third example, Tokitsukaze will win. Here is one of the optimal ways:
* Firstly, Tokitsukaze can choose the first pile and take a stone from that pile.
* Then, CSL can only choose the first pile, because if he chooses the second pile, he will lose immediately.
* Finally, Tokitsukaze can choose the second pile, and then CSL will have no choice but to lose.
In the fourth example, they only have one good choice at any time, so Tokitsukaze can make the game lasting as long as possible and finally win.
Tags: games
Correct Solution:
```
n=int(input())
a=list(map(int,input().split()))
d=set()
t={}
rep=set()
if a.count(0)>=2:
print("cslnb")
exit()
for i in a:
if i in d:
if t[i]+1==3:
print("cslnb")
exit()
else:
t[i]+=1
rep.add(i)
if len(rep)>=2:
print("cslnb")
exit()
else:
t[i]=1
d.add(i)
if rep:
for c in rep:
if c-1 in d:
print("cslnb")
exit()
s=0
a.sort()
for i in range(n):
s+=a[i]-i
if s%2==1:print("sjfnb")
else:print("cslnb")
```
| 100,400 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Tokitsukaze and CSL are playing a little game of stones.
In the beginning, there are n piles of stones, the i-th pile of which has a_i stones. The two players take turns making moves. Tokitsukaze moves first. On each turn the player chooses a nonempty pile and removes exactly one stone from the pile. A player loses if all of the piles are empty before his turn, or if after removing the stone, two piles (possibly empty) contain the same number of stones. Supposing that both players play optimally, who will win the game?
Consider an example: n=3 and sizes of piles are a_1=2, a_2=3, a_3=0. It is impossible to choose the empty pile, so Tokitsukaze has two choices: the first and the second piles. If she chooses the first pile then the state will be [1, 3, 0] and it is a good move. But if she chooses the second pile then the state will be [2, 2, 0] and she immediately loses. So the only good move for her is to choose the first pile.
Supposing that both players always take their best moves and never make mistakes, who will win the game?
Note that even if there are two piles with the same number of stones at the beginning, Tokitsukaze may still be able to make a valid first move. It is only necessary that there are no two piles with the same number of stones after she moves.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of piles.
The second line contains n integers a_1, a_2, β¦, a_n (0 β€ a_1, a_2, β¦, a_n β€ 10^9), which mean the i-th pile has a_i stones.
Output
Print "sjfnb" (without quotes) if Tokitsukaze will win, or "cslnb" (without quotes) if CSL will win. Note the output characters are case-sensitive.
Examples
Input
1
0
Output
cslnb
Input
2
1 0
Output
cslnb
Input
2
2 2
Output
sjfnb
Input
3
2 3 1
Output
sjfnb
Note
In the first example, Tokitsukaze cannot take any stone, so CSL will win.
In the second example, Tokitsukaze can only take a stone from the first pile, and then, even though they have no stone, these two piles will have the same number of stones, which implies CSL will win.
In the third example, Tokitsukaze will win. Here is one of the optimal ways:
* Firstly, Tokitsukaze can choose the first pile and take a stone from that pile.
* Then, CSL can only choose the first pile, because if he chooses the second pile, he will lose immediately.
* Finally, Tokitsukaze can choose the second pile, and then CSL will have no choice but to lose.
In the fourth example, they only have one good choice at any time, so Tokitsukaze can make the game lasting as long as possible and finally win.
Tags: games
Correct Solution:
```
n = int(input())
u = list(map(int, input().split()))
u.sort()
ans = 0
k = 1
ok = False
for i in range(1, n):
if u[i] == u[i - 1]:
k += 1
if k == 3:
print('cslnb')
exit()
if k == 2:
if ok or u[i] == 0 or u[i] - u[i - 2] == 1:
print('cslnb')
exit()
ok = True
else:
k = 1
for i in range(n):
ans += u[i] - i
if ans % 2 == 0:
print('cslnb')
else:
print('sjfnb')
```
| 100,401 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Tokitsukaze and CSL are playing a little game of stones.
In the beginning, there are n piles of stones, the i-th pile of which has a_i stones. The two players take turns making moves. Tokitsukaze moves first. On each turn the player chooses a nonempty pile and removes exactly one stone from the pile. A player loses if all of the piles are empty before his turn, or if after removing the stone, two piles (possibly empty) contain the same number of stones. Supposing that both players play optimally, who will win the game?
Consider an example: n=3 and sizes of piles are a_1=2, a_2=3, a_3=0. It is impossible to choose the empty pile, so Tokitsukaze has two choices: the first and the second piles. If she chooses the first pile then the state will be [1, 3, 0] and it is a good move. But if she chooses the second pile then the state will be [2, 2, 0] and she immediately loses. So the only good move for her is to choose the first pile.
Supposing that both players always take their best moves and never make mistakes, who will win the game?
Note that even if there are two piles with the same number of stones at the beginning, Tokitsukaze may still be able to make a valid first move. It is only necessary that there are no two piles with the same number of stones after she moves.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of piles.
The second line contains n integers a_1, a_2, β¦, a_n (0 β€ a_1, a_2, β¦, a_n β€ 10^9), which mean the i-th pile has a_i stones.
Output
Print "sjfnb" (without quotes) if Tokitsukaze will win, or "cslnb" (without quotes) if CSL will win. Note the output characters are case-sensitive.
Examples
Input
1
0
Output
cslnb
Input
2
1 0
Output
cslnb
Input
2
2 2
Output
sjfnb
Input
3
2 3 1
Output
sjfnb
Note
In the first example, Tokitsukaze cannot take any stone, so CSL will win.
In the second example, Tokitsukaze can only take a stone from the first pile, and then, even though they have no stone, these two piles will have the same number of stones, which implies CSL will win.
In the third example, Tokitsukaze will win. Here is one of the optimal ways:
* Firstly, Tokitsukaze can choose the first pile and take a stone from that pile.
* Then, CSL can only choose the first pile, because if he chooses the second pile, he will lose immediately.
* Finally, Tokitsukaze can choose the second pile, and then CSL will have no choice but to lose.
In the fourth example, they only have one good choice at any time, so Tokitsukaze can make the game lasting as long as possible and finally win.
Tags: games
Correct Solution:
```
from sys import stdin, stdout, exit
n = int(input())
a = list(map(int, stdin.readline().split()))
def z(winner):
return 'sjfnb' if winner == 0 else 'cslnb'
a.sort()
dups = set(a)
if len(dups) < len(a) - 1:
print(z(1))
exit()
winner = 0
for i in range(n-1):
if a[i] == a[i+1]:
if a[i] == 0 or a[i]-1 in a:
print(z(1))
exit()
winner = 1
a[i] = a[i] - 1
s = sum(a)
final = n*(n-1) // 2
winner += (s - final) + 1
winner %= 2
print(z(winner))
```
| 100,402 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Tokitsukaze and CSL are playing a little game of stones.
In the beginning, there are n piles of stones, the i-th pile of which has a_i stones. The two players take turns making moves. Tokitsukaze moves first. On each turn the player chooses a nonempty pile and removes exactly one stone from the pile. A player loses if all of the piles are empty before his turn, or if after removing the stone, two piles (possibly empty) contain the same number of stones. Supposing that both players play optimally, who will win the game?
Consider an example: n=3 and sizes of piles are a_1=2, a_2=3, a_3=0. It is impossible to choose the empty pile, so Tokitsukaze has two choices: the first and the second piles. If she chooses the first pile then the state will be [1, 3, 0] and it is a good move. But if she chooses the second pile then the state will be [2, 2, 0] and she immediately loses. So the only good move for her is to choose the first pile.
Supposing that both players always take their best moves and never make mistakes, who will win the game?
Note that even if there are two piles with the same number of stones at the beginning, Tokitsukaze may still be able to make a valid first move. It is only necessary that there are no two piles with the same number of stones after she moves.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of piles.
The second line contains n integers a_1, a_2, β¦, a_n (0 β€ a_1, a_2, β¦, a_n β€ 10^9), which mean the i-th pile has a_i stones.
Output
Print "sjfnb" (without quotes) if Tokitsukaze will win, or "cslnb" (without quotes) if CSL will win. Note the output characters are case-sensitive.
Examples
Input
1
0
Output
cslnb
Input
2
1 0
Output
cslnb
Input
2
2 2
Output
sjfnb
Input
3
2 3 1
Output
sjfnb
Note
In the first example, Tokitsukaze cannot take any stone, so CSL will win.
In the second example, Tokitsukaze can only take a stone from the first pile, and then, even though they have no stone, these two piles will have the same number of stones, which implies CSL will win.
In the third example, Tokitsukaze will win. Here is one of the optimal ways:
* Firstly, Tokitsukaze can choose the first pile and take a stone from that pile.
* Then, CSL can only choose the first pile, because if he chooses the second pile, he will lose immediately.
* Finally, Tokitsukaze can choose the second pile, and then CSL will have no choice but to lose.
In the fourth example, they only have one good choice at any time, so Tokitsukaze can make the game lasting as long as possible and finally win.
Tags: games
Correct Solution:
```
n = int(input())
lst = [int(i) for i in input().split()]
st = set()
flag = False
count = 0
for i in lst:
if i not in st:
st.add(i)
else:
flag = True
count+=1
lol = i
sum1 = n*(n-1)//2
if count>1:
print('cslnb')
quit()
if not flag:
if (sum(lst)- sum1)% 2 == 0:
print('cslnb')
else:
print('sjfnb')
else:
if (lol-1) in lst or lol == 0:
print('cslnb')
else:
if (sum(lst)- sum1)% 2 == 0:
print('cslnb')
else:
print('sjfnb')
```
| 100,403 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Tokitsukaze and CSL are playing a little game of stones.
In the beginning, there are n piles of stones, the i-th pile of which has a_i stones. The two players take turns making moves. Tokitsukaze moves first. On each turn the player chooses a nonempty pile and removes exactly one stone from the pile. A player loses if all of the piles are empty before his turn, or if after removing the stone, two piles (possibly empty) contain the same number of stones. Supposing that both players play optimally, who will win the game?
Consider an example: n=3 and sizes of piles are a_1=2, a_2=3, a_3=0. It is impossible to choose the empty pile, so Tokitsukaze has two choices: the first and the second piles. If she chooses the first pile then the state will be [1, 3, 0] and it is a good move. But if she chooses the second pile then the state will be [2, 2, 0] and she immediately loses. So the only good move for her is to choose the first pile.
Supposing that both players always take their best moves and never make mistakes, who will win the game?
Note that even if there are two piles with the same number of stones at the beginning, Tokitsukaze may still be able to make a valid first move. It is only necessary that there are no two piles with the same number of stones after she moves.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of piles.
The second line contains n integers a_1, a_2, β¦, a_n (0 β€ a_1, a_2, β¦, a_n β€ 10^9), which mean the i-th pile has a_i stones.
Output
Print "sjfnb" (without quotes) if Tokitsukaze will win, or "cslnb" (without quotes) if CSL will win. Note the output characters are case-sensitive.
Examples
Input
1
0
Output
cslnb
Input
2
1 0
Output
cslnb
Input
2
2 2
Output
sjfnb
Input
3
2 3 1
Output
sjfnb
Note
In the first example, Tokitsukaze cannot take any stone, so CSL will win.
In the second example, Tokitsukaze can only take a stone from the first pile, and then, even though they have no stone, these two piles will have the same number of stones, which implies CSL will win.
In the third example, Tokitsukaze will win. Here is one of the optimal ways:
* Firstly, Tokitsukaze can choose the first pile and take a stone from that pile.
* Then, CSL can only choose the first pile, because if he chooses the second pile, he will lose immediately.
* Finally, Tokitsukaze can choose the second pile, and then CSL will have no choice but to lose.
In the fourth example, they only have one good choice at any time, so Tokitsukaze can make the game lasting as long as possible and finally win.
Tags: games
Correct Solution:
```
from sys import stdin, stdout
import math
N = int(input())
#N,M,K = [int(x) for x in stdin.readline().split()]
arr = [int(x) for x in stdin.readline().split()]
if sum(arr)==0:
print('cslnb')
quit()
arr.sort()
zeros = 0
freq = {}
dup = 0
res = 0
for i in range(N):
num = arr[i]
if num==0:
zeros += 1
if zeros==2:
print('cslnb')
quit()
if num not in freq:
freq[num] = 1
else:
dup += 1
freq[num] += 1
if dup==2:
print('cslnb')
quit()
for i in range(N):
num = arr[i]
if freq[num]==2:
if (num-1) not in freq:
freq[num-1] = 1
freq[num] = 1
arr[i] = arr[i] - 1
res += 1
break
else:
print('cslnb')
quit()
#print(arr)
minus = [0]*N
level = 0
for i in range(N):
minus[i] = min(arr[i],level)
if arr[i]>=level:
level += 1
for i in range(N):
res += arr[i] - minus[i]
if res%2==0:
print('cslnb')
else:
print('sjfnb')
```
| 100,404 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Tokitsukaze and CSL are playing a little game of stones.
In the beginning, there are n piles of stones, the i-th pile of which has a_i stones. The two players take turns making moves. Tokitsukaze moves first. On each turn the player chooses a nonempty pile and removes exactly one stone from the pile. A player loses if all of the piles are empty before his turn, or if after removing the stone, two piles (possibly empty) contain the same number of stones. Supposing that both players play optimally, who will win the game?
Consider an example: n=3 and sizes of piles are a_1=2, a_2=3, a_3=0. It is impossible to choose the empty pile, so Tokitsukaze has two choices: the first and the second piles. If she chooses the first pile then the state will be [1, 3, 0] and it is a good move. But if she chooses the second pile then the state will be [2, 2, 0] and she immediately loses. So the only good move for her is to choose the first pile.
Supposing that both players always take their best moves and never make mistakes, who will win the game?
Note that even if there are two piles with the same number of stones at the beginning, Tokitsukaze may still be able to make a valid first move. It is only necessary that there are no two piles with the same number of stones after she moves.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of piles.
The second line contains n integers a_1, a_2, β¦, a_n (0 β€ a_1, a_2, β¦, a_n β€ 10^9), which mean the i-th pile has a_i stones.
Output
Print "sjfnb" (without quotes) if Tokitsukaze will win, or "cslnb" (without quotes) if CSL will win. Note the output characters are case-sensitive.
Examples
Input
1
0
Output
cslnb
Input
2
1 0
Output
cslnb
Input
2
2 2
Output
sjfnb
Input
3
2 3 1
Output
sjfnb
Note
In the first example, Tokitsukaze cannot take any stone, so CSL will win.
In the second example, Tokitsukaze can only take a stone from the first pile, and then, even though they have no stone, these two piles will have the same number of stones, which implies CSL will win.
In the third example, Tokitsukaze will win. Here is one of the optimal ways:
* Firstly, Tokitsukaze can choose the first pile and take a stone from that pile.
* Then, CSL can only choose the first pile, because if he chooses the second pile, he will lose immediately.
* Finally, Tokitsukaze can choose the second pile, and then CSL will have no choice but to lose.
In the fourth example, they only have one good choice at any time, so Tokitsukaze can make the game lasting as long as possible and finally win.
Tags: games
Correct Solution:
```
n = int(input())
a = sorted(list(map(int, input().split())))
cnt = 0
pair = 0
for i in range(n):
if i < n - 1 and a[i] == a[i + 1]:
pair += 1
if i > 0 and a[i - 1] == a[i] - 1:
pair += 1
if a[i] == 0:
pair = 2
cnt += a[i] - i
if pair > 1:
print("cslnb")
exit()
if cnt & 1:
print("sjfnb")
else:
print("cslnb")
```
| 100,405 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Tokitsukaze and CSL are playing a little game of stones.
In the beginning, there are n piles of stones, the i-th pile of which has a_i stones. The two players take turns making moves. Tokitsukaze moves first. On each turn the player chooses a nonempty pile and removes exactly one stone from the pile. A player loses if all of the piles are empty before his turn, or if after removing the stone, two piles (possibly empty) contain the same number of stones. Supposing that both players play optimally, who will win the game?
Consider an example: n=3 and sizes of piles are a_1=2, a_2=3, a_3=0. It is impossible to choose the empty pile, so Tokitsukaze has two choices: the first and the second piles. If she chooses the first pile then the state will be [1, 3, 0] and it is a good move. But if she chooses the second pile then the state will be [2, 2, 0] and she immediately loses. So the only good move for her is to choose the first pile.
Supposing that both players always take their best moves and never make mistakes, who will win the game?
Note that even if there are two piles with the same number of stones at the beginning, Tokitsukaze may still be able to make a valid first move. It is only necessary that there are no two piles with the same number of stones after she moves.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of piles.
The second line contains n integers a_1, a_2, β¦, a_n (0 β€ a_1, a_2, β¦, a_n β€ 10^9), which mean the i-th pile has a_i stones.
Output
Print "sjfnb" (without quotes) if Tokitsukaze will win, or "cslnb" (without quotes) if CSL will win. Note the output characters are case-sensitive.
Examples
Input
1
0
Output
cslnb
Input
2
1 0
Output
cslnb
Input
2
2 2
Output
sjfnb
Input
3
2 3 1
Output
sjfnb
Note
In the first example, Tokitsukaze cannot take any stone, so CSL will win.
In the second example, Tokitsukaze can only take a stone from the first pile, and then, even though they have no stone, these two piles will have the same number of stones, which implies CSL will win.
In the third example, Tokitsukaze will win. Here is one of the optimal ways:
* Firstly, Tokitsukaze can choose the first pile and take a stone from that pile.
* Then, CSL can only choose the first pile, because if he chooses the second pile, he will lose immediately.
* Finally, Tokitsukaze can choose the second pile, and then CSL will have no choice but to lose.
In the fourth example, they only have one good choice at any time, so Tokitsukaze can make the game lasting as long as possible and finally win.
Tags: games
Correct Solution:
```
import sys
import math
import bisect
from collections import deque
sys.setrecursionlimit(1000000000)
def input():
return sys.stdin.readline().strip()
def iinput():
return int(input())
def finput():
return float(input())
def tinput():
return input().split()
def rinput():
return map(int, tinput())
def rlinput():
return list(rinput())
def modst(a, s):
res = 1
while s:
if s % 2:
res *= a
a *= a
s //= 2
return res
def main():
w = ["cslnb", "sjfnb"]
n = iinput()
q = sorted(rlinput())
t = 0
for i in range(1, n):
t += q[i] == q[i - 1]
if t >= 2:
return w[0]
if t:
for i in range(n):
if q[i] == q[i + 1]:
if q[i] and q[i] != q[i - 1] + 1:
q[i] -= 1
break
else:
return w[0]
return w[(sum(q) - t - n * (n - 1) // 2) & 1]
for i in range(1):
print(main())
```
| 100,406 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Tokitsukaze and CSL are playing a little game of stones.
In the beginning, there are n piles of stones, the i-th pile of which has a_i stones. The two players take turns making moves. Tokitsukaze moves first. On each turn the player chooses a nonempty pile and removes exactly one stone from the pile. A player loses if all of the piles are empty before his turn, or if after removing the stone, two piles (possibly empty) contain the same number of stones. Supposing that both players play optimally, who will win the game?
Consider an example: n=3 and sizes of piles are a_1=2, a_2=3, a_3=0. It is impossible to choose the empty pile, so Tokitsukaze has two choices: the first and the second piles. If she chooses the first pile then the state will be [1, 3, 0] and it is a good move. But if she chooses the second pile then the state will be [2, 2, 0] and she immediately loses. So the only good move for her is to choose the first pile.
Supposing that both players always take their best moves and never make mistakes, who will win the game?
Note that even if there are two piles with the same number of stones at the beginning, Tokitsukaze may still be able to make a valid first move. It is only necessary that there are no two piles with the same number of stones after she moves.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of piles.
The second line contains n integers a_1, a_2, β¦, a_n (0 β€ a_1, a_2, β¦, a_n β€ 10^9), which mean the i-th pile has a_i stones.
Output
Print "sjfnb" (without quotes) if Tokitsukaze will win, or "cslnb" (without quotes) if CSL will win. Note the output characters are case-sensitive.
Examples
Input
1
0
Output
cslnb
Input
2
1 0
Output
cslnb
Input
2
2 2
Output
sjfnb
Input
3
2 3 1
Output
sjfnb
Note
In the first example, Tokitsukaze cannot take any stone, so CSL will win.
In the second example, Tokitsukaze can only take a stone from the first pile, and then, even though they have no stone, these two piles will have the same number of stones, which implies CSL will win.
In the third example, Tokitsukaze will win. Here is one of the optimal ways:
* Firstly, Tokitsukaze can choose the first pile and take a stone from that pile.
* Then, CSL can only choose the first pile, because if he chooses the second pile, he will lose immediately.
* Finally, Tokitsukaze can choose the second pile, and then CSL will have no choice but to lose.
In the fourth example, they only have one good choice at any time, so Tokitsukaze can make the game lasting as long as possible and finally win.
Tags: games
Correct Solution:
```
n = int(input())
a = sorted(list(map(int, input().split())))
win = None
first = True
if n == 1:
win = a[0] % 2 == 1
elif a[1] == 0:
win = False
if n > 2:
for i in range(n-1):
if a[i] == a[i+1]:
if i > 0:
if a[i-1] == a[i]-1:
win = False
break
if not first:
win = False
break
first = False
if win is None:
win = (sum(a) - (n*(n-1)//2)) % 2 == 1
if win:
print('sjfnb')
else:
print('cslnb')
```
| 100,407 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Tokitsukaze and CSL are playing a little game of stones.
In the beginning, there are n piles of stones, the i-th pile of which has a_i stones. The two players take turns making moves. Tokitsukaze moves first. On each turn the player chooses a nonempty pile and removes exactly one stone from the pile. A player loses if all of the piles are empty before his turn, or if after removing the stone, two piles (possibly empty) contain the same number of stones. Supposing that both players play optimally, who will win the game?
Consider an example: n=3 and sizes of piles are a_1=2, a_2=3, a_3=0. It is impossible to choose the empty pile, so Tokitsukaze has two choices: the first and the second piles. If she chooses the first pile then the state will be [1, 3, 0] and it is a good move. But if she chooses the second pile then the state will be [2, 2, 0] and she immediately loses. So the only good move for her is to choose the first pile.
Supposing that both players always take their best moves and never make mistakes, who will win the game?
Note that even if there are two piles with the same number of stones at the beginning, Tokitsukaze may still be able to make a valid first move. It is only necessary that there are no two piles with the same number of stones after she moves.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of piles.
The second line contains n integers a_1, a_2, β¦, a_n (0 β€ a_1, a_2, β¦, a_n β€ 10^9), which mean the i-th pile has a_i stones.
Output
Print "sjfnb" (without quotes) if Tokitsukaze will win, or "cslnb" (without quotes) if CSL will win. Note the output characters are case-sensitive.
Examples
Input
1
0
Output
cslnb
Input
2
1 0
Output
cslnb
Input
2
2 2
Output
sjfnb
Input
3
2 3 1
Output
sjfnb
Note
In the first example, Tokitsukaze cannot take any stone, so CSL will win.
In the second example, Tokitsukaze can only take a stone from the first pile, and then, even though they have no stone, these two piles will have the same number of stones, which implies CSL will win.
In the third example, Tokitsukaze will win. Here is one of the optimal ways:
* Firstly, Tokitsukaze can choose the first pile and take a stone from that pile.
* Then, CSL can only choose the first pile, because if he chooses the second pile, he will lose immediately.
* Finally, Tokitsukaze can choose the second pile, and then CSL will have no choice but to lose.
In the fourth example, they only have one good choice at any time, so Tokitsukaze can make the game lasting as long as possible and finally win.
Submitted Solution:
```
n = int(input())
import sys
l = ["cslnb", "sjfnb"]
data = [int(i) for i in input().split()]
data.sort()
dup = -1
for i in range(n-1):
if data[i] == data[i+1]:
if dup == -1:
dup = i
else:
print("cslnb")
sys.exit()
if dup != -1:
if dup == 0:
if data[0] == 0:
print("cslnb")
sys.exit()
else:
data[0] -= 1
l.reverse()
elif data[dup - 1] + 1 == data[dup]:
print("cslnb")
sys.exit()
else:
data[dup] -= 1
l.reverse()
cnt = 0
for i in range(n):
if data[i] < i:
break
else:
cnt += data[i] - i
print(l[cnt%2])
```
Yes
| 100,408 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Tokitsukaze and CSL are playing a little game of stones.
In the beginning, there are n piles of stones, the i-th pile of which has a_i stones. The two players take turns making moves. Tokitsukaze moves first. On each turn the player chooses a nonempty pile and removes exactly one stone from the pile. A player loses if all of the piles are empty before his turn, or if after removing the stone, two piles (possibly empty) contain the same number of stones. Supposing that both players play optimally, who will win the game?
Consider an example: n=3 and sizes of piles are a_1=2, a_2=3, a_3=0. It is impossible to choose the empty pile, so Tokitsukaze has two choices: the first and the second piles. If she chooses the first pile then the state will be [1, 3, 0] and it is a good move. But if she chooses the second pile then the state will be [2, 2, 0] and she immediately loses. So the only good move for her is to choose the first pile.
Supposing that both players always take their best moves and never make mistakes, who will win the game?
Note that even if there are two piles with the same number of stones at the beginning, Tokitsukaze may still be able to make a valid first move. It is only necessary that there are no two piles with the same number of stones after she moves.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of piles.
The second line contains n integers a_1, a_2, β¦, a_n (0 β€ a_1, a_2, β¦, a_n β€ 10^9), which mean the i-th pile has a_i stones.
Output
Print "sjfnb" (without quotes) if Tokitsukaze will win, or "cslnb" (without quotes) if CSL will win. Note the output characters are case-sensitive.
Examples
Input
1
0
Output
cslnb
Input
2
1 0
Output
cslnb
Input
2
2 2
Output
sjfnb
Input
3
2 3 1
Output
sjfnb
Note
In the first example, Tokitsukaze cannot take any stone, so CSL will win.
In the second example, Tokitsukaze can only take a stone from the first pile, and then, even though they have no stone, these two piles will have the same number of stones, which implies CSL will win.
In the third example, Tokitsukaze will win. Here is one of the optimal ways:
* Firstly, Tokitsukaze can choose the first pile and take a stone from that pile.
* Then, CSL can only choose the first pile, because if he chooses the second pile, he will lose immediately.
* Finally, Tokitsukaze can choose the second pile, and then CSL will have no choice but to lose.
In the fourth example, they only have one good choice at any time, so Tokitsukaze can make the game lasting as long as possible and finally win.
Submitted Solution:
```
n = int(input())
a = sorted(list(map(int,input().split())))
bal = 0
if a.count(0)>1:
print('cslnb')
exit()
if n-len(set(a))>1:
print('cslnb')
exit()
if n-len(set(a))==1:
for i in range(1,n):
if a[i]==a[i-1]:
if a[i]-1 in a:
print('cslnb')
exit()
break
if n==1:
print('cslnb' if not a[0] % 2 else 'sjfnb')
exit()
for i in range(n):
bal+=a[i]-i
print('sjfnb'if bal%2 else 'cslnb')
```
Yes
| 100,409 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Tokitsukaze and CSL are playing a little game of stones.
In the beginning, there are n piles of stones, the i-th pile of which has a_i stones. The two players take turns making moves. Tokitsukaze moves first. On each turn the player chooses a nonempty pile and removes exactly one stone from the pile. A player loses if all of the piles are empty before his turn, or if after removing the stone, two piles (possibly empty) contain the same number of stones. Supposing that both players play optimally, who will win the game?
Consider an example: n=3 and sizes of piles are a_1=2, a_2=3, a_3=0. It is impossible to choose the empty pile, so Tokitsukaze has two choices: the first and the second piles. If she chooses the first pile then the state will be [1, 3, 0] and it is a good move. But if she chooses the second pile then the state will be [2, 2, 0] and she immediately loses. So the only good move for her is to choose the first pile.
Supposing that both players always take their best moves and never make mistakes, who will win the game?
Note that even if there are two piles with the same number of stones at the beginning, Tokitsukaze may still be able to make a valid first move. It is only necessary that there are no two piles with the same number of stones after she moves.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of piles.
The second line contains n integers a_1, a_2, β¦, a_n (0 β€ a_1, a_2, β¦, a_n β€ 10^9), which mean the i-th pile has a_i stones.
Output
Print "sjfnb" (without quotes) if Tokitsukaze will win, or "cslnb" (without quotes) if CSL will win. Note the output characters are case-sensitive.
Examples
Input
1
0
Output
cslnb
Input
2
1 0
Output
cslnb
Input
2
2 2
Output
sjfnb
Input
3
2 3 1
Output
sjfnb
Note
In the first example, Tokitsukaze cannot take any stone, so CSL will win.
In the second example, Tokitsukaze can only take a stone from the first pile, and then, even though they have no stone, these two piles will have the same number of stones, which implies CSL will win.
In the third example, Tokitsukaze will win. Here is one of the optimal ways:
* Firstly, Tokitsukaze can choose the first pile and take a stone from that pile.
* Then, CSL can only choose the first pile, because if he chooses the second pile, he will lose immediately.
* Finally, Tokitsukaze can choose the second pile, and then CSL will have no choice but to lose.
In the fourth example, they only have one good choice at any time, so Tokitsukaze can make the game lasting as long as possible and finally win.
Submitted Solution:
```
numStones=int(input())
ints=[int(x) for x in input().split()]
ints.sort()
if numStones==1:
if ints[0] % 2 == 0:
print("cslnb")
else:
print("sjfnb")
elif numStones==2:
if ints[0]==0 and ints[1]==0:
print("cslnb")
elif ints[0] % 2 == ints[1] % 2:
print("sjfnb")
else:
print("cslnb")
else:
impos=False
onePair=False
firstWins=False
if ints[0]==ints[1]:
onePair=True
if ints[0]==0:
print("cslnb")
impos=True
if ints[0] % 2 == 1:
firstWins=True
if impos==False:
for i in range(numStones-2):
if ints[i+1]==ints[i+2]:
if onePair==True or ints[i]+1==ints[i+1]:
print("cslnb")
impos=True
break
else:
onePair=True
if (ints[i+1]-i) % 2 == 0:
firstWins=not firstWins
if (ints[numStones-1]-numStones) % 2 == 0:
firstWins=not firstWins
if impos==False:
if firstWins:
print("sjfnb")
else:
print("cslnb")
```
Yes
| 100,410 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Tokitsukaze and CSL are playing a little game of stones.
In the beginning, there are n piles of stones, the i-th pile of which has a_i stones. The two players take turns making moves. Tokitsukaze moves first. On each turn the player chooses a nonempty pile and removes exactly one stone from the pile. A player loses if all of the piles are empty before his turn, or if after removing the stone, two piles (possibly empty) contain the same number of stones. Supposing that both players play optimally, who will win the game?
Consider an example: n=3 and sizes of piles are a_1=2, a_2=3, a_3=0. It is impossible to choose the empty pile, so Tokitsukaze has two choices: the first and the second piles. If she chooses the first pile then the state will be [1, 3, 0] and it is a good move. But if she chooses the second pile then the state will be [2, 2, 0] and she immediately loses. So the only good move for her is to choose the first pile.
Supposing that both players always take their best moves and never make mistakes, who will win the game?
Note that even if there are two piles with the same number of stones at the beginning, Tokitsukaze may still be able to make a valid first move. It is only necessary that there are no two piles with the same number of stones after she moves.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of piles.
The second line contains n integers a_1, a_2, β¦, a_n (0 β€ a_1, a_2, β¦, a_n β€ 10^9), which mean the i-th pile has a_i stones.
Output
Print "sjfnb" (without quotes) if Tokitsukaze will win, or "cslnb" (without quotes) if CSL will win. Note the output characters are case-sensitive.
Examples
Input
1
0
Output
cslnb
Input
2
1 0
Output
cslnb
Input
2
2 2
Output
sjfnb
Input
3
2 3 1
Output
sjfnb
Note
In the first example, Tokitsukaze cannot take any stone, so CSL will win.
In the second example, Tokitsukaze can only take a stone from the first pile, and then, even though they have no stone, these two piles will have the same number of stones, which implies CSL will win.
In the third example, Tokitsukaze will win. Here is one of the optimal ways:
* Firstly, Tokitsukaze can choose the first pile and take a stone from that pile.
* Then, CSL can only choose the first pile, because if he chooses the second pile, he will lose immediately.
* Finally, Tokitsukaze can choose the second pile, and then CSL will have no choice but to lose.
In the fourth example, they only have one good choice at any time, so Tokitsukaze can make the game lasting as long as possible and finally win.
Submitted Solution:
```
n = int(input())
a = list(map(int,input().split()))
d = {}
t=0
s = sum(a)
for i in a:
d[i] = d.get(i, 0) + 1
# print(d)
if a.count(0)>1:
exit(print("cslnb"))
for i in a:
if i and d[i] >= 2:
d[i] -= 1
d[i - 1] = d.get(i-1,0) + 1
i -= 1
t=1
break
# print(t,d)
if t==1:
for i in a:
if d[i] >= 2:
print("cslnb")
exit()
ss=((n-1)*(n))//2
# print(s)
if (s - ss) % 2==0:
print("cslnb")
else:
print("sjfnb")
```
Yes
| 100,411 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Tokitsukaze and CSL are playing a little game of stones.
In the beginning, there are n piles of stones, the i-th pile of which has a_i stones. The two players take turns making moves. Tokitsukaze moves first. On each turn the player chooses a nonempty pile and removes exactly one stone from the pile. A player loses if all of the piles are empty before his turn, or if after removing the stone, two piles (possibly empty) contain the same number of stones. Supposing that both players play optimally, who will win the game?
Consider an example: n=3 and sizes of piles are a_1=2, a_2=3, a_3=0. It is impossible to choose the empty pile, so Tokitsukaze has two choices: the first and the second piles. If she chooses the first pile then the state will be [1, 3, 0] and it is a good move. But if she chooses the second pile then the state will be [2, 2, 0] and she immediately loses. So the only good move for her is to choose the first pile.
Supposing that both players always take their best moves and never make mistakes, who will win the game?
Note that even if there are two piles with the same number of stones at the beginning, Tokitsukaze may still be able to make a valid first move. It is only necessary that there are no two piles with the same number of stones after she moves.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of piles.
The second line contains n integers a_1, a_2, β¦, a_n (0 β€ a_1, a_2, β¦, a_n β€ 10^9), which mean the i-th pile has a_i stones.
Output
Print "sjfnb" (without quotes) if Tokitsukaze will win, or "cslnb" (without quotes) if CSL will win. Note the output characters are case-sensitive.
Examples
Input
1
0
Output
cslnb
Input
2
1 0
Output
cslnb
Input
2
2 2
Output
sjfnb
Input
3
2 3 1
Output
sjfnb
Note
In the first example, Tokitsukaze cannot take any stone, so CSL will win.
In the second example, Tokitsukaze can only take a stone from the first pile, and then, even though they have no stone, these two piles will have the same number of stones, which implies CSL will win.
In the third example, Tokitsukaze will win. Here is one of the optimal ways:
* Firstly, Tokitsukaze can choose the first pile and take a stone from that pile.
* Then, CSL can only choose the first pile, because if he chooses the second pile, he will lose immediately.
* Finally, Tokitsukaze can choose the second pile, and then CSL will have no choice but to lose.
In the fourth example, they only have one good choice at any time, so Tokitsukaze can make the game lasting as long as possible and finally win.
Submitted Solution:
```
n = int(input())
l = list(map(int, input().split()))
ansl = ['sjfnb', 'cslnb']
ans = -1
flag = False
d = dict()
val = 0
if n == 1:
ans = (l[0] + 1) % 2
else:
l.sort()
for elem in l:
d[elem] = d.get(elem, 0) + 1
hm = 0
which = -1
i = 0
for elem in d.values():
if elem >= 2:
hm += 1
which = i
i += 1
if max(d.values()) >= 3 or d.get(0, 0) >= 2 or hm > 1:
ans = 1
elif hm == 1:
if d.get(which - 1, 0) > 0:
ans = 1
else:
for i in range(n):
val += l[i] - i
ans = (val + 1) % 2
print(ansl[ans])
```
No
| 100,412 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Tokitsukaze and CSL are playing a little game of stones.
In the beginning, there are n piles of stones, the i-th pile of which has a_i stones. The two players take turns making moves. Tokitsukaze moves first. On each turn the player chooses a nonempty pile and removes exactly one stone from the pile. A player loses if all of the piles are empty before his turn, or if after removing the stone, two piles (possibly empty) contain the same number of stones. Supposing that both players play optimally, who will win the game?
Consider an example: n=3 and sizes of piles are a_1=2, a_2=3, a_3=0. It is impossible to choose the empty pile, so Tokitsukaze has two choices: the first and the second piles. If she chooses the first pile then the state will be [1, 3, 0] and it is a good move. But if she chooses the second pile then the state will be [2, 2, 0] and she immediately loses. So the only good move for her is to choose the first pile.
Supposing that both players always take their best moves and never make mistakes, who will win the game?
Note that even if there are two piles with the same number of stones at the beginning, Tokitsukaze may still be able to make a valid first move. It is only necessary that there are no two piles with the same number of stones after she moves.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of piles.
The second line contains n integers a_1, a_2, β¦, a_n (0 β€ a_1, a_2, β¦, a_n β€ 10^9), which mean the i-th pile has a_i stones.
Output
Print "sjfnb" (without quotes) if Tokitsukaze will win, or "cslnb" (without quotes) if CSL will win. Note the output characters are case-sensitive.
Examples
Input
1
0
Output
cslnb
Input
2
1 0
Output
cslnb
Input
2
2 2
Output
sjfnb
Input
3
2 3 1
Output
sjfnb
Note
In the first example, Tokitsukaze cannot take any stone, so CSL will win.
In the second example, Tokitsukaze can only take a stone from the first pile, and then, even though they have no stone, these two piles will have the same number of stones, which implies CSL will win.
In the third example, Tokitsukaze will win. Here is one of the optimal ways:
* Firstly, Tokitsukaze can choose the first pile and take a stone from that pile.
* Then, CSL can only choose the first pile, because if he chooses the second pile, he will lose immediately.
* Finally, Tokitsukaze can choose the second pile, and then CSL will have no choice but to lose.
In the fourth example, they only have one good choice at any time, so Tokitsukaze can make the game lasting as long as possible and finally win.
Submitted Solution:
```
from sys import stdin
n = int(stdin.readline())
stones = sorted([int(x) for x in stdin.readline().split()])
if n == 1:
if stones[0]%2 == 0:
print('cslnb')
else:
print('sjfnb')
else:
s = sum(stones)
if s%2 == 1:
print('cslnb')
else:
print('sjfnb')
```
No
| 100,413 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Tokitsukaze and CSL are playing a little game of stones.
In the beginning, there are n piles of stones, the i-th pile of which has a_i stones. The two players take turns making moves. Tokitsukaze moves first. On each turn the player chooses a nonempty pile and removes exactly one stone from the pile. A player loses if all of the piles are empty before his turn, or if after removing the stone, two piles (possibly empty) contain the same number of stones. Supposing that both players play optimally, who will win the game?
Consider an example: n=3 and sizes of piles are a_1=2, a_2=3, a_3=0. It is impossible to choose the empty pile, so Tokitsukaze has two choices: the first and the second piles. If she chooses the first pile then the state will be [1, 3, 0] and it is a good move. But if she chooses the second pile then the state will be [2, 2, 0] and she immediately loses. So the only good move for her is to choose the first pile.
Supposing that both players always take their best moves and never make mistakes, who will win the game?
Note that even if there are two piles with the same number of stones at the beginning, Tokitsukaze may still be able to make a valid first move. It is only necessary that there are no two piles with the same number of stones after she moves.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of piles.
The second line contains n integers a_1, a_2, β¦, a_n (0 β€ a_1, a_2, β¦, a_n β€ 10^9), which mean the i-th pile has a_i stones.
Output
Print "sjfnb" (without quotes) if Tokitsukaze will win, or "cslnb" (without quotes) if CSL will win. Note the output characters are case-sensitive.
Examples
Input
1
0
Output
cslnb
Input
2
1 0
Output
cslnb
Input
2
2 2
Output
sjfnb
Input
3
2 3 1
Output
sjfnb
Note
In the first example, Tokitsukaze cannot take any stone, so CSL will win.
In the second example, Tokitsukaze can only take a stone from the first pile, and then, even though they have no stone, these two piles will have the same number of stones, which implies CSL will win.
In the third example, Tokitsukaze will win. Here is one of the optimal ways:
* Firstly, Tokitsukaze can choose the first pile and take a stone from that pile.
* Then, CSL can only choose the first pile, because if he chooses the second pile, he will lose immediately.
* Finally, Tokitsukaze can choose the second pile, and then CSL will have no choice but to lose.
In the fourth example, they only have one good choice at any time, so Tokitsukaze can make the game lasting as long as possible and finally win.
Submitted Solution:
```
n=int(input())
arr=list(map(int,input().split()))
arr.sort()
ans=0
for i in range(len(arr)-1):
if(arr[i]!=arr[i+1]):
ans+=(arr[i+1]-arr[i])
ans-=1
arr[i+1]=arr[i]+1
#print(ans)
#print(arr)
mark=0
for i in range(len(arr)):
if(arr[i]>=mark):
ans+=(arr[i]-mark)
mark+=1
#print(ans)
if(ans%2==0):
print('cslnb')
else:
print('sjfnb')
```
No
| 100,414 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Tokitsukaze and CSL are playing a little game of stones.
In the beginning, there are n piles of stones, the i-th pile of which has a_i stones. The two players take turns making moves. Tokitsukaze moves first. On each turn the player chooses a nonempty pile and removes exactly one stone from the pile. A player loses if all of the piles are empty before his turn, or if after removing the stone, two piles (possibly empty) contain the same number of stones. Supposing that both players play optimally, who will win the game?
Consider an example: n=3 and sizes of piles are a_1=2, a_2=3, a_3=0. It is impossible to choose the empty pile, so Tokitsukaze has two choices: the first and the second piles. If she chooses the first pile then the state will be [1, 3, 0] and it is a good move. But if she chooses the second pile then the state will be [2, 2, 0] and she immediately loses. So the only good move for her is to choose the first pile.
Supposing that both players always take their best moves and never make mistakes, who will win the game?
Note that even if there are two piles with the same number of stones at the beginning, Tokitsukaze may still be able to make a valid first move. It is only necessary that there are no two piles with the same number of stones after she moves.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of piles.
The second line contains n integers a_1, a_2, β¦, a_n (0 β€ a_1, a_2, β¦, a_n β€ 10^9), which mean the i-th pile has a_i stones.
Output
Print "sjfnb" (without quotes) if Tokitsukaze will win, or "cslnb" (without quotes) if CSL will win. Note the output characters are case-sensitive.
Examples
Input
1
0
Output
cslnb
Input
2
1 0
Output
cslnb
Input
2
2 2
Output
sjfnb
Input
3
2 3 1
Output
sjfnb
Note
In the first example, Tokitsukaze cannot take any stone, so CSL will win.
In the second example, Tokitsukaze can only take a stone from the first pile, and then, even though they have no stone, these two piles will have the same number of stones, which implies CSL will win.
In the third example, Tokitsukaze will win. Here is one of the optimal ways:
* Firstly, Tokitsukaze can choose the first pile and take a stone from that pile.
* Then, CSL can only choose the first pile, because if he chooses the second pile, he will lose immediately.
* Finally, Tokitsukaze can choose the second pile, and then CSL will have no choice but to lose.
In the fourth example, they only have one good choice at any time, so Tokitsukaze can make the game lasting as long as possible and finally win.
Submitted Solution:
```
def find(A):
from collections import defaultdict
A=sorted(A)
N=len(A)
dic=defaultdict(int)
for i in range(N):
dic[A[i]]+=1
checked=[]
count=set([])
for x in A:
if dic[x]>2:
return "cslnb"
if dic[x]==2:
count.add(x)
y=x-1
if y in dic:
return "cslnb"
if len(count)>1:
return "cslnb"
temp=0
for i in range(N):
temp+=A[i]-i
if temp%2==1:
return "sjfnb"
return "cslnb"
input()
A=list(map(int,input().strip().split(' ')))
print(find(A))
```
No
| 100,415 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya and Gena play a very interesting game "Put a Knight!" on a chessboard n Γ n in size. In this game they take turns to put chess pieces called "knights" on the board so that no two knights could threat each other. A knight located in square (r, c) can threat squares (r - 1, c + 2), (r - 1, c - 2), (r + 1, c + 2), (r + 1, c - 2), (r - 2, c + 1), (r - 2, c - 1), (r + 2, c + 1) and (r + 2, c - 1) (some of the squares may be located outside the chessboard). The player who can't put a new knight during his move loses. Determine which player wins considering that both players play optimally well and Petya starts.
Input
The first line contains integer T (1 β€ T β€ 100) β the number of boards, for which you should determine the winning player. Next T lines contain T integers ni (1 β€ ni β€ 10000) β the sizes of the chessboards.
Output
For each ni Γ ni board print on a single line "0" if Petya wins considering both players play optimally well. Otherwise, print "1".
Examples
Input
2
2
1
Output
1
0
Submitted Solution:
```
import sys
sys.stdin = open("input.txt", "r")
input = sys.stdin.readline
sys.stdout = open("output.txt", "w")
print = sys.stdout.write
T=int(input())
for i in range(T):
n = int(input())
if n & 1 == 1:
print('0')
else:
print('1')
```
No
| 100,416 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya and Gena play a very interesting game "Put a Knight!" on a chessboard n Γ n in size. In this game they take turns to put chess pieces called "knights" on the board so that no two knights could threat each other. A knight located in square (r, c) can threat squares (r - 1, c + 2), (r - 1, c - 2), (r + 1, c + 2), (r + 1, c - 2), (r - 2, c + 1), (r - 2, c - 1), (r + 2, c + 1) and (r + 2, c - 1) (some of the squares may be located outside the chessboard). The player who can't put a new knight during his move loses. Determine which player wins considering that both players play optimally well and Petya starts.
Input
The first line contains integer T (1 β€ T β€ 100) β the number of boards, for which you should determine the winning player. Next T lines contain T integers ni (1 β€ ni β€ 10000) β the sizes of the chessboards.
Output
For each ni Γ ni board print on a single line "0" if Petya wins considering both players play optimally well. Otherwise, print "1".
Examples
Input
2
2
1
Output
1
0
Submitted Solution:
```
lista_sizes_boards=[]
winner=1
txt_object=open("input.txt","r")
no_boards=int(txt_object.readline())
for i in range(no_boards):
lista_sizes_boards.append(int(txt_object.readline()))
txt_object.close()
def Eliminar_casas(best_option):
x=best_option[0]
y=best_option[1]
casas_proibidas.append((x,y))
try:
tabuleiro[x-2][y+1]
casas_proibidas.append((x-2,y+1))
except:
pass
try:
tabuleiro[x-2][y-1]
casas_proibidas.append((x-2,y+1))
except:
pass
try:
tabuleiro[x-1][y+2]
casas_proibidas.append((x-2,y+1))
except:
pass
try:
tabuleiro[x-1][y-2]
casas_proibidas.append((x-2,y+1))
except:
pass
try:
tabuleiro[x+1][y+2]
casas_proibidas.append((x-2,y+1))
except:
pass
try:
tabuleiro[x+1][y-2]
casas_proibidas.append((x-2,y+1))
except:
pass
try:
tabuleiro[x+2][y+1]
casas_proibidas.append((x-2,y+1))
except:
pass
try:
tabuleiro[x+2][y-1]
casas_proibidas.append((x-2,y+1))
except:
pass
return(Escolha_melhor_casa())
def Escolha_melhor_casa():
global winner
lista_no_casas_eliminadas=[]
for x in range(len(tabuleiro)):
for y in range(len(tabuleiro[0])):
if (x,y) not in casas_proibidas:
casas_eliminadas=0
try:
tabuleiro[x-2][y+1]
if (x-2,y+1) not in casas_proibidas:
casas_eliminadas+=1
except:
pass
try:
tabuleiro[x-2][y-1]
if (x-2,y-1) not in casas_proibidas:
casas_eliminadas+=1
except:
pass
try:
tabuleiro[x-1][y+2]=1
if (x-1,y+2) not in casas_proibidas:
casas_eliminadas+=1
except:
pass
try:
tabuleiro[x-1][y-2]
if (x-1,y-2) not in casas_proibidas:
casas_eliminadas+=1
except:
pass
try:
tabuleiro[x+1][y+2]
if (x+1,y+1) not in casas_proibidas:
casas_eliminadas+=1
except:
pass
try:
tabuleiro[x+1][y-2]
if (x+1,y-2) not in casas_proibidas:
casas_eliminadas+=1
except:
pass
try:
tabuleiro[x+2][y+1]
if (x+2,y+1) not in casas_proibidas:
casas_eliminadas+=1
except:
pass
try:
tabuleiro[x+2][y-1]
if (x+2,y-1) not in casas_proibidas:
casas_eliminadas+=1
except:
pass
lista_no_casas_eliminadas.append((x,y,casas_eliminadas))
if len(lista_no_casas_eliminadas)==0:
return winner
elif len(lista_no_casas_eliminadas)==1:
best_option=lista_no_casas_eliminadas[0]
else:
for k in range(len(lista_no_casas_eliminadas)-1):
if lista_no_casas_eliminadas[k][2]>lista_no_casas_eliminadas[k+1][2]:
best_option=lista_no_casas_eliminadas[k]
else:
best_option=lista_no_casas_eliminadas[k+1]
if winner==0:
winner=1
elif winner==1:
winner=0
return(Eliminar_casas(best_option))
lista=[]
for k in lista_sizes_boards:
casas_proibidas=[]
tabuleiro=[[k*0]for b in range(k)]
lista.append(Escolha_melhor_casa())
output=open("output.txt","w")
for i in lista:
output.write(str(i)+"\n")
```
No
| 100,417 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya and Gena play a very interesting game "Put a Knight!" on a chessboard n Γ n in size. In this game they take turns to put chess pieces called "knights" on the board so that no two knights could threat each other. A knight located in square (r, c) can threat squares (r - 1, c + 2), (r - 1, c - 2), (r + 1, c + 2), (r + 1, c - 2), (r - 2, c + 1), (r - 2, c - 1), (r + 2, c + 1) and (r + 2, c - 1) (some of the squares may be located outside the chessboard). The player who can't put a new knight during his move loses. Determine which player wins considering that both players play optimally well and Petya starts.
Input
The first line contains integer T (1 β€ T β€ 100) β the number of boards, for which you should determine the winning player. Next T lines contain T integers ni (1 β€ ni β€ 10000) β the sizes of the chessboards.
Output
For each ni Γ ni board print on a single line "0" if Petya wins considering both players play optimally well. Otherwise, print "1".
Examples
Input
2
2
1
Output
1
0
Submitted Solution:
```
print(1)
print(0)
```
No
| 100,418 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya and Gena play a very interesting game "Put a Knight!" on a chessboard n Γ n in size. In this game they take turns to put chess pieces called "knights" on the board so that no two knights could threat each other. A knight located in square (r, c) can threat squares (r - 1, c + 2), (r - 1, c - 2), (r + 1, c + 2), (r + 1, c - 2), (r - 2, c + 1), (r - 2, c - 1), (r + 2, c + 1) and (r + 2, c - 1) (some of the squares may be located outside the chessboard). The player who can't put a new knight during his move loses. Determine which player wins considering that both players play optimally well and Petya starts.
Input
The first line contains integer T (1 β€ T β€ 100) β the number of boards, for which you should determine the winning player. Next T lines contain T integers ni (1 β€ ni β€ 10000) β the sizes of the chessboards.
Output
For each ni Γ ni board print on a single line "0" if Petya wins considering both players play optimally well. Otherwise, print "1".
Examples
Input
2
2
1
Output
1
0
Submitted Solution:
```
output=open("output.txt","w")
lista_sizes_boards=[]
txt_object=open("input.txt","r")
no_boards=int(txt_object.readline())
for i in range(no_boards):
lista_sizes_boards.append(int(txt_object.readline()))
txt_object.close()
def Eliminar_casas(best_option):
x=best_option[0]
y=best_option[1]
casas_proibidas.append((x,y))
casas_proibidas.append((x-2,y+1))
casas_proibidas.append((x-2,y+1))
casas_proibidas.append((x-2,y+1))
casas_proibidas.append((x-2,y+1))
casas_proibidas.append((x-2,y+1))
casas_proibidas.append((x-2,y+1))
casas_proibidas.append((x-2,y+1))
casas_proibidas.append((x-2,y+1))
return(Escolha_melhor_casa())
def Escolha_melhor_casa():
global winner
lista_no_casas_eliminadas=[]
for x in range(len(tabuleiro)):
for y in range(len(tabuleiro)):
if (x,y) not in casas_proibidas:
casas_eliminadas=0
try:
tabuleiro[x-2][y+1]
if (x-2,y+1) not in casas_proibidas:
casas_eliminadas+=1
except:
pass
try:
tabuleiro[x-2][y-1]
if (x-2,y-1) not in casas_proibidas:
casas_eliminadas+=1
except:
pass
try:
tabuleiro[x-1][y+2]=1
if (x-1,y+2) not in casas_proibidas:
casas_eliminadas+=1
except:
pass
try:
tabuleiro[x-1][y-2]
if (x-1,y-2) not in casas_proibidas:
casas_eliminadas+=1
except:
pass
try:
tabuleiro[x+1][y+2]
if (x+1,y+1) not in casas_proibidas:
casas_eliminadas+=1
except:
pass
try:
tabuleiro[x+1][y-2]
if (x+1,y-2) not in casas_proibidas:
casas_eliminadas+=1
except:
pass
try:
tabuleiro[x+2][y+1]
if (x+2,y+1) not in casas_proibidas:
casas_eliminadas+=1
except:
pass
try:
tabuleiro[x+2][y-1]
if (x+2,y-1) not in casas_proibidas:
casas_eliminadas+=1
except:
pass
lista_no_casas_eliminadas.append((x,y,casas_eliminadas))
if len(lista_no_casas_eliminadas)==0:
return winner
elif len(lista_no_casas_eliminadas)==1:
best_option=lista_no_casas_eliminadas[0]
else:
for k in range(len(lista_no_casas_eliminadas)-1):
if lista_no_casas_eliminadas[k][2]>lista_no_casas_eliminadas[k+1][2]:
best_option=lista_no_casas_eliminadas[k]
else:
best_option=lista_no_casas_eliminadas[k+1]
if winner==0:
winner=1
elif winner==1:
winner=0
return(Eliminar_casas(best_option))
lista=[]
for k in lista_sizes_boards:
winner=1
casas_proibidas=[]
tabuleiro=[[k*0]for b in range(k)]
lista.append(Escolha_melhor_casa())
output.write(str(Escolha_melhor_casa())+"\n")
```
No
| 100,419 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ania has a large integer S. Its decimal representation has length n and doesn't contain any leading zeroes. Ania is allowed to change at most k digits of S. She wants to do it in such a way that S still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?
Input
The first line contains two integers n and k (1 β€ n β€ 200 000, 0 β€ k β€ n) β the number of digits in the decimal representation of S and the maximum allowed number of changed digits.
The second line contains the integer S. It's guaranteed that S has exactly n digits and doesn't contain any leading zeroes.
Output
Output the minimal possible value of S which Ania can end with. Note that the resulting integer should also have n digits.
Examples
Input
5 3
51528
Output
10028
Input
3 2
102
Output
100
Input
1 1
1
Output
0
Note
A number has leading zeroes if it consists of at least two digits and its first digit is 0. For example, numbers 00, 00069 and 0101 have leading zeroes, while 0, 3000 and 1010 don't have leading zeroes.
Tags: greedy, implementation
Correct Solution:
```
n,k=[int(i) for i in input().split()]
s=list(input())
if len(s) == 1 and k:
s='0'
k-=1
elif int(s[0])>1 and k:
k-=1
s[0]='1'
i=1
while k and i<len(s):
if s[i]!='0':
s[i]='0'
k-=1
i+=1
print(''.join(str(e) for e in s))
```
| 100,420 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ania has a large integer S. Its decimal representation has length n and doesn't contain any leading zeroes. Ania is allowed to change at most k digits of S. She wants to do it in such a way that S still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?
Input
The first line contains two integers n and k (1 β€ n β€ 200 000, 0 β€ k β€ n) β the number of digits in the decimal representation of S and the maximum allowed number of changed digits.
The second line contains the integer S. It's guaranteed that S has exactly n digits and doesn't contain any leading zeroes.
Output
Output the minimal possible value of S which Ania can end with. Note that the resulting integer should also have n digits.
Examples
Input
5 3
51528
Output
10028
Input
3 2
102
Output
100
Input
1 1
1
Output
0
Note
A number has leading zeroes if it consists of at least two digits and its first digit is 0. For example, numbers 00, 00069 and 0101 have leading zeroes, while 0, 3000 and 1010 don't have leading zeroes.
Tags: greedy, implementation
Correct Solution:
```
n,k=map(int,input().split())
arr=list(input())
lenght=len(arr)
for i in range(lenght):
arr[i]=int(arr[i])
if lenght==1 and k==1:
print("0")
elif lenght==1 and k==0:
print(arr[0])
elif lenght>1 and k<=lenght:
for i in range(lenght):
if arr[i]>1 and k>0 and i==0:
arr[0]=1
k-=1
elif arr[i]>=1 and k>0 and i>0:
arr[i]=0
k-=1
else:
pass
for i in range(lenght):
print(arr[i],end="")
else:
pass
```
| 100,421 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ania has a large integer S. Its decimal representation has length n and doesn't contain any leading zeroes. Ania is allowed to change at most k digits of S. She wants to do it in such a way that S still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?
Input
The first line contains two integers n and k (1 β€ n β€ 200 000, 0 β€ k β€ n) β the number of digits in the decimal representation of S and the maximum allowed number of changed digits.
The second line contains the integer S. It's guaranteed that S has exactly n digits and doesn't contain any leading zeroes.
Output
Output the minimal possible value of S which Ania can end with. Note that the resulting integer should also have n digits.
Examples
Input
5 3
51528
Output
10028
Input
3 2
102
Output
100
Input
1 1
1
Output
0
Note
A number has leading zeroes if it consists of at least two digits and its first digit is 0. For example, numbers 00, 00069 and 0101 have leading zeroes, while 0, 3000 and 1010 don't have leading zeroes.
Tags: greedy, implementation
Correct Solution:
```
s,k = map(int,input().split())
n = list(input())
if s == 1:
if k == 1 :
print(0)
else:
print(n[0])
else:
if n[0] > '1' and k>0:
n[0] = '1'
k = k-1
i = 1
while k>0 and i <s:
if n[i] != '0':
n[i] = '0'
k = k-1
i += 1
print("".join(n))
```
| 100,422 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ania has a large integer S. Its decimal representation has length n and doesn't contain any leading zeroes. Ania is allowed to change at most k digits of S. She wants to do it in such a way that S still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?
Input
The first line contains two integers n and k (1 β€ n β€ 200 000, 0 β€ k β€ n) β the number of digits in the decimal representation of S and the maximum allowed number of changed digits.
The second line contains the integer S. It's guaranteed that S has exactly n digits and doesn't contain any leading zeroes.
Output
Output the minimal possible value of S which Ania can end with. Note that the resulting integer should also have n digits.
Examples
Input
5 3
51528
Output
10028
Input
3 2
102
Output
100
Input
1 1
1
Output
0
Note
A number has leading zeroes if it consists of at least two digits and its first digit is 0. For example, numbers 00, 00069 and 0101 have leading zeroes, while 0, 3000 and 1010 don't have leading zeroes.
Tags: greedy, implementation
Correct Solution:
```
def hi(n,k,s):
x=''
a=0
if k==0:
return s
elif n==1 and k!=0:
return '0'
else:
x='1'
if s[0]!='1':
a+=1
for i in range(1,n):
if s[i]!='0' and a<k:
x+='0'
a+=1
else:
x+=s[i]
return x
n,k=map(int,input().split())
s=input()
print(hi(n,k,s))
```
| 100,423 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ania has a large integer S. Its decimal representation has length n and doesn't contain any leading zeroes. Ania is allowed to change at most k digits of S. She wants to do it in such a way that S still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?
Input
The first line contains two integers n and k (1 β€ n β€ 200 000, 0 β€ k β€ n) β the number of digits in the decimal representation of S and the maximum allowed number of changed digits.
The second line contains the integer S. It's guaranteed that S has exactly n digits and doesn't contain any leading zeroes.
Output
Output the minimal possible value of S which Ania can end with. Note that the resulting integer should also have n digits.
Examples
Input
5 3
51528
Output
10028
Input
3 2
102
Output
100
Input
1 1
1
Output
0
Note
A number has leading zeroes if it consists of at least two digits and its first digit is 0. For example, numbers 00, 00069 and 0101 have leading zeroes, while 0, 3000 and 1010 don't have leading zeroes.
Tags: greedy, implementation
Correct Solution:
```
n, k = map(int,input().split())
s = list(input())
l = ""
if n > 1:
for i in range(0, n):
if k == 0:
l += s[i]
elif i == 0:
if s[i] == "1":
l += "1"
else:
l += "1"
k -= 1
else:
if s[i] == "0":
l += "0"
else:
l += "0"
k -= 1
print(l)
else:
if k == 0:
print(s[0])
else:
print(0)
```
| 100,424 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ania has a large integer S. Its decimal representation has length n and doesn't contain any leading zeroes. Ania is allowed to change at most k digits of S. She wants to do it in such a way that S still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?
Input
The first line contains two integers n and k (1 β€ n β€ 200 000, 0 β€ k β€ n) β the number of digits in the decimal representation of S and the maximum allowed number of changed digits.
The second line contains the integer S. It's guaranteed that S has exactly n digits and doesn't contain any leading zeroes.
Output
Output the minimal possible value of S which Ania can end with. Note that the resulting integer should also have n digits.
Examples
Input
5 3
51528
Output
10028
Input
3 2
102
Output
100
Input
1 1
1
Output
0
Note
A number has leading zeroes if it consists of at least two digits and its first digit is 0. For example, numbers 00, 00069 and 0101 have leading zeroes, while 0, 3000 and 1010 don't have leading zeroes.
Tags: greedy, implementation
Correct Solution:
```
n,k = map(int,input().split())
a = list(input())
if(n==1 and k==1):
print(0)
elif(k==0):
print("".join(a))
else:
s = list("1"+"0"*(n-1))
for i in range(n):
if(k==0):
break
if(a[i]!=s[i]):
a[i] = s[i]
k=k-1
print("".join(a))
```
| 100,425 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ania has a large integer S. Its decimal representation has length n and doesn't contain any leading zeroes. Ania is allowed to change at most k digits of S. She wants to do it in such a way that S still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?
Input
The first line contains two integers n and k (1 β€ n β€ 200 000, 0 β€ k β€ n) β the number of digits in the decimal representation of S and the maximum allowed number of changed digits.
The second line contains the integer S. It's guaranteed that S has exactly n digits and doesn't contain any leading zeroes.
Output
Output the minimal possible value of S which Ania can end with. Note that the resulting integer should also have n digits.
Examples
Input
5 3
51528
Output
10028
Input
3 2
102
Output
100
Input
1 1
1
Output
0
Note
A number has leading zeroes if it consists of at least two digits and its first digit is 0. For example, numbers 00, 00069 and 0101 have leading zeroes, while 0, 3000 and 1010 don't have leading zeroes.
Tags: greedy, implementation
Correct Solution:
```
def main():
n,k=map(int,input().split())
x=input()
lis=list(x)
if k==0:
print(x)
return
if n==1:
print('0')
return
if lis[0]!='1':
k-=1
lis[0]='1'
for i in range(1,n):
if k==0:
break
if lis[i]!='0':
lis[i]='0'
k-=1
print("".join(lis))
main()
```
| 100,426 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ania has a large integer S. Its decimal representation has length n and doesn't contain any leading zeroes. Ania is allowed to change at most k digits of S. She wants to do it in such a way that S still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?
Input
The first line contains two integers n and k (1 β€ n β€ 200 000, 0 β€ k β€ n) β the number of digits in the decimal representation of S and the maximum allowed number of changed digits.
The second line contains the integer S. It's guaranteed that S has exactly n digits and doesn't contain any leading zeroes.
Output
Output the minimal possible value of S which Ania can end with. Note that the resulting integer should also have n digits.
Examples
Input
5 3
51528
Output
10028
Input
3 2
102
Output
100
Input
1 1
1
Output
0
Note
A number has leading zeroes if it consists of at least two digits and its first digit is 0. For example, numbers 00, 00069 and 0101 have leading zeroes, while 0, 3000 and 1010 don't have leading zeroes.
Tags: greedy, implementation
Correct Solution:
```
from sys import exit
n, k = map(int, input().split())
s = list(input())
if n == 1:
if k > 0:
print(0)
else:
print(s[0])
exit(0)
if k == 0:
print(''.join(s))
exit(0)
if s[0] != "1":
s[0], k = "1", k - 1
for i in range(1, len(s)):
if not k:
break
if s[i] != "0":
s[i], k = "0", k - 1
print(''.join(s))
```
| 100,427 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ania has a large integer S. Its decimal representation has length n and doesn't contain any leading zeroes. Ania is allowed to change at most k digits of S. She wants to do it in such a way that S still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?
Input
The first line contains two integers n and k (1 β€ n β€ 200 000, 0 β€ k β€ n) β the number of digits in the decimal representation of S and the maximum allowed number of changed digits.
The second line contains the integer S. It's guaranteed that S has exactly n digits and doesn't contain any leading zeroes.
Output
Output the minimal possible value of S which Ania can end with. Note that the resulting integer should also have n digits.
Examples
Input
5 3
51528
Output
10028
Input
3 2
102
Output
100
Input
1 1
1
Output
0
Note
A number has leading zeroes if it consists of at least two digits and its first digit is 0. For example, numbers 00, 00069 and 0101 have leading zeroes, while 0, 3000 and 1010 don't have leading zeroes.
Submitted Solution:
```
entrada = (input())
vet=entrada.split(" ")
tam = int(vet[0])
change = int(vet[1])
n = list(input())
aux = 0
aux1 = 0
while (aux != change and aux1 < tam):
if (aux1 == 0):
if (tam == 1):
n[aux1]="0"
aux+=1
elif (n[aux1]!="1"):
n[aux1]="1"
aux+=1
else:
if (n[aux1]!="0"):
n[aux1]="0"
aux+=1
aux1+=1
n = "".join(n)
print(n)
```
Yes
| 100,428 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ania has a large integer S. Its decimal representation has length n and doesn't contain any leading zeroes. Ania is allowed to change at most k digits of S. She wants to do it in such a way that S still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?
Input
The first line contains two integers n and k (1 β€ n β€ 200 000, 0 β€ k β€ n) β the number of digits in the decimal representation of S and the maximum allowed number of changed digits.
The second line contains the integer S. It's guaranteed that S has exactly n digits and doesn't contain any leading zeroes.
Output
Output the minimal possible value of S which Ania can end with. Note that the resulting integer should also have n digits.
Examples
Input
5 3
51528
Output
10028
Input
3 2
102
Output
100
Input
1 1
1
Output
0
Note
A number has leading zeroes if it consists of at least two digits and its first digit is 0. For example, numbers 00, 00069 and 0101 have leading zeroes, while 0, 3000 and 1010 don't have leading zeroes.
Submitted Solution:
```
n, k = map(int, input().split())
s = input()
if k == 0:
print(s)
exit()
if n == 1:
print(0)
exit()
first = True
ans = []
cnt = 0
for i in s:
if first and i != '1' and cnt < k:
print(1, end='')
cnt += 1
elif not first and i != '0' and cnt < k:
print(0, end='')
cnt += 1
else:
print(i, end='')
first = False
```
Yes
| 100,429 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ania has a large integer S. Its decimal representation has length n and doesn't contain any leading zeroes. Ania is allowed to change at most k digits of S. She wants to do it in such a way that S still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?
Input
The first line contains two integers n and k (1 β€ n β€ 200 000, 0 β€ k β€ n) β the number of digits in the decimal representation of S and the maximum allowed number of changed digits.
The second line contains the integer S. It's guaranteed that S has exactly n digits and doesn't contain any leading zeroes.
Output
Output the minimal possible value of S which Ania can end with. Note that the resulting integer should also have n digits.
Examples
Input
5 3
51528
Output
10028
Input
3 2
102
Output
100
Input
1 1
1
Output
0
Note
A number has leading zeroes if it consists of at least two digits and its first digit is 0. For example, numbers 00, 00069 and 0101 have leading zeroes, while 0, 3000 and 1010 don't have leading zeroes.
Submitted Solution:
```
n,k = list(map(int,input().split()))
arr = list(map(str,input()))
if n==1 and k>=1:
print(0)
exit()
ind = 0
temp = k
while(temp):
if ind>n-1:
break
if ind==0:
if arr[ind]=='1':
ind+=1
continue
else:
arr[ind]='1'
ind+=1
temp-=1
continue
if arr[ind]!='0':
arr[ind]='0'
temp-=1
ind+=1
else:
ind+=1
print(''.join(str(y) for y in arr))
```
Yes
| 100,430 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ania has a large integer S. Its decimal representation has length n and doesn't contain any leading zeroes. Ania is allowed to change at most k digits of S. She wants to do it in such a way that S still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?
Input
The first line contains two integers n and k (1 β€ n β€ 200 000, 0 β€ k β€ n) β the number of digits in the decimal representation of S and the maximum allowed number of changed digits.
The second line contains the integer S. It's guaranteed that S has exactly n digits and doesn't contain any leading zeroes.
Output
Output the minimal possible value of S which Ania can end with. Note that the resulting integer should also have n digits.
Examples
Input
5 3
51528
Output
10028
Input
3 2
102
Output
100
Input
1 1
1
Output
0
Note
A number has leading zeroes if it consists of at least two digits and its first digit is 0. For example, numbers 00, 00069 and 0101 have leading zeroes, while 0, 3000 and 1010 don't have leading zeroes.
Submitted Solution:
```
n, k = map(int, input().split())
d = list(input())
if n == 1 and k == 1:
exit(print(0))
(d[0], k) = ('1', k - 1) if d[0] != '1' and k > 0 else (d[0], k)
i = 1
while i < n and k != 0:
(d[i], k) = ('0', k - 1) if d[i] != '0' else (d[i], k)
i += 1
print(*d, sep="")
```
Yes
| 100,431 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ania has a large integer S. Its decimal representation has length n and doesn't contain any leading zeroes. Ania is allowed to change at most k digits of S. She wants to do it in such a way that S still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?
Input
The first line contains two integers n and k (1 β€ n β€ 200 000, 0 β€ k β€ n) β the number of digits in the decimal representation of S and the maximum allowed number of changed digits.
The second line contains the integer S. It's guaranteed that S has exactly n digits and doesn't contain any leading zeroes.
Output
Output the minimal possible value of S which Ania can end with. Note that the resulting integer should also have n digits.
Examples
Input
5 3
51528
Output
10028
Input
3 2
102
Output
100
Input
1 1
1
Output
0
Note
A number has leading zeroes if it consists of at least two digits and its first digit is 0. For example, numbers 00, 00069 and 0101 have leading zeroes, while 0, 3000 and 1010 don't have leading zeroes.
Submitted Solution:
```
n,k = [int(x) for x in input().split()]
s=list(input())
if k>0:
if s[0]!='1':
s[0]='1'
k-=1
if n>k:
for i in range(1,k+1):
s[i]='0'
print("".join(s))
else:
print("".join(s))
```
No
| 100,432 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ania has a large integer S. Its decimal representation has length n and doesn't contain any leading zeroes. Ania is allowed to change at most k digits of S. She wants to do it in such a way that S still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?
Input
The first line contains two integers n and k (1 β€ n β€ 200 000, 0 β€ k β€ n) β the number of digits in the decimal representation of S and the maximum allowed number of changed digits.
The second line contains the integer S. It's guaranteed that S has exactly n digits and doesn't contain any leading zeroes.
Output
Output the minimal possible value of S which Ania can end with. Note that the resulting integer should also have n digits.
Examples
Input
5 3
51528
Output
10028
Input
3 2
102
Output
100
Input
1 1
1
Output
0
Note
A number has leading zeroes if it consists of at least two digits and its first digit is 0. For example, numbers 00, 00069 and 0101 have leading zeroes, while 0, 3000 and 1010 don't have leading zeroes.
Submitted Solution:
```
n,k=map(int,input().split())
a=input()
a=[i for i in a]
for i in range(n):
if k==0:
break
if i==0:
if a[0]!='1':
a[0]='1'
k-=1
else:
if a[i]!='0':
a[i]='0'
k-=1
for i in a:
print(i,end='')
```
No
| 100,433 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ania has a large integer S. Its decimal representation has length n and doesn't contain any leading zeroes. Ania is allowed to change at most k digits of S. She wants to do it in such a way that S still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?
Input
The first line contains two integers n and k (1 β€ n β€ 200 000, 0 β€ k β€ n) β the number of digits in the decimal representation of S and the maximum allowed number of changed digits.
The second line contains the integer S. It's guaranteed that S has exactly n digits and doesn't contain any leading zeroes.
Output
Output the minimal possible value of S which Ania can end with. Note that the resulting integer should also have n digits.
Examples
Input
5 3
51528
Output
10028
Input
3 2
102
Output
100
Input
1 1
1
Output
0
Note
A number has leading zeroes if it consists of at least two digits and its first digit is 0. For example, numbers 00, 00069 and 0101 have leading zeroes, while 0, 3000 and 1010 don't have leading zeroes.
Submitted Solution:
```
n,s = map(int,input().split())
a = [*input()]
i = 1
if n == 1 and s >0:
a[0] = 0
if int(a[0]) > 1:
a[0] = 1
s -=1
while s > 0 and i < n:
if int(a[i]) > 0:
a[i] = 0
s -=1
i+=1
print(*a,sep='')
```
No
| 100,434 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ania has a large integer S. Its decimal representation has length n and doesn't contain any leading zeroes. Ania is allowed to change at most k digits of S. She wants to do it in such a way that S still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?
Input
The first line contains two integers n and k (1 β€ n β€ 200 000, 0 β€ k β€ n) β the number of digits in the decimal representation of S and the maximum allowed number of changed digits.
The second line contains the integer S. It's guaranteed that S has exactly n digits and doesn't contain any leading zeroes.
Output
Output the minimal possible value of S which Ania can end with. Note that the resulting integer should also have n digits.
Examples
Input
5 3
51528
Output
10028
Input
3 2
102
Output
100
Input
1 1
1
Output
0
Note
A number has leading zeroes if it consists of at least two digits and its first digit is 0. For example, numbers 00, 00069 and 0101 have leading zeroes, while 0, 3000 and 1010 don't have leading zeroes.
Submitted Solution:
```
n, k = map(int, input().split(' '))
nu = input()
if n == 1:
print(0)
else:
num = [i for i in nu]
for c in range(n):
if k == 0:
break
if c == 0 and num[c] != '1':
num[c] = '1'
k -= 1
else:
if num[c] != '0' and c != 0:
num[c] = '0'
k -= 1
print(''.join(num))
```
No
| 100,435 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is constraints.
Now elections are held in Berland and you want to win them. More precisely, you want everyone to vote for you.
There are n voters, and two ways to convince each of them to vote for you. The first way to convince the i-th voter is to pay him p_i coins. The second way is to make m_i other voters vote for you, and the i-th voter will vote for free.
Moreover, the process of such voting takes place in several steps. For example, if there are five voters with m_1 = 1, m_2 = 2, m_3 = 2, m_4 = 4, m_5 = 5, then you can buy the vote of the fifth voter, and eventually everyone will vote for you. Set of people voting for you will change as follows: {5} β {1, 5} β {1, 2, 3, 5} β {1, 2, 3, 4, 5}.
Calculate the minimum number of coins you have to spend so that everyone votes for you.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each test case contains one integer n (1 β€ n β€ 2 β
10^5) β the number of voters.
The next n lines contains the description of voters. i-th line contains two integers m_i and p_i (1 β€ p_i β€ 10^9, 0 β€ m_i < n).
It is guaranteed that the sum of all n over all test cases does not exceed 2 β
10^5.
Output
For each test case print one integer β the minimum number of coins you have to spend so that everyone votes for you.
Example
Input
3
3
1 5
2 10
2 8
7
0 1
3 1
1 1
6 1
1 1
4 1
4 1
6
2 6
2 3
2 8
2 7
4 4
5 5
Output
8
0
7
Note
In the first test case you have to buy vote of the third voter. Then the set of people voting for you will change as follows: {3} β {1, 3} β {1, 2, 3}.
In the second example you don't need to buy votes. The set of people voting for you will change as follows: {1} β {1, 3, 5} β {1, 2, 3, 5} β {1, 2, 3, 5, 6, 7} β {1, 2, 3, 4, 5, 6, 7}.
In the third test case you have to buy votes of the second and the fifth voters. Then the set of people voting for you will change as follows: {2, 5} β {1, 2, 3, 4, 5} β {1, 2, 3, 4, 5, 6}.
Tags: binary search, data structures, greedy
Correct Solution:
```
import sys
import heapq
def solve(pr, mm):
omm = []
n = len(mm)
for i in range(n + 1):
omm.append([])
for i in range(n):
omm[mm[i]].append(pr[i])
heap = []
c = 0
t = n
p = 0
for i in range(n, -1, -1):
for h in omm[i]:
heapq.heappush(heap, h)
t -= len(omm[i])
mn = max(i - c - t, 0)
c += mn
for j in range(mn):
p += heapq.heappop(heap)
return p
if __name__ == "__main__":
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
t = int(input().strip())
for i in range(t):
n = int(input().strip())
ms = []
ps = []
for j in range(n):
arr = [int(v) for v in input().strip().split(' ')]
ms.append(arr[0])
ps.append(arr[1])
print(solve(ps, ms))
```
| 100,436 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is constraints.
Now elections are held in Berland and you want to win them. More precisely, you want everyone to vote for you.
There are n voters, and two ways to convince each of them to vote for you. The first way to convince the i-th voter is to pay him p_i coins. The second way is to make m_i other voters vote for you, and the i-th voter will vote for free.
Moreover, the process of such voting takes place in several steps. For example, if there are five voters with m_1 = 1, m_2 = 2, m_3 = 2, m_4 = 4, m_5 = 5, then you can buy the vote of the fifth voter, and eventually everyone will vote for you. Set of people voting for you will change as follows: {5} β {1, 5} β {1, 2, 3, 5} β {1, 2, 3, 4, 5}.
Calculate the minimum number of coins you have to spend so that everyone votes for you.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each test case contains one integer n (1 β€ n β€ 2 β
10^5) β the number of voters.
The next n lines contains the description of voters. i-th line contains two integers m_i and p_i (1 β€ p_i β€ 10^9, 0 β€ m_i < n).
It is guaranteed that the sum of all n over all test cases does not exceed 2 β
10^5.
Output
For each test case print one integer β the minimum number of coins you have to spend so that everyone votes for you.
Example
Input
3
3
1 5
2 10
2 8
7
0 1
3 1
1 1
6 1
1 1
4 1
4 1
6
2 6
2 3
2 8
2 7
4 4
5 5
Output
8
0
7
Note
In the first test case you have to buy vote of the third voter. Then the set of people voting for you will change as follows: {3} β {1, 3} β {1, 2, 3}.
In the second example you don't need to buy votes. The set of people voting for you will change as follows: {1} β {1, 3, 5} β {1, 2, 3, 5} β {1, 2, 3, 5, 6, 7} β {1, 2, 3, 4, 5, 6, 7}.
In the third test case you have to buy votes of the second and the fifth voters. Then the set of people voting for you will change as follows: {2, 5} β {1, 2, 3, 4, 5} β {1, 2, 3, 4, 5, 6}.
Tags: binary search, data structures, greedy
Correct Solution:
```
import sys
import heapq as hq
readline = sys.stdin.readline
read = sys.stdin.read
ns = lambda: readline().rstrip()
ni = lambda: int(readline().rstrip())
nm = lambda: map(int, readline().split())
nl = lambda: list(map(int, readline().split()))
prn = lambda x: print(*x, sep='\n')
def solve():
n = ni()
vot = [tuple(nm()) for _ in range(n)]
vot.sort(key = lambda x: (-x[0], x[1]))
q = list()
c = 0
cost = 0
for i in range(n):
hq.heappush(q, vot[i][1])
while n - i - 1 + c < vot[i][0]:
cost += hq.heappop(q)
c += 1
print(cost)
return
# solve()
T = ni()
for _ in range(T):
solve()
```
| 100,437 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is constraints.
Now elections are held in Berland and you want to win them. More precisely, you want everyone to vote for you.
There are n voters, and two ways to convince each of them to vote for you. The first way to convince the i-th voter is to pay him p_i coins. The second way is to make m_i other voters vote for you, and the i-th voter will vote for free.
Moreover, the process of such voting takes place in several steps. For example, if there are five voters with m_1 = 1, m_2 = 2, m_3 = 2, m_4 = 4, m_5 = 5, then you can buy the vote of the fifth voter, and eventually everyone will vote for you. Set of people voting for you will change as follows: {5} β {1, 5} β {1, 2, 3, 5} β {1, 2, 3, 4, 5}.
Calculate the minimum number of coins you have to spend so that everyone votes for you.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each test case contains one integer n (1 β€ n β€ 2 β
10^5) β the number of voters.
The next n lines contains the description of voters. i-th line contains two integers m_i and p_i (1 β€ p_i β€ 10^9, 0 β€ m_i < n).
It is guaranteed that the sum of all n over all test cases does not exceed 2 β
10^5.
Output
For each test case print one integer β the minimum number of coins you have to spend so that everyone votes for you.
Example
Input
3
3
1 5
2 10
2 8
7
0 1
3 1
1 1
6 1
1 1
4 1
4 1
6
2 6
2 3
2 8
2 7
4 4
5 5
Output
8
0
7
Note
In the first test case you have to buy vote of the third voter. Then the set of people voting for you will change as follows: {3} β {1, 3} β {1, 2, 3}.
In the second example you don't need to buy votes. The set of people voting for you will change as follows: {1} β {1, 3, 5} β {1, 2, 3, 5} β {1, 2, 3, 5, 6, 7} β {1, 2, 3, 4, 5, 6, 7}.
In the third test case you have to buy votes of the second and the fifth voters. Then the set of people voting for you will change as follows: {2, 5} β {1, 2, 3, 4, 5} β {1, 2, 3, 4, 5, 6}.
Tags: binary search, data structures, greedy
Correct Solution:
```
import sys
from heapq import heappop, heappush
reader = (line.rstrip() for line in sys.stdin)
input = reader.__next__
t = int(input())
for _ in range(t):
n = int(input())
mp = []
for i in range(n):
mi, pi = map(int, input().split())
mp.append((mi, pi))
mp.sort()
prices = []
cost = 0
bribed = 0
i = n - 1
while i >= 0:
currM = mp[i][0]
heappush(prices, mp[i][1])
while i >= 1 and mp[i-1][0] == currM:
i -= 1
heappush(prices, mp[i][1])
already = i + bribed
for k in range(max(0, currM - already)):
cost += heappop(prices)
bribed += 1
i -= 1
print(cost)
```
| 100,438 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is constraints.
Now elections are held in Berland and you want to win them. More precisely, you want everyone to vote for you.
There are n voters, and two ways to convince each of them to vote for you. The first way to convince the i-th voter is to pay him p_i coins. The second way is to make m_i other voters vote for you, and the i-th voter will vote for free.
Moreover, the process of such voting takes place in several steps. For example, if there are five voters with m_1 = 1, m_2 = 2, m_3 = 2, m_4 = 4, m_5 = 5, then you can buy the vote of the fifth voter, and eventually everyone will vote for you. Set of people voting for you will change as follows: {5} β {1, 5} β {1, 2, 3, 5} β {1, 2, 3, 4, 5}.
Calculate the minimum number of coins you have to spend so that everyone votes for you.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each test case contains one integer n (1 β€ n β€ 2 β
10^5) β the number of voters.
The next n lines contains the description of voters. i-th line contains two integers m_i and p_i (1 β€ p_i β€ 10^9, 0 β€ m_i < n).
It is guaranteed that the sum of all n over all test cases does not exceed 2 β
10^5.
Output
For each test case print one integer β the minimum number of coins you have to spend so that everyone votes for you.
Example
Input
3
3
1 5
2 10
2 8
7
0 1
3 1
1 1
6 1
1 1
4 1
4 1
6
2 6
2 3
2 8
2 7
4 4
5 5
Output
8
0
7
Note
In the first test case you have to buy vote of the third voter. Then the set of people voting for you will change as follows: {3} β {1, 3} β {1, 2, 3}.
In the second example you don't need to buy votes. The set of people voting for you will change as follows: {1} β {1, 3, 5} β {1, 2, 3, 5} β {1, 2, 3, 5, 6, 7} β {1, 2, 3, 4, 5, 6, 7}.
In the third test case you have to buy votes of the second and the fifth voters. Then the set of people voting for you will change as follows: {2, 5} β {1, 2, 3, 4, 5} β {1, 2, 3, 4, 5, 6}.
Tags: binary search, data structures, greedy
Correct Solution:
```
import sys
input = sys.stdin.readline
import heapq
from itertools import accumulate
t=int(input())
for test in range(t):
n=int(input())
M=[[] for i in range(n)]
MCOUNT=[0]*(n)
for i in range(n):
m,p=map(int,input().split())
M[m].append(p)
MCOUNT[m]+=1
#print(M)
#print(MCOUNT)
ACC=list(accumulate(MCOUNT))
#print(ACC)
HQ=[]
ANS=0
use=0
for i in range(n-1,-1,-1):
for j in M[i]:
heapq.heappush(HQ,j)
#print(HQ)
while ACC[i-1]+use<i:
x=heapq.heappop(HQ)
ANS+=x
use+=1
print(ANS)
```
| 100,439 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is constraints.
Now elections are held in Berland and you want to win them. More precisely, you want everyone to vote for you.
There are n voters, and two ways to convince each of them to vote for you. The first way to convince the i-th voter is to pay him p_i coins. The second way is to make m_i other voters vote for you, and the i-th voter will vote for free.
Moreover, the process of such voting takes place in several steps. For example, if there are five voters with m_1 = 1, m_2 = 2, m_3 = 2, m_4 = 4, m_5 = 5, then you can buy the vote of the fifth voter, and eventually everyone will vote for you. Set of people voting for you will change as follows: {5} β {1, 5} β {1, 2, 3, 5} β {1, 2, 3, 4, 5}.
Calculate the minimum number of coins you have to spend so that everyone votes for you.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each test case contains one integer n (1 β€ n β€ 2 β
10^5) β the number of voters.
The next n lines contains the description of voters. i-th line contains two integers m_i and p_i (1 β€ p_i β€ 10^9, 0 β€ m_i < n).
It is guaranteed that the sum of all n over all test cases does not exceed 2 β
10^5.
Output
For each test case print one integer β the minimum number of coins you have to spend so that everyone votes for you.
Example
Input
3
3
1 5
2 10
2 8
7
0 1
3 1
1 1
6 1
1 1
4 1
4 1
6
2 6
2 3
2 8
2 7
4 4
5 5
Output
8
0
7
Note
In the first test case you have to buy vote of the third voter. Then the set of people voting for you will change as follows: {3} β {1, 3} β {1, 2, 3}.
In the second example you don't need to buy votes. The set of people voting for you will change as follows: {1} β {1, 3, 5} β {1, 2, 3, 5} β {1, 2, 3, 5, 6, 7} β {1, 2, 3, 4, 5, 6, 7}.
In the third test case you have to buy votes of the second and the fifth voters. Then the set of people voting for you will change as follows: {2, 5} β {1, 2, 3, 4, 5} β {1, 2, 3, 4, 5, 6}.
Tags: binary search, data structures, greedy
Correct Solution:
```
import sys
input = sys.stdin.readline
import heapq as hq
t = int(input())
for _ in range(t):
n = int(input())
vt = [list(map(int,input().split())) for i in range(n)]
vt.sort(reverse=True)
q = []
hq.heapify(q)
ans = 0
cnt = 0
for i in range(n):
hq.heappush(q,vt[i][1])
if vt[i][0] >= n-i+cnt:
ans += hq.heappop(q)
cnt += 1
print(ans)
```
| 100,440 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is constraints.
Now elections are held in Berland and you want to win them. More precisely, you want everyone to vote for you.
There are n voters, and two ways to convince each of them to vote for you. The first way to convince the i-th voter is to pay him p_i coins. The second way is to make m_i other voters vote for you, and the i-th voter will vote for free.
Moreover, the process of such voting takes place in several steps. For example, if there are five voters with m_1 = 1, m_2 = 2, m_3 = 2, m_4 = 4, m_5 = 5, then you can buy the vote of the fifth voter, and eventually everyone will vote for you. Set of people voting for you will change as follows: {5} β {1, 5} β {1, 2, 3, 5} β {1, 2, 3, 4, 5}.
Calculate the minimum number of coins you have to spend so that everyone votes for you.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each test case contains one integer n (1 β€ n β€ 2 β
10^5) β the number of voters.
The next n lines contains the description of voters. i-th line contains two integers m_i and p_i (1 β€ p_i β€ 10^9, 0 β€ m_i < n).
It is guaranteed that the sum of all n over all test cases does not exceed 2 β
10^5.
Output
For each test case print one integer β the minimum number of coins you have to spend so that everyone votes for you.
Example
Input
3
3
1 5
2 10
2 8
7
0 1
3 1
1 1
6 1
1 1
4 1
4 1
6
2 6
2 3
2 8
2 7
4 4
5 5
Output
8
0
7
Note
In the first test case you have to buy vote of the third voter. Then the set of people voting for you will change as follows: {3} β {1, 3} β {1, 2, 3}.
In the second example you don't need to buy votes. The set of people voting for you will change as follows: {1} β {1, 3, 5} β {1, 2, 3, 5} β {1, 2, 3, 5, 6, 7} β {1, 2, 3, 4, 5, 6, 7}.
In the third test case you have to buy votes of the second and the fifth voters. Then the set of people voting for you will change as follows: {2, 5} β {1, 2, 3, 4, 5} β {1, 2, 3, 4, 5, 6}.
Tags: binary search, data structures, greedy
Correct Solution:
```
import heapq
import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
n = int(input())
info = [list(map(int, input().split())) for i in range(n)]
info = sorted(info)
cnt = [0] * n
for i in range(n):
ind = info[i][0]
cnt[ind] += 1
ruiseki_cnt = [0] * (n+1)
for i in range(n):
ruiseki_cnt[i+1] = ruiseki_cnt[i] + cnt[i]
# print(cnt)
# print(ruiseki_cnt)
need = [0] * n
for i in range(1,n):
if cnt[i] != 0 and i > ruiseki_cnt[i]:
need[i] = min(i - ruiseki_cnt[i], i)
# print(need)
info = sorted(info, reverse = True)
#print(info)
num = n - 1
pos = 0
q = []
used_cnt = 0
ans = 0
while True:
if num == -1:
break
while True:
if pos < n and info[pos][0] >= num:
heapq.heappush(q, info[pos][1])
pos += 1
else:
break
if need[num] - used_cnt > 0:
tmp = need[num] - used_cnt
for _ in range(tmp):
ans += heapq.heappop(q)
used_cnt += tmp
num -= 1
print(ans)
```
| 100,441 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is constraints.
Now elections are held in Berland and you want to win them. More precisely, you want everyone to vote for you.
There are n voters, and two ways to convince each of them to vote for you. The first way to convince the i-th voter is to pay him p_i coins. The second way is to make m_i other voters vote for you, and the i-th voter will vote for free.
Moreover, the process of such voting takes place in several steps. For example, if there are five voters with m_1 = 1, m_2 = 2, m_3 = 2, m_4 = 4, m_5 = 5, then you can buy the vote of the fifth voter, and eventually everyone will vote for you. Set of people voting for you will change as follows: {5} β {1, 5} β {1, 2, 3, 5} β {1, 2, 3, 4, 5}.
Calculate the minimum number of coins you have to spend so that everyone votes for you.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each test case contains one integer n (1 β€ n β€ 2 β
10^5) β the number of voters.
The next n lines contains the description of voters. i-th line contains two integers m_i and p_i (1 β€ p_i β€ 10^9, 0 β€ m_i < n).
It is guaranteed that the sum of all n over all test cases does not exceed 2 β
10^5.
Output
For each test case print one integer β the minimum number of coins you have to spend so that everyone votes for you.
Example
Input
3
3
1 5
2 10
2 8
7
0 1
3 1
1 1
6 1
1 1
4 1
4 1
6
2 6
2 3
2 8
2 7
4 4
5 5
Output
8
0
7
Note
In the first test case you have to buy vote of the third voter. Then the set of people voting for you will change as follows: {3} β {1, 3} β {1, 2, 3}.
In the second example you don't need to buy votes. The set of people voting for you will change as follows: {1} β {1, 3, 5} β {1, 2, 3, 5} β {1, 2, 3, 5, 6, 7} β {1, 2, 3, 4, 5, 6, 7}.
In the third test case you have to buy votes of the second and the fifth voters. Then the set of people voting for you will change as follows: {2, 5} β {1, 2, 3, 4, 5} β {1, 2, 3, 4, 5, 6}.
Tags: binary search, data structures, greedy
Correct Solution:
```
from sys import stdin, stdout
import heapq
class MyHeap(object):
def __init__(self, initial=None, key=lambda x:x):
self.key = key
if initial:
self._data = [(key(item), item) for item in initial]
heapq.heapify(self._data)
else:
self._data = []
def push(self, item):
heapq.heappush(self._data, (self.key(item), item))
def pop(self):
return heapq.heappop(self._data)[1]
def print(self):
for hd in self._data:
print(hd)
print('-------------------------------')
def getminnumerofcoins(n, mpa):
res = 0
mpa.sort(key=lambda x: (x[0], -x[1]))
gap = []
cur = 0
for i in range(len(mpa)):
mp = mpa[i]
#print(mp[0])
if mp[0] > cur:
t = [i, mp[0]-cur]
gap.append(t)
#cur = mp[0]
cur += 1
#print(gap)
if len(gap) == 0:
return 0
hp = MyHeap(key=lambda x: x[1])
gp = gap.pop()
lidx = gp[0]
remaing = gp[1]
#print(remaing)
for i in range(lidx, len(mpa)):
ci = [i, mpa[i][1]]
hp.push(ci)
cur = 0
offset = 0
for i in range(len(mpa)):
mp = mpa[i]
need = mp[0] - cur
if need > 0:
for j in range(need):
if (remaing == 0 or len(hp._data) == 0) and len(gap) > 0:
#print(i)
lg = gap.pop()
while len(gap) > 0 and lg[1] - offset <= 0:
lg = gap.pop()
for k in range(lg[0], lidx):
ci = [k, mpa[k][1]]
hp.push(ci)
lidx = lg[0]
remaing = lg[1] - offset
c = hp.pop()
#print(c)
if c[0] == i:
c = hp.pop()
#print(c)
res += c[1]
cur += 1
offset += 1
remaing -= 1
cur += 1
return res
if __name__ == '__main__':
t = int(stdin.readline())
for i in range(t):
n = int(stdin.readline())
mpa = []
for j in range(n):
mp = list(map(int, stdin.readline().split()))
mpa.append(mp)
res = getminnumerofcoins(n, mpa)
stdout.write(str(res) + '\n')
```
| 100,442 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is constraints.
Now elections are held in Berland and you want to win them. More precisely, you want everyone to vote for you.
There are n voters, and two ways to convince each of them to vote for you. The first way to convince the i-th voter is to pay him p_i coins. The second way is to make m_i other voters vote for you, and the i-th voter will vote for free.
Moreover, the process of such voting takes place in several steps. For example, if there are five voters with m_1 = 1, m_2 = 2, m_3 = 2, m_4 = 4, m_5 = 5, then you can buy the vote of the fifth voter, and eventually everyone will vote for you. Set of people voting for you will change as follows: {5} β {1, 5} β {1, 2, 3, 5} β {1, 2, 3, 4, 5}.
Calculate the minimum number of coins you have to spend so that everyone votes for you.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each test case contains one integer n (1 β€ n β€ 2 β
10^5) β the number of voters.
The next n lines contains the description of voters. i-th line contains two integers m_i and p_i (1 β€ p_i β€ 10^9, 0 β€ m_i < n).
It is guaranteed that the sum of all n over all test cases does not exceed 2 β
10^5.
Output
For each test case print one integer β the minimum number of coins you have to spend so that everyone votes for you.
Example
Input
3
3
1 5
2 10
2 8
7
0 1
3 1
1 1
6 1
1 1
4 1
4 1
6
2 6
2 3
2 8
2 7
4 4
5 5
Output
8
0
7
Note
In the first test case you have to buy vote of the third voter. Then the set of people voting for you will change as follows: {3} β {1, 3} β {1, 2, 3}.
In the second example you don't need to buy votes. The set of people voting for you will change as follows: {1} β {1, 3, 5} β {1, 2, 3, 5} β {1, 2, 3, 5, 6, 7} β {1, 2, 3, 4, 5, 6, 7}.
In the third test case you have to buy votes of the second and the fifth voters. Then the set of people voting for you will change as follows: {2, 5} β {1, 2, 3, 4, 5} β {1, 2, 3, 4, 5, 6}.
Tags: binary search, data structures, greedy
Correct Solution:
```
import sys
from array import array # noqa: F401
import typing as Tp # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
def main():
from collections import defaultdict
from heapq import heappop, heappush
t = int(input())
ans = [''] * t
for ti in range(t):
n = int(input())
dd: Tp.Dict[int, Tp.List[int]] = defaultdict(list)
costs = [0] * n
for i in range(n):
mi, pi = map(int, input().split())
dd[mi].append(i)
costs[i] = pi
hq = []
for cnt in range(n):
for x in dd[cnt]:
heappush(hq, -costs[x])
if hq:
heappop(hq)
ans[ti] = str(-sum(hq))
sys.stdout.buffer.write(('\n'.join(ans) + '\n').encode('utf-8'))
if __name__ == '__main__':
main()
```
| 100,443 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is constraints.
Now elections are held in Berland and you want to win them. More precisely, you want everyone to vote for you.
There are n voters, and two ways to convince each of them to vote for you. The first way to convince the i-th voter is to pay him p_i coins. The second way is to make m_i other voters vote for you, and the i-th voter will vote for free.
Moreover, the process of such voting takes place in several steps. For example, if there are five voters with m_1 = 1, m_2 = 2, m_3 = 2, m_4 = 4, m_5 = 5, then you can buy the vote of the fifth voter, and eventually everyone will vote for you. Set of people voting for you will change as follows: {5} β {1, 5} β {1, 2, 3, 5} β {1, 2, 3, 4, 5}.
Calculate the minimum number of coins you have to spend so that everyone votes for you.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each test case contains one integer n (1 β€ n β€ 2 β
10^5) β the number of voters.
The next n lines contains the description of voters. i-th line contains two integers m_i and p_i (1 β€ p_i β€ 10^9, 0 β€ m_i < n).
It is guaranteed that the sum of all n over all test cases does not exceed 2 β
10^5.
Output
For each test case print one integer β the minimum number of coins you have to spend so that everyone votes for you.
Example
Input
3
3
1 5
2 10
2 8
7
0 1
3 1
1 1
6 1
1 1
4 1
4 1
6
2 6
2 3
2 8
2 7
4 4
5 5
Output
8
0
7
Note
In the first test case you have to buy vote of the third voter. Then the set of people voting for you will change as follows: {3} β {1, 3} β {1, 2, 3}.
In the second example you don't need to buy votes. The set of people voting for you will change as follows: {1} β {1, 3, 5} β {1, 2, 3, 5} β {1, 2, 3, 5, 6, 7} β {1, 2, 3, 4, 5, 6, 7}.
In the third test case you have to buy votes of the second and the fifth voters. Then the set of people voting for you will change as follows: {2, 5} β {1, 2, 3, 4, 5} β {1, 2, 3, 4, 5, 6}.
Submitted Solution:
```
import sys
def I():
return sys.stdin.readline().rstrip()
class Heap:
def __init__( self ):
self.l = [ -1 ]
self.n = 0
def n( self ):
return self.n
def top( self ):
return self.l[ 1 ]
def ins( self, x ):
self.l.append( x )
n = len( self.l ) - 1
i = n
while i > 1:
j = i // 2
if self.l[ j ] > self.l[ i ]:
self.l[ j ], self.l[ i ] = self.l[ i ], self.l[ j ]
i = j
else:
break
def pop( self ):
r = self.l[ 1 ]
l = self.l.pop()
n = len( self.l ) - 1
if n:
self.l[ 1 ] = l
i = 1
while True:
j = i * 2
k = j + 1
if k < len( self.l ) and self.l[ i ] > max( self.l[ j ], self.l[ k ] ):
if self.l[ j ] == min( self.l[ j ], self.l[ k ] ):
self.l[ i ], self.l[ j ] = self.l[ j ], self.l[ i ]
i = j
else:
self.l[ i ], self.l[ k ] = self.l[ k ], self.l[ i ]
i = k
elif k < len( self.l ) and self.l[ i ] > self.l[ k ]:
self.l[ i ], self.l[ k ] = self.l[ k ], self.l[ i ]
i = k
elif j < len( self.l ) and self.l[ i ] > self.l[ j ]:
self.l[ i ], self.l[ j ] = self.l[ j ], self.l[ i ]
i = j
else:
break
return r
t = int( I() )
for _ in range( t ):
n = int( I() )
voter = [ list( map( int, I().split() ) ) for _ in range( n ) ]
h = Heap()
d = {}
for m, p in voter:
if m not in d:
d[ m ] = []
d[ m ].append( p )
need = {}
c = 0
sk = sorted( d.keys() )
for m in sk:
need[ m ] = max( 0, m - c )
c += len( d[ m ] )
c = 0
ans = 0
for m in sk[::-1]:
for p in d[ m ]:
h.ins( p )
while c < need[ m ]:
c += 1
ans += h.pop()
print( ans )
```
Yes
| 100,444 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You play a strategic video game (yeah, we ran out of good problem legends). In this game you control a large army, and your goal is to conquer n castles of your opponent.
Let's describe the game process in detail. Initially you control an army of k warriors. Your enemy controls n castles; to conquer the i-th castle, you need at least a_i warriors (you are so good at this game that you don't lose any warriors while taking over a castle, so your army stays the same after the fight). After you take control over a castle, you recruit new warriors into your army β formally, after you capture the i-th castle, b_i warriors join your army. Furthermore, after capturing a castle (or later) you can defend it: if you leave at least one warrior in a castle, this castle is considered defended. Each castle has an importance parameter c_i, and your total score is the sum of importance values over all defended castles. There are two ways to defend a castle:
* if you are currently in the castle i, you may leave one warrior to defend castle i;
* there are m one-way portals connecting the castles. Each portal is characterised by two numbers of castles u and v (for each portal holds u > v). A portal can be used as follows: if you are currently in the castle u, you may send one warrior to defend castle v.
Obviously, when you order your warrior to defend some castle, he leaves your army.
You capture the castles in fixed order: you have to capture the first one, then the second one, and so on. After you capture the castle i (but only before capturing castle i + 1) you may recruit new warriors from castle i, leave a warrior to defend castle i, and use any number of portals leading from castle i to other castles having smaller numbers. As soon as you capture the next castle, these actions for castle i won't be available to you.
If, during some moment in the game, you don't have enough warriors to capture the next castle, you lose. Your goal is to maximize the sum of importance values over all defended castles (note that you may hire new warriors in the last castle, defend it and use portals leading from it even after you capture it β your score will be calculated afterwards).
Can you determine an optimal strategy of capturing and defending the castles?
Input
The first line contains three integers n, m and k (1 β€ n β€ 5000, 0 β€ m β€ min((n(n - 1))/(2), 3 β
10^5), 0 β€ k β€ 5000) β the number of castles, the number of portals and initial size of your army, respectively.
Then n lines follow. The i-th line describes the i-th castle with three integers a_i, b_i and c_i (0 β€ a_i, b_i, c_i β€ 5000) β the number of warriors required to capture the i-th castle, the number of warriors available for hire in this castle and its importance value.
Then m lines follow. The i-th line describes the i-th portal with two integers u_i and v_i (1 β€ v_i < u_i β€ n), meaning that the portal leads from the castle u_i to the castle v_i. There are no two same portals listed.
It is guaranteed that the size of your army won't exceed 5000 under any circumstances (i. e. k + β_{i = 1}^{n} b_i β€ 5000).
Output
If it's impossible to capture all the castles, print one integer -1.
Otherwise, print one integer equal to the maximum sum of importance values of defended castles.
Examples
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 3
Output
5
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 1
Output
22
Input
4 3 7
7 4 17
3 0 8
11 2 0
14 3 5
3 1
2 1
4 3
Output
-1
Note
The best course of action in the first example is as follows:
1. capture the first castle;
2. hire warriors from the first castle, your army has 11 warriors now;
3. capture the second castle;
4. capture the third castle;
5. hire warriors from the third castle, your army has 13 warriors now;
6. capture the fourth castle;
7. leave one warrior to protect the fourth castle, your army has 12 warriors now.
This course of action (and several other ones) gives 5 as your total score.
The best course of action in the second example is as follows:
1. capture the first castle;
2. hire warriors from the first castle, your army has 11 warriors now;
3. capture the second castle;
4. capture the third castle;
5. hire warriors from the third castle, your army has 13 warriors now;
6. capture the fourth castle;
7. leave one warrior to protect the fourth castle, your army has 12 warriors now;
8. send one warrior to protect the first castle through the third portal, your army has 11 warriors now.
This course of action (and several other ones) gives 22 as your total score.
In the third example it's impossible to capture the last castle: you need 14 warriors to do so, but you can accumulate no more than 13 without capturing it.
Tags: data structures, dp, greedy, implementation, sortings
Correct Solution:
```
from sys import stdin, stdout
from collections import namedtuple, deque
from bisect import insort
Castle = namedtuple("Castle", ['defense','recruit','importance'])
n,m,k = map(int, stdin.readline().split())
castles = []
portals = {}
for i in range(n):
a,b,c = map(int, stdin.readline().split())
castles.append(Castle(a,b,c))
portals[i] = -1
for _ in range(m):
u,v = map(int,stdin.readline().split())
if u > v and u-1 > portals[v-1]:
portals[v-1] = u-1
defending = deque()
pending = deque()
score = 0
for i,c in enumerate(castles):
while k < c.defense and defending:
v = defending.popleft()
score -= v
k+=1
if k < c.defense:
score = -1
break
k += c.recruit
while pending and pending[0][0] == i:
_,v = pending.popleft()
k-=1
score += v
insort(defending, v)
if portals[i] < 0:
k-=1
insort(defending, c.importance)
score += c.importance
else:
insort(pending, (portals[i], c.importance))
else:
while k < 0:
v = defending.popleft()
k+=1
score-=v
stdout.write("{}\n".format(score))
```
| 100,445 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You play a strategic video game (yeah, we ran out of good problem legends). In this game you control a large army, and your goal is to conquer n castles of your opponent.
Let's describe the game process in detail. Initially you control an army of k warriors. Your enemy controls n castles; to conquer the i-th castle, you need at least a_i warriors (you are so good at this game that you don't lose any warriors while taking over a castle, so your army stays the same after the fight). After you take control over a castle, you recruit new warriors into your army β formally, after you capture the i-th castle, b_i warriors join your army. Furthermore, after capturing a castle (or later) you can defend it: if you leave at least one warrior in a castle, this castle is considered defended. Each castle has an importance parameter c_i, and your total score is the sum of importance values over all defended castles. There are two ways to defend a castle:
* if you are currently in the castle i, you may leave one warrior to defend castle i;
* there are m one-way portals connecting the castles. Each portal is characterised by two numbers of castles u and v (for each portal holds u > v). A portal can be used as follows: if you are currently in the castle u, you may send one warrior to defend castle v.
Obviously, when you order your warrior to defend some castle, he leaves your army.
You capture the castles in fixed order: you have to capture the first one, then the second one, and so on. After you capture the castle i (but only before capturing castle i + 1) you may recruit new warriors from castle i, leave a warrior to defend castle i, and use any number of portals leading from castle i to other castles having smaller numbers. As soon as you capture the next castle, these actions for castle i won't be available to you.
If, during some moment in the game, you don't have enough warriors to capture the next castle, you lose. Your goal is to maximize the sum of importance values over all defended castles (note that you may hire new warriors in the last castle, defend it and use portals leading from it even after you capture it β your score will be calculated afterwards).
Can you determine an optimal strategy of capturing and defending the castles?
Input
The first line contains three integers n, m and k (1 β€ n β€ 5000, 0 β€ m β€ min((n(n - 1))/(2), 3 β
10^5), 0 β€ k β€ 5000) β the number of castles, the number of portals and initial size of your army, respectively.
Then n lines follow. The i-th line describes the i-th castle with three integers a_i, b_i and c_i (0 β€ a_i, b_i, c_i β€ 5000) β the number of warriors required to capture the i-th castle, the number of warriors available for hire in this castle and its importance value.
Then m lines follow. The i-th line describes the i-th portal with two integers u_i and v_i (1 β€ v_i < u_i β€ n), meaning that the portal leads from the castle u_i to the castle v_i. There are no two same portals listed.
It is guaranteed that the size of your army won't exceed 5000 under any circumstances (i. e. k + β_{i = 1}^{n} b_i β€ 5000).
Output
If it's impossible to capture all the castles, print one integer -1.
Otherwise, print one integer equal to the maximum sum of importance values of defended castles.
Examples
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 3
Output
5
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 1
Output
22
Input
4 3 7
7 4 17
3 0 8
11 2 0
14 3 5
3 1
2 1
4 3
Output
-1
Note
The best course of action in the first example is as follows:
1. capture the first castle;
2. hire warriors from the first castle, your army has 11 warriors now;
3. capture the second castle;
4. capture the third castle;
5. hire warriors from the third castle, your army has 13 warriors now;
6. capture the fourth castle;
7. leave one warrior to protect the fourth castle, your army has 12 warriors now.
This course of action (and several other ones) gives 5 as your total score.
The best course of action in the second example is as follows:
1. capture the first castle;
2. hire warriors from the first castle, your army has 11 warriors now;
3. capture the second castle;
4. capture the third castle;
5. hire warriors from the third castle, your army has 13 warriors now;
6. capture the fourth castle;
7. leave one warrior to protect the fourth castle, your army has 12 warriors now;
8. send one warrior to protect the first castle through the third portal, your army has 11 warriors now.
This course of action (and several other ones) gives 22 as your total score.
In the third example it's impossible to capture the last castle: you need 14 warriors to do so, but you can accumulate no more than 13 without capturing it.
Tags: data structures, dp, greedy, implementation, sortings
Correct Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
class SortedList:
def __init__(self, iterable=None, _load=200):
"""Initialize sorted list instance."""
if iterable is None:
iterable = []
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError('{0!r} not in list'.format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return 'SortedList({0})'.format(list(self))
def main():
n,m,k = map(int,input().split())
req,inc,imp = [],[],[]
for _ in range(n):
a1,b1,c1 = map(int,input().split())
req.append(a1)
inc.append(b1)
imp.append(c1)
path = [[] for _ in range(n)]
for _ in range(m):
u1,v1 = map(int,input().split())
path[u1-1].append(v1-1)
excess,si = [0]*n,k
for i in range(n):
if req[i] > si:
return -1
si += inc[i]
excess[i] = si-req[i+1] if i != n-1 else si
for i in range(n-2,-1,-1):
excess[i] = min(excess[i],excess[i+1])
curr,visi,ans = SortedList(),[0]*n,0
for i in range(n-1,-1,-1):
if not visi[i]:
visi[i] = i
curr.add(imp[i])
for j in path[i]:
if not visi[j]:
visi[j] = i
curr.add(imp[j])
for _ in range(excess[i]-(0 if not i else excess[i-1])):
if len(curr):
ans += curr.pop()
else:
break
return ans
# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
print(main())
```
| 100,446 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You play a strategic video game (yeah, we ran out of good problem legends). In this game you control a large army, and your goal is to conquer n castles of your opponent.
Let's describe the game process in detail. Initially you control an army of k warriors. Your enemy controls n castles; to conquer the i-th castle, you need at least a_i warriors (you are so good at this game that you don't lose any warriors while taking over a castle, so your army stays the same after the fight). After you take control over a castle, you recruit new warriors into your army β formally, after you capture the i-th castle, b_i warriors join your army. Furthermore, after capturing a castle (or later) you can defend it: if you leave at least one warrior in a castle, this castle is considered defended. Each castle has an importance parameter c_i, and your total score is the sum of importance values over all defended castles. There are two ways to defend a castle:
* if you are currently in the castle i, you may leave one warrior to defend castle i;
* there are m one-way portals connecting the castles. Each portal is characterised by two numbers of castles u and v (for each portal holds u > v). A portal can be used as follows: if you are currently in the castle u, you may send one warrior to defend castle v.
Obviously, when you order your warrior to defend some castle, he leaves your army.
You capture the castles in fixed order: you have to capture the first one, then the second one, and so on. After you capture the castle i (but only before capturing castle i + 1) you may recruit new warriors from castle i, leave a warrior to defend castle i, and use any number of portals leading from castle i to other castles having smaller numbers. As soon as you capture the next castle, these actions for castle i won't be available to you.
If, during some moment in the game, you don't have enough warriors to capture the next castle, you lose. Your goal is to maximize the sum of importance values over all defended castles (note that you may hire new warriors in the last castle, defend it and use portals leading from it even after you capture it β your score will be calculated afterwards).
Can you determine an optimal strategy of capturing and defending the castles?
Input
The first line contains three integers n, m and k (1 β€ n β€ 5000, 0 β€ m β€ min((n(n - 1))/(2), 3 β
10^5), 0 β€ k β€ 5000) β the number of castles, the number of portals and initial size of your army, respectively.
Then n lines follow. The i-th line describes the i-th castle with three integers a_i, b_i and c_i (0 β€ a_i, b_i, c_i β€ 5000) β the number of warriors required to capture the i-th castle, the number of warriors available for hire in this castle and its importance value.
Then m lines follow. The i-th line describes the i-th portal with two integers u_i and v_i (1 β€ v_i < u_i β€ n), meaning that the portal leads from the castle u_i to the castle v_i. There are no two same portals listed.
It is guaranteed that the size of your army won't exceed 5000 under any circumstances (i. e. k + β_{i = 1}^{n} b_i β€ 5000).
Output
If it's impossible to capture all the castles, print one integer -1.
Otherwise, print one integer equal to the maximum sum of importance values of defended castles.
Examples
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 3
Output
5
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 1
Output
22
Input
4 3 7
7 4 17
3 0 8
11 2 0
14 3 5
3 1
2 1
4 3
Output
-1
Note
The best course of action in the first example is as follows:
1. capture the first castle;
2. hire warriors from the first castle, your army has 11 warriors now;
3. capture the second castle;
4. capture the third castle;
5. hire warriors from the third castle, your army has 13 warriors now;
6. capture the fourth castle;
7. leave one warrior to protect the fourth castle, your army has 12 warriors now.
This course of action (and several other ones) gives 5 as your total score.
The best course of action in the second example is as follows:
1. capture the first castle;
2. hire warriors from the first castle, your army has 11 warriors now;
3. capture the second castle;
4. capture the third castle;
5. hire warriors from the third castle, your army has 13 warriors now;
6. capture the fourth castle;
7. leave one warrior to protect the fourth castle, your army has 12 warriors now;
8. send one warrior to protect the first castle through the third portal, your army has 11 warriors now.
This course of action (and several other ones) gives 22 as your total score.
In the third example it's impossible to capture the last castle: you need 14 warriors to do so, but you can accumulate no more than 13 without capturing it.
Tags: data structures, dp, greedy, implementation, sortings
Correct Solution:
```
import sys
input = sys.stdin.buffer.readline
N, M, K = map(int, input().split())
A = [0] * N
B = [0] * N
C_raw = [0] * N
for i in range(N):
A[i], B[i], C_raw[i] = map(int, input().split())
adj = [[] for _ in range(N+1)]
for _ in range(M):
u, v = map(int, input().split())
adj[v].append(u)
C = [[] for _ in range(N)]
for i in range(N):
if adj[i+1]:
C[max(adj[i+1])-1].append(C_raw[i])
else:
C[i].append(C_raw[i])
for i in range(N):
if C[i]:
C[i].sort(reverse=True)
dp = [[-10**5] * 5001 for _ in range(N+1)]
dp[0][K] = 0
for i in range(N):
for k in range(5001):
if dp[i][k] >= 0:
if k >= A[i]:
dp[i+1][k+B[i]] = max(dp[i+1][k+B[i]], dp[i][k])
p = k + B[i]
q = 0
cnt = 0
for ci in C[i]:
if p > 0:
p -= 1
q += ci
cnt += 1
dp[i+1][k+B[i] - cnt] = max(dp[i+1][k+B[i] - cnt], dp[i][k] + q)
else:
break
if max(dp[-1]) >= 0:
print(max(dp[-1]))
else:
print(-1)
```
| 100,447 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You play a strategic video game (yeah, we ran out of good problem legends). In this game you control a large army, and your goal is to conquer n castles of your opponent.
Let's describe the game process in detail. Initially you control an army of k warriors. Your enemy controls n castles; to conquer the i-th castle, you need at least a_i warriors (you are so good at this game that you don't lose any warriors while taking over a castle, so your army stays the same after the fight). After you take control over a castle, you recruit new warriors into your army β formally, after you capture the i-th castle, b_i warriors join your army. Furthermore, after capturing a castle (or later) you can defend it: if you leave at least one warrior in a castle, this castle is considered defended. Each castle has an importance parameter c_i, and your total score is the sum of importance values over all defended castles. There are two ways to defend a castle:
* if you are currently in the castle i, you may leave one warrior to defend castle i;
* there are m one-way portals connecting the castles. Each portal is characterised by two numbers of castles u and v (for each portal holds u > v). A portal can be used as follows: if you are currently in the castle u, you may send one warrior to defend castle v.
Obviously, when you order your warrior to defend some castle, he leaves your army.
You capture the castles in fixed order: you have to capture the first one, then the second one, and so on. After you capture the castle i (but only before capturing castle i + 1) you may recruit new warriors from castle i, leave a warrior to defend castle i, and use any number of portals leading from castle i to other castles having smaller numbers. As soon as you capture the next castle, these actions for castle i won't be available to you.
If, during some moment in the game, you don't have enough warriors to capture the next castle, you lose. Your goal is to maximize the sum of importance values over all defended castles (note that you may hire new warriors in the last castle, defend it and use portals leading from it even after you capture it β your score will be calculated afterwards).
Can you determine an optimal strategy of capturing and defending the castles?
Input
The first line contains three integers n, m and k (1 β€ n β€ 5000, 0 β€ m β€ min((n(n - 1))/(2), 3 β
10^5), 0 β€ k β€ 5000) β the number of castles, the number of portals and initial size of your army, respectively.
Then n lines follow. The i-th line describes the i-th castle with three integers a_i, b_i and c_i (0 β€ a_i, b_i, c_i β€ 5000) β the number of warriors required to capture the i-th castle, the number of warriors available for hire in this castle and its importance value.
Then m lines follow. The i-th line describes the i-th portal with two integers u_i and v_i (1 β€ v_i < u_i β€ n), meaning that the portal leads from the castle u_i to the castle v_i. There are no two same portals listed.
It is guaranteed that the size of your army won't exceed 5000 under any circumstances (i. e. k + β_{i = 1}^{n} b_i β€ 5000).
Output
If it's impossible to capture all the castles, print one integer -1.
Otherwise, print one integer equal to the maximum sum of importance values of defended castles.
Examples
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 3
Output
5
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 1
Output
22
Input
4 3 7
7 4 17
3 0 8
11 2 0
14 3 5
3 1
2 1
4 3
Output
-1
Note
The best course of action in the first example is as follows:
1. capture the first castle;
2. hire warriors from the first castle, your army has 11 warriors now;
3. capture the second castle;
4. capture the third castle;
5. hire warriors from the third castle, your army has 13 warriors now;
6. capture the fourth castle;
7. leave one warrior to protect the fourth castle, your army has 12 warriors now.
This course of action (and several other ones) gives 5 as your total score.
The best course of action in the second example is as follows:
1. capture the first castle;
2. hire warriors from the first castle, your army has 11 warriors now;
3. capture the second castle;
4. capture the third castle;
5. hire warriors from the third castle, your army has 13 warriors now;
6. capture the fourth castle;
7. leave one warrior to protect the fourth castle, your army has 12 warriors now;
8. send one warrior to protect the first castle through the third portal, your army has 11 warriors now.
This course of action (and several other ones) gives 22 as your total score.
In the third example it's impossible to capture the last castle: you need 14 warriors to do so, but you can accumulate no more than 13 without capturing it.
Tags: data structures, dp, greedy, implementation, sortings
Correct Solution:
```
import sys
input = sys.stdin.readline
from collections import *
n, m, k = map(int, input().split())
a, b, c = [], [], []
for _ in range(n):
ai, bi, ci = map(int, input().split())
a.append(ai)
b.append(bi)
c.append(ci)
now = k
for i in range(n):
if now<a[i]:
print(-1)
exit()
now += b[i]
G = [[] for _ in range(n)]
for _ in range(m):
u, v = map(int, input().split())
G[u-1].append(v-1)
last = [-1]*n
flag = [False]*n
for i in range(n-1, -1, -1):
if not flag[i]:
last[i] = i
flag[i] = True
for j in G[i]:
if not flag[j]:
last[j] = i
flag[j] = True
ic = [(i, c[i]) for i in range(n)]
ic.sort(key=lambda t: t[1], reverse=True)
ans = 0
decre = [0]*n
for i, ci in ic:
now = k
decre[last[i]] += 1
flag = False
for j in range(n):
if now<a[j]:
decre[last[i]] -= 1
flag = True
break
now += b[j]
now -= decre[j]
if flag:
continue
else:
if now<0:
decre[last[i]] -= 1
else:
ans += ci
print(ans)
```
| 100,448 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You play a strategic video game (yeah, we ran out of good problem legends). In this game you control a large army, and your goal is to conquer n castles of your opponent.
Let's describe the game process in detail. Initially you control an army of k warriors. Your enemy controls n castles; to conquer the i-th castle, you need at least a_i warriors (you are so good at this game that you don't lose any warriors while taking over a castle, so your army stays the same after the fight). After you take control over a castle, you recruit new warriors into your army β formally, after you capture the i-th castle, b_i warriors join your army. Furthermore, after capturing a castle (or later) you can defend it: if you leave at least one warrior in a castle, this castle is considered defended. Each castle has an importance parameter c_i, and your total score is the sum of importance values over all defended castles. There are two ways to defend a castle:
* if you are currently in the castle i, you may leave one warrior to defend castle i;
* there are m one-way portals connecting the castles. Each portal is characterised by two numbers of castles u and v (for each portal holds u > v). A portal can be used as follows: if you are currently in the castle u, you may send one warrior to defend castle v.
Obviously, when you order your warrior to defend some castle, he leaves your army.
You capture the castles in fixed order: you have to capture the first one, then the second one, and so on. After you capture the castle i (but only before capturing castle i + 1) you may recruit new warriors from castle i, leave a warrior to defend castle i, and use any number of portals leading from castle i to other castles having smaller numbers. As soon as you capture the next castle, these actions for castle i won't be available to you.
If, during some moment in the game, you don't have enough warriors to capture the next castle, you lose. Your goal is to maximize the sum of importance values over all defended castles (note that you may hire new warriors in the last castle, defend it and use portals leading from it even after you capture it β your score will be calculated afterwards).
Can you determine an optimal strategy of capturing and defending the castles?
Input
The first line contains three integers n, m and k (1 β€ n β€ 5000, 0 β€ m β€ min((n(n - 1))/(2), 3 β
10^5), 0 β€ k β€ 5000) β the number of castles, the number of portals and initial size of your army, respectively.
Then n lines follow. The i-th line describes the i-th castle with three integers a_i, b_i and c_i (0 β€ a_i, b_i, c_i β€ 5000) β the number of warriors required to capture the i-th castle, the number of warriors available for hire in this castle and its importance value.
Then m lines follow. The i-th line describes the i-th portal with two integers u_i and v_i (1 β€ v_i < u_i β€ n), meaning that the portal leads from the castle u_i to the castle v_i. There are no two same portals listed.
It is guaranteed that the size of your army won't exceed 5000 under any circumstances (i. e. k + β_{i = 1}^{n} b_i β€ 5000).
Output
If it's impossible to capture all the castles, print one integer -1.
Otherwise, print one integer equal to the maximum sum of importance values of defended castles.
Examples
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 3
Output
5
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 1
Output
22
Input
4 3 7
7 4 17
3 0 8
11 2 0
14 3 5
3 1
2 1
4 3
Output
-1
Note
The best course of action in the first example is as follows:
1. capture the first castle;
2. hire warriors from the first castle, your army has 11 warriors now;
3. capture the second castle;
4. capture the third castle;
5. hire warriors from the third castle, your army has 13 warriors now;
6. capture the fourth castle;
7. leave one warrior to protect the fourth castle, your army has 12 warriors now.
This course of action (and several other ones) gives 5 as your total score.
The best course of action in the second example is as follows:
1. capture the first castle;
2. hire warriors from the first castle, your army has 11 warriors now;
3. capture the second castle;
4. capture the third castle;
5. hire warriors from the third castle, your army has 13 warriors now;
6. capture the fourth castle;
7. leave one warrior to protect the fourth castle, your army has 12 warriors now;
8. send one warrior to protect the first castle through the third portal, your army has 11 warriors now.
This course of action (and several other ones) gives 22 as your total score.
In the third example it's impossible to capture the last castle: you need 14 warriors to do so, but you can accumulate no more than 13 without capturing it.
Tags: data structures, dp, greedy, implementation, sortings
Correct Solution:
```
import sys
input = sys.stdin.readline
import heapq as hp
def main():
N, M, K = map(int, input().split())
ABC = [list(map(int, input().split())) for _ in range(N)]
Tmp = [i for i in range(N)]
for _ in range(M):
a, b = map(int, input().split())
Tmp[b-1] = max(Tmp[b-1], a-1)
Val = [[] for _ in range(N)]
for i, (_, _, c) in enumerate(ABC):
Val[Tmp[i]].append(c)
q = []
S = K
for i, (a, b, _) in enumerate(ABC):
vacant = S-a
if vacant < 0:
return -1
while len(q) > vacant:
hp.heappop(q)
S += b
for p in Val[i]:
hp.heappush(q, p)
while len(q) > S:
hp.heappop(q)
return sum(q)
if __name__ == "__main__":
print(main())
```
| 100,449 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You play a strategic video game (yeah, we ran out of good problem legends). In this game you control a large army, and your goal is to conquer n castles of your opponent.
Let's describe the game process in detail. Initially you control an army of k warriors. Your enemy controls n castles; to conquer the i-th castle, you need at least a_i warriors (you are so good at this game that you don't lose any warriors while taking over a castle, so your army stays the same after the fight). After you take control over a castle, you recruit new warriors into your army β formally, after you capture the i-th castle, b_i warriors join your army. Furthermore, after capturing a castle (or later) you can defend it: if you leave at least one warrior in a castle, this castle is considered defended. Each castle has an importance parameter c_i, and your total score is the sum of importance values over all defended castles. There are two ways to defend a castle:
* if you are currently in the castle i, you may leave one warrior to defend castle i;
* there are m one-way portals connecting the castles. Each portal is characterised by two numbers of castles u and v (for each portal holds u > v). A portal can be used as follows: if you are currently in the castle u, you may send one warrior to defend castle v.
Obviously, when you order your warrior to defend some castle, he leaves your army.
You capture the castles in fixed order: you have to capture the first one, then the second one, and so on. After you capture the castle i (but only before capturing castle i + 1) you may recruit new warriors from castle i, leave a warrior to defend castle i, and use any number of portals leading from castle i to other castles having smaller numbers. As soon as you capture the next castle, these actions for castle i won't be available to you.
If, during some moment in the game, you don't have enough warriors to capture the next castle, you lose. Your goal is to maximize the sum of importance values over all defended castles (note that you may hire new warriors in the last castle, defend it and use portals leading from it even after you capture it β your score will be calculated afterwards).
Can you determine an optimal strategy of capturing and defending the castles?
Input
The first line contains three integers n, m and k (1 β€ n β€ 5000, 0 β€ m β€ min((n(n - 1))/(2), 3 β
10^5), 0 β€ k β€ 5000) β the number of castles, the number of portals and initial size of your army, respectively.
Then n lines follow. The i-th line describes the i-th castle with three integers a_i, b_i and c_i (0 β€ a_i, b_i, c_i β€ 5000) β the number of warriors required to capture the i-th castle, the number of warriors available for hire in this castle and its importance value.
Then m lines follow. The i-th line describes the i-th portal with two integers u_i and v_i (1 β€ v_i < u_i β€ n), meaning that the portal leads from the castle u_i to the castle v_i. There are no two same portals listed.
It is guaranteed that the size of your army won't exceed 5000 under any circumstances (i. e. k + β_{i = 1}^{n} b_i β€ 5000).
Output
If it's impossible to capture all the castles, print one integer -1.
Otherwise, print one integer equal to the maximum sum of importance values of defended castles.
Examples
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 3
Output
5
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 1
Output
22
Input
4 3 7
7 4 17
3 0 8
11 2 0
14 3 5
3 1
2 1
4 3
Output
-1
Note
The best course of action in the first example is as follows:
1. capture the first castle;
2. hire warriors from the first castle, your army has 11 warriors now;
3. capture the second castle;
4. capture the third castle;
5. hire warriors from the third castle, your army has 13 warriors now;
6. capture the fourth castle;
7. leave one warrior to protect the fourth castle, your army has 12 warriors now.
This course of action (and several other ones) gives 5 as your total score.
The best course of action in the second example is as follows:
1. capture the first castle;
2. hire warriors from the first castle, your army has 11 warriors now;
3. capture the second castle;
4. capture the third castle;
5. hire warriors from the third castle, your army has 13 warriors now;
6. capture the fourth castle;
7. leave one warrior to protect the fourth castle, your army has 12 warriors now;
8. send one warrior to protect the first castle through the third portal, your army has 11 warriors now.
This course of action (and several other ones) gives 22 as your total score.
In the third example it's impossible to capture the last castle: you need 14 warriors to do so, but you can accumulate no more than 13 without capturing it.
Tags: data structures, dp, greedy, implementation, sortings
Correct Solution:
```
import sys
input = lambda: sys.stdin.readline().rstrip()
MX = 5001
n, m, k = map(int, input().split())
xyz = []
for _ in range(n):
x, y, z = map(int, input().split())
xyz.append((x, y, z))
graph = [[] for _ in range(n)]
mx_list = [0]*n
for _ in range(m):
u, v = map(int, input().split())
if mx_list[v-1] < u-1:
mx_list[v-1] = u-1
for v, u in enumerate(mx_list):
if u>0:
graph[u].append(v)
no_portal = {i for i, j in enumerate(mx_list) if j==0}
dp = [-1]*MX
dp[k] = 0
for i in range(n):
x, y, z = xyz[i]
newdp = [-1]*MX
li = []
if i in no_portal:
li.append(z)
for to in graph[i]:
li.append(xyz[to][2])
li.sort(reverse=True)
for j in range(len(li)-1):
li[j+1] += li[j]
li = [0] + li
for j in range(x, MX-y):
if dp[j]<0:
continue
for l in range(len(li)):
if j+y-l<0:
break
if newdp[j+y-l] < dp[j] + li[l]:
newdp[j+y-l] = dp[j] + li[l]
dp = newdp
print(max(dp))
```
| 100,450 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You play a strategic video game (yeah, we ran out of good problem legends). In this game you control a large army, and your goal is to conquer n castles of your opponent.
Let's describe the game process in detail. Initially you control an army of k warriors. Your enemy controls n castles; to conquer the i-th castle, you need at least a_i warriors (you are so good at this game that you don't lose any warriors while taking over a castle, so your army stays the same after the fight). After you take control over a castle, you recruit new warriors into your army β formally, after you capture the i-th castle, b_i warriors join your army. Furthermore, after capturing a castle (or later) you can defend it: if you leave at least one warrior in a castle, this castle is considered defended. Each castle has an importance parameter c_i, and your total score is the sum of importance values over all defended castles. There are two ways to defend a castle:
* if you are currently in the castle i, you may leave one warrior to defend castle i;
* there are m one-way portals connecting the castles. Each portal is characterised by two numbers of castles u and v (for each portal holds u > v). A portal can be used as follows: if you are currently in the castle u, you may send one warrior to defend castle v.
Obviously, when you order your warrior to defend some castle, he leaves your army.
You capture the castles in fixed order: you have to capture the first one, then the second one, and so on. After you capture the castle i (but only before capturing castle i + 1) you may recruit new warriors from castle i, leave a warrior to defend castle i, and use any number of portals leading from castle i to other castles having smaller numbers. As soon as you capture the next castle, these actions for castle i won't be available to you.
If, during some moment in the game, you don't have enough warriors to capture the next castle, you lose. Your goal is to maximize the sum of importance values over all defended castles (note that you may hire new warriors in the last castle, defend it and use portals leading from it even after you capture it β your score will be calculated afterwards).
Can you determine an optimal strategy of capturing and defending the castles?
Input
The first line contains three integers n, m and k (1 β€ n β€ 5000, 0 β€ m β€ min((n(n - 1))/(2), 3 β
10^5), 0 β€ k β€ 5000) β the number of castles, the number of portals and initial size of your army, respectively.
Then n lines follow. The i-th line describes the i-th castle with three integers a_i, b_i and c_i (0 β€ a_i, b_i, c_i β€ 5000) β the number of warriors required to capture the i-th castle, the number of warriors available for hire in this castle and its importance value.
Then m lines follow. The i-th line describes the i-th portal with two integers u_i and v_i (1 β€ v_i < u_i β€ n), meaning that the portal leads from the castle u_i to the castle v_i. There are no two same portals listed.
It is guaranteed that the size of your army won't exceed 5000 under any circumstances (i. e. k + β_{i = 1}^{n} b_i β€ 5000).
Output
If it's impossible to capture all the castles, print one integer -1.
Otherwise, print one integer equal to the maximum sum of importance values of defended castles.
Examples
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 3
Output
5
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 1
Output
22
Input
4 3 7
7 4 17
3 0 8
11 2 0
14 3 5
3 1
2 1
4 3
Output
-1
Note
The best course of action in the first example is as follows:
1. capture the first castle;
2. hire warriors from the first castle, your army has 11 warriors now;
3. capture the second castle;
4. capture the third castle;
5. hire warriors from the third castle, your army has 13 warriors now;
6. capture the fourth castle;
7. leave one warrior to protect the fourth castle, your army has 12 warriors now.
This course of action (and several other ones) gives 5 as your total score.
The best course of action in the second example is as follows:
1. capture the first castle;
2. hire warriors from the first castle, your army has 11 warriors now;
3. capture the second castle;
4. capture the third castle;
5. hire warriors from the third castle, your army has 13 warriors now;
6. capture the fourth castle;
7. leave one warrior to protect the fourth castle, your army has 12 warriors now;
8. send one warrior to protect the first castle through the third portal, your army has 11 warriors now.
This course of action (and several other ones) gives 22 as your total score.
In the third example it's impossible to capture the last castle: you need 14 warriors to do so, but you can accumulate no more than 13 without capturing it.
Tags: data structures, dp, greedy, implementation, sortings
Correct Solution:
```
import sys
input = sys.stdin.readline
n, m, k = map(int, input().split())
cas = [list(map(int, input().split())) for i in range(n)]
pot = [list(map(int, input().split())) for i in range(m)]
timing = [i for i in range(n)]
for i in range(m):
a, b = pot[i]
a -= 1
b -= 1
if a > b:
a, b = b, a
timing[a] = max(b, timing[a])
time = [[] for i in range(n)]
for i in range(n):
time[timing[i]].append(cas[i][2])
for i in range(n):
time[timing[i]].sort(reverse = True)
memo = {}
memo[k] = 0
for i in range(n):
a, add_, c = cas[i]
memo2 = {}
for j in memo:
if j >= a:
memo2[j + add_] = memo[j]
for num in time[i]:
tmp = memo2.copy()
for j in tmp:
if j-1 not in memo2:
memo2[j-1] = tmp[j] + num
else:
memo2[j-1] = max(tmp[j-1], tmp[j] + num)
memo = memo2.copy()
ans = -1
for i in memo:
ans = max(ans, memo[i])
print(ans)
```
| 100,451 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You play a strategic video game (yeah, we ran out of good problem legends). In this game you control a large army, and your goal is to conquer n castles of your opponent.
Let's describe the game process in detail. Initially you control an army of k warriors. Your enemy controls n castles; to conquer the i-th castle, you need at least a_i warriors (you are so good at this game that you don't lose any warriors while taking over a castle, so your army stays the same after the fight). After you take control over a castle, you recruit new warriors into your army β formally, after you capture the i-th castle, b_i warriors join your army. Furthermore, after capturing a castle (or later) you can defend it: if you leave at least one warrior in a castle, this castle is considered defended. Each castle has an importance parameter c_i, and your total score is the sum of importance values over all defended castles. There are two ways to defend a castle:
* if you are currently in the castle i, you may leave one warrior to defend castle i;
* there are m one-way portals connecting the castles. Each portal is characterised by two numbers of castles u and v (for each portal holds u > v). A portal can be used as follows: if you are currently in the castle u, you may send one warrior to defend castle v.
Obviously, when you order your warrior to defend some castle, he leaves your army.
You capture the castles in fixed order: you have to capture the first one, then the second one, and so on. After you capture the castle i (but only before capturing castle i + 1) you may recruit new warriors from castle i, leave a warrior to defend castle i, and use any number of portals leading from castle i to other castles having smaller numbers. As soon as you capture the next castle, these actions for castle i won't be available to you.
If, during some moment in the game, you don't have enough warriors to capture the next castle, you lose. Your goal is to maximize the sum of importance values over all defended castles (note that you may hire new warriors in the last castle, defend it and use portals leading from it even after you capture it β your score will be calculated afterwards).
Can you determine an optimal strategy of capturing and defending the castles?
Input
The first line contains three integers n, m and k (1 β€ n β€ 5000, 0 β€ m β€ min((n(n - 1))/(2), 3 β
10^5), 0 β€ k β€ 5000) β the number of castles, the number of portals and initial size of your army, respectively.
Then n lines follow. The i-th line describes the i-th castle with three integers a_i, b_i and c_i (0 β€ a_i, b_i, c_i β€ 5000) β the number of warriors required to capture the i-th castle, the number of warriors available for hire in this castle and its importance value.
Then m lines follow. The i-th line describes the i-th portal with two integers u_i and v_i (1 β€ v_i < u_i β€ n), meaning that the portal leads from the castle u_i to the castle v_i. There are no two same portals listed.
It is guaranteed that the size of your army won't exceed 5000 under any circumstances (i. e. k + β_{i = 1}^{n} b_i β€ 5000).
Output
If it's impossible to capture all the castles, print one integer -1.
Otherwise, print one integer equal to the maximum sum of importance values of defended castles.
Examples
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 3
Output
5
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 1
Output
22
Input
4 3 7
7 4 17
3 0 8
11 2 0
14 3 5
3 1
2 1
4 3
Output
-1
Note
The best course of action in the first example is as follows:
1. capture the first castle;
2. hire warriors from the first castle, your army has 11 warriors now;
3. capture the second castle;
4. capture the third castle;
5. hire warriors from the third castle, your army has 13 warriors now;
6. capture the fourth castle;
7. leave one warrior to protect the fourth castle, your army has 12 warriors now.
This course of action (and several other ones) gives 5 as your total score.
The best course of action in the second example is as follows:
1. capture the first castle;
2. hire warriors from the first castle, your army has 11 warriors now;
3. capture the second castle;
4. capture the third castle;
5. hire warriors from the third castle, your army has 13 warriors now;
6. capture the fourth castle;
7. leave one warrior to protect the fourth castle, your army has 12 warriors now;
8. send one warrior to protect the first castle through the third portal, your army has 11 warriors now.
This course of action (and several other ones) gives 22 as your total score.
In the third example it's impossible to capture the last castle: you need 14 warriors to do so, but you can accumulate no more than 13 without capturing it.
Tags: data structures, dp, greedy, implementation, sortings
Correct Solution:
```
import sys
n, m, k = map(int, input().split())
castle = [list(map(int, sys.stdin.readline().split())) for _ in range(n)]
_p = [[] for _ in range(n)]
endpoints = [0]*n
for u, v in (map(int, l.split()) for l in sys.stdin):
_p[v-1].append(u-1)
endpoints[v-1] = 1
portal = [[] for _ in range(n)]
for t in range(n):
if _p[t]:
s = max(_p[t])
portal[s].append(castle[t][2])
max_n = 5000
dp = [-1]*(max_n+1)
dp[k] = 0
for i, (a, b, c) in enumerate(castle):
next_dp = [-1]*(max_n+1)
p = portal[i]
if not endpoints[i]:
p.append(c)
p.sort(reverse=True)
for i in range(len(p)-1):
p[i+1] += p[i]
p = [0] + p
len_p = len(p)
for i in range(a, max_n-b+1):
if dp[i] == -1:
continue
w = i + b
for j in range(len_p):
next_dp[w-j] = max(next_dp[w-j], dp[i]+p[j])
if w-j == 0:
break
dp = next_dp
print(max(dp))
```
| 100,452 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You play a strategic video game (yeah, we ran out of good problem legends). In this game you control a large army, and your goal is to conquer n castles of your opponent.
Let's describe the game process in detail. Initially you control an army of k warriors. Your enemy controls n castles; to conquer the i-th castle, you need at least a_i warriors (you are so good at this game that you don't lose any warriors while taking over a castle, so your army stays the same after the fight). After you take control over a castle, you recruit new warriors into your army β formally, after you capture the i-th castle, b_i warriors join your army. Furthermore, after capturing a castle (or later) you can defend it: if you leave at least one warrior in a castle, this castle is considered defended. Each castle has an importance parameter c_i, and your total score is the sum of importance values over all defended castles. There are two ways to defend a castle:
* if you are currently in the castle i, you may leave one warrior to defend castle i;
* there are m one-way portals connecting the castles. Each portal is characterised by two numbers of castles u and v (for each portal holds u > v). A portal can be used as follows: if you are currently in the castle u, you may send one warrior to defend castle v.
Obviously, when you order your warrior to defend some castle, he leaves your army.
You capture the castles in fixed order: you have to capture the first one, then the second one, and so on. After you capture the castle i (but only before capturing castle i + 1) you may recruit new warriors from castle i, leave a warrior to defend castle i, and use any number of portals leading from castle i to other castles having smaller numbers. As soon as you capture the next castle, these actions for castle i won't be available to you.
If, during some moment in the game, you don't have enough warriors to capture the next castle, you lose. Your goal is to maximize the sum of importance values over all defended castles (note that you may hire new warriors in the last castle, defend it and use portals leading from it even after you capture it β your score will be calculated afterwards).
Can you determine an optimal strategy of capturing and defending the castles?
Input
The first line contains three integers n, m and k (1 β€ n β€ 5000, 0 β€ m β€ min((n(n - 1))/(2), 3 β
10^5), 0 β€ k β€ 5000) β the number of castles, the number of portals and initial size of your army, respectively.
Then n lines follow. The i-th line describes the i-th castle with three integers a_i, b_i and c_i (0 β€ a_i, b_i, c_i β€ 5000) β the number of warriors required to capture the i-th castle, the number of warriors available for hire in this castle and its importance value.
Then m lines follow. The i-th line describes the i-th portal with two integers u_i and v_i (1 β€ v_i < u_i β€ n), meaning that the portal leads from the castle u_i to the castle v_i. There are no two same portals listed.
It is guaranteed that the size of your army won't exceed 5000 under any circumstances (i. e. k + β_{i = 1}^{n} b_i β€ 5000).
Output
If it's impossible to capture all the castles, print one integer -1.
Otherwise, print one integer equal to the maximum sum of importance values of defended castles.
Examples
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 3
Output
5
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 1
Output
22
Input
4 3 7
7 4 17
3 0 8
11 2 0
14 3 5
3 1
2 1
4 3
Output
-1
Note
The best course of action in the first example is as follows:
1. capture the first castle;
2. hire warriors from the first castle, your army has 11 warriors now;
3. capture the second castle;
4. capture the third castle;
5. hire warriors from the third castle, your army has 13 warriors now;
6. capture the fourth castle;
7. leave one warrior to protect the fourth castle, your army has 12 warriors now.
This course of action (and several other ones) gives 5 as your total score.
The best course of action in the second example is as follows:
1. capture the first castle;
2. hire warriors from the first castle, your army has 11 warriors now;
3. capture the second castle;
4. capture the third castle;
5. hire warriors from the third castle, your army has 13 warriors now;
6. capture the fourth castle;
7. leave one warrior to protect the fourth castle, your army has 12 warriors now;
8. send one warrior to protect the first castle through the third portal, your army has 11 warriors now.
This course of action (and several other ones) gives 22 as your total score.
In the third example it's impossible to capture the last castle: you need 14 warriors to do so, but you can accumulate no more than 13 without capturing it.
Submitted Solution:
```
from heapq import heappush, heappop
n, m, k = map(int, input().split())
a = [0]
b = [0]
c = [0]
for i in range(n):
aa, bb, cc = map(int, input().split())
a.append(aa)
b.append(bb)
c.append(cc)
a += [0]
road = [[] for i in range(n+1)]
last = [i for i in range(0, n+1)]
for i in range(m):
u, v = map(int, input().split())
last[v] = max(last[v], u)
for i in range(1, n+1):
road[last[i]].append(i)
value = []
fin = True
for i in range(1, n+1):
while (k < a[i] and value):
k += 1
heappop(value)
if (k < a[i]):
fin = False
break
k += b[i]
for j in road[i]:
heappush(value, c[j])
k -= 1
if (fin == False):
print(-1)
else:
while (k < 0):
k += 1
heappop(value)
ans = 0
while (value):
ans += heappop(value)
print(ans)
```
Yes
| 100,453 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You play a strategic video game (yeah, we ran out of good problem legends). In this game you control a large army, and your goal is to conquer n castles of your opponent.
Let's describe the game process in detail. Initially you control an army of k warriors. Your enemy controls n castles; to conquer the i-th castle, you need at least a_i warriors (you are so good at this game that you don't lose any warriors while taking over a castle, so your army stays the same after the fight). After you take control over a castle, you recruit new warriors into your army β formally, after you capture the i-th castle, b_i warriors join your army. Furthermore, after capturing a castle (or later) you can defend it: if you leave at least one warrior in a castle, this castle is considered defended. Each castle has an importance parameter c_i, and your total score is the sum of importance values over all defended castles. There are two ways to defend a castle:
* if you are currently in the castle i, you may leave one warrior to defend castle i;
* there are m one-way portals connecting the castles. Each portal is characterised by two numbers of castles u and v (for each portal holds u > v). A portal can be used as follows: if you are currently in the castle u, you may send one warrior to defend castle v.
Obviously, when you order your warrior to defend some castle, he leaves your army.
You capture the castles in fixed order: you have to capture the first one, then the second one, and so on. After you capture the castle i (but only before capturing castle i + 1) you may recruit new warriors from castle i, leave a warrior to defend castle i, and use any number of portals leading from castle i to other castles having smaller numbers. As soon as you capture the next castle, these actions for castle i won't be available to you.
If, during some moment in the game, you don't have enough warriors to capture the next castle, you lose. Your goal is to maximize the sum of importance values over all defended castles (note that you may hire new warriors in the last castle, defend it and use portals leading from it even after you capture it β your score will be calculated afterwards).
Can you determine an optimal strategy of capturing and defending the castles?
Input
The first line contains three integers n, m and k (1 β€ n β€ 5000, 0 β€ m β€ min((n(n - 1))/(2), 3 β
10^5), 0 β€ k β€ 5000) β the number of castles, the number of portals and initial size of your army, respectively.
Then n lines follow. The i-th line describes the i-th castle with three integers a_i, b_i and c_i (0 β€ a_i, b_i, c_i β€ 5000) β the number of warriors required to capture the i-th castle, the number of warriors available for hire in this castle and its importance value.
Then m lines follow. The i-th line describes the i-th portal with two integers u_i and v_i (1 β€ v_i < u_i β€ n), meaning that the portal leads from the castle u_i to the castle v_i. There are no two same portals listed.
It is guaranteed that the size of your army won't exceed 5000 under any circumstances (i. e. k + β_{i = 1}^{n} b_i β€ 5000).
Output
If it's impossible to capture all the castles, print one integer -1.
Otherwise, print one integer equal to the maximum sum of importance values of defended castles.
Examples
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 3
Output
5
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 1
Output
22
Input
4 3 7
7 4 17
3 0 8
11 2 0
14 3 5
3 1
2 1
4 3
Output
-1
Note
The best course of action in the first example is as follows:
1. capture the first castle;
2. hire warriors from the first castle, your army has 11 warriors now;
3. capture the second castle;
4. capture the third castle;
5. hire warriors from the third castle, your army has 13 warriors now;
6. capture the fourth castle;
7. leave one warrior to protect the fourth castle, your army has 12 warriors now.
This course of action (and several other ones) gives 5 as your total score.
The best course of action in the second example is as follows:
1. capture the first castle;
2. hire warriors from the first castle, your army has 11 warriors now;
3. capture the second castle;
4. capture the third castle;
5. hire warriors from the third castle, your army has 13 warriors now;
6. capture the fourth castle;
7. leave one warrior to protect the fourth castle, your army has 12 warriors now;
8. send one warrior to protect the first castle through the third portal, your army has 11 warriors now.
This course of action (and several other ones) gives 22 as your total score.
In the third example it's impossible to capture the last castle: you need 14 warriors to do so, but you can accumulate no more than 13 without capturing it.
Submitted Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
#import threading
from collections import defaultdict
#threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
#sys.setrecursionlimit(300000)
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----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=300006, func=lambda a, b: min(a , b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default, func=lambda a, b:min(a , b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] <=key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
class TrieNode:
def __init__(self):
self.children = [None] * 26
self.isEndOfWord = False
class Trie:
def __init__(self):
self.root = self.getNode()
def getNode(self):
return TrieNode()
def _charToIndex(self, ch):
return ord(ch) - ord('a')
def insert(self, key):
pCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])
if not pCrawl.children[index]:
pCrawl.children[index] = self.getNode()
pCrawl = pCrawl.children[index]
pCrawl.isEndOfWord = True
def search(self, key):
pCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])
if not pCrawl.children[index]:
return False
pCrawl = pCrawl.children[index]
return pCrawl != None and pCrawl.isEndOfWord
#-----------------------------------------trie---------------------------------
class Node:
def __init__(self, data):
self.data = data
self.count=0
self.left = None # left node for 0
self.right = None # right node for 1
class BinaryTrie:
def __init__(self):
self.root = Node(0)
def insert(self, pre_xor):
self.temp = self.root
for i in range(31, -1, -1):
val = pre_xor & (1 << i)
if val:
if not self.temp.right:
self.temp.right = Node(0)
self.temp = self.temp.right
self.temp.count+=1
if not val:
if not self.temp.left:
self.temp.left = Node(0)
self.temp = self.temp.left
self.temp.count += 1
self.temp.data = pre_xor
def query(self, xor):
self.temp = self.root
for i in range(31, -1, -1):
val = xor & (1 << i)
if not val:
if self.temp.left and self.temp.left.count>0:
self.temp = self.temp.left
elif self.temp.right:
self.temp = self.temp.right
else:
if self.temp.right and self.temp.right.count>0:
self.temp = self.temp.right
elif self.temp.left:
self.temp = self.temp.left
self.temp.count-=1
return xor ^ self.temp.data
#-------------------------bin trie-------------------------------------------
n,m,k=map(int,input().split())
l=[]
N=5005
for i in range(n):
a,b,c=map(int,input().split())
l.append((a,b,c))
d=defaultdict(list)
w=defaultdict(int)
sw=set()
for i in range(m):
a,b=map(int,input().split())
sw.add(b)
w[b]=max(w[b],a)
for i in w:
d[w[i]].append(i)
dp=[[-30000000 for j in range(N)]for i in range(n+1)]
dp[0][k]=0
for i in range(1,n+1):
for j in range(N):
t=l[i-1][0]
t1=l[i-1][1]
if 0<=j+t1<N and j>=t:
dp[i][j+t1]=max(dp[i][j+t1],dp[i-1][j])
if i not in sw and 0<=j+t1-1<N:
dp[i][j+t1-1]=max(dp[i][j+t1-1],dp[i-1][j]+l[i-1][2])
for t in d[i]:
for j in range(N):
if 0<=j-1<N:
dp[i][j-1]=max(dp[i][j-1],dp[i][j]+l[t-1][2])
ans=-99999999999
for i in range(N):
ans=max(ans,dp[-1][i])
if ans<0:
print(-1)
else:
print(ans)
```
Yes
| 100,454 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You play a strategic video game (yeah, we ran out of good problem legends). In this game you control a large army, and your goal is to conquer n castles of your opponent.
Let's describe the game process in detail. Initially you control an army of k warriors. Your enemy controls n castles; to conquer the i-th castle, you need at least a_i warriors (you are so good at this game that you don't lose any warriors while taking over a castle, so your army stays the same after the fight). After you take control over a castle, you recruit new warriors into your army β formally, after you capture the i-th castle, b_i warriors join your army. Furthermore, after capturing a castle (or later) you can defend it: if you leave at least one warrior in a castle, this castle is considered defended. Each castle has an importance parameter c_i, and your total score is the sum of importance values over all defended castles. There are two ways to defend a castle:
* if you are currently in the castle i, you may leave one warrior to defend castle i;
* there are m one-way portals connecting the castles. Each portal is characterised by two numbers of castles u and v (for each portal holds u > v). A portal can be used as follows: if you are currently in the castle u, you may send one warrior to defend castle v.
Obviously, when you order your warrior to defend some castle, he leaves your army.
You capture the castles in fixed order: you have to capture the first one, then the second one, and so on. After you capture the castle i (but only before capturing castle i + 1) you may recruit new warriors from castle i, leave a warrior to defend castle i, and use any number of portals leading from castle i to other castles having smaller numbers. As soon as you capture the next castle, these actions for castle i won't be available to you.
If, during some moment in the game, you don't have enough warriors to capture the next castle, you lose. Your goal is to maximize the sum of importance values over all defended castles (note that you may hire new warriors in the last castle, defend it and use portals leading from it even after you capture it β your score will be calculated afterwards).
Can you determine an optimal strategy of capturing and defending the castles?
Input
The first line contains three integers n, m and k (1 β€ n β€ 5000, 0 β€ m β€ min((n(n - 1))/(2), 3 β
10^5), 0 β€ k β€ 5000) β the number of castles, the number of portals and initial size of your army, respectively.
Then n lines follow. The i-th line describes the i-th castle with three integers a_i, b_i and c_i (0 β€ a_i, b_i, c_i β€ 5000) β the number of warriors required to capture the i-th castle, the number of warriors available for hire in this castle and its importance value.
Then m lines follow. The i-th line describes the i-th portal with two integers u_i and v_i (1 β€ v_i < u_i β€ n), meaning that the portal leads from the castle u_i to the castle v_i. There are no two same portals listed.
It is guaranteed that the size of your army won't exceed 5000 under any circumstances (i. e. k + β_{i = 1}^{n} b_i β€ 5000).
Output
If it's impossible to capture all the castles, print one integer -1.
Otherwise, print one integer equal to the maximum sum of importance values of defended castles.
Examples
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 3
Output
5
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 1
Output
22
Input
4 3 7
7 4 17
3 0 8
11 2 0
14 3 5
3 1
2 1
4 3
Output
-1
Note
The best course of action in the first example is as follows:
1. capture the first castle;
2. hire warriors from the first castle, your army has 11 warriors now;
3. capture the second castle;
4. capture the third castle;
5. hire warriors from the third castle, your army has 13 warriors now;
6. capture the fourth castle;
7. leave one warrior to protect the fourth castle, your army has 12 warriors now.
This course of action (and several other ones) gives 5 as your total score.
The best course of action in the second example is as follows:
1. capture the first castle;
2. hire warriors from the first castle, your army has 11 warriors now;
3. capture the second castle;
4. capture the third castle;
5. hire warriors from the third castle, your army has 13 warriors now;
6. capture the fourth castle;
7. leave one warrior to protect the fourth castle, your army has 12 warriors now;
8. send one warrior to protect the first castle through the third portal, your army has 11 warriors now.
This course of action (and several other ones) gives 22 as your total score.
In the third example it's impossible to capture the last castle: you need 14 warriors to do so, but you can accumulate no more than 13 without capturing it.
Submitted Solution:
```
import sys
from heapq import heappush, heappop
# inf = open('input.txt', 'r')
# reader = (map(int, line.split()) for line in inf)
reader = (map(int, line.split()) for line in sys.stdin)
n, m, k = next(reader)
castle = [list(next(reader)) for _ in range(n)]
last = [i for i in range(n)]
for _ in range(m):
u, v = next(reader)
u -= 1
v -= 1
last[v] = max(last[v], u)
portal = [[] for _ in range(n)]
for v, u in enumerate(last):
portal[u].append(v)
queue = []
possible = True
for i, (a, b, c) in enumerate(castle):
while k < a and queue:
k += 1
heappop(queue)
if k < a:
possible = False
break
k += b
for v in portal[i]:
k -= 1
heappush(queue, castle[v][2])
if not possible:
print(-1)
else:
while k < 0:
heappop(queue)
k += 1
sum_cost = 0
while queue:
sum_cost += heappop(queue)
print(sum_cost)
# inf.close()
```
Yes
| 100,455 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You play a strategic video game (yeah, we ran out of good problem legends). In this game you control a large army, and your goal is to conquer n castles of your opponent.
Let's describe the game process in detail. Initially you control an army of k warriors. Your enemy controls n castles; to conquer the i-th castle, you need at least a_i warriors (you are so good at this game that you don't lose any warriors while taking over a castle, so your army stays the same after the fight). After you take control over a castle, you recruit new warriors into your army β formally, after you capture the i-th castle, b_i warriors join your army. Furthermore, after capturing a castle (or later) you can defend it: if you leave at least one warrior in a castle, this castle is considered defended. Each castle has an importance parameter c_i, and your total score is the sum of importance values over all defended castles. There are two ways to defend a castle:
* if you are currently in the castle i, you may leave one warrior to defend castle i;
* there are m one-way portals connecting the castles. Each portal is characterised by two numbers of castles u and v (for each portal holds u > v). A portal can be used as follows: if you are currently in the castle u, you may send one warrior to defend castle v.
Obviously, when you order your warrior to defend some castle, he leaves your army.
You capture the castles in fixed order: you have to capture the first one, then the second one, and so on. After you capture the castle i (but only before capturing castle i + 1) you may recruit new warriors from castle i, leave a warrior to defend castle i, and use any number of portals leading from castle i to other castles having smaller numbers. As soon as you capture the next castle, these actions for castle i won't be available to you.
If, during some moment in the game, you don't have enough warriors to capture the next castle, you lose. Your goal is to maximize the sum of importance values over all defended castles (note that you may hire new warriors in the last castle, defend it and use portals leading from it even after you capture it β your score will be calculated afterwards).
Can you determine an optimal strategy of capturing and defending the castles?
Input
The first line contains three integers n, m and k (1 β€ n β€ 5000, 0 β€ m β€ min((n(n - 1))/(2), 3 β
10^5), 0 β€ k β€ 5000) β the number of castles, the number of portals and initial size of your army, respectively.
Then n lines follow. The i-th line describes the i-th castle with three integers a_i, b_i and c_i (0 β€ a_i, b_i, c_i β€ 5000) β the number of warriors required to capture the i-th castle, the number of warriors available for hire in this castle and its importance value.
Then m lines follow. The i-th line describes the i-th portal with two integers u_i and v_i (1 β€ v_i < u_i β€ n), meaning that the portal leads from the castle u_i to the castle v_i. There are no two same portals listed.
It is guaranteed that the size of your army won't exceed 5000 under any circumstances (i. e. k + β_{i = 1}^{n} b_i β€ 5000).
Output
If it's impossible to capture all the castles, print one integer -1.
Otherwise, print one integer equal to the maximum sum of importance values of defended castles.
Examples
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 3
Output
5
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 1
Output
22
Input
4 3 7
7 4 17
3 0 8
11 2 0
14 3 5
3 1
2 1
4 3
Output
-1
Note
The best course of action in the first example is as follows:
1. capture the first castle;
2. hire warriors from the first castle, your army has 11 warriors now;
3. capture the second castle;
4. capture the third castle;
5. hire warriors from the third castle, your army has 13 warriors now;
6. capture the fourth castle;
7. leave one warrior to protect the fourth castle, your army has 12 warriors now.
This course of action (and several other ones) gives 5 as your total score.
The best course of action in the second example is as follows:
1. capture the first castle;
2. hire warriors from the first castle, your army has 11 warriors now;
3. capture the second castle;
4. capture the third castle;
5. hire warriors from the third castle, your army has 13 warriors now;
6. capture the fourth castle;
7. leave one warrior to protect the fourth castle, your army has 12 warriors now;
8. send one warrior to protect the first castle through the third portal, your army has 11 warriors now.
This course of action (and several other ones) gives 22 as your total score.
In the third example it's impossible to capture the last castle: you need 14 warriors to do so, but you can accumulate no more than 13 without capturing it.
Submitted Solution:
```
import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
class RAQ_RMQ():
def __init__(self, n, inf=2**31-1):
self.n0 = 1<<(n-1).bit_length()
self.INF = inf
self.data = [0]*(2*self.n0)
self.lazy = [0]*(2*self.n0)
def getIndex(self, l, r):
l += self.n0; r += self.n0
lm = (l // (l & -l)) >> 1
rm = (r // (r & -r)) >> 1
while l < r:
if r <= rm:
yield r
if l <= lm:
yield l
l >>= 1; r >>= 1
while l:
yield l
l >>= 1
def propagates(self, *ids):
for i in reversed(ids):
v = self.lazy[i-1]
if not v:
continue
self.lazy[2*i-1] += v; self.lazy[2*i] += v
self.data[2*i-1] += v; self.data[2*i] += v
self.lazy[i-1] = 0
def update(self, l, r, x):
*ids, = self.getIndex(l, r)
l += self.n0; r += self.n0
while l < r:
if r & 1:
r -= 1
self.lazy[r-1] += x; self.data[r-1] += x
if l & 1:
self.lazy[l-1] += x; self.data[l-1] += x
l += 1
l >>= 1; r >>= 1
for i in ids:
self.data[i-1] = min(self.data[2*i-1], self.data[2*i]) + self.lazy[i-1]
def query(self, l, r):
self.propagates(*self.getIndex(l, r))
l += self.n0; r += self.n0
s = self.INF
while l < r:
if r & 1:
r -= 1
s = min(s, self.data[r-1])
if l & 1:
s = min(s, self.data[l-1])
l += 1
l >>= 1; r >>= 1
return s
n,m,k = map(int, input().split())
l = [0]*(n+1)
now = k
point = [0]*n
for i in range(n):
a,b,c = map(int, input().split())
point[i] = c
now = now-a
l[i] = now
now += b+a
l[n] = now
RMQ = RAQ_RMQ(n+1)
for i in range(n+1):
RMQ.update(i,i+1,l[i])
portal = list(range(n))
for i in range(m):
u,v = map(int, input().split())
u,v = u-1, v-1
if portal[v]<u:
portal[v] = u
if RMQ.query(0, n+1) < 0:
print(-1)
exit()
heap = [(-point[i], -portal[i]) for i in range(n)]
from heapq import heapify, heappop
heapify(heap)
ans = 0
while heap:
p,i = heappop(heap)
p,i = -p,-i
if RMQ.query(i+1, n+1)>0:
ans += p
RMQ.update(i+1, n+1, -1)
print(ans)
```
Yes
| 100,456 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You play a strategic video game (yeah, we ran out of good problem legends). In this game you control a large army, and your goal is to conquer n castles of your opponent.
Let's describe the game process in detail. Initially you control an army of k warriors. Your enemy controls n castles; to conquer the i-th castle, you need at least a_i warriors (you are so good at this game that you don't lose any warriors while taking over a castle, so your army stays the same after the fight). After you take control over a castle, you recruit new warriors into your army β formally, after you capture the i-th castle, b_i warriors join your army. Furthermore, after capturing a castle (or later) you can defend it: if you leave at least one warrior in a castle, this castle is considered defended. Each castle has an importance parameter c_i, and your total score is the sum of importance values over all defended castles. There are two ways to defend a castle:
* if you are currently in the castle i, you may leave one warrior to defend castle i;
* there are m one-way portals connecting the castles. Each portal is characterised by two numbers of castles u and v (for each portal holds u > v). A portal can be used as follows: if you are currently in the castle u, you may send one warrior to defend castle v.
Obviously, when you order your warrior to defend some castle, he leaves your army.
You capture the castles in fixed order: you have to capture the first one, then the second one, and so on. After you capture the castle i (but only before capturing castle i + 1) you may recruit new warriors from castle i, leave a warrior to defend castle i, and use any number of portals leading from castle i to other castles having smaller numbers. As soon as you capture the next castle, these actions for castle i won't be available to you.
If, during some moment in the game, you don't have enough warriors to capture the next castle, you lose. Your goal is to maximize the sum of importance values over all defended castles (note that you may hire new warriors in the last castle, defend it and use portals leading from it even after you capture it β your score will be calculated afterwards).
Can you determine an optimal strategy of capturing and defending the castles?
Input
The first line contains three integers n, m and k (1 β€ n β€ 5000, 0 β€ m β€ min((n(n - 1))/(2), 3 β
10^5), 0 β€ k β€ 5000) β the number of castles, the number of portals and initial size of your army, respectively.
Then n lines follow. The i-th line describes the i-th castle with three integers a_i, b_i and c_i (0 β€ a_i, b_i, c_i β€ 5000) β the number of warriors required to capture the i-th castle, the number of warriors available for hire in this castle and its importance value.
Then m lines follow. The i-th line describes the i-th portal with two integers u_i and v_i (1 β€ v_i < u_i β€ n), meaning that the portal leads from the castle u_i to the castle v_i. There are no two same portals listed.
It is guaranteed that the size of your army won't exceed 5000 under any circumstances (i. e. k + β_{i = 1}^{n} b_i β€ 5000).
Output
If it's impossible to capture all the castles, print one integer -1.
Otherwise, print one integer equal to the maximum sum of importance values of defended castles.
Examples
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 3
Output
5
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 1
Output
22
Input
4 3 7
7 4 17
3 0 8
11 2 0
14 3 5
3 1
2 1
4 3
Output
-1
Note
The best course of action in the first example is as follows:
1. capture the first castle;
2. hire warriors from the first castle, your army has 11 warriors now;
3. capture the second castle;
4. capture the third castle;
5. hire warriors from the third castle, your army has 13 warriors now;
6. capture the fourth castle;
7. leave one warrior to protect the fourth castle, your army has 12 warriors now.
This course of action (and several other ones) gives 5 as your total score.
The best course of action in the second example is as follows:
1. capture the first castle;
2. hire warriors from the first castle, your army has 11 warriors now;
3. capture the second castle;
4. capture the third castle;
5. hire warriors from the third castle, your army has 13 warriors now;
6. capture the fourth castle;
7. leave one warrior to protect the fourth castle, your army has 12 warriors now;
8. send one warrior to protect the first castle through the third portal, your army has 11 warriors now.
This course of action (and several other ones) gives 22 as your total score.
In the third example it's impossible to capture the last castle: you need 14 warriors to do so, but you can accumulate no more than 13 without capturing it.
Submitted Solution:
```
#!/usr/bin/env python3
import sys
import heapq
input = sys.stdin.readline
n, m, k = [int(item) for item in input().split()]
castle = []
for i in range(n):
a, b, c = [int(item) for item in input().split()]
castle.append((a, b, c, i))
portal = [[] for _ in range(n)]
for i in range(m):
u, v = [int(item) - 1 for item in input().split()]
portal[u].append(v)
rest = []
takable = []
for a, b, c, index in castle:
if k < a:
print(-1)
exit()
rest.append(k - a)
k += b
castle.sort(key=lambda x: x[2], reverse=True)
val = 10**9
for i in range(n):
val = min(rest[n-1-i], val)
rest[n-1-i] = val
rest.append(k)
rest.reverse()
rest.pop()
place = set()
prev = k
visited = [0] * n
ans = 0
for i in range(n):
if rest[i] == prev:
place.update(portal[n - 1 - i])
place.add(n-1-i)
else:
capable = prev - rest[i]
for a, b, c, index in castle:
if visited[index]:
continue
if index in place:
ans += c
capable -= 1
visited[index] = 1
if capable == 0:
break
place = set()
prev = rest[i]
print(ans)
```
No
| 100,457 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You play a strategic video game (yeah, we ran out of good problem legends). In this game you control a large army, and your goal is to conquer n castles of your opponent.
Let's describe the game process in detail. Initially you control an army of k warriors. Your enemy controls n castles; to conquer the i-th castle, you need at least a_i warriors (you are so good at this game that you don't lose any warriors while taking over a castle, so your army stays the same after the fight). After you take control over a castle, you recruit new warriors into your army β formally, after you capture the i-th castle, b_i warriors join your army. Furthermore, after capturing a castle (or later) you can defend it: if you leave at least one warrior in a castle, this castle is considered defended. Each castle has an importance parameter c_i, and your total score is the sum of importance values over all defended castles. There are two ways to defend a castle:
* if you are currently in the castle i, you may leave one warrior to defend castle i;
* there are m one-way portals connecting the castles. Each portal is characterised by two numbers of castles u and v (for each portal holds u > v). A portal can be used as follows: if you are currently in the castle u, you may send one warrior to defend castle v.
Obviously, when you order your warrior to defend some castle, he leaves your army.
You capture the castles in fixed order: you have to capture the first one, then the second one, and so on. After you capture the castle i (but only before capturing castle i + 1) you may recruit new warriors from castle i, leave a warrior to defend castle i, and use any number of portals leading from castle i to other castles having smaller numbers. As soon as you capture the next castle, these actions for castle i won't be available to you.
If, during some moment in the game, you don't have enough warriors to capture the next castle, you lose. Your goal is to maximize the sum of importance values over all defended castles (note that you may hire new warriors in the last castle, defend it and use portals leading from it even after you capture it β your score will be calculated afterwards).
Can you determine an optimal strategy of capturing and defending the castles?
Input
The first line contains three integers n, m and k (1 β€ n β€ 5000, 0 β€ m β€ min((n(n - 1))/(2), 3 β
10^5), 0 β€ k β€ 5000) β the number of castles, the number of portals and initial size of your army, respectively.
Then n lines follow. The i-th line describes the i-th castle with three integers a_i, b_i and c_i (0 β€ a_i, b_i, c_i β€ 5000) β the number of warriors required to capture the i-th castle, the number of warriors available for hire in this castle and its importance value.
Then m lines follow. The i-th line describes the i-th portal with two integers u_i and v_i (1 β€ v_i < u_i β€ n), meaning that the portal leads from the castle u_i to the castle v_i. There are no two same portals listed.
It is guaranteed that the size of your army won't exceed 5000 under any circumstances (i. e. k + β_{i = 1}^{n} b_i β€ 5000).
Output
If it's impossible to capture all the castles, print one integer -1.
Otherwise, print one integer equal to the maximum sum of importance values of defended castles.
Examples
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 3
Output
5
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 1
Output
22
Input
4 3 7
7 4 17
3 0 8
11 2 0
14 3 5
3 1
2 1
4 3
Output
-1
Note
The best course of action in the first example is as follows:
1. capture the first castle;
2. hire warriors from the first castle, your army has 11 warriors now;
3. capture the second castle;
4. capture the third castle;
5. hire warriors from the third castle, your army has 13 warriors now;
6. capture the fourth castle;
7. leave one warrior to protect the fourth castle, your army has 12 warriors now.
This course of action (and several other ones) gives 5 as your total score.
The best course of action in the second example is as follows:
1. capture the first castle;
2. hire warriors from the first castle, your army has 11 warriors now;
3. capture the second castle;
4. capture the third castle;
5. hire warriors from the third castle, your army has 13 warriors now;
6. capture the fourth castle;
7. leave one warrior to protect the fourth castle, your army has 12 warriors now;
8. send one warrior to protect the first castle through the third portal, your army has 11 warriors now.
This course of action (and several other ones) gives 22 as your total score.
In the third example it's impossible to capture the last castle: you need 14 warriors to do so, but you can accumulate no more than 13 without capturing it.
Submitted Solution:
```
n,m,k = [int(i) for i in input().split()]
a,b,c = [],[],[]
for _ in range(n):
x = [int(i) for i in input().split()]
a.append(x[0])
b.append(x[1])
c.append(x[2])
p = {}
for i in range(n):
p[i] = [i]
for _ in range(m):
x = [int(i) for i in input().split()]
p[x[0]-1].append(x[1]-1)
psort = sorted([(c[j],j) for j in range(n) if c[j]>0])
psort = reversed([j[1] for j in psort])
def error(h, a, i, n):
if(i+1<n):
for j in range(i+1, n):
if h[i]<a[i]: return True
return False
def solve(a,b,c,n,m,k,p):
h = [k]
for x in b:
h.append(h[-1] + x)
for i in range(n):
if(h[i] < a[i]): return -1
vis = []
for i in reversed(range(n)):
for x in psort:
if (x in vis) or (not x in p[i]): continue
h[i+1:] = [j-1 for j in h[i+1:]]
if error(h,a,i,n):
return sum([c[y] for y in vis])
vis.append(x)
return sum([c[y] for y in vis])
print(solve(a,b,c,n,m,k,p))
```
No
| 100,458 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You play a strategic video game (yeah, we ran out of good problem legends). In this game you control a large army, and your goal is to conquer n castles of your opponent.
Let's describe the game process in detail. Initially you control an army of k warriors. Your enemy controls n castles; to conquer the i-th castle, you need at least a_i warriors (you are so good at this game that you don't lose any warriors while taking over a castle, so your army stays the same after the fight). After you take control over a castle, you recruit new warriors into your army β formally, after you capture the i-th castle, b_i warriors join your army. Furthermore, after capturing a castle (or later) you can defend it: if you leave at least one warrior in a castle, this castle is considered defended. Each castle has an importance parameter c_i, and your total score is the sum of importance values over all defended castles. There are two ways to defend a castle:
* if you are currently in the castle i, you may leave one warrior to defend castle i;
* there are m one-way portals connecting the castles. Each portal is characterised by two numbers of castles u and v (for each portal holds u > v). A portal can be used as follows: if you are currently in the castle u, you may send one warrior to defend castle v.
Obviously, when you order your warrior to defend some castle, he leaves your army.
You capture the castles in fixed order: you have to capture the first one, then the second one, and so on. After you capture the castle i (but only before capturing castle i + 1) you may recruit new warriors from castle i, leave a warrior to defend castle i, and use any number of portals leading from castle i to other castles having smaller numbers. As soon as you capture the next castle, these actions for castle i won't be available to you.
If, during some moment in the game, you don't have enough warriors to capture the next castle, you lose. Your goal is to maximize the sum of importance values over all defended castles (note that you may hire new warriors in the last castle, defend it and use portals leading from it even after you capture it β your score will be calculated afterwards).
Can you determine an optimal strategy of capturing and defending the castles?
Input
The first line contains three integers n, m and k (1 β€ n β€ 5000, 0 β€ m β€ min((n(n - 1))/(2), 3 β
10^5), 0 β€ k β€ 5000) β the number of castles, the number of portals and initial size of your army, respectively.
Then n lines follow. The i-th line describes the i-th castle with three integers a_i, b_i and c_i (0 β€ a_i, b_i, c_i β€ 5000) β the number of warriors required to capture the i-th castle, the number of warriors available for hire in this castle and its importance value.
Then m lines follow. The i-th line describes the i-th portal with two integers u_i and v_i (1 β€ v_i < u_i β€ n), meaning that the portal leads from the castle u_i to the castle v_i. There are no two same portals listed.
It is guaranteed that the size of your army won't exceed 5000 under any circumstances (i. e. k + β_{i = 1}^{n} b_i β€ 5000).
Output
If it's impossible to capture all the castles, print one integer -1.
Otherwise, print one integer equal to the maximum sum of importance values of defended castles.
Examples
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 3
Output
5
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 1
Output
22
Input
4 3 7
7 4 17
3 0 8
11 2 0
14 3 5
3 1
2 1
4 3
Output
-1
Note
The best course of action in the first example is as follows:
1. capture the first castle;
2. hire warriors from the first castle, your army has 11 warriors now;
3. capture the second castle;
4. capture the third castle;
5. hire warriors from the third castle, your army has 13 warriors now;
6. capture the fourth castle;
7. leave one warrior to protect the fourth castle, your army has 12 warriors now.
This course of action (and several other ones) gives 5 as your total score.
The best course of action in the second example is as follows:
1. capture the first castle;
2. hire warriors from the first castle, your army has 11 warriors now;
3. capture the second castle;
4. capture the third castle;
5. hire warriors from the third castle, your army has 13 warriors now;
6. capture the fourth castle;
7. leave one warrior to protect the fourth castle, your army has 12 warriors now;
8. send one warrior to protect the first castle through the third portal, your army has 11 warriors now.
This course of action (and several other ones) gives 22 as your total score.
In the third example it's impossible to capture the last castle: you need 14 warriors to do so, but you can accumulate no more than 13 without capturing it.
Submitted Solution:
```
n,m,k = [int(i) for i in input().split()]
a,b,c = [],[],[]
for _ in range(n):
x = [int(i) for i in input().split()]
a.append(x[0])
b.append(x[1])
c.append(x[2])
p = {}
for i in range(n):
p[i] = [i]
for _ in range(m):
x = [int(i) for i in input().split()]
p[x[0]-1].append(x[1]-1)
psort = sorted([(c[j],j) for j in range(n) if c[j]>0])
# print(psort)
psort = list(reversed([j[1] for j in psort]))
def error(h, a, i, n):
if(i+1<n):
for j in range(i+1, n):
if h[j]<a[j]: return True
return False
def solve(a,b,c,n,m,k,p):
h = [k]
for x in b:
h.append(h[-1] + x)
for i in range(n):
if(h[i] < a[i]): return -1
vis = []
# print('start', psort)
for i in reversed(range(n)):
# print('vis', vis)
# print('===> i = ', i, p[i])
for x in psort:
if (x in vis) or (not x in p[i]):
# print('cont')
continue
h[i+1:] = [j-1 for j in h[i+1:]]
# print('add')
if error(h,a,i,n):
# print('error')
return sum([c[y] for y in vis])
vis.append(x)
return sum([c[y] for y in vis])
print(solve(a,b,c,n,m,k,p))
```
No
| 100,459 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You play a strategic video game (yeah, we ran out of good problem legends). In this game you control a large army, and your goal is to conquer n castles of your opponent.
Let's describe the game process in detail. Initially you control an army of k warriors. Your enemy controls n castles; to conquer the i-th castle, you need at least a_i warriors (you are so good at this game that you don't lose any warriors while taking over a castle, so your army stays the same after the fight). After you take control over a castle, you recruit new warriors into your army β formally, after you capture the i-th castle, b_i warriors join your army. Furthermore, after capturing a castle (or later) you can defend it: if you leave at least one warrior in a castle, this castle is considered defended. Each castle has an importance parameter c_i, and your total score is the sum of importance values over all defended castles. There are two ways to defend a castle:
* if you are currently in the castle i, you may leave one warrior to defend castle i;
* there are m one-way portals connecting the castles. Each portal is characterised by two numbers of castles u and v (for each portal holds u > v). A portal can be used as follows: if you are currently in the castle u, you may send one warrior to defend castle v.
Obviously, when you order your warrior to defend some castle, he leaves your army.
You capture the castles in fixed order: you have to capture the first one, then the second one, and so on. After you capture the castle i (but only before capturing castle i + 1) you may recruit new warriors from castle i, leave a warrior to defend castle i, and use any number of portals leading from castle i to other castles having smaller numbers. As soon as you capture the next castle, these actions for castle i won't be available to you.
If, during some moment in the game, you don't have enough warriors to capture the next castle, you lose. Your goal is to maximize the sum of importance values over all defended castles (note that you may hire new warriors in the last castle, defend it and use portals leading from it even after you capture it β your score will be calculated afterwards).
Can you determine an optimal strategy of capturing and defending the castles?
Input
The first line contains three integers n, m and k (1 β€ n β€ 5000, 0 β€ m β€ min((n(n - 1))/(2), 3 β
10^5), 0 β€ k β€ 5000) β the number of castles, the number of portals and initial size of your army, respectively.
Then n lines follow. The i-th line describes the i-th castle with three integers a_i, b_i and c_i (0 β€ a_i, b_i, c_i β€ 5000) β the number of warriors required to capture the i-th castle, the number of warriors available for hire in this castle and its importance value.
Then m lines follow. The i-th line describes the i-th portal with two integers u_i and v_i (1 β€ v_i < u_i β€ n), meaning that the portal leads from the castle u_i to the castle v_i. There are no two same portals listed.
It is guaranteed that the size of your army won't exceed 5000 under any circumstances (i. e. k + β_{i = 1}^{n} b_i β€ 5000).
Output
If it's impossible to capture all the castles, print one integer -1.
Otherwise, print one integer equal to the maximum sum of importance values of defended castles.
Examples
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 3
Output
5
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 1
Output
22
Input
4 3 7
7 4 17
3 0 8
11 2 0
14 3 5
3 1
2 1
4 3
Output
-1
Note
The best course of action in the first example is as follows:
1. capture the first castle;
2. hire warriors from the first castle, your army has 11 warriors now;
3. capture the second castle;
4. capture the third castle;
5. hire warriors from the third castle, your army has 13 warriors now;
6. capture the fourth castle;
7. leave one warrior to protect the fourth castle, your army has 12 warriors now.
This course of action (and several other ones) gives 5 as your total score.
The best course of action in the second example is as follows:
1. capture the first castle;
2. hire warriors from the first castle, your army has 11 warriors now;
3. capture the second castle;
4. capture the third castle;
5. hire warriors from the third castle, your army has 13 warriors now;
6. capture the fourth castle;
7. leave one warrior to protect the fourth castle, your army has 12 warriors now;
8. send one warrior to protect the first castle through the third portal, your army has 11 warriors now.
This course of action (and several other ones) gives 22 as your total score.
In the third example it's impossible to capture the last castle: you need 14 warriors to do so, but you can accumulate no more than 13 without capturing it.
Submitted Solution:
```
import os, sys, math
import collections
if os.path.exists('testing'):
name = os.path.basename(__file__)
if name.endswith('.py'):
name = name[:-3]
src = open(name + '.txt', encoding='utf8')
input = src.readline
def solve():
bit_count = int(math.floor(math.log2(n)) + 1)
counter_array = [ 0 ] * (2 ** (bit_count + 1))
def counter_set(index):
index = (2 ** bit_count) + index
while index > 0:
counter_array[index] += 1
index = index // 2
def counter_get(index):
index = (2 ** bit_count) + index
s = counter_array[index]
while index > 1:
if index & 1:
s += counter_array[index - 1]
index = index // 2
return s
current_minimal_warrior_count = 0
minimal_warriors_count = [ 0 ] * n
for x in range(n - 1, -1, -1):
required_to_conquer, available_for_hire, _ = castles[x]
current_minimal_warrior_count = max(current_minimal_warrior_count - available_for_hire, required_to_conquer)
minimal_warriors_count[x] = current_minimal_warrior_count
spare_warriors_count = [ 0 ] * n
total_warrior_count = k
for x in range(n):
required_to_conquer, available_for_hire, _ = castles[x]
if total_warrior_count < required_to_conquer:
return -1
total_warrior_count += available_for_hire
if x < n - 1:
spare_warriors_count[x] = max(0, total_warrior_count - minimal_warriors_count[x + 1])
else:
spare_warriors_count[x] = total_warrior_count
reversed_portals = collections.defaultdict(list)
for u, v in portals:
reversed_portals[v - 1].append(u - 1)
total_importance_acquired = 0
castles_sorted_by_importance = list(sorted(enumerate(castles), key=lambda x: -x[1][2]))
for castle_index, (_, _, importance_value) in castles_sorted_by_importance:
access = reversed_portals.get(castle_index, None)
if access:
access = max(access)
else:
access = castle_index
already_used = counter_get(access)
spares_available = spare_warriors_count[access]
if already_used < spares_available:
counter_set(access)
total_importance_acquired += importance_value
return total_importance_acquired
# minimal_warriors_count 7 11 11 13
# total_warrior_count 11 11 13 16
# spare_warriors_count 0 0 0 16
# castles 4, portals 3, initial army 7
# required to capture hire importance
# c1 7 4 17
# c2 3 0 8
# c3 11 2 0
# c4 13 3 5
# p1 3 1
# p2 2 1
# p3 4 3
def integers():
return map(int, input().strip().split())
def array_of_integers(q):
return [
tuple(map(int, input().strip().split())) for _ in range(q)
]
n, m, k = integers()
castles = array_of_integers(n)
portals = array_of_integers(m)
if n == 100 and m == k == 0:
print(';'.join(':'.join(list(map(str, q))) for q in castles))
print(';'.join(':'.join(list(map(str, q))) for q in portals))
res = solve()
print(res)
```
No
| 100,460 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rectangular matrix of size n Γ m consisting of integers from 1 to 2 β
10^5.
In one move, you can:
* choose any element of the matrix and change its value to any integer between 1 and n β
m, inclusive;
* take any column and shift it one cell up cyclically (see the example of such cyclic shift below).
A cyclic shift is an operation such that you choose some j (1 β€ j β€ m) and set a_{1, j} := a_{2, j}, a_{2, j} := a_{3, j}, ..., a_{n, j} := a_{1, j} simultaneously.
<image> Example of cyclic shift of the first column
You want to perform the minimum number of moves to make this matrix look like this:
<image>
In other words, the goal is to obtain the matrix, where a_{1, 1} = 1, a_{1, 2} = 2, ..., a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, ..., a_{n, m} = n β
m (i.e. a_{i, j} = (i - 1) β
m + j) with the minimum number of moves performed.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 2 β
10^5, n β
m β€ 2 β
10^5) β the size of the matrix.
The next n lines contain m integers each. The number at the line i and position j is a_{i, j} (1 β€ a_{i, j} β€ 2 β
10^5).
Output
Print one integer β the minimum number of moves required to obtain the matrix, where a_{1, 1} = 1, a_{1, 2} = 2, ..., a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, ..., a_{n, m} = n β
m (a_{i, j} = (i - 1)m + j).
Examples
Input
3 3
3 2 1
1 2 3
4 5 6
Output
6
Input
4 3
1 2 3
4 5 6
7 8 9
10 11 12
Output
0
Input
3 4
1 6 3 4
5 10 7 8
9 2 11 12
Output
2
Note
In the first example, you can set a_{1, 1} := 7, a_{1, 2} := 8 and a_{1, 3} := 9 then shift the first, the second and the third columns cyclically, so the answer is 6. It can be shown that you cannot achieve a better answer.
In the second example, the matrix is already good so the answer is 0.
In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 2.
Tags: greedy, implementation, math
Correct Solution:
```
n, m = (int(i) for i in input().split())
a = [[int(i) for i in input().split()] for _ in range(n)]
res = 0
for j in range(m):
b = [0] * n
for i in range(n):
if a[i][j] <= n*m and (a[i][j]-j-1)%m == 0:
pos = (a[i][j]-j-1)//m
shift = i-pos if i>=pos else i-pos+n
b[shift] += 1
res += min(i+n-b[i] for i in range(n))
print(res)
```
| 100,461 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rectangular matrix of size n Γ m consisting of integers from 1 to 2 β
10^5.
In one move, you can:
* choose any element of the matrix and change its value to any integer between 1 and n β
m, inclusive;
* take any column and shift it one cell up cyclically (see the example of such cyclic shift below).
A cyclic shift is an operation such that you choose some j (1 β€ j β€ m) and set a_{1, j} := a_{2, j}, a_{2, j} := a_{3, j}, ..., a_{n, j} := a_{1, j} simultaneously.
<image> Example of cyclic shift of the first column
You want to perform the minimum number of moves to make this matrix look like this:
<image>
In other words, the goal is to obtain the matrix, where a_{1, 1} = 1, a_{1, 2} = 2, ..., a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, ..., a_{n, m} = n β
m (i.e. a_{i, j} = (i - 1) β
m + j) with the minimum number of moves performed.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 2 β
10^5, n β
m β€ 2 β
10^5) β the size of the matrix.
The next n lines contain m integers each. The number at the line i and position j is a_{i, j} (1 β€ a_{i, j} β€ 2 β
10^5).
Output
Print one integer β the minimum number of moves required to obtain the matrix, where a_{1, 1} = 1, a_{1, 2} = 2, ..., a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, ..., a_{n, m} = n β
m (a_{i, j} = (i - 1)m + j).
Examples
Input
3 3
3 2 1
1 2 3
4 5 6
Output
6
Input
4 3
1 2 3
4 5 6
7 8 9
10 11 12
Output
0
Input
3 4
1 6 3 4
5 10 7 8
9 2 11 12
Output
2
Note
In the first example, you can set a_{1, 1} := 7, a_{1, 2} := 8 and a_{1, 3} := 9 then shift the first, the second and the third columns cyclically, so the answer is 6. It can be shown that you cannot achieve a better answer.
In the second example, the matrix is already good so the answer is 0.
In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 2.
Tags: greedy, implementation, math
Correct Solution:
```
#from bisect import bisect_left as bl #c++ lowerbound bl(array,element)
#from bisect import bisect_right as br #c++ upperbound br(array,element)
#from __future__ import print_function, division #while using python2
# from itertools import accumulate
from collections import defaultdict, Counter
def main():
#sys.stdin = open('input.txt', 'r')
#sys.stdout = open('output.txt', 'w')
n, m = [int(x) for x in input().split()]
grid = [[-1] * (m+1) for i in range(n+1)]
for i in range(1, n+1):
arr = [int(x) for x in input().split()]
for j in range(1, m+1):
grid[i][j] = arr[j-1]
# print(grid)
ans = 0
for j in range(1, m+1):
cur_col_ans = 1e9
off_by_above = defaultdict(lambda : 0)
off_by_below = defaultdict(lambda : 0)
for i in range(1, n+1):
cur = j + (i-1)*m
off_by_below[grid[i][j] - cur] += 1
for i in range(1, n+1):
# print("i = ", i)
d = m*(i-1)
temp = i-1
# print(temp)
temp += (n-i+1 - off_by_below[-d])
# print(temp)
temp += (i-1 - off_by_above[(n+1-i)*m])
# print(temp)
cur_col_ans = min(cur_col_ans, temp)
# print("ans from ", grid[i][j], " = ", i-1+(n-off_by[-d]))
off_by_below[grid[i][j] - (j + (i-1)*m)] -= 1
off_by_above[grid[i][j] - (j + (i-1)*m)] += 1
# print("col", j, ":", cur_col_ans)
# print(dict(off_by))
ans += cur_col_ans
print(ans)
#------------------ Python 2 and 3 footer by Pajenegod and c1729-----------------------------------------
py2 = round(0.5)
if py2:
from future_builtins import ascii, filter, hex, map, oct, zip
range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192
class FastIO(BytesIO):
newlines = 0
def __init__(self, file):
self._file = file
self._fd = file.fileno()
self.writable = "x" in file.mode or "w" in file.mode
self.write = super(FastIO, self).write if self.writable else None
def _fill(self):
s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0])
return s
def read(self):
while self._fill(): pass
return super(FastIO,self).read()
def readline(self):
while self.newlines == 0:
s = self._fill(); self.newlines = s.count(b"\n") + (not s)
self.newlines -= 1
return super(FastIO, self).readline()
def flush(self):
if self.writable:
os.write(self._fd, self.getvalue())
self.truncate(0), self.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
if py2:
self.write = self.buffer.write
self.read = self.buffer.read
self.readline = self.buffer.readline
else:
self.write = lambda s:self.buffer.write(s.encode('ascii'))
self.read = lambda:self.buffer.read().decode('ascii')
self.readline = lambda:self.buffer.readline().decode('ascii')
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')
if __name__ == '__main__':
main()
```
| 100,462 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rectangular matrix of size n Γ m consisting of integers from 1 to 2 β
10^5.
In one move, you can:
* choose any element of the matrix and change its value to any integer between 1 and n β
m, inclusive;
* take any column and shift it one cell up cyclically (see the example of such cyclic shift below).
A cyclic shift is an operation such that you choose some j (1 β€ j β€ m) and set a_{1, j} := a_{2, j}, a_{2, j} := a_{3, j}, ..., a_{n, j} := a_{1, j} simultaneously.
<image> Example of cyclic shift of the first column
You want to perform the minimum number of moves to make this matrix look like this:
<image>
In other words, the goal is to obtain the matrix, where a_{1, 1} = 1, a_{1, 2} = 2, ..., a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, ..., a_{n, m} = n β
m (i.e. a_{i, j} = (i - 1) β
m + j) with the minimum number of moves performed.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 2 β
10^5, n β
m β€ 2 β
10^5) β the size of the matrix.
The next n lines contain m integers each. The number at the line i and position j is a_{i, j} (1 β€ a_{i, j} β€ 2 β
10^5).
Output
Print one integer β the minimum number of moves required to obtain the matrix, where a_{1, 1} = 1, a_{1, 2} = 2, ..., a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, ..., a_{n, m} = n β
m (a_{i, j} = (i - 1)m + j).
Examples
Input
3 3
3 2 1
1 2 3
4 5 6
Output
6
Input
4 3
1 2 3
4 5 6
7 8 9
10 11 12
Output
0
Input
3 4
1 6 3 4
5 10 7 8
9 2 11 12
Output
2
Note
In the first example, you can set a_{1, 1} := 7, a_{1, 2} := 8 and a_{1, 3} := 9 then shift the first, the second and the third columns cyclically, so the answer is 6. It can be shown that you cannot achieve a better answer.
In the second example, the matrix is already good so the answer is 0.
In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 2.
Tags: greedy, implementation, math
Correct Solution:
```
from sys import stdin, stdout
def main():
arr = list(map(int, stdin.readline().split()))
X = arr[0]
Y = arr[1]
rect = list()
temp = list()
for j in range(X):
temp.append(0)
for i in range(Y):
rect.append(list(temp))
for i in range(X):
arr = list(map(int, stdin.readline().split()))
for j in range(Y):
if (arr[j] - j - 1) % Y != 0 or (arr[j]) > X*Y:
continue
sure = int((arr[j] - j - 1) / Y)
sure = i - sure
if sure < 0:
sure += X
rect[j][sure] += 1
total_sum = 0
for i in range (Y):
maxer = X
for j in range(X):
count = X - rect[i][j] + j
if count < maxer:
maxer = count
total_sum += maxer
stdout.write(str(total_sum))
main()
```
| 100,463 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rectangular matrix of size n Γ m consisting of integers from 1 to 2 β
10^5.
In one move, you can:
* choose any element of the matrix and change its value to any integer between 1 and n β
m, inclusive;
* take any column and shift it one cell up cyclically (see the example of such cyclic shift below).
A cyclic shift is an operation such that you choose some j (1 β€ j β€ m) and set a_{1, j} := a_{2, j}, a_{2, j} := a_{3, j}, ..., a_{n, j} := a_{1, j} simultaneously.
<image> Example of cyclic shift of the first column
You want to perform the minimum number of moves to make this matrix look like this:
<image>
In other words, the goal is to obtain the matrix, where a_{1, 1} = 1, a_{1, 2} = 2, ..., a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, ..., a_{n, m} = n β
m (i.e. a_{i, j} = (i - 1) β
m + j) with the minimum number of moves performed.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 2 β
10^5, n β
m β€ 2 β
10^5) β the size of the matrix.
The next n lines contain m integers each. The number at the line i and position j is a_{i, j} (1 β€ a_{i, j} β€ 2 β
10^5).
Output
Print one integer β the minimum number of moves required to obtain the matrix, where a_{1, 1} = 1, a_{1, 2} = 2, ..., a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, ..., a_{n, m} = n β
m (a_{i, j} = (i - 1)m + j).
Examples
Input
3 3
3 2 1
1 2 3
4 5 6
Output
6
Input
4 3
1 2 3
4 5 6
7 8 9
10 11 12
Output
0
Input
3 4
1 6 3 4
5 10 7 8
9 2 11 12
Output
2
Note
In the first example, you can set a_{1, 1} := 7, a_{1, 2} := 8 and a_{1, 3} := 9 then shift the first, the second and the third columns cyclically, so the answer is 6. It can be shown that you cannot achieve a better answer.
In the second example, the matrix is already good so the answer is 0.
In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 2.
Tags: greedy, implementation, math
Correct Solution:
```
''' Hey stalker :) '''
INF = 10**10
def main():
#print = out.append
''' Cook your dish here! '''
n, m = get_list()
mat = [get_list() for _ in range(n)]
res = 0
for j in range(m):
shifts = [0]*n
for i in range(n):
if (mat[i][j] - (j+1))%m == 0:
org = (mat[i][j] - (j+1))//m
#print(i, j, org)
if 0<=org<n:
shifts[(i-org)%n] += 1
#print(shifts)
drop = 0
for i, ele in enumerate(shifts):
drop = max(drop, ele-i)
res += n-drop
print(res)
''' Pythonista fLite 1.1 '''
import sys
from collections import defaultdict, Counter
from bisect import bisect_left, bisect_right
#from functools import reduce
import math
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
out = []
get_int = lambda: int(input())
get_list = lambda: list(map(int, input().split()))
main()
#[main() for _ in range(int(input()))]
print(*out, sep='\n')
```
| 100,464 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rectangular matrix of size n Γ m consisting of integers from 1 to 2 β
10^5.
In one move, you can:
* choose any element of the matrix and change its value to any integer between 1 and n β
m, inclusive;
* take any column and shift it one cell up cyclically (see the example of such cyclic shift below).
A cyclic shift is an operation such that you choose some j (1 β€ j β€ m) and set a_{1, j} := a_{2, j}, a_{2, j} := a_{3, j}, ..., a_{n, j} := a_{1, j} simultaneously.
<image> Example of cyclic shift of the first column
You want to perform the minimum number of moves to make this matrix look like this:
<image>
In other words, the goal is to obtain the matrix, where a_{1, 1} = 1, a_{1, 2} = 2, ..., a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, ..., a_{n, m} = n β
m (i.e. a_{i, j} = (i - 1) β
m + j) with the minimum number of moves performed.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 2 β
10^5, n β
m β€ 2 β
10^5) β the size of the matrix.
The next n lines contain m integers each. The number at the line i and position j is a_{i, j} (1 β€ a_{i, j} β€ 2 β
10^5).
Output
Print one integer β the minimum number of moves required to obtain the matrix, where a_{1, 1} = 1, a_{1, 2} = 2, ..., a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, ..., a_{n, m} = n β
m (a_{i, j} = (i - 1)m + j).
Examples
Input
3 3
3 2 1
1 2 3
4 5 6
Output
6
Input
4 3
1 2 3
4 5 6
7 8 9
10 11 12
Output
0
Input
3 4
1 6 3 4
5 10 7 8
9 2 11 12
Output
2
Note
In the first example, you can set a_{1, 1} := 7, a_{1, 2} := 8 and a_{1, 3} := 9 then shift the first, the second and the third columns cyclically, so the answer is 6. It can be shown that you cannot achieve a better answer.
In the second example, the matrix is already good so the answer is 0.
In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 2.
Tags: greedy, implementation, math
Correct Solution:
```
import sys
from collections import defaultdict, deque
inp = sys.stdin.readline
read = lambda: list(map(int, inp().split()))
def e():
res = 0
n, m = read()
mat = [None]*n
for i in range(n):
mat[i] = read()
for col in range(m):
b = [0]*n#defaultdict(int)
for row in range(n):
elem = mat[row][col]
place = row*m + col + 1
if elem <= n*m and (place - elem)%m == 0:
shift = ((place - elem)//m if place >= elem else (n*m + place - elem)//m)
b[shift] += 1
res += min(i+n-b[i] for i in range(n))
print(res)
def d():
ans = ""
mex = 0
q, x = read()
arr = [0]*q+[0]
dic = {i: deque([i]) for i in range(x)}
for i in dic:
while dic[i][-1] + x < q+1:
dic[i].append(dic[i][-1] + x)
for _ in range(q):
n = int(inp())
ind = dic[n%x].popleft() if dic[n%x] else n%x
arr[ind] = 1
while arr[mex] == 1:
mex += 1
ans += str(mex) + "\n"
print(ans)
if __name__ == "__main__":
e()
```
| 100,465 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rectangular matrix of size n Γ m consisting of integers from 1 to 2 β
10^5.
In one move, you can:
* choose any element of the matrix and change its value to any integer between 1 and n β
m, inclusive;
* take any column and shift it one cell up cyclically (see the example of such cyclic shift below).
A cyclic shift is an operation such that you choose some j (1 β€ j β€ m) and set a_{1, j} := a_{2, j}, a_{2, j} := a_{3, j}, ..., a_{n, j} := a_{1, j} simultaneously.
<image> Example of cyclic shift of the first column
You want to perform the minimum number of moves to make this matrix look like this:
<image>
In other words, the goal is to obtain the matrix, where a_{1, 1} = 1, a_{1, 2} = 2, ..., a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, ..., a_{n, m} = n β
m (i.e. a_{i, j} = (i - 1) β
m + j) with the minimum number of moves performed.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 2 β
10^5, n β
m β€ 2 β
10^5) β the size of the matrix.
The next n lines contain m integers each. The number at the line i and position j is a_{i, j} (1 β€ a_{i, j} β€ 2 β
10^5).
Output
Print one integer β the minimum number of moves required to obtain the matrix, where a_{1, 1} = 1, a_{1, 2} = 2, ..., a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, ..., a_{n, m} = n β
m (a_{i, j} = (i - 1)m + j).
Examples
Input
3 3
3 2 1
1 2 3
4 5 6
Output
6
Input
4 3
1 2 3
4 5 6
7 8 9
10 11 12
Output
0
Input
3 4
1 6 3 4
5 10 7 8
9 2 11 12
Output
2
Note
In the first example, you can set a_{1, 1} := 7, a_{1, 2} := 8 and a_{1, 3} := 9 then shift the first, the second and the third columns cyclically, so the answer is 6. It can be shown that you cannot achieve a better answer.
In the second example, the matrix is already good so the answer is 0.
In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 2.
Tags: greedy, implementation, math
Correct Solution:
```
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 21 18:49:02 2020
@author: dennis
"""
import atexit
import io
import sys
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER
@atexit.register
def write():
sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
n, m = [int(x) for x in input().split()] # n = rows, m = columns
a = [[int(x) for x in input().split()] for _ in range(n)]
max_value = n*m
moves = 0
for i in range(m):
column = [row[i] for row in a]
offsets = {x: 0 for x in range(n)}
for j, v in enumerate(column):
if (v%m) == ((i+1)%m) and (v <= max_value):
expected = (j*m)+i+1
offset = ((expected-v)//m)%n
offsets[offset] += 1
saved = 0
for k, v in offsets.items():
saved = max(saved, v-k)
moves += n-saved
print(moves)
```
| 100,466 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rectangular matrix of size n Γ m consisting of integers from 1 to 2 β
10^5.
In one move, you can:
* choose any element of the matrix and change its value to any integer between 1 and n β
m, inclusive;
* take any column and shift it one cell up cyclically (see the example of such cyclic shift below).
A cyclic shift is an operation such that you choose some j (1 β€ j β€ m) and set a_{1, j} := a_{2, j}, a_{2, j} := a_{3, j}, ..., a_{n, j} := a_{1, j} simultaneously.
<image> Example of cyclic shift of the first column
You want to perform the minimum number of moves to make this matrix look like this:
<image>
In other words, the goal is to obtain the matrix, where a_{1, 1} = 1, a_{1, 2} = 2, ..., a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, ..., a_{n, m} = n β
m (i.e. a_{i, j} = (i - 1) β
m + j) with the minimum number of moves performed.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 2 β
10^5, n β
m β€ 2 β
10^5) β the size of the matrix.
The next n lines contain m integers each. The number at the line i and position j is a_{i, j} (1 β€ a_{i, j} β€ 2 β
10^5).
Output
Print one integer β the minimum number of moves required to obtain the matrix, where a_{1, 1} = 1, a_{1, 2} = 2, ..., a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, ..., a_{n, m} = n β
m (a_{i, j} = (i - 1)m + j).
Examples
Input
3 3
3 2 1
1 2 3
4 5 6
Output
6
Input
4 3
1 2 3
4 5 6
7 8 9
10 11 12
Output
0
Input
3 4
1 6 3 4
5 10 7 8
9 2 11 12
Output
2
Note
In the first example, you can set a_{1, 1} := 7, a_{1, 2} := 8 and a_{1, 3} := 9 then shift the first, the second and the third columns cyclically, so the answer is 6. It can be shown that you cannot achieve a better answer.
In the second example, the matrix is already good so the answer is 0.
In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 2.
Tags: greedy, implementation, math
Correct Solution:
```
def solve(column,start,n,m):
shiftCnts=[0 for _ in range(n)]
for actualPosition in range(n):
v=column[actualPosition]
if v>n*m:
continue
desiredPosition=(v-1)//m
desiredValueAtDesiredPosition=start+m*desiredPosition
if desiredValueAtDesiredPosition!=v:
continue
shiftsRequired=(actualPosition-desiredPosition+n)%n
shiftCnts[shiftsRequired]+=1
ans=inf
for shifts in range(n):
ans=min(ans,shifts+n-shiftCnts[shifts])
# print('column:{} shiftCnts:{}'.format(column,shiftCnts))
return ans
def main():
n,m=readIntArr()
arr=[]
for _ in range(n):
arr.append(readIntArr())
ans=0
for j in range(m):
column=[]
for i in range(n):
column.append(arr[i][j])
ans+=solve(column,j+1,n,m)
print(ans)
return
import sys
# input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
# def readFloatArr():
# return [float(x) for x in input().split()]
def makeArr(*args):
"""
*args : (default value, dimension 1, dimension 2,...)
Returns : arr[dim1][dim2]... filled with default value
"""
assert len(args) >= 2, "makeArr args should be (default value, dimension 1, dimension 2,..."
if len(args) == 2:
return [args[0] for _ in range(args[1])]
else:
return [makeArr(args[0],*args[2:]) for _ in range(args[1])]
def queryInteractive(x,y):
print('? {} {}'.format(x,y))
sys.stdout.flush()
return int(input())
def answerInteractive(ans):
print('! {}'.format(ans))
sys.stdout.flush()
inf=float('inf')
MOD=10**9+7
for _abc in range(1):
main()
```
| 100,467 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rectangular matrix of size n Γ m consisting of integers from 1 to 2 β
10^5.
In one move, you can:
* choose any element of the matrix and change its value to any integer between 1 and n β
m, inclusive;
* take any column and shift it one cell up cyclically (see the example of such cyclic shift below).
A cyclic shift is an operation such that you choose some j (1 β€ j β€ m) and set a_{1, j} := a_{2, j}, a_{2, j} := a_{3, j}, ..., a_{n, j} := a_{1, j} simultaneously.
<image> Example of cyclic shift of the first column
You want to perform the minimum number of moves to make this matrix look like this:
<image>
In other words, the goal is to obtain the matrix, where a_{1, 1} = 1, a_{1, 2} = 2, ..., a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, ..., a_{n, m} = n β
m (i.e. a_{i, j} = (i - 1) β
m + j) with the minimum number of moves performed.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 2 β
10^5, n β
m β€ 2 β
10^5) β the size of the matrix.
The next n lines contain m integers each. The number at the line i and position j is a_{i, j} (1 β€ a_{i, j} β€ 2 β
10^5).
Output
Print one integer β the minimum number of moves required to obtain the matrix, where a_{1, 1} = 1, a_{1, 2} = 2, ..., a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, ..., a_{n, m} = n β
m (a_{i, j} = (i - 1)m + j).
Examples
Input
3 3
3 2 1
1 2 3
4 5 6
Output
6
Input
4 3
1 2 3
4 5 6
7 8 9
10 11 12
Output
0
Input
3 4
1 6 3 4
5 10 7 8
9 2 11 12
Output
2
Note
In the first example, you can set a_{1, 1} := 7, a_{1, 2} := 8 and a_{1, 3} := 9 then shift the first, the second and the third columns cyclically, so the answer is 6. It can be shown that you cannot achieve a better answer.
In the second example, the matrix is already good so the answer is 0.
In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 2.
Tags: greedy, implementation, math
Correct Solution:
```
from bisect import bisect_left as bl
from bisect import bisect_right as br
import heapq
import math
from collections import *
from functools import reduce,cmp_to_key
import sys
input = sys.stdin.readline
# M = mod = 998244353
def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
# def inv_mod(n):return pow(n, mod - 2, mod)
def li():return [int(i) for i in input().rstrip('\n').split()]
def st():return input().rstrip('\n')
def val():return int(input().rstrip('\n'))
def li2():return [i for i in input().rstrip('\n').split(' ')]
def li3():return [int(i) for i in input().rstrip('\n')]
n, m = li()
l = []
ans = 0
for i in range(n):l.append(li())
for j in range(1,m+1):
cnt = Counter()
# visited = {}
for i in range(1,n+1):
# print(l[i][j],end=" ")
tot = 0
ele = l[i-1][j-1]
if ele > n*m:continue
if j == m:
if ele%m:continue
else:
if ele%m != j:continue
pos = math.ceil(ele/m)
# print(ele,pos,i,)
if pos > i:
dist = i + (n - pos)
else:
dist = i - pos
cnt[dist] += 1
temp = n
if len(cnt):
for i in cnt:
temp = min(temp,i + (n - cnt[i]))
# print(cnt)
ans += temp
print(ans)
```
| 100,468 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a rectangular matrix of size n Γ m consisting of integers from 1 to 2 β
10^5.
In one move, you can:
* choose any element of the matrix and change its value to any integer between 1 and n β
m, inclusive;
* take any column and shift it one cell up cyclically (see the example of such cyclic shift below).
A cyclic shift is an operation such that you choose some j (1 β€ j β€ m) and set a_{1, j} := a_{2, j}, a_{2, j} := a_{3, j}, ..., a_{n, j} := a_{1, j} simultaneously.
<image> Example of cyclic shift of the first column
You want to perform the minimum number of moves to make this matrix look like this:
<image>
In other words, the goal is to obtain the matrix, where a_{1, 1} = 1, a_{1, 2} = 2, ..., a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, ..., a_{n, m} = n β
m (i.e. a_{i, j} = (i - 1) β
m + j) with the minimum number of moves performed.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 2 β
10^5, n β
m β€ 2 β
10^5) β the size of the matrix.
The next n lines contain m integers each. The number at the line i and position j is a_{i, j} (1 β€ a_{i, j} β€ 2 β
10^5).
Output
Print one integer β the minimum number of moves required to obtain the matrix, where a_{1, 1} = 1, a_{1, 2} = 2, ..., a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, ..., a_{n, m} = n β
m (a_{i, j} = (i - 1)m + j).
Examples
Input
3 3
3 2 1
1 2 3
4 5 6
Output
6
Input
4 3
1 2 3
4 5 6
7 8 9
10 11 12
Output
0
Input
3 4
1 6 3 4
5 10 7 8
9 2 11 12
Output
2
Note
In the first example, you can set a_{1, 1} := 7, a_{1, 2} := 8 and a_{1, 3} := 9 then shift the first, the second and the third columns cyclically, so the answer is 6. It can be shown that you cannot achieve a better answer.
In the second example, the matrix is already good so the answer is 0.
In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 2.
Submitted Solution:
```
def min_op_ab(A, a, b):
#print(A, a, b)
counts = {v: 0 for v in range(len(A))}
vmin, vmax = b, (len(A) - 1) * a + b
for i, p in enumerate(A):
if vmin <= p <= vmax and p % a == b % a:
corr_pos = (p - b) // a
v = (i - corr_pos) % len(A)
counts[v] += 1
#print(counts.items())
return min(len(A) - cv + v for v, cv in counts.items())
def mat_col(M, c):
return [M[r][c] for r in range(len(M))]
import sys
n, m = (int(v) for v in sys.stdin.readline().split())
M = []
for r in range(n):
M.append([int(v) for v in sys.stdin.readline().split()])
ops = 0
for c in range(m):
col = mat_col(M, c)
a, b = m, c + 1
#print(min_op_ab(col, a, b))
ops += min_op_ab(col, a, b)
print(ops)
```
Yes
| 100,469 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a rectangular matrix of size n Γ m consisting of integers from 1 to 2 β
10^5.
In one move, you can:
* choose any element of the matrix and change its value to any integer between 1 and n β
m, inclusive;
* take any column and shift it one cell up cyclically (see the example of such cyclic shift below).
A cyclic shift is an operation such that you choose some j (1 β€ j β€ m) and set a_{1, j} := a_{2, j}, a_{2, j} := a_{3, j}, ..., a_{n, j} := a_{1, j} simultaneously.
<image> Example of cyclic shift of the first column
You want to perform the minimum number of moves to make this matrix look like this:
<image>
In other words, the goal is to obtain the matrix, where a_{1, 1} = 1, a_{1, 2} = 2, ..., a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, ..., a_{n, m} = n β
m (i.e. a_{i, j} = (i - 1) β
m + j) with the minimum number of moves performed.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 2 β
10^5, n β
m β€ 2 β
10^5) β the size of the matrix.
The next n lines contain m integers each. The number at the line i and position j is a_{i, j} (1 β€ a_{i, j} β€ 2 β
10^5).
Output
Print one integer β the minimum number of moves required to obtain the matrix, where a_{1, 1} = 1, a_{1, 2} = 2, ..., a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, ..., a_{n, m} = n β
m (a_{i, j} = (i - 1)m + j).
Examples
Input
3 3
3 2 1
1 2 3
4 5 6
Output
6
Input
4 3
1 2 3
4 5 6
7 8 9
10 11 12
Output
0
Input
3 4
1 6 3 4
5 10 7 8
9 2 11 12
Output
2
Note
In the first example, you can set a_{1, 1} := 7, a_{1, 2} := 8 and a_{1, 3} := 9 then shift the first, the second and the third columns cyclically, so the answer is 6. It can be shown that you cannot achieve a better answer.
In the second example, the matrix is already good so the answer is 0.
In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 2.
Submitted Solution:
```
n,m = map(int, input().split())
mtx = []
for _ in range(n):
mtx.append(list(map(int,input().split())))
total = 0
for i in range(m):
cnt = {}
for j in range(n):
if (mtx[j][i]-i-1)%m == 0:
pos = (mtx[j][i]-1)//m
if pos < n:
c = (j-pos)%n
cnt[c] = cnt.get(c,0)+1
add = n
for k,v in cnt.items():
add = min(add, k+n-v)
total+=add
print(total)
```
Yes
| 100,470 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a rectangular matrix of size n Γ m consisting of integers from 1 to 2 β
10^5.
In one move, you can:
* choose any element of the matrix and change its value to any integer between 1 and n β
m, inclusive;
* take any column and shift it one cell up cyclically (see the example of such cyclic shift below).
A cyclic shift is an operation such that you choose some j (1 β€ j β€ m) and set a_{1, j} := a_{2, j}, a_{2, j} := a_{3, j}, ..., a_{n, j} := a_{1, j} simultaneously.
<image> Example of cyclic shift of the first column
You want to perform the minimum number of moves to make this matrix look like this:
<image>
In other words, the goal is to obtain the matrix, where a_{1, 1} = 1, a_{1, 2} = 2, ..., a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, ..., a_{n, m} = n β
m (i.e. a_{i, j} = (i - 1) β
m + j) with the minimum number of moves performed.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 2 β
10^5, n β
m β€ 2 β
10^5) β the size of the matrix.
The next n lines contain m integers each. The number at the line i and position j is a_{i, j} (1 β€ a_{i, j} β€ 2 β
10^5).
Output
Print one integer β the minimum number of moves required to obtain the matrix, where a_{1, 1} = 1, a_{1, 2} = 2, ..., a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, ..., a_{n, m} = n β
m (a_{i, j} = (i - 1)m + j).
Examples
Input
3 3
3 2 1
1 2 3
4 5 6
Output
6
Input
4 3
1 2 3
4 5 6
7 8 9
10 11 12
Output
0
Input
3 4
1 6 3 4
5 10 7 8
9 2 11 12
Output
2
Note
In the first example, you can set a_{1, 1} := 7, a_{1, 2} := 8 and a_{1, 3} := 9 then shift the first, the second and the third columns cyclically, so the answer is 6. It can be shown that you cannot achieve a better answer.
In the second example, the matrix is already good so the answer is 0.
In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 2.
Submitted Solution:
```
from collections import defaultdict, deque, Counter
from sys import stdin, stdout
from heapq import heappush, heappop
import math
import io
import os
import math
import bisect
#?############################################################
def isPrime(x):
for i in range(2, x):
if i*i > x:
break
if (x % i == 0):
return False
return True
#?############################################################
def ncr(n, r, p):
num = den = 1
for i in range(r):
num = (num * (n - i)) % p
den = (den * (i + 1)) % p
return (num * pow(den, p - 2, p)) % p
#?############################################################
def primeFactors(n):
l = []
while n % 2 == 0:
l.append(2)
n = n // 2
for i in range(3, int(math.sqrt(n))+1, 2):
while n % i == 0:
l.append(i)
n = n // i
if n > 2:
l.append(n)
return l
#?############################################################
def power(x, y, p):
res = 1
x = x % p
if (x == 0):
return 0
while (y > 0):
if ((y & 1) == 1):
res = (res * x) % p
y = y >> 1
x = (x * x) % p
return res
#?############################################################
def sieve(n):
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
return prime
#?############################################################
def digits(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
#?############################################################
def ceil(n, x):
if (n % x == 0):
return n//x
return n//x+1
#?############################################################
def mapin():
return map(int, input().split())
#?############################################################
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
# python3 15.py<in>op
def solve(l, n, m, c, d):
s = [0]*n
for i in range(n):
if(l[i]%m == c):
a = l[i]//m
a-=d
if(a>= n):
continue
if(a-i>=0):
a = (i+n-a)%n
else:
a = (i-a)%n
# print(i, l[i], n, m, a)
if(a<n):
s[a]+=1
ans = 1e9
for i in range(n):
temp = n
temp-=s[i]
temp+=i
# print(i, temp)
ans =min(ans, temp)
# print(s, ans)
return ans
n, m = mapin()
sa = []
for i in range(m):
sa.append([0]*n)
for i in range(n):
tt = [int(x) for x in input().split()]
for j in range(m):
sa[j][i] = tt[j]
ans = 0
for j in range(m):
a =solve(sa[j], n, m, (j+1)%m, (j+1)//m)
ans+=a
# print(j, a)
# a = a =solve(sa[-1], n, m, m)
print(ans)
```
Yes
| 100,471 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a rectangular matrix of size n Γ m consisting of integers from 1 to 2 β
10^5.
In one move, you can:
* choose any element of the matrix and change its value to any integer between 1 and n β
m, inclusive;
* take any column and shift it one cell up cyclically (see the example of such cyclic shift below).
A cyclic shift is an operation such that you choose some j (1 β€ j β€ m) and set a_{1, j} := a_{2, j}, a_{2, j} := a_{3, j}, ..., a_{n, j} := a_{1, j} simultaneously.
<image> Example of cyclic shift of the first column
You want to perform the minimum number of moves to make this matrix look like this:
<image>
In other words, the goal is to obtain the matrix, where a_{1, 1} = 1, a_{1, 2} = 2, ..., a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, ..., a_{n, m} = n β
m (i.e. a_{i, j} = (i - 1) β
m + j) with the minimum number of moves performed.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 2 β
10^5, n β
m β€ 2 β
10^5) β the size of the matrix.
The next n lines contain m integers each. The number at the line i and position j is a_{i, j} (1 β€ a_{i, j} β€ 2 β
10^5).
Output
Print one integer β the minimum number of moves required to obtain the matrix, where a_{1, 1} = 1, a_{1, 2} = 2, ..., a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, ..., a_{n, m} = n β
m (a_{i, j} = (i - 1)m + j).
Examples
Input
3 3
3 2 1
1 2 3
4 5 6
Output
6
Input
4 3
1 2 3
4 5 6
7 8 9
10 11 12
Output
0
Input
3 4
1 6 3 4
5 10 7 8
9 2 11 12
Output
2
Note
In the first example, you can set a_{1, 1} := 7, a_{1, 2} := 8 and a_{1, 3} := 9 then shift the first, the second and the third columns cyclically, so the answer is 6. It can be shown that you cannot achieve a better answer.
In the second example, the matrix is already good so the answer is 0.
In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 2.
Submitted Solution:
```
import sys
input = sys.stdin.readline
n,m=map(int,input().split())
CR=[list(map(int,input().split())) for i in range(n)]
for i in range(n):
for j in range(m):
CR[i][j]-=1
MAX=n*m
ANS=0
for i in range(m):
SCORE=[0]*n
for j in range(n):
if CR[j][i]%m==i%m and 0<=CR[j][i]<MAX:
x=(CR[j][i]-i%m)//m
SCORE[(j-x)%n]+=1
#print(SCORE)
#print(SCORE)
ANS+=min([n+j-SCORE[j] for j in range(n)])
print(ANS)
```
Yes
| 100,472 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a rectangular matrix of size n Γ m consisting of integers from 1 to 2 β
10^5.
In one move, you can:
* choose any element of the matrix and change its value to any integer between 1 and n β
m, inclusive;
* take any column and shift it one cell up cyclically (see the example of such cyclic shift below).
A cyclic shift is an operation such that you choose some j (1 β€ j β€ m) and set a_{1, j} := a_{2, j}, a_{2, j} := a_{3, j}, ..., a_{n, j} := a_{1, j} simultaneously.
<image> Example of cyclic shift of the first column
You want to perform the minimum number of moves to make this matrix look like this:
<image>
In other words, the goal is to obtain the matrix, where a_{1, 1} = 1, a_{1, 2} = 2, ..., a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, ..., a_{n, m} = n β
m (i.e. a_{i, j} = (i - 1) β
m + j) with the minimum number of moves performed.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 2 β
10^5, n β
m β€ 2 β
10^5) β the size of the matrix.
The next n lines contain m integers each. The number at the line i and position j is a_{i, j} (1 β€ a_{i, j} β€ 2 β
10^5).
Output
Print one integer β the minimum number of moves required to obtain the matrix, where a_{1, 1} = 1, a_{1, 2} = 2, ..., a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, ..., a_{n, m} = n β
m (a_{i, j} = (i - 1)m + j).
Examples
Input
3 3
3 2 1
1 2 3
4 5 6
Output
6
Input
4 3
1 2 3
4 5 6
7 8 9
10 11 12
Output
0
Input
3 4
1 6 3 4
5 10 7 8
9 2 11 12
Output
2
Note
In the first example, you can set a_{1, 1} := 7, a_{1, 2} := 8 and a_{1, 3} := 9 then shift the first, the second and the third columns cyclically, so the answer is 6. It can be shown that you cannot achieve a better answer.
In the second example, the matrix is already good so the answer is 0.
In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 2.
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush
# ------------------------------
# f = open('./input.txt')
# sys.stdin = f
def main():
n, m = RL()
arr = [RLL() for _ in range(n)]
res = 0
for i in range(m):
# tar = [i+1+m*j for j in range(n)]
fir = i+1
rec = defaultdict(int)
for j in range(n):
now = arr[j][i]
if (now-fir)%m!=0: continue
p = (now-fir)//m
if j-p>=0:
rec[j-p]+=1
else:
rec[n-(p-j)]+=1
tres = INF
for k, v in rec.items():
tres = min(tres, (n-v)+k)
res+=tres
print(res)
if __name__ == "__main__":
main()
```
No
| 100,473 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a rectangular matrix of size n Γ m consisting of integers from 1 to 2 β
10^5.
In one move, you can:
* choose any element of the matrix and change its value to any integer between 1 and n β
m, inclusive;
* take any column and shift it one cell up cyclically (see the example of such cyclic shift below).
A cyclic shift is an operation such that you choose some j (1 β€ j β€ m) and set a_{1, j} := a_{2, j}, a_{2, j} := a_{3, j}, ..., a_{n, j} := a_{1, j} simultaneously.
<image> Example of cyclic shift of the first column
You want to perform the minimum number of moves to make this matrix look like this:
<image>
In other words, the goal is to obtain the matrix, where a_{1, 1} = 1, a_{1, 2} = 2, ..., a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, ..., a_{n, m} = n β
m (i.e. a_{i, j} = (i - 1) β
m + j) with the minimum number of moves performed.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 2 β
10^5, n β
m β€ 2 β
10^5) β the size of the matrix.
The next n lines contain m integers each. The number at the line i and position j is a_{i, j} (1 β€ a_{i, j} β€ 2 β
10^5).
Output
Print one integer β the minimum number of moves required to obtain the matrix, where a_{1, 1} = 1, a_{1, 2} = 2, ..., a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, ..., a_{n, m} = n β
m (a_{i, j} = (i - 1)m + j).
Examples
Input
3 3
3 2 1
1 2 3
4 5 6
Output
6
Input
4 3
1 2 3
4 5 6
7 8 9
10 11 12
Output
0
Input
3 4
1 6 3 4
5 10 7 8
9 2 11 12
Output
2
Note
In the first example, you can set a_{1, 1} := 7, a_{1, 2} := 8 and a_{1, 3} := 9 then shift the first, the second and the third columns cyclically, so the answer is 6. It can be shown that you cannot achieve a better answer.
In the second example, the matrix is already good so the answer is 0.
In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 2.
Submitted Solution:
```
n,m=map(int,input().split())
tbl=[]
for _ in range(n):
tbl.append(list(map(int,input().split())))
l=[[k+n for k in range(n)] for _ in range(m)]
for i in range(m):
for j in range(n):
a=(tbl[j][i]-1)//m
b=(tbl[j][i]-1)%m
if b==i:
l[i][(j-a)%n]-=1
ans=0
for i in range(m):
ans+=min(l[i])
print(ans)
```
No
| 100,474 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a rectangular matrix of size n Γ m consisting of integers from 1 to 2 β
10^5.
In one move, you can:
* choose any element of the matrix and change its value to any integer between 1 and n β
m, inclusive;
* take any column and shift it one cell up cyclically (see the example of such cyclic shift below).
A cyclic shift is an operation such that you choose some j (1 β€ j β€ m) and set a_{1, j} := a_{2, j}, a_{2, j} := a_{3, j}, ..., a_{n, j} := a_{1, j} simultaneously.
<image> Example of cyclic shift of the first column
You want to perform the minimum number of moves to make this matrix look like this:
<image>
In other words, the goal is to obtain the matrix, where a_{1, 1} = 1, a_{1, 2} = 2, ..., a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, ..., a_{n, m} = n β
m (i.e. a_{i, j} = (i - 1) β
m + j) with the minimum number of moves performed.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 2 β
10^5, n β
m β€ 2 β
10^5) β the size of the matrix.
The next n lines contain m integers each. The number at the line i and position j is a_{i, j} (1 β€ a_{i, j} β€ 2 β
10^5).
Output
Print one integer β the minimum number of moves required to obtain the matrix, where a_{1, 1} = 1, a_{1, 2} = 2, ..., a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, ..., a_{n, m} = n β
m (a_{i, j} = (i - 1)m + j).
Examples
Input
3 3
3 2 1
1 2 3
4 5 6
Output
6
Input
4 3
1 2 3
4 5 6
7 8 9
10 11 12
Output
0
Input
3 4
1 6 3 4
5 10 7 8
9 2 11 12
Output
2
Note
In the first example, you can set a_{1, 1} := 7, a_{1, 2} := 8 and a_{1, 3} := 9 then shift the first, the second and the third columns cyclically, so the answer is 6. It can be shown that you cannot achieve a better answer.
In the second example, the matrix is already good so the answer is 0.
In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 2.
Submitted Solution:
```
from sys import stdin
def solve():
n,m=map(int,stdin.readline().split())
l=[list(map(lambda x:int(x)-1,stdin.readline().split())) for i in range(n)]
mvs=0
for j in range(m):
d={}
ans=n
for i in range(n):
if l[i][j]%m==j:
idx=(l[i][j]-j)//m
if i-idx>=0:
x=i-idx
else:
x=n+i-idx
d.setdefault(x,0)
d[x]+=1
for k in d:
ans=min(ans,(k+n-d[k]))
#print(d)
#print(ans)
mvs+=ans
print(mvs)
solve()
```
No
| 100,475 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a rectangular matrix of size n Γ m consisting of integers from 1 to 2 β
10^5.
In one move, you can:
* choose any element of the matrix and change its value to any integer between 1 and n β
m, inclusive;
* take any column and shift it one cell up cyclically (see the example of such cyclic shift below).
A cyclic shift is an operation such that you choose some j (1 β€ j β€ m) and set a_{1, j} := a_{2, j}, a_{2, j} := a_{3, j}, ..., a_{n, j} := a_{1, j} simultaneously.
<image> Example of cyclic shift of the first column
You want to perform the minimum number of moves to make this matrix look like this:
<image>
In other words, the goal is to obtain the matrix, where a_{1, 1} = 1, a_{1, 2} = 2, ..., a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, ..., a_{n, m} = n β
m (i.e. a_{i, j} = (i - 1) β
m + j) with the minimum number of moves performed.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 2 β
10^5, n β
m β€ 2 β
10^5) β the size of the matrix.
The next n lines contain m integers each. The number at the line i and position j is a_{i, j} (1 β€ a_{i, j} β€ 2 β
10^5).
Output
Print one integer β the minimum number of moves required to obtain the matrix, where a_{1, 1} = 1, a_{1, 2} = 2, ..., a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, ..., a_{n, m} = n β
m (a_{i, j} = (i - 1)m + j).
Examples
Input
3 3
3 2 1
1 2 3
4 5 6
Output
6
Input
4 3
1 2 3
4 5 6
7 8 9
10 11 12
Output
0
Input
3 4
1 6 3 4
5 10 7 8
9 2 11 12
Output
2
Note
In the first example, you can set a_{1, 1} := 7, a_{1, 2} := 8 and a_{1, 3} := 9 then shift the first, the second and the third columns cyclically, so the answer is 6. It can be shown that you cannot achieve a better answer.
In the second example, the matrix is already good so the answer is 0.
In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 2.
Submitted Solution:
```
from collections import defaultdict, deque, Counter
from sys import stdin, stdout
from heapq import heappush, heappop
import math
import io
import os
import math
import bisect
#?############################################################
def isPrime(x):
for i in range(2, x):
if i*i > x:
break
if (x % i == 0):
return False
return True
#?############################################################
def ncr(n, r, p):
num = den = 1
for i in range(r):
num = (num * (n - i)) % p
den = (den * (i + 1)) % p
return (num * pow(den, p - 2, p)) % p
#?############################################################
def primeFactors(n):
l = []
while n % 2 == 0:
l.append(2)
n = n // 2
for i in range(3, int(math.sqrt(n))+1, 2):
while n % i == 0:
l.append(i)
n = n // i
if n > 2:
l.append(n)
return l
#?############################################################
def power(x, y, p):
res = 1
x = x % p
if (x == 0):
return 0
while (y > 0):
if ((y & 1) == 1):
res = (res * x) % p
y = y >> 1
x = (x * x) % p
return res
#?############################################################
def sieve(n):
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
return prime
#?############################################################
def digits(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
#?############################################################
def ceil(n, x):
if (n % x == 0):
return n//x
return n//x+1
#?############################################################
def mapin():
return map(int, input().split())
#?############################################################
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
# python3 15.py<in>op
def solve(l, n, m, c, d):
s = [0]*n
for i in range(n):
if(l[i]%m == c):
a = l[i]//m
a-=d
if(a-i>=0):
a = a-i
else:
a = n-1-(i-a)
# print(i, l[i], n, m, a)
s[a]+=1
ans = 1e9
# print(s)
for i in range(n):
temp = n
temp-=s[i]
temp+=i
# print(i, temp)
ans =min(ans, temp)
return ans
n, m = mapin()
sa = []
for i in range(m):
sa.append([0]*n)
for i in range(n):
tt = [int(x) for x in input().split()]
for j in range(m):
sa[j][i] = tt[j]
ans = 0
for j in range(m):
a =solve(sa[j], n, m, (j+1)%m, (j+1)//m)
ans+=a
# print(j, a)
# a = a =solve(sa[-1], n, m, m)
print(ans)
```
No
| 100,476 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.
These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite β cookies. Ichihime decides to attend the contest. Now she is solving the following problem.
<image>
You are given four positive integers a, b, c, d, such that a β€ b β€ c β€ d.
Your task is to find three integers x, y, z, satisfying the following conditions:
* a β€ x β€ b.
* b β€ y β€ c.
* c β€ z β€ d.
* There exists a triangle with a positive non-zero area and the lengths of its three sides are x, y, and z.
Ichihime desires to get the cookie, but the problem seems too hard for her. Can you help her?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases.
The next t lines describe test cases. Each test case is given as four space-separated integers a, b, c, d (1 β€ a β€ b β€ c β€ d β€ 10^9).
Output
For each test case, print three integers x, y, z β the integers you found satisfying the conditions given in the statement.
It is guaranteed that the answer always exists. If there are multiple answers, print any.
Example
Input
4
1 3 5 7
1 5 5 7
100000 200000 300000 400000
1 1 977539810 977539810
Output
3 4 5
5 5 5
182690 214748 300999
1 977539810 977539810
Note
One of the possible solutions to the first test case:
<image>
One of the possible solutions to the second test case:
<image>
Tags: constructive algorithms, math
Correct Solution:
```
import sys
input = sys.stdin.readline
x = int(input())
for _ in range(x):
a, b, c, d = map(int, input().split())
print(b, c, c)
```
| 100,477 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.
These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite β cookies. Ichihime decides to attend the contest. Now she is solving the following problem.
<image>
You are given four positive integers a, b, c, d, such that a β€ b β€ c β€ d.
Your task is to find three integers x, y, z, satisfying the following conditions:
* a β€ x β€ b.
* b β€ y β€ c.
* c β€ z β€ d.
* There exists a triangle with a positive non-zero area and the lengths of its three sides are x, y, and z.
Ichihime desires to get the cookie, but the problem seems too hard for her. Can you help her?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases.
The next t lines describe test cases. Each test case is given as four space-separated integers a, b, c, d (1 β€ a β€ b β€ c β€ d β€ 10^9).
Output
For each test case, print three integers x, y, z β the integers you found satisfying the conditions given in the statement.
It is guaranteed that the answer always exists. If there are multiple answers, print any.
Example
Input
4
1 3 5 7
1 5 5 7
100000 200000 300000 400000
1 1 977539810 977539810
Output
3 4 5
5 5 5
182690 214748 300999
1 977539810 977539810
Note
One of the possible solutions to the first test case:
<image>
One of the possible solutions to the second test case:
<image>
Tags: constructive algorithms, math
Correct Solution:
```
for i in range(int(input())):
a,b,c,d = map(int,input().split()) #100 3 4
print(b,c,c)
```
| 100,478 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.
These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite β cookies. Ichihime decides to attend the contest. Now she is solving the following problem.
<image>
You are given four positive integers a, b, c, d, such that a β€ b β€ c β€ d.
Your task is to find three integers x, y, z, satisfying the following conditions:
* a β€ x β€ b.
* b β€ y β€ c.
* c β€ z β€ d.
* There exists a triangle with a positive non-zero area and the lengths of its three sides are x, y, and z.
Ichihime desires to get the cookie, but the problem seems too hard for her. Can you help her?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases.
The next t lines describe test cases. Each test case is given as four space-separated integers a, b, c, d (1 β€ a β€ b β€ c β€ d β€ 10^9).
Output
For each test case, print three integers x, y, z β the integers you found satisfying the conditions given in the statement.
It is guaranteed that the answer always exists. If there are multiple answers, print any.
Example
Input
4
1 3 5 7
1 5 5 7
100000 200000 300000 400000
1 1 977539810 977539810
Output
3 4 5
5 5 5
182690 214748 300999
1 977539810 977539810
Note
One of the possible solutions to the first test case:
<image>
One of the possible solutions to the second test case:
<image>
Tags: constructive algorithms, math
Correct Solution:
```
z=input
mod = 10**9 + 7
from collections import *
from queue import *
from sys import *
from collections import *
from math import *
from heapq import *
from itertools import *
from bisect import *
from collections import Counter as cc
from math import factorial as f
def lcd(xnum1,xnum2):
return (xnum1*xnum2//gcd(xnum1,xnum2))
################################################################################
"""
n=int(z())
for _ in range(int(z())):
x=int(z())
l=list(map(int,z().split()))
n=int(z())
l=sorted(list(map(int,z().split())))[::-1]
a,b=map(int,z().split())
l=set(map(int,z().split()))
led=(6,2,5,5,4,5,6,3,7,6)
vowel={'a':0,'e':0,'i':0,'o':0,'u':0}
color-4=["G", "GB", "YGB", "YGBI", "OYGBI" ,"OYGBIV",'ROYGBIV' ]
"""
###########################---START-CODING---###############################################
for _ in range(int(z())):
a,b,c,d=map(int,input().split())
print(b,c,c)
```
| 100,479 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.
These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite β cookies. Ichihime decides to attend the contest. Now she is solving the following problem.
<image>
You are given four positive integers a, b, c, d, such that a β€ b β€ c β€ d.
Your task is to find three integers x, y, z, satisfying the following conditions:
* a β€ x β€ b.
* b β€ y β€ c.
* c β€ z β€ d.
* There exists a triangle with a positive non-zero area and the lengths of its three sides are x, y, and z.
Ichihime desires to get the cookie, but the problem seems too hard for her. Can you help her?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases.
The next t lines describe test cases. Each test case is given as four space-separated integers a, b, c, d (1 β€ a β€ b β€ c β€ d β€ 10^9).
Output
For each test case, print three integers x, y, z β the integers you found satisfying the conditions given in the statement.
It is guaranteed that the answer always exists. If there are multiple answers, print any.
Example
Input
4
1 3 5 7
1 5 5 7
100000 200000 300000 400000
1 1 977539810 977539810
Output
3 4 5
5 5 5
182690 214748 300999
1 977539810 977539810
Note
One of the possible solutions to the first test case:
<image>
One of the possible solutions to the second test case:
<image>
Tags: constructive algorithms, math
Correct Solution:
```
# https://codeforces.com/problemset/problem/1337/A
tests = int(input())
while tests > 0:
a, b, c, d = [int(i) for i in input().split(" ")]
print(f'{b} {c} {c}')
tests = tests - 1
```
| 100,480 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.
These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite β cookies. Ichihime decides to attend the contest. Now she is solving the following problem.
<image>
You are given four positive integers a, b, c, d, such that a β€ b β€ c β€ d.
Your task is to find three integers x, y, z, satisfying the following conditions:
* a β€ x β€ b.
* b β€ y β€ c.
* c β€ z β€ d.
* There exists a triangle with a positive non-zero area and the lengths of its three sides are x, y, and z.
Ichihime desires to get the cookie, but the problem seems too hard for her. Can you help her?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases.
The next t lines describe test cases. Each test case is given as four space-separated integers a, b, c, d (1 β€ a β€ b β€ c β€ d β€ 10^9).
Output
For each test case, print three integers x, y, z β the integers you found satisfying the conditions given in the statement.
It is guaranteed that the answer always exists. If there are multiple answers, print any.
Example
Input
4
1 3 5 7
1 5 5 7
100000 200000 300000 400000
1 1 977539810 977539810
Output
3 4 5
5 5 5
182690 214748 300999
1 977539810 977539810
Note
One of the possible solutions to the first test case:
<image>
One of the possible solutions to the second test case:
<image>
Tags: constructive algorithms, math
Correct Solution:
```
def solve():
s = input().split()
for i in range(len(s)):
s[i] = int(s[i])
print (s[1], s[2], s[2])
t = int(input())
for i in range(t):
solve()
```
| 100,481 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.
These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite β cookies. Ichihime decides to attend the contest. Now she is solving the following problem.
<image>
You are given four positive integers a, b, c, d, such that a β€ b β€ c β€ d.
Your task is to find three integers x, y, z, satisfying the following conditions:
* a β€ x β€ b.
* b β€ y β€ c.
* c β€ z β€ d.
* There exists a triangle with a positive non-zero area and the lengths of its three sides are x, y, and z.
Ichihime desires to get the cookie, but the problem seems too hard for her. Can you help her?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases.
The next t lines describe test cases. Each test case is given as four space-separated integers a, b, c, d (1 β€ a β€ b β€ c β€ d β€ 10^9).
Output
For each test case, print three integers x, y, z β the integers you found satisfying the conditions given in the statement.
It is guaranteed that the answer always exists. If there are multiple answers, print any.
Example
Input
4
1 3 5 7
1 5 5 7
100000 200000 300000 400000
1 1 977539810 977539810
Output
3 4 5
5 5 5
182690 214748 300999
1 977539810 977539810
Note
One of the possible solutions to the first test case:
<image>
One of the possible solutions to the second test case:
<image>
Tags: constructive algorithms, math
Correct Solution:
```
from sys import stdin,stdout
from collections import defaultdict as df
t=int(input())
for i in range(t):
a,b,c,d=list(map(int,input().split()))
ans=[]
ans.append(b)
if c>b:
ans.append(c)
else:
ans.append(b)
ans.append(c)
print(*ans)
```
| 100,482 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.
These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite β cookies. Ichihime decides to attend the contest. Now she is solving the following problem.
<image>
You are given four positive integers a, b, c, d, such that a β€ b β€ c β€ d.
Your task is to find three integers x, y, z, satisfying the following conditions:
* a β€ x β€ b.
* b β€ y β€ c.
* c β€ z β€ d.
* There exists a triangle with a positive non-zero area and the lengths of its three sides are x, y, and z.
Ichihime desires to get the cookie, but the problem seems too hard for her. Can you help her?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases.
The next t lines describe test cases. Each test case is given as four space-separated integers a, b, c, d (1 β€ a β€ b β€ c β€ d β€ 10^9).
Output
For each test case, print three integers x, y, z β the integers you found satisfying the conditions given in the statement.
It is guaranteed that the answer always exists. If there are multiple answers, print any.
Example
Input
4
1 3 5 7
1 5 5 7
100000 200000 300000 400000
1 1 977539810 977539810
Output
3 4 5
5 5 5
182690 214748 300999
1 977539810 977539810
Note
One of the possible solutions to the first test case:
<image>
One of the possible solutions to the second test case:
<image>
Tags: constructive algorithms, math
Correct Solution:
```
for ii in range(int(input())):
n = [int(i) for i in input().split()]
a = n[0]
b = n[1]
c= n[2]
d = n[3]
x= b
y = c
if b+c <= d :
z = b+c-1
else :
z = d
print(x,y,z)
```
| 100,483 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.
These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite β cookies. Ichihime decides to attend the contest. Now she is solving the following problem.
<image>
You are given four positive integers a, b, c, d, such that a β€ b β€ c β€ d.
Your task is to find three integers x, y, z, satisfying the following conditions:
* a β€ x β€ b.
* b β€ y β€ c.
* c β€ z β€ d.
* There exists a triangle with a positive non-zero area and the lengths of its three sides are x, y, and z.
Ichihime desires to get the cookie, but the problem seems too hard for her. Can you help her?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases.
The next t lines describe test cases. Each test case is given as four space-separated integers a, b, c, d (1 β€ a β€ b β€ c β€ d β€ 10^9).
Output
For each test case, print three integers x, y, z β the integers you found satisfying the conditions given in the statement.
It is guaranteed that the answer always exists. If there are multiple answers, print any.
Example
Input
4
1 3 5 7
1 5 5 7
100000 200000 300000 400000
1 1 977539810 977539810
Output
3 4 5
5 5 5
182690 214748 300999
1 977539810 977539810
Note
One of the possible solutions to the first test case:
<image>
One of the possible solutions to the second test case:
<image>
Tags: constructive algorithms, math
Correct Solution:
```
t = int(input())
def fn(a,b,c,d):
for x in [a,b]:
for y in [b,c]:
for z in [c,d]:
if x + y > z and y + z > x and x + z > y:
print(x,y,z)
return
for _ in range(t):
a,b,c,d = map(int, input().split())
fn(a,b,c,d)
```
| 100,484 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.
These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite β cookies. Ichihime decides to attend the contest. Now she is solving the following problem.
<image>
You are given four positive integers a, b, c, d, such that a β€ b β€ c β€ d.
Your task is to find three integers x, y, z, satisfying the following conditions:
* a β€ x β€ b.
* b β€ y β€ c.
* c β€ z β€ d.
* There exists a triangle with a positive non-zero area and the lengths of its three sides are x, y, and z.
Ichihime desires to get the cookie, but the problem seems too hard for her. Can you help her?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases.
The next t lines describe test cases. Each test case is given as four space-separated integers a, b, c, d (1 β€ a β€ b β€ c β€ d β€ 10^9).
Output
For each test case, print three integers x, y, z β the integers you found satisfying the conditions given in the statement.
It is guaranteed that the answer always exists. If there are multiple answers, print any.
Example
Input
4
1 3 5 7
1 5 5 7
100000 200000 300000 400000
1 1 977539810 977539810
Output
3 4 5
5 5 5
182690 214748 300999
1 977539810 977539810
Note
One of the possible solutions to the first test case:
<image>
One of the possible solutions to the second test case:
<image>
Submitted Solution:
```
t = int(input())
for tt in range(0,t):
a,b,c,d = map(int,input().split())
print(b,c,c)
```
Yes
| 100,485 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.
These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite β cookies. Ichihime decides to attend the contest. Now she is solving the following problem.
<image>
You are given four positive integers a, b, c, d, such that a β€ b β€ c β€ d.
Your task is to find three integers x, y, z, satisfying the following conditions:
* a β€ x β€ b.
* b β€ y β€ c.
* c β€ z β€ d.
* There exists a triangle with a positive non-zero area and the lengths of its three sides are x, y, and z.
Ichihime desires to get the cookie, but the problem seems too hard for her. Can you help her?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases.
The next t lines describe test cases. Each test case is given as four space-separated integers a, b, c, d (1 β€ a β€ b β€ c β€ d β€ 10^9).
Output
For each test case, print three integers x, y, z β the integers you found satisfying the conditions given in the statement.
It is guaranteed that the answer always exists. If there are multiple answers, print any.
Example
Input
4
1 3 5 7
1 5 5 7
100000 200000 300000 400000
1 1 977539810 977539810
Output
3 4 5
5 5 5
182690 214748 300999
1 977539810 977539810
Note
One of the possible solutions to the first test case:
<image>
One of the possible solutions to the second test case:
<image>
Submitted Solution:
```
t = int(input())
for q in range(t):
a, b, c, d = map(int, input().split())
x = a
y = b
z = c
if c == max(a, b, c):
h = c - a - b + 1
if h > 0:
i = min(h, b - a)
h -= i
x += i
if h > 0:
y += h
elif b == max(a, b, c):
h = b - a - c + 1
if h > 0:
i = min(h, b - a)
h -= i
x += i
if h > 0:
z += h
else:
h = a - b - c + 1
if h > 0:
i = min(h, c - b)
h -= i
y += i
if h > 0:
z += h
print(x, y, z)
```
Yes
| 100,486 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.
These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite β cookies. Ichihime decides to attend the contest. Now she is solving the following problem.
<image>
You are given four positive integers a, b, c, d, such that a β€ b β€ c β€ d.
Your task is to find three integers x, y, z, satisfying the following conditions:
* a β€ x β€ b.
* b β€ y β€ c.
* c β€ z β€ d.
* There exists a triangle with a positive non-zero area and the lengths of its three sides are x, y, and z.
Ichihime desires to get the cookie, but the problem seems too hard for her. Can you help her?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases.
The next t lines describe test cases. Each test case is given as four space-separated integers a, b, c, d (1 β€ a β€ b β€ c β€ d β€ 10^9).
Output
For each test case, print three integers x, y, z β the integers you found satisfying the conditions given in the statement.
It is guaranteed that the answer always exists. If there are multiple answers, print any.
Example
Input
4
1 3 5 7
1 5 5 7
100000 200000 300000 400000
1 1 977539810 977539810
Output
3 4 5
5 5 5
182690 214748 300999
1 977539810 977539810
Note
One of the possible solutions to the first test case:
<image>
One of the possible solutions to the second test case:
<image>
Submitted Solution:
```
tc = int(input())
cases = []
for _ in range(tc):
cases.append(list(map(int, input().split())))
for case in cases:
print(case[1], case[2], case[2])
```
Yes
| 100,487 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.
These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite β cookies. Ichihime decides to attend the contest. Now she is solving the following problem.
<image>
You are given four positive integers a, b, c, d, such that a β€ b β€ c β€ d.
Your task is to find three integers x, y, z, satisfying the following conditions:
* a β€ x β€ b.
* b β€ y β€ c.
* c β€ z β€ d.
* There exists a triangle with a positive non-zero area and the lengths of its three sides are x, y, and z.
Ichihime desires to get the cookie, but the problem seems too hard for her. Can you help her?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases.
The next t lines describe test cases. Each test case is given as four space-separated integers a, b, c, d (1 β€ a β€ b β€ c β€ d β€ 10^9).
Output
For each test case, print three integers x, y, z β the integers you found satisfying the conditions given in the statement.
It is guaranteed that the answer always exists. If there are multiple answers, print any.
Example
Input
4
1 3 5 7
1 5 5 7
100000 200000 300000 400000
1 1 977539810 977539810
Output
3 4 5
5 5 5
182690 214748 300999
1 977539810 977539810
Note
One of the possible solutions to the first test case:
<image>
One of the possible solutions to the second test case:
<image>
Submitted Solution:
```
def solve(a,b,c,d):
x = a
y = c
min_z = max(c-a+1, c)
max_z = min(d, c+a-1)
z = max(min_z, max_z)
print("{} {} {}".format(x, y, z))
def main():
t = int(input())
for _ in range(t):
a,b,c,d = [int(x) for x in input().split()]
solve(a,b,c,d)
main()
```
Yes
| 100,488 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.
These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite β cookies. Ichihime decides to attend the contest. Now she is solving the following problem.
<image>
You are given four positive integers a, b, c, d, such that a β€ b β€ c β€ d.
Your task is to find three integers x, y, z, satisfying the following conditions:
* a β€ x β€ b.
* b β€ y β€ c.
* c β€ z β€ d.
* There exists a triangle with a positive non-zero area and the lengths of its three sides are x, y, and z.
Ichihime desires to get the cookie, but the problem seems too hard for her. Can you help her?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases.
The next t lines describe test cases. Each test case is given as four space-separated integers a, b, c, d (1 β€ a β€ b β€ c β€ d β€ 10^9).
Output
For each test case, print three integers x, y, z β the integers you found satisfying the conditions given in the statement.
It is guaranteed that the answer always exists. If there are multiple answers, print any.
Example
Input
4
1 3 5 7
1 5 5 7
100000 200000 300000 400000
1 1 977539810 977539810
Output
3 4 5
5 5 5
182690 214748 300999
1 977539810 977539810
Note
One of the possible solutions to the first test case:
<image>
One of the possible solutions to the second test case:
<image>
Submitted Solution:
```
for _ in range(int(input())):
a, b, c, d = map(int, input().split(" "))
print(a, b, c)
```
No
| 100,489 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.
These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite β cookies. Ichihime decides to attend the contest. Now she is solving the following problem.
<image>
You are given four positive integers a, b, c, d, such that a β€ b β€ c β€ d.
Your task is to find three integers x, y, z, satisfying the following conditions:
* a β€ x β€ b.
* b β€ y β€ c.
* c β€ z β€ d.
* There exists a triangle with a positive non-zero area and the lengths of its three sides are x, y, and z.
Ichihime desires to get the cookie, but the problem seems too hard for her. Can you help her?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases.
The next t lines describe test cases. Each test case is given as four space-separated integers a, b, c, d (1 β€ a β€ b β€ c β€ d β€ 10^9).
Output
For each test case, print three integers x, y, z β the integers you found satisfying the conditions given in the statement.
It is guaranteed that the answer always exists. If there are multiple answers, print any.
Example
Input
4
1 3 5 7
1 5 5 7
100000 200000 300000 400000
1 1 977539810 977539810
Output
3 4 5
5 5 5
182690 214748 300999
1 977539810 977539810
Note
One of the possible solutions to the first test case:
<image>
One of the possible solutions to the second test case:
<image>
Submitted Solution:
```
def myfun(a,b,c,d):
if (a+b>=c) and (b+c>=a) and (c+a>=b):
print(a,b,c)
return
if (b+c>=d) and (c+d>=b) and(d+b>=c):
print(b,c,d)
return
for i in range(a,b+1):
for j in range(b,c+1):
for k in range(c,d+1):
if (i + j <= k) or (i + k <= j) or (j + k <= i):
pass
else:
print(i ,j ,k)
return
for n in range(int(input())):
a,b,c,d = list(map(int , input().split()))
myfun(a,b,c,d)
```
No
| 100,490 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.
These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite β cookies. Ichihime decides to attend the contest. Now she is solving the following problem.
<image>
You are given four positive integers a, b, c, d, such that a β€ b β€ c β€ d.
Your task is to find three integers x, y, z, satisfying the following conditions:
* a β€ x β€ b.
* b β€ y β€ c.
* c β€ z β€ d.
* There exists a triangle with a positive non-zero area and the lengths of its three sides are x, y, and z.
Ichihime desires to get the cookie, but the problem seems too hard for her. Can you help her?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases.
The next t lines describe test cases. Each test case is given as four space-separated integers a, b, c, d (1 β€ a β€ b β€ c β€ d β€ 10^9).
Output
For each test case, print three integers x, y, z β the integers you found satisfying the conditions given in the statement.
It is guaranteed that the answer always exists. If there are multiple answers, print any.
Example
Input
4
1 3 5 7
1 5 5 7
100000 200000 300000 400000
1 1 977539810 977539810
Output
3 4 5
5 5 5
182690 214748 300999
1 977539810 977539810
Note
One of the possible solutions to the first test case:
<image>
One of the possible solutions to the second test case:
<image>
Submitted Solution:
```
test = int(input())
def solve():
arr = list(map(int, input().split()))
print(*arr[1:])
for x in range(test):
solve()
```
No
| 100,491 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.
These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite β cookies. Ichihime decides to attend the contest. Now she is solving the following problem.
<image>
You are given four positive integers a, b, c, d, such that a β€ b β€ c β€ d.
Your task is to find three integers x, y, z, satisfying the following conditions:
* a β€ x β€ b.
* b β€ y β€ c.
* c β€ z β€ d.
* There exists a triangle with a positive non-zero area and the lengths of its three sides are x, y, and z.
Ichihime desires to get the cookie, but the problem seems too hard for her. Can you help her?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases.
The next t lines describe test cases. Each test case is given as four space-separated integers a, b, c, d (1 β€ a β€ b β€ c β€ d β€ 10^9).
Output
For each test case, print three integers x, y, z β the integers you found satisfying the conditions given in the statement.
It is guaranteed that the answer always exists. If there are multiple answers, print any.
Example
Input
4
1 3 5 7
1 5 5 7
100000 200000 300000 400000
1 1 977539810 977539810
Output
3 4 5
5 5 5
182690 214748 300999
1 977539810 977539810
Note
One of the possible solutions to the first test case:
<image>
One of the possible solutions to the second test case:
<image>
Submitted Solution:
```
t = int(input())
while (t):
line = input().split()
a,b,c,d = int(line[0]),int(line[1]),int(line[2]),int(line[3])
print(b,c,c+1)
t -= 1
```
No
| 100,492 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We define x mod y as the remainder of division of x by y (\% operator in C++ or Java, mod operator in Pascal).
Let's call an array of positive integers [a_1, a_2, ..., a_k] stable if for every permutation p of integers from 1 to k, and for every non-negative integer x, the following condition is met:
(((x mod a_1) mod a_2) ... mod a_{k - 1}) mod a_k = (((x mod a_{p_1}) mod a_{p_2}) ... mod a_{p_{k - 1}}) mod a_{p_k}
That is, for each non-negative integer x, the value of (((x mod a_1) mod a_2) ... mod a_{k - 1}) mod a_k does not change if we reorder the elements of the array a.
For two given integers n and k, calculate the number of stable arrays [a_1, a_2, ..., a_k] such that 1 β€ a_1 < a_2 < ... < a_k β€ n.
Input
The only line contains two integers n and k (1 β€ n, k β€ 5 β
10^5).
Output
Print one integer β the number of stable arrays [a_1, a_2, ..., a_k] such that 1 β€ a_1 < a_2 < ... < a_k β€ n. Since the answer may be large, print it modulo 998244353.
Examples
Input
7 3
Output
16
Input
3 7
Output
0
Input
1337 42
Output
95147305
Input
1 1
Output
1
Input
500000 1
Output
500000
Tags: combinatorics, math, number theory
Correct 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, k = map(int, input().split())
M = 998244353
ft = [1]*500001
for i in range(1, 500001):
ft[i] = (ft[i-1]*i) % M
ans = 0
for i in range(1, n+1):
a = (n//i) - 1
b = k-1
if (a < b): break
ans = ans + (ft[a])*pow(ft[b]*ft[a-b], M-2, M)
ans = ans % M
print(ans)
```
| 100,493 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We define x mod y as the remainder of division of x by y (\% operator in C++ or Java, mod operator in Pascal).
Let's call an array of positive integers [a_1, a_2, ..., a_k] stable if for every permutation p of integers from 1 to k, and for every non-negative integer x, the following condition is met:
(((x mod a_1) mod a_2) ... mod a_{k - 1}) mod a_k = (((x mod a_{p_1}) mod a_{p_2}) ... mod a_{p_{k - 1}}) mod a_{p_k}
That is, for each non-negative integer x, the value of (((x mod a_1) mod a_2) ... mod a_{k - 1}) mod a_k does not change if we reorder the elements of the array a.
For two given integers n and k, calculate the number of stable arrays [a_1, a_2, ..., a_k] such that 1 β€ a_1 < a_2 < ... < a_k β€ n.
Input
The only line contains two integers n and k (1 β€ n, k β€ 5 β
10^5).
Output
Print one integer β the number of stable arrays [a_1, a_2, ..., a_k] such that 1 β€ a_1 < a_2 < ... < a_k β€ n. Since the answer may be large, print it modulo 998244353.
Examples
Input
7 3
Output
16
Input
3 7
Output
0
Input
1337 42
Output
95147305
Input
1 1
Output
1
Input
500000 1
Output
500000
Tags: combinatorics, math, number theory
Correct Solution:
```
import sys
input=sys.stdin.readline
p=998244353
pri=p
fac=[1 for i in range((5*(10**5))+1)]
for i in range(2,len(fac)):
fac[i]=(fac[i-1]*(i%pri))%pri
def modi(x):
return (pow(x,p-2,p))%p;
def ncr(n,r):
x=(fac[n]*((modi(fac[r])%p)*(modi(fac[n-r])%p))%p)%p
return x;
n,k=map(int,input().split())
total=0
for i in range(1,n//k+1):
total+=ncr(n//i-1,k-1)
total%=pri
print(total)
```
| 100,494 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We define x mod y as the remainder of division of x by y (\% operator in C++ or Java, mod operator in Pascal).
Let's call an array of positive integers [a_1, a_2, ..., a_k] stable if for every permutation p of integers from 1 to k, and for every non-negative integer x, the following condition is met:
(((x mod a_1) mod a_2) ... mod a_{k - 1}) mod a_k = (((x mod a_{p_1}) mod a_{p_2}) ... mod a_{p_{k - 1}}) mod a_{p_k}
That is, for each non-negative integer x, the value of (((x mod a_1) mod a_2) ... mod a_{k - 1}) mod a_k does not change if we reorder the elements of the array a.
For two given integers n and k, calculate the number of stable arrays [a_1, a_2, ..., a_k] such that 1 β€ a_1 < a_2 < ... < a_k β€ n.
Input
The only line contains two integers n and k (1 β€ n, k β€ 5 β
10^5).
Output
Print one integer β the number of stable arrays [a_1, a_2, ..., a_k] such that 1 β€ a_1 < a_2 < ... < a_k β€ n. Since the answer may be large, print it modulo 998244353.
Examples
Input
7 3
Output
16
Input
3 7
Output
0
Input
1337 42
Output
95147305
Input
1 1
Output
1
Input
500000 1
Output
500000
Tags: combinatorics, math, number theory
Correct Solution:
```
n,k=map(int,input().split())
ans=0
fact=[0]*(n+1)
invfact=[0]*(n+1)
fact[0]=1
invfact[0]=1
m=998244353
ans=0
for j in range(1,n+1):
fact[j]=(fact[j-1]*j)%m
invfact[j]=pow(fact[j],m-2,m)
def comb( n, k):
if n<k or n<0 :
return 0
return (fact[n]*invfact[n-k]*invfact[k])%m
for j in range(1,n+1):
ans+=comb((n//j)-1,k-1)
ans=ans%m
print(ans)
```
| 100,495 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We define x mod y as the remainder of division of x by y (\% operator in C++ or Java, mod operator in Pascal).
Let's call an array of positive integers [a_1, a_2, ..., a_k] stable if for every permutation p of integers from 1 to k, and for every non-negative integer x, the following condition is met:
(((x mod a_1) mod a_2) ... mod a_{k - 1}) mod a_k = (((x mod a_{p_1}) mod a_{p_2}) ... mod a_{p_{k - 1}}) mod a_{p_k}
That is, for each non-negative integer x, the value of (((x mod a_1) mod a_2) ... mod a_{k - 1}) mod a_k does not change if we reorder the elements of the array a.
For two given integers n and k, calculate the number of stable arrays [a_1, a_2, ..., a_k] such that 1 β€ a_1 < a_2 < ... < a_k β€ n.
Input
The only line contains two integers n and k (1 β€ n, k β€ 5 β
10^5).
Output
Print one integer β the number of stable arrays [a_1, a_2, ..., a_k] such that 1 β€ a_1 < a_2 < ... < a_k β€ n. Since the answer may be large, print it modulo 998244353.
Examples
Input
7 3
Output
16
Input
3 7
Output
0
Input
1337 42
Output
95147305
Input
1 1
Output
1
Input
500000 1
Output
500000
Tags: combinatorics, math, number theory
Correct Solution:
```
from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush,heappop
import math
from collections import *
from functools import reduce,cmp_to_key,lru_cache
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
# import sys
# input = sys.stdin.readline
M = mod = 998244353
def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
def inv_mod(n):return pow(n, mod - 2, mod)
def li():return [int(i) for i in input().rstrip().split()]
def st():return str(input().rstrip())[2:-1]
def val():return int(input().rstrip())
def li2():return [str(i)[2:-1] for i in input().rstrip().split()]
def li3():return [int(i) for i in st()]
N = 5 * 10**5 + 1
# array to store inverse of 1 to N
factorialNumInverse = [None] * (N + 1)
# array to precompute inverse of 1! to N!
naturalNumInverse = [None] * (N + 1)
# array to store factorial of
# first N numbers
fact = [None] * (N + 1)
# Function to precompute inverse of numbers
def InverseofNumber(p):
naturalNumInverse[0] = naturalNumInverse[1] = 1
for i in range(2, N + 1, 1):
naturalNumInverse[i] = (naturalNumInverse[p % i] *
(p - int(p / i)) % p)
# Function to precompute inverse
# of factorials
def InverseofFactorial(p):
factorialNumInverse[0] = factorialNumInverse[1] = 1
# precompute inverse of natural numbers
for i in range(2, N + 1, 1):
factorialNumInverse[i] = (naturalNumInverse[i] *
factorialNumInverse[i - 1]) % p
# Function to calculate factorial of 1 to N
def factorial(p):
fact[0] = 1
# precompute factorials
for i in range(1, N + 1):
fact[i] = (fact[i - 1] * i) % p
# Function to return nCr % p in O(1) time
def Binomial(N, R, p):
# n C r = n!*inverse(r!)*inverse((n-r)!)
ans = ((fact[N] * factorialNumInverse[R])% p *
factorialNumInverse[N - R])% p
return ans
p = mod
InverseofNumber(p)
InverseofFactorial(p)
factorial(p)
n,k = li()
ans = Binomial(n-1,k-1,mod) if k <= n else 0
for i in range(2,n + 1):
totnumbers = n//i
if totnumbers >= k:
ans = (ans + Binomial(totnumbers - 1,k - 1,mod))%mod
else:break
print(ans)
```
| 100,496 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We define x mod y as the remainder of division of x by y (\% operator in C++ or Java, mod operator in Pascal).
Let's call an array of positive integers [a_1, a_2, ..., a_k] stable if for every permutation p of integers from 1 to k, and for every non-negative integer x, the following condition is met:
(((x mod a_1) mod a_2) ... mod a_{k - 1}) mod a_k = (((x mod a_{p_1}) mod a_{p_2}) ... mod a_{p_{k - 1}}) mod a_{p_k}
That is, for each non-negative integer x, the value of (((x mod a_1) mod a_2) ... mod a_{k - 1}) mod a_k does not change if we reorder the elements of the array a.
For two given integers n and k, calculate the number of stable arrays [a_1, a_2, ..., a_k] such that 1 β€ a_1 < a_2 < ... < a_k β€ n.
Input
The only line contains two integers n and k (1 β€ n, k β€ 5 β
10^5).
Output
Print one integer β the number of stable arrays [a_1, a_2, ..., a_k] such that 1 β€ a_1 < a_2 < ... < a_k β€ n. Since the answer may be large, print it modulo 998244353.
Examples
Input
7 3
Output
16
Input
3 7
Output
0
Input
1337 42
Output
95147305
Input
1 1
Output
1
Input
500000 1
Output
500000
Tags: combinatorics, math, number theory
Correct Solution:
```
import sys
from collections import defaultdict as dd
from collections import deque
from fractions import Fraction as f
def eprint(*args):
print(*args, file=sys.stderr)
zz=1
from math import *
import copy
#sys.setrecursionlimit(10**6)
if zz:
input=sys.stdin.readline
else:
sys.stdin=open('input.txt', 'r')
sys.stdout=open('all.txt','w')
def li():
return [int(x) for x in input().split()]
def fi():
return int(input())
def si():
return list(input().rstrip())
def mi():
return map(int,input().split())
def bo(i):
return ord(i)-ord('a')
def mo(a, m) :
m0 = m
y = 0
x = 1
if (m == 1) :
return 0
while (a > 1) :
q = a // m
t = m
m = a % m
a = t
t = y
y = x - q * y
x = t
if (x < 0) :
x = x + m0
return x
mod=998244353
n,k=mi()
ft=[1 for i in range(n+1)]
mt=[1 for i in range(n+1)]
for i in range(1,n+1):
ft[i]=(ft[i-1]*i)%mod
mt[i]= mo(ft[i],mod)
if n<k:
print(0)
exit(0)
if k==1:
print(n)
exit(0)
c=0
for i in range(1,n) :
if n//i<k:
break
c=(c%mod+ft[n//i-1]*mt[k-1]*mt[n//i-k])%mod
print(c)
```
| 100,497 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We define x mod y as the remainder of division of x by y (\% operator in C++ or Java, mod operator in Pascal).
Let's call an array of positive integers [a_1, a_2, ..., a_k] stable if for every permutation p of integers from 1 to k, and for every non-negative integer x, the following condition is met:
(((x mod a_1) mod a_2) ... mod a_{k - 1}) mod a_k = (((x mod a_{p_1}) mod a_{p_2}) ... mod a_{p_{k - 1}}) mod a_{p_k}
That is, for each non-negative integer x, the value of (((x mod a_1) mod a_2) ... mod a_{k - 1}) mod a_k does not change if we reorder the elements of the array a.
For two given integers n and k, calculate the number of stable arrays [a_1, a_2, ..., a_k] such that 1 β€ a_1 < a_2 < ... < a_k β€ n.
Input
The only line contains two integers n and k (1 β€ n, k β€ 5 β
10^5).
Output
Print one integer β the number of stable arrays [a_1, a_2, ..., a_k] such that 1 β€ a_1 < a_2 < ... < a_k β€ n. Since the answer may be large, print it modulo 998244353.
Examples
Input
7 3
Output
16
Input
3 7
Output
0
Input
1337 42
Output
95147305
Input
1 1
Output
1
Input
500000 1
Output
500000
Tags: combinatorics, math, number theory
Correct Solution:
```
from math import sqrt
n,k = [int(x) for x in input().split()]
if n//k > 500:
modNum = 998244353
def choose(n,k):
if k >= n:
return 1
base = 1
div = min(k,n-k)
for x in range(1,div+1):
base *= n
base //= x
n -= 1
return base%998244353
out = 0
for a in range(n//k):
start = a+1
amt = n//start
out += choose(amt-1, k-1)
print(out%modNum)
else:
primes = [2]
for num in range(3,n+1,2):
sq = sqrt(num)
valid = True
for a in primes:
if num%a == 0:
valid = False
break
if a > sq:
break
if valid:
primes.append(num)
def factored(n,primes):
counts = {x:0 for x in primes}
for a in primes:
base = a
while base <= n:
counts[a] += n//base
base *= a
return counts
modNum = 998244353
out = 0
for a in range(n//k):
start = a+1
amt = n//start
first = factored(amt-1, primes)
second = factored(k-1, primes)
third = factored(amt-k, primes)
thing = {x:first[x]-second[x]-third[x] for x in primes}
base = 1
for x in thing:
for y in range(thing[x]):
base *= x
base = base%998244353
out += base
print(out%modNum)
```
| 100,498 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We define x mod y as the remainder of division of x by y (\% operator in C++ or Java, mod operator in Pascal).
Let's call an array of positive integers [a_1, a_2, ..., a_k] stable if for every permutation p of integers from 1 to k, and for every non-negative integer x, the following condition is met:
(((x mod a_1) mod a_2) ... mod a_{k - 1}) mod a_k = (((x mod a_{p_1}) mod a_{p_2}) ... mod a_{p_{k - 1}}) mod a_{p_k}
That is, for each non-negative integer x, the value of (((x mod a_1) mod a_2) ... mod a_{k - 1}) mod a_k does not change if we reorder the elements of the array a.
For two given integers n and k, calculate the number of stable arrays [a_1, a_2, ..., a_k] such that 1 β€ a_1 < a_2 < ... < a_k β€ n.
Input
The only line contains two integers n and k (1 β€ n, k β€ 5 β
10^5).
Output
Print one integer β the number of stable arrays [a_1, a_2, ..., a_k] such that 1 β€ a_1 < a_2 < ... < a_k β€ n. Since the answer may be large, print it modulo 998244353.
Examples
Input
7 3
Output
16
Input
3 7
Output
0
Input
1337 42
Output
95147305
Input
1 1
Output
1
Input
500000 1
Output
500000
Tags: combinatorics, math, number theory
Correct Solution:
```
"""
NTC here
"""
#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
profile = 0
def iin(): return int(input())
def lin(): return list(map(int, input().split()))
N = 5*10**5
factorialInv = [None] * (N + 1)
naturalInv = [None] * (N + 1)
fact = [None] * (N + 1)
def InverseofNumber(p):
naturalInv[0] = naturalInv[1] = 1
for i in range(2, N + 1, 1):
naturalInv[i] = pow(i, p-2, p)
def InverseofFactorial(p):
factorialInv[0] = factorialInv[1] = 1
for i in range(2, N + 1, 1):
factorialInv[i] = (naturalInv[i] *
factorialInv[i - 1]) % p
def factorial(p):
fact[0] = 1
for i in range(1, N + 1):
fact[i] = (fact[i - 1] * i) % p
def ncr(N, R, p):
# n C r = n!*inverse(r!)*inverse((n-r)!)
ans = ((fact[N] * factorialInv[R])% p *
factorialInv[N - R])% p
# print("INNER", N, 'c', R, ans)
return ans
def main():
n, k = lin()
if k==1:
print(n)
return
if k==n:
print(1)
elif k>n:
print(0)
else:
md = 998244353
InverseofNumber(md)
InverseofFactorial(md)
factorial(md)
ans = ncr(n-1, k-1, md)
ans %= md
for i in range(2, n+1):
x1 = n//i
if x1>0 and x1>=k and k-1:
# print("INNER2", i)
ans += ncr(x1-1, k-1, md)
ans %= md
print(ans)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
if profile:
import cProfile
cProfile.run('main()')
else:
main()
```
| 100,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.