message
stringlengths 2
39.6k
| message_type
stringclasses 2
values | message_id
int64 0
1
| conversation_id
int64 450
109k
| cluster
float64 2
2
| __index_level_0__
int64 900
217k
|
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n castles in the Lannister's Kingdom and some walls connect two castles, no two castles are connected by more than one wall, no wall connects a castle to itself.
Sir Jaime Lannister has discovered that Daenerys Targaryen is going to attack his kingdom soon. Therefore he wants to defend his kingdom. He has k liters of a strange liquid. He wants to distribute that liquid among the castles, so each castle may contain some liquid (possibly zero or non-integer number of liters). After that the stability of a wall is defined as follows: if the wall connects two castles a and b, and they contain x and y liters of that liquid, respectively, then the strength of that wall is x·y.
Your task is to print the maximum possible sum of stabilities of the walls that Sir Jaime Lannister can achieve.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 40, 1 ≤ k ≤ 1000).
Then n lines follows. The i-th of these lines contains n integers ai, 1, ai, 2, ..., ai, n (<image>). If castles i and j are connected by a wall, then ai, j = 1. Otherwise it is equal to 0.
It is guaranteed that ai, j = aj, i and ai, i = 0 for all 1 ≤ i, j ≤ n.
Output
Print the maximum possible sum of stabilities of the walls that Sir Jaime Lannister can achieve.
Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.
Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>.
Examples
Input
3 1
0 1 0
1 0 0
0 0 0
Output
0.250000000000
Input
4 4
0 1 0 1
1 0 1 0
0 1 0 1
1 0 1 0
Output
4.000000000000
Note
In the first sample, we can assign 0.5, 0.5, 0 liters of liquid to castles 1, 2, 3, respectively, to get the maximum sum (0.25).
In the second sample, we can assign 1.0, 1.0, 1.0, 1.0 liters of liquid to castles 1, 2, 3, 4, respectively, to get the maximum sum (4.0)
Submitted Solution:
```
read = lambda: map(int, input().split())
n, K = read()
a = [list(read()) for i in range(n)]
ans = 1 / 4
for i in range(n):
for j in range(i + 1, n):
for k in range(j + 1, n):
if a[i][j] == a[j][k] == a[k][i] == 1:
ans = 1 / 3
break
print(ans * K * K)
```
|
instruction
| 0
| 11,320
| 2
| 22,640
|
No
|
output
| 1
| 11,320
| 2
| 22,641
|
Provide a correct Python 3 solution for this coding contest problem.
Ibis is fighting with a monster.
The health of the monster is H.
Ibis can cast N kinds of spells. Casting the i-th spell decreases the monster's health by A_i, at the cost of B_i Magic Points.
The same spell can be cast multiple times. There is no way other than spells to decrease the monster's health.
Ibis wins when the health of the monster becomes 0 or below.
Find the minimum total Magic Points that have to be consumed before winning.
Constraints
* 1 \leq H \leq 10^4
* 1 \leq N \leq 10^3
* 1 \leq A_i \leq 10^4
* 1 \leq B_i \leq 10^4
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
H N
A_1 B_1
:
A_N B_N
Output
Print the minimum total Magic Points that have to be consumed before winning.
Examples
Input
9 3
8 3
4 2
2 1
Output
4
Input
100 6
1 1
2 3
3 9
4 27
5 81
6 243
Output
100
Input
9999 10
540 7550
691 9680
700 9790
510 7150
415 5818
551 7712
587 8227
619 8671
588 8228
176 2461
Output
139815
|
instruction
| 0
| 13,124
| 2
| 26,248
|
"Correct Solution:
```
H, N, *AB = map(int, open(0).read().split())
dp = [0] * (H + max(AB[::2]))
for i in range(1, len(dp)):
dp[i] = min(dp[i - a] + b for a, b in zip(*[iter(AB)] * 2))
print(min(dp[H:]))
```
|
output
| 1
| 13,124
| 2
| 26,249
|
Provide a correct Python 3 solution for this coding contest problem.
Ibis is fighting with a monster.
The health of the monster is H.
Ibis can cast N kinds of spells. Casting the i-th spell decreases the monster's health by A_i, at the cost of B_i Magic Points.
The same spell can be cast multiple times. There is no way other than spells to decrease the monster's health.
Ibis wins when the health of the monster becomes 0 or below.
Find the minimum total Magic Points that have to be consumed before winning.
Constraints
* 1 \leq H \leq 10^4
* 1 \leq N \leq 10^3
* 1 \leq A_i \leq 10^4
* 1 \leq B_i \leq 10^4
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
H N
A_1 B_1
:
A_N B_N
Output
Print the minimum total Magic Points that have to be consumed before winning.
Examples
Input
9 3
8 3
4 2
2 1
Output
4
Input
100 6
1 1
2 3
3 9
4 27
5 81
6 243
Output
100
Input
9999 10
540 7550
691 9680
700 9790
510 7150
415 5818
551 7712
587 8227
619 8671
588 8228
176 2461
Output
139815
|
instruction
| 0
| 13,125
| 2
| 26,250
|
"Correct Solution:
```
H,N = map(int,input().split())
AB = [list(map(int,input().split())) for _ in range(N)]
maxA = max(a for a,b in AB)
dp = [0]*(H+maxA)
for i in range(1,H + maxA):
dp[i] = min(dp[i-a]+b for a,b in AB)
print(dp[H])
```
|
output
| 1
| 13,125
| 2
| 26,251
|
Provide a correct Python 3 solution for this coding contest problem.
Ibis is fighting with a monster.
The health of the monster is H.
Ibis can cast N kinds of spells. Casting the i-th spell decreases the monster's health by A_i, at the cost of B_i Magic Points.
The same spell can be cast multiple times. There is no way other than spells to decrease the monster's health.
Ibis wins when the health of the monster becomes 0 or below.
Find the minimum total Magic Points that have to be consumed before winning.
Constraints
* 1 \leq H \leq 10^4
* 1 \leq N \leq 10^3
* 1 \leq A_i \leq 10^4
* 1 \leq B_i \leq 10^4
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
H N
A_1 B_1
:
A_N B_N
Output
Print the minimum total Magic Points that have to be consumed before winning.
Examples
Input
9 3
8 3
4 2
2 1
Output
4
Input
100 6
1 1
2 3
3 9
4 27
5 81
6 243
Output
100
Input
9999 10
540 7550
691 9680
700 9790
510 7150
415 5818
551 7712
587 8227
619 8671
588 8228
176 2461
Output
139815
|
instruction
| 0
| 13,126
| 2
| 26,252
|
"Correct Solution:
```
h, n = map(int, input().split())
AB = [list(map(int, input().split())) for _ in range(n)]
dp = [1 << 31] * (h + 10**4)
dp[0] = 0
for i in range(h):
for a, b in AB:
dp[i + a] = min(dp[i + a], dp[i] + b)
print(min(dp[h:]))
```
|
output
| 1
| 13,126
| 2
| 26,253
|
Provide a correct Python 3 solution for this coding contest problem.
Ibis is fighting with a monster.
The health of the monster is H.
Ibis can cast N kinds of spells. Casting the i-th spell decreases the monster's health by A_i, at the cost of B_i Magic Points.
The same spell can be cast multiple times. There is no way other than spells to decrease the monster's health.
Ibis wins when the health of the monster becomes 0 or below.
Find the minimum total Magic Points that have to be consumed before winning.
Constraints
* 1 \leq H \leq 10^4
* 1 \leq N \leq 10^3
* 1 \leq A_i \leq 10^4
* 1 \leq B_i \leq 10^4
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
H N
A_1 B_1
:
A_N B_N
Output
Print the minimum total Magic Points that have to be consumed before winning.
Examples
Input
9 3
8 3
4 2
2 1
Output
4
Input
100 6
1 1
2 3
3 9
4 27
5 81
6 243
Output
100
Input
9999 10
540 7550
691 9680
700 9790
510 7150
415 5818
551 7712
587 8227
619 8671
588 8228
176 2461
Output
139815
|
instruction
| 0
| 13,127
| 2
| 26,254
|
"Correct Solution:
```
h,n=map(int,input().split())
dp=[10**10 for i in range(h+1)]
dp[0]=0
for i in range(n):
x,y=map(int,input().split())
for j in range(h+1):
nj=min(h,j+x)
dp[nj]=min(dp[nj],dp[j]+y)
print(dp[h])
```
|
output
| 1
| 13,127
| 2
| 26,255
|
Provide a correct Python 3 solution for this coding contest problem.
Ibis is fighting with a monster.
The health of the monster is H.
Ibis can cast N kinds of spells. Casting the i-th spell decreases the monster's health by A_i, at the cost of B_i Magic Points.
The same spell can be cast multiple times. There is no way other than spells to decrease the monster's health.
Ibis wins when the health of the monster becomes 0 or below.
Find the minimum total Magic Points that have to be consumed before winning.
Constraints
* 1 \leq H \leq 10^4
* 1 \leq N \leq 10^3
* 1 \leq A_i \leq 10^4
* 1 \leq B_i \leq 10^4
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
H N
A_1 B_1
:
A_N B_N
Output
Print the minimum total Magic Points that have to be consumed before winning.
Examples
Input
9 3
8 3
4 2
2 1
Output
4
Input
100 6
1 1
2 3
3 9
4 27
5 81
6 243
Output
100
Input
9999 10
540 7550
691 9680
700 9790
510 7150
415 5818
551 7712
587 8227
619 8671
588 8228
176 2461
Output
139815
|
instruction
| 0
| 13,128
| 2
| 26,256
|
"Correct Solution:
```
H,N = map(int,input().split())
MAXH = H+10000
DP = [float("inf")]*MAXH
DP[0] = 0
for i in range(N):
a,b = map(int,input().split())
for j in range(MAXH-a):
if j>H+a:break
DP[j+a] = min(DP[j+a],DP[j]+b)
print(min(DP[H:]))
```
|
output
| 1
| 13,128
| 2
| 26,257
|
Provide a correct Python 3 solution for this coding contest problem.
Ibis is fighting with a monster.
The health of the monster is H.
Ibis can cast N kinds of spells. Casting the i-th spell decreases the monster's health by A_i, at the cost of B_i Magic Points.
The same spell can be cast multiple times. There is no way other than spells to decrease the monster's health.
Ibis wins when the health of the monster becomes 0 or below.
Find the minimum total Magic Points that have to be consumed before winning.
Constraints
* 1 \leq H \leq 10^4
* 1 \leq N \leq 10^3
* 1 \leq A_i \leq 10^4
* 1 \leq B_i \leq 10^4
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
H N
A_1 B_1
:
A_N B_N
Output
Print the minimum total Magic Points that have to be consumed before winning.
Examples
Input
9 3
8 3
4 2
2 1
Output
4
Input
100 6
1 1
2 3
3 9
4 27
5 81
6 243
Output
100
Input
9999 10
540 7550
691 9680
700 9790
510 7150
415 5818
551 7712
587 8227
619 8671
588 8228
176 2461
Output
139815
|
instruction
| 0
| 13,129
| 2
| 26,258
|
"Correct Solution:
```
h,n = map(int, input().split())
magics = [tuple(map(int, input().split())) for _ in range(n)]
max_a = sorted(magics, key=lambda x: x[0], reverse=True)[0][0]
dp = [0]*(h+max_a)
for i in range(1, h+max_a):
dp[i] = min(dp[i-a]+b for a,b in magics)
print(min(dp[h:]))
```
|
output
| 1
| 13,129
| 2
| 26,259
|
Provide a correct Python 3 solution for this coding contest problem.
Ibis is fighting with a monster.
The health of the monster is H.
Ibis can cast N kinds of spells. Casting the i-th spell decreases the monster's health by A_i, at the cost of B_i Magic Points.
The same spell can be cast multiple times. There is no way other than spells to decrease the monster's health.
Ibis wins when the health of the monster becomes 0 or below.
Find the minimum total Magic Points that have to be consumed before winning.
Constraints
* 1 \leq H \leq 10^4
* 1 \leq N \leq 10^3
* 1 \leq A_i \leq 10^4
* 1 \leq B_i \leq 10^4
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
H N
A_1 B_1
:
A_N B_N
Output
Print the minimum total Magic Points that have to be consumed before winning.
Examples
Input
9 3
8 3
4 2
2 1
Output
4
Input
100 6
1 1
2 3
3 9
4 27
5 81
6 243
Output
100
Input
9999 10
540 7550
691 9680
700 9790
510 7150
415 5818
551 7712
587 8227
619 8671
588 8228
176 2461
Output
139815
|
instruction
| 0
| 13,130
| 2
| 26,260
|
"Correct Solution:
```
h, n = map(int, input().split())
ab = [list(map(int, input().split())) for i in range(n)]
table = [float("inf")] * (h + 10000)
table[0] = 0
for a, b in ab:
for i in range(h):
table[i+a] = min(table[i+a], table[i] + b)
print(min(table[h:]))
```
|
output
| 1
| 13,130
| 2
| 26,261
|
Provide a correct Python 3 solution for this coding contest problem.
Ibis is fighting with a monster.
The health of the monster is H.
Ibis can cast N kinds of spells. Casting the i-th spell decreases the monster's health by A_i, at the cost of B_i Magic Points.
The same spell can be cast multiple times. There is no way other than spells to decrease the monster's health.
Ibis wins when the health of the monster becomes 0 or below.
Find the minimum total Magic Points that have to be consumed before winning.
Constraints
* 1 \leq H \leq 10^4
* 1 \leq N \leq 10^3
* 1 \leq A_i \leq 10^4
* 1 \leq B_i \leq 10^4
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
H N
A_1 B_1
:
A_N B_N
Output
Print the minimum total Magic Points that have to be consumed before winning.
Examples
Input
9 3
8 3
4 2
2 1
Output
4
Input
100 6
1 1
2 3
3 9
4 27
5 81
6 243
Output
100
Input
9999 10
540 7550
691 9680
700 9790
510 7150
415 5818
551 7712
587 8227
619 8671
588 8228
176 2461
Output
139815
|
instruction
| 0
| 13,131
| 2
| 26,262
|
"Correct Solution:
```
h, n = map(int, input().split())
magics = [list(map(int, input().split())) for _ in range(n)]
max_damage = max(a for a, b in magics)
dp = [0] * (h + max_damage)
for i in range(1, h + max_damage):
dp[i] = min(dp[i - a] + b for a, b in magics)
print(dp[h])
```
|
output
| 1
| 13,131
| 2
| 26,263
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ibis is fighting with a monster.
The health of the monster is H.
Ibis can cast N kinds of spells. Casting the i-th spell decreases the monster's health by A_i, at the cost of B_i Magic Points.
The same spell can be cast multiple times. There is no way other than spells to decrease the monster's health.
Ibis wins when the health of the monster becomes 0 or below.
Find the minimum total Magic Points that have to be consumed before winning.
Constraints
* 1 \leq H \leq 10^4
* 1 \leq N \leq 10^3
* 1 \leq A_i \leq 10^4
* 1 \leq B_i \leq 10^4
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
H N
A_1 B_1
:
A_N B_N
Output
Print the minimum total Magic Points that have to be consumed before winning.
Examples
Input
9 3
8 3
4 2
2 1
Output
4
Input
100 6
1 1
2 3
3 9
4 27
5 81
6 243
Output
100
Input
9999 10
540 7550
691 9680
700 9790
510 7150
415 5818
551 7712
587 8227
619 8671
588 8228
176 2461
Output
139815
Submitted Solution:
```
h, n = list(map(int, input().split()))
ab = [list(map(int, input().split())) for _ in range(n)]
dp = [0] * (h+max(a for a,b in ab))
for i in range(1, len(dp)):
dp[i] = min(dp[i-a]+b for a, b in ab)
print(min(dp[h:]))
```
|
instruction
| 0
| 13,132
| 2
| 26,264
|
Yes
|
output
| 1
| 13,132
| 2
| 26,265
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ibis is fighting with a monster.
The health of the monster is H.
Ibis can cast N kinds of spells. Casting the i-th spell decreases the monster's health by A_i, at the cost of B_i Magic Points.
The same spell can be cast multiple times. There is no way other than spells to decrease the monster's health.
Ibis wins when the health of the monster becomes 0 or below.
Find the minimum total Magic Points that have to be consumed before winning.
Constraints
* 1 \leq H \leq 10^4
* 1 \leq N \leq 10^3
* 1 \leq A_i \leq 10^4
* 1 \leq B_i \leq 10^4
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
H N
A_1 B_1
:
A_N B_N
Output
Print the minimum total Magic Points that have to be consumed before winning.
Examples
Input
9 3
8 3
4 2
2 1
Output
4
Input
100 6
1 1
2 3
3 9
4 27
5 81
6 243
Output
100
Input
9999 10
540 7550
691 9680
700 9790
510 7150
415 5818
551 7712
587 8227
619 8671
588 8228
176 2461
Output
139815
Submitted Solution:
```
h,n=map(int,input().split())
l=[list(map(int,input().split())) for _ in range(n)]
dp=[10**9]*(h+max(l)[0])
dp[0]=0
for i in range(1,len(dp)):
for a,b in l:
if i-a>=0:
dp[i]=min(dp[i],dp[i-a]+b)
print(min(dp[h:]))
```
|
instruction
| 0
| 13,133
| 2
| 26,266
|
Yes
|
output
| 1
| 13,133
| 2
| 26,267
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ibis is fighting with a monster.
The health of the monster is H.
Ibis can cast N kinds of spells. Casting the i-th spell decreases the monster's health by A_i, at the cost of B_i Magic Points.
The same spell can be cast multiple times. There is no way other than spells to decrease the monster's health.
Ibis wins when the health of the monster becomes 0 or below.
Find the minimum total Magic Points that have to be consumed before winning.
Constraints
* 1 \leq H \leq 10^4
* 1 \leq N \leq 10^3
* 1 \leq A_i \leq 10^4
* 1 \leq B_i \leq 10^4
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
H N
A_1 B_1
:
A_N B_N
Output
Print the minimum total Magic Points that have to be consumed before winning.
Examples
Input
9 3
8 3
4 2
2 1
Output
4
Input
100 6
1 1
2 3
3 9
4 27
5 81
6 243
Output
100
Input
9999 10
540 7550
691 9680
700 9790
510 7150
415 5818
551 7712
587 8227
619 8671
588 8228
176 2461
Output
139815
Submitted Solution:
```
h,n = list(map(int, input().split()))
ab = [list(map(int, input().split())) for _ in range(n)]
dp = [10**10]*(h+1)
dp[h] = 0
for i in range(h,0,-1):
for j in ab:
tmp = max(0,i-j[0])
dp[tmp] = min(dp[tmp], dp[i]+j[1])
print(dp[0])
```
|
instruction
| 0
| 13,134
| 2
| 26,268
|
Yes
|
output
| 1
| 13,134
| 2
| 26,269
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ibis is fighting with a monster.
The health of the monster is H.
Ibis can cast N kinds of spells. Casting the i-th spell decreases the monster's health by A_i, at the cost of B_i Magic Points.
The same spell can be cast multiple times. There is no way other than spells to decrease the monster's health.
Ibis wins when the health of the monster becomes 0 or below.
Find the minimum total Magic Points that have to be consumed before winning.
Constraints
* 1 \leq H \leq 10^4
* 1 \leq N \leq 10^3
* 1 \leq A_i \leq 10^4
* 1 \leq B_i \leq 10^4
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
H N
A_1 B_1
:
A_N B_N
Output
Print the minimum total Magic Points that have to be consumed before winning.
Examples
Input
9 3
8 3
4 2
2 1
Output
4
Input
100 6
1 1
2 3
3 9
4 27
5 81
6 243
Output
100
Input
9999 10
540 7550
691 9680
700 9790
510 7150
415 5818
551 7712
587 8227
619 8671
588 8228
176 2461
Output
139815
Submitted Solution:
```
from operator import itemgetter
h,n=map(int,input().split())
ab=[list(map(int,input().split())) for i in range(n)]
infi=10**9
dp=[infi]*2*10**4
dp[0]=0
for a,b in ab:
for i in range(h):
if dp[i]!=infi:
dp[i+a]=min(dp[i+a],dp[i]+b)
print(min(dp[h:]))
```
|
instruction
| 0
| 13,135
| 2
| 26,270
|
Yes
|
output
| 1
| 13,135
| 2
| 26,271
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ibis is fighting with a monster.
The health of the monster is H.
Ibis can cast N kinds of spells. Casting the i-th spell decreases the monster's health by A_i, at the cost of B_i Magic Points.
The same spell can be cast multiple times. There is no way other than spells to decrease the monster's health.
Ibis wins when the health of the monster becomes 0 or below.
Find the minimum total Magic Points that have to be consumed before winning.
Constraints
* 1 \leq H \leq 10^4
* 1 \leq N \leq 10^3
* 1 \leq A_i \leq 10^4
* 1 \leq B_i \leq 10^4
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
H N
A_1 B_1
:
A_N B_N
Output
Print the minimum total Magic Points that have to be consumed before winning.
Examples
Input
9 3
8 3
4 2
2 1
Output
4
Input
100 6
1 1
2 3
3 9
4 27
5 81
6 243
Output
100
Input
9999 10
540 7550
691 9680
700 9790
510 7150
415 5818
551 7712
587 8227
619 8671
588 8228
176 2461
Output
139815
Submitted Solution:
```
inf = 1000000000
dp = [inf] * 20000
h, n = map(int, input().split())
dp[0] = 0
for j in range(n):
a, b = map(int, input().split())
for i in range(h + 1):
dp[i + a] = min(dp[i + a], dp[i] + b)
print(min(dp[h:]))
```
|
instruction
| 0
| 13,136
| 2
| 26,272
|
No
|
output
| 1
| 13,136
| 2
| 26,273
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ibis is fighting with a monster.
The health of the monster is H.
Ibis can cast N kinds of spells. Casting the i-th spell decreases the monster's health by A_i, at the cost of B_i Magic Points.
The same spell can be cast multiple times. There is no way other than spells to decrease the monster's health.
Ibis wins when the health of the monster becomes 0 or below.
Find the minimum total Magic Points that have to be consumed before winning.
Constraints
* 1 \leq H \leq 10^4
* 1 \leq N \leq 10^3
* 1 \leq A_i \leq 10^4
* 1 \leq B_i \leq 10^4
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
H N
A_1 B_1
:
A_N B_N
Output
Print the minimum total Magic Points that have to be consumed before winning.
Examples
Input
9 3
8 3
4 2
2 1
Output
4
Input
100 6
1 1
2 3
3 9
4 27
5 81
6 243
Output
100
Input
9999 10
540 7550
691 9680
700 9790
510 7150
415 5818
551 7712
587 8227
619 8671
588 8228
176 2461
Output
139815
Submitted Solution:
```
h,n=map(int,input().split())
ab=[list(map(int,input().split())) for _ in range(n)]
max_a=max(a for a,_ in ab)
dp = [0] * (h+max_a)
for i in range(0,h+max_a):
if i==0:
d[i]=0
else:
dp[i]=min(dp[i-a]+b for a,b in ab)
print(min(dp[h:]))
```
|
instruction
| 0
| 13,137
| 2
| 26,274
|
No
|
output
| 1
| 13,137
| 2
| 26,275
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ibis is fighting with a monster.
The health of the monster is H.
Ibis can cast N kinds of spells. Casting the i-th spell decreases the monster's health by A_i, at the cost of B_i Magic Points.
The same spell can be cast multiple times. There is no way other than spells to decrease the monster's health.
Ibis wins when the health of the monster becomes 0 or below.
Find the minimum total Magic Points that have to be consumed before winning.
Constraints
* 1 \leq H \leq 10^4
* 1 \leq N \leq 10^3
* 1 \leq A_i \leq 10^4
* 1 \leq B_i \leq 10^4
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
H N
A_1 B_1
:
A_N B_N
Output
Print the minimum total Magic Points that have to be consumed before winning.
Examples
Input
9 3
8 3
4 2
2 1
Output
4
Input
100 6
1 1
2 3
3 9
4 27
5 81
6 243
Output
100
Input
9999 10
540 7550
691 9680
700 9790
510 7150
415 5818
551 7712
587 8227
619 8671
588 8228
176 2461
Output
139815
Submitted Solution:
```
h,n,*L=map(int,open(0).read().split())
dp=[float('inf')]*(h+10100)
dp[0]=0
for a,b in zip(*[iter(L)]*2):
for i in range(h):
t=dp[i]+b
if t<dp[i+a]:
dp[i+a]=dp[i]+b
print(min(dp[h:]))
```
|
instruction
| 0
| 13,138
| 2
| 26,276
|
No
|
output
| 1
| 13,138
| 2
| 26,277
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ibis is fighting with a monster.
The health of the monster is H.
Ibis can cast N kinds of spells. Casting the i-th spell decreases the monster's health by A_i, at the cost of B_i Magic Points.
The same spell can be cast multiple times. There is no way other than spells to decrease the monster's health.
Ibis wins when the health of the monster becomes 0 or below.
Find the minimum total Magic Points that have to be consumed before winning.
Constraints
* 1 \leq H \leq 10^4
* 1 \leq N \leq 10^3
* 1 \leq A_i \leq 10^4
* 1 \leq B_i \leq 10^4
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
H N
A_1 B_1
:
A_N B_N
Output
Print the minimum total Magic Points that have to be consumed before winning.
Examples
Input
9 3
8 3
4 2
2 1
Output
4
Input
100 6
1 1
2 3
3 9
4 27
5 81
6 243
Output
100
Input
9999 10
540 7550
691 9680
700 9790
510 7150
415 5818
551 7712
587 8227
619 8671
588 8228
176 2461
Output
139815
Submitted Solution:
```
H,N=map(int, input().split())
AB = [list(map(int,input().split())) for i in range(N)]
dp=[10**8]*(H+1)
dp[0]=0
for i in range(1,H+1):
for ab in AB:
dp[i]=min(dp[max(0,i-ab[0])] + ab[1], dp[i])
print(dp[-1])
```
|
instruction
| 0
| 13,139
| 2
| 26,278
|
No
|
output
| 1
| 13,139
| 2
| 26,279
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Paladin Manao caught the trail of the ancient Book of Evil in a swampy area. This area contains n settlements numbered from 1 to n. Moving through the swamp is very difficult, so people tramped exactly n - 1 paths. Each of these paths connects some pair of settlements and is bidirectional. Moreover, it is possible to reach any settlement from any other one by traversing one or several paths.
The distance between two settlements is the minimum number of paths that have to be crossed to get from one settlement to the other one. Manao knows that the Book of Evil has got a damage range d. This means that if the Book of Evil is located in some settlement, its damage (for example, emergence of ghosts and werewolves) affects other settlements at distance d or less from the settlement where the Book resides.
Manao has heard of m settlements affected by the Book of Evil. Their numbers are p1, p2, ..., pm. Note that the Book may be affecting other settlements as well, but this has not been detected yet. Manao wants to determine which settlements may contain the Book. Help him with this difficult task.
Input
The first line contains three space-separated integers n, m and d (1 ≤ m ≤ n ≤ 100000; 0 ≤ d ≤ n - 1). The second line contains m distinct space-separated integers p1, p2, ..., pm (1 ≤ pi ≤ n). Then n - 1 lines follow, each line describes a path made in the area. A path is described by a pair of space-separated integers ai and bi representing the ends of this path.
Output
Print a single number — the number of settlements that may contain the Book of Evil. It is possible that Manao received some controversial information and there is no settlement that may contain the Book. In such case, print 0.
Examples
Input
6 2 3
1 2
1 5
2 3
3 4
4 5
5 6
Output
3
Note
Sample 1. The damage range of the Book of Evil equals 3 and its effects have been noticed in settlements 1 and 2. Thus, it can be in settlements 3, 4 or 5.
<image>
|
instruction
| 0
| 13,615
| 2
| 27,230
|
Tags: dfs and similar, divide and conquer, dp, trees
Correct Solution:
```
from collections import defaultdict
import sys
input=sys.stdin.readline
class graph:
def __init__(self,n,mark):
self.d=defaultdict(list)
self.n=n
self.mark=mark
def add(self,s,d):
self.d[s].append(d)
self.d[d].append(s)
def bfs(self,s,dis):
marked=s
visited=[False]*self.n
visited[s]=True
q=[s]
while q:
s=q.pop(0)
if(s in mark):
marked=s
for i in self.d[s]:
if(visited[i]==False):
q.append(i)
visited[i]=True
dis[i]+=dis[s]+1
return marked
n,m,k=map(int,input().split())
mrk=[int(x) for x in input().split()]
mark={}
for i in mrk:
mark[i-1]=1
g=graph(n,mark)
for i in range(n-1):
a,b=map(int,input().split())
g.add(a-1,b-1)
dis=[0]*n
u=g.bfs(0,dis)
dis=[0]*n
d=g.bfs(u,dis)
#print(dis)
temp=[0]*n
x=g.bfs(d,temp)
#print(temp)
count=0
for i in range(n):
if(temp[i]<=k and dis[i]<=k):
count+=1
print(count)
```
|
output
| 1
| 13,615
| 2
| 27,231
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Paladin Manao caught the trail of the ancient Book of Evil in a swampy area. This area contains n settlements numbered from 1 to n. Moving through the swamp is very difficult, so people tramped exactly n - 1 paths. Each of these paths connects some pair of settlements and is bidirectional. Moreover, it is possible to reach any settlement from any other one by traversing one or several paths.
The distance between two settlements is the minimum number of paths that have to be crossed to get from one settlement to the other one. Manao knows that the Book of Evil has got a damage range d. This means that if the Book of Evil is located in some settlement, its damage (for example, emergence of ghosts and werewolves) affects other settlements at distance d or less from the settlement where the Book resides.
Manao has heard of m settlements affected by the Book of Evil. Their numbers are p1, p2, ..., pm. Note that the Book may be affecting other settlements as well, but this has not been detected yet. Manao wants to determine which settlements may contain the Book. Help him with this difficult task.
Input
The first line contains three space-separated integers n, m and d (1 ≤ m ≤ n ≤ 100000; 0 ≤ d ≤ n - 1). The second line contains m distinct space-separated integers p1, p2, ..., pm (1 ≤ pi ≤ n). Then n - 1 lines follow, each line describes a path made in the area. A path is described by a pair of space-separated integers ai and bi representing the ends of this path.
Output
Print a single number — the number of settlements that may contain the Book of Evil. It is possible that Manao received some controversial information and there is no settlement that may contain the Book. In such case, print 0.
Examples
Input
6 2 3
1 2
1 5
2 3
3 4
4 5
5 6
Output
3
Note
Sample 1. The damage range of the Book of Evil equals 3 and its effects have been noticed in settlements 1 and 2. Thus, it can be in settlements 3, 4 or 5.
<image>
|
instruction
| 0
| 13,616
| 2
| 27,232
|
Tags: dfs and similar, divide and conquer, dp, trees
Correct Solution:
```
import heapq
def dfs(graph, start):
n = len(graph)
dist = [-0 for i in range(n + 1)]
visited = [False for i in range(n + 1)]
visited[start] = True
stack = []
dist[start] = 0
heapq.heappush(stack, start)
while stack:
u = heapq.heappop(stack)
for v in graph[u]:
if not visited[v]:
visited[v] = True
dist[v] = dist[u] + 1
heapq.heappush(stack, v)
return dist
def solution():
n, m, d = map(int, input().strip().split())
p = list(map(int, input().strip().split()))
graph = [[] for i in range(n + 1)]
for i in range(n - 1):
a, b = map(int, input().strip().split())
graph[a].append(b)
graph[b].append(a)
dist = dfs(graph, 1)
max_distance = -1
u = -1
v = -1
for i in p:
if dist[i] > max_distance:
max_distance = dist[i]
u = i
distu = dfs(graph, u)
max_distance = -1
for i in p:
if distu[i] > max_distance:
max_distance = distu[i]
v = i
distv = dfs(graph, v)
affected = 0
for i in range(1, n + 1):
if 0 <= distu[i] <= d and 0 <= distv[i] <= d:
affected += 1
print(affected)
solution()
```
|
output
| 1
| 13,616
| 2
| 27,233
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Your friend is developing a computer game. He has already decided how the game world should look like — it should consist of n locations connected by m two-way passages. The passages are designed in such a way that it should be possible to get from any location to any other location.
Of course, some passages should be guarded by the monsters (if you just can go everywhere without any difficulties, then it's not fun, right?). Some crucial passages will be guarded by really fearsome monsters, requiring the hero to prepare for battle and designing his own tactics of defeating them (commonly these kinds of monsters are called bosses). And your friend wants you to help him place these bosses.
The game will start in location s and end in location t, but these locations are not chosen yet. After choosing these locations, your friend will place a boss in each passage such that it is impossible to get from s to t without using this passage. Your friend wants to place as much bosses as possible (because more challenges means more fun, right?), so he asks you to help him determine the maximum possible number of bosses, considering that any location can be chosen as s or as t.
Input
The first line contains two integers n and m (2 ≤ n ≤ 3 ⋅ 10^5, n - 1 ≤ m ≤ 3 ⋅ 10^5) — the number of locations and passages, respectively.
Then m lines follow, each containing two integers x and y (1 ≤ x, y ≤ n, x ≠ y) describing the endpoints of one of the passages.
It is guaranteed that there is no pair of locations directly connected by two or more passages, and that any location is reachable from any other location.
Output
Print one integer — the maximum number of bosses your friend can place, considering all possible choices for s and t.
Examples
Input
5 5
1 2
2 3
3 1
4 1
5 2
Output
2
Input
4 3
1 2
4 3
3 2
Output
3
|
instruction
| 0
| 14,146
| 2
| 28,292
|
Tags: dfs and similar, graphs, trees
Correct Solution:
```
import sys
from array import array # noqa: F401
def readline(): return sys.stdin.buffer.readline().decode('utf-8')
def build_bridge_tree(v_count, edge_count, adj, edge_index):
from collections import deque
preorder = [0]
parent, order, low = [0]+[-1]*v_count, [0]+[-1]*(v_count-1), [0]*v_count
stack = [(0, adj[0][::])]
pre_i = 1
while stack:
v, dests = stack.pop()
while dests:
dest = dests.pop()
if order[dest] == -1:
preorder.append(dest)
order[dest] = low[dest] = pre_i
parent[dest] = v
pre_i += 1
stack.extend(((v, dests), (dest, adj[dest][::])))
break
is_bridge = array('b', [0]) * edge_count
for v in reversed(preorder):
for dest, ei in zip(adj[v], edge_index[v]):
if dest != parent[v] and low[v] > low[dest]:
low[v] = low[dest]
if dest != parent[v] and order[v] < low[dest]:
is_bridge[ei] = 1
bridge_tree = [[] for _ in range(v_count)]
stack = [0]
visited = array('b', [1] + [0]*(v_count-1))
while stack:
v = stack.pop()
dq = deque([v])
while dq:
u = dq.popleft()
for dest, ei in zip(adj[u], edge_index[u]):
if visited[dest]:
continue
visited[dest] = 1
if is_bridge[ei]:
bridge_tree[v].append(dest)
bridge_tree[dest].append(v)
stack.append(dest)
else:
dq.append(dest)
return bridge_tree
def get_dia(adj):
from collections import deque
n = len(adj)
dq = deque([(0, -1)])
while dq:
end1, par = dq.popleft()
for dest in adj[end1]:
if dest != par:
dq.append((dest, end1))
prev = [-1]*n
prev[end1] = -2
dq = deque([(end1, 0)])
while dq:
end2, diameter = dq.popleft()
for dest in adj[end2]:
if prev[dest] == -1:
prev[dest] = end2
dq.append((dest, diameter+1))
return end1, end2, diameter, prev
n, m = map(int, readline().split())
adj = [[] for _ in range(n)]
eindex = [[] for _ in range(n)]
for ei in range(m):
u, v = map(int, readline().split())
adj[u-1].append(v-1)
adj[v-1].append(u-1)
eindex[u-1].append(ei)
eindex[v-1].append(ei)
btree = build_bridge_tree(n, m, adj, eindex)
print(get_dia(btree)[2])
```
|
output
| 1
| 14,146
| 2
| 28,293
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Your friend is developing a computer game. He has already decided how the game world should look like — it should consist of n locations connected by m two-way passages. The passages are designed in such a way that it should be possible to get from any location to any other location.
Of course, some passages should be guarded by the monsters (if you just can go everywhere without any difficulties, then it's not fun, right?). Some crucial passages will be guarded by really fearsome monsters, requiring the hero to prepare for battle and designing his own tactics of defeating them (commonly these kinds of monsters are called bosses). And your friend wants you to help him place these bosses.
The game will start in location s and end in location t, but these locations are not chosen yet. After choosing these locations, your friend will place a boss in each passage such that it is impossible to get from s to t without using this passage. Your friend wants to place as much bosses as possible (because more challenges means more fun, right?), so he asks you to help him determine the maximum possible number of bosses, considering that any location can be chosen as s or as t.
Input
The first line contains two integers n and m (2 ≤ n ≤ 3 ⋅ 10^5, n - 1 ≤ m ≤ 3 ⋅ 10^5) — the number of locations and passages, respectively.
Then m lines follow, each containing two integers x and y (1 ≤ x, y ≤ n, x ≠ y) describing the endpoints of one of the passages.
It is guaranteed that there is no pair of locations directly connected by two or more passages, and that any location is reachable from any other location.
Output
Print one integer — the maximum number of bosses your friend can place, considering all possible choices for s and t.
Examples
Input
5 5
1 2
2 3
3 1
4 1
5 2
Output
2
Input
4 3
1 2
4 3
3 2
Output
3
|
instruction
| 0
| 14,147
| 2
| 28,294
|
Tags: dfs and similar, graphs, trees
Correct Solution:
```
import sys
from array import array # noqa: F401
def readline(): return sys.stdin.buffer.readline().decode('utf-8')
def build_bridge_tree(v_count, edge_count, adj, edge_index):
from collections import deque
preorder = [0]
parent, order, low = [0]+[-1]*v_count, [0]+[-1]*(v_count-1), [0]*v_count
stack = [0]
rem = [len(dests)-1 for dests in adj]
pre_i = 1
while stack:
v = stack.pop()
while rem[v] >= 0:
dest = adj[v][rem[v]]
rem[v] -= 1
if order[dest] == -1:
preorder.append(dest)
order[dest] = low[dest] = pre_i
parent[dest] = v
pre_i += 1
stack.extend((v, dest))
break
is_bridge = array('b', [0]) * edge_count
for v in reversed(preorder):
for dest, ei in zip(adj[v], edge_index[v]):
if dest != parent[v] and low[v] > low[dest]:
low[v] = low[dest]
if dest != parent[v] and order[v] < low[dest]:
is_bridge[ei] = 1
bridge_tree = [[] for _ in range(v_count)]
stack = [0]
visited = array('b', [1] + [0]*(v_count-1))
while stack:
v = stack.pop()
dq = deque([v])
while dq:
u = dq.popleft()
for dest, ei in zip(adj[u], edge_index[u]):
if visited[dest]:
continue
visited[dest] = 1
if is_bridge[ei]:
bridge_tree[v].append(dest)
bridge_tree[dest].append(v)
stack.append(dest)
else:
dq.append(dest)
return bridge_tree
def get_dia(adj):
from collections import deque
n = len(adj)
dq = deque([(0, -1)])
while dq:
end1, par = dq.popleft()
for dest in adj[end1]:
if dest != par:
dq.append((dest, end1))
prev = [-1]*n
prev[end1] = -2
dq = deque([(end1, 0)])
while dq:
end2, diameter = dq.popleft()
for dest in adj[end2]:
if prev[dest] == -1:
prev[dest] = end2
dq.append((dest, diameter+1))
return end1, end2, diameter, prev
n, m = map(int, readline().split())
adj = [[] for _ in range(n)]
eindex = [[] for _ in range(n)]
for ei in range(m):
u, v = map(int, readline().split())
adj[u-1].append(v-1)
adj[v-1].append(u-1)
eindex[u-1].append(ei)
eindex[v-1].append(ei)
btree = build_bridge_tree(n, m, adj, eindex)
print(get_dia(btree)[2])
```
|
output
| 1
| 14,147
| 2
| 28,295
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Your friend is developing a computer game. He has already decided how the game world should look like — it should consist of n locations connected by m two-way passages. The passages are designed in such a way that it should be possible to get from any location to any other location.
Of course, some passages should be guarded by the monsters (if you just can go everywhere without any difficulties, then it's not fun, right?). Some crucial passages will be guarded by really fearsome monsters, requiring the hero to prepare for battle and designing his own tactics of defeating them (commonly these kinds of monsters are called bosses). And your friend wants you to help him place these bosses.
The game will start in location s and end in location t, but these locations are not chosen yet. After choosing these locations, your friend will place a boss in each passage such that it is impossible to get from s to t without using this passage. Your friend wants to place as much bosses as possible (because more challenges means more fun, right?), so he asks you to help him determine the maximum possible number of bosses, considering that any location can be chosen as s or as t.
Input
The first line contains two integers n and m (2 ≤ n ≤ 3 ⋅ 10^5, n - 1 ≤ m ≤ 3 ⋅ 10^5) — the number of locations and passages, respectively.
Then m lines follow, each containing two integers x and y (1 ≤ x, y ≤ n, x ≠ y) describing the endpoints of one of the passages.
It is guaranteed that there is no pair of locations directly connected by two or more passages, and that any location is reachable from any other location.
Output
Print one integer — the maximum number of bosses your friend can place, considering all possible choices for s and t.
Examples
Input
5 5
1 2
2 3
3 1
4 1
5 2
Output
2
Input
4 3
1 2
4 3
3 2
Output
3
|
instruction
| 0
| 14,148
| 2
| 28,296
|
Tags: dfs and similar, graphs, trees
Correct Solution:
```
import sys
def get_input():
n, m = [int(x) for x in sys.stdin.readline().split(' ')]
graph = [[] for _ in range(n + 1)]
for _ in range(m):
u, v = [int(x) for x in sys.stdin.readline().split(' ')]
graph[u].append(v)
graph[v].append(u)
return graph
def dfs_bridges(graph, node):
n = len(graph)
time = 0
discover_time = [0] * n
low = [0] * n
pi = [None] * n
color = ['white'] * n
ecc = [-1] * n
ecc_number = 0
bridges = []
stack = [node]
discover_stack = []
while stack:
current_node = stack[-1]
if color[current_node] != 'white':
stack.pop()
if color[current_node] == 'grey':
if pi[current_node] is not None:
low[pi[current_node]] = min(low[pi[current_node]], low[current_node])
if low[current_node] == discover_time[current_node]:
bridges.append((pi[current_node], current_node))
while discover_stack:
top = discover_stack.pop()
ecc[top] = ecc_number
if top == current_node:
break
ecc_number += 1
color[current_node] = 'black'
continue
time += 1
color[current_node] = 'grey'
low[current_node] = discover_time[current_node] = time
discover_stack.append(current_node)
for adj in graph[current_node]:
if color[adj] == 'white':
pi[adj] = current_node
stack.append(adj)
elif pi[current_node] != adj:
low[current_node] = min(low[current_node], discover_time[adj])
else:
while discover_stack:
top = discover_stack.pop()
ecc[top] = ecc_number
ecc_number += 1
return ecc_number, ecc, bridges
def build_bridge_tree(ecc_count, ecc, bridges):
n = len(graph)
bridge_tree = [[] for _ in range(ecc_count)]
for u, v in bridges:
if ecc[u] != ecc[v]:
bridge_tree[ecc[u]].append(ecc[v])
bridge_tree[ecc[v]].append(ecc[u])
return bridge_tree
def dfs_tree(tree, node):
n = len(tree)
visited = [False] * n
distances = [0] * n
current_distance = 0
stack = [node]
while stack:
current_node = stack[-1]
if visited[current_node]:
stack.pop()
current_distance -= 1
continue
visited[current_node] = True
distances[current_node] = current_distance
current_distance += 1
for adj in tree[current_node]:
if not visited[adj]:
stack.append(adj)
return distances
def diameter(tree):
distances = dfs_tree(bridge_tree, 0)
node = max(enumerate(distances), key=lambda t: t[1])[0]
distances = dfs_tree(bridge_tree, node)
return max(distances)
if __name__ == "__main__":
graph = get_input()
ecc_count, ecc, bridges = dfs_bridges(graph, 1)
bridge_tree = build_bridge_tree(ecc_count, ecc, bridges)
print(diameter(bridge_tree))
```
|
output
| 1
| 14,148
| 2
| 28,297
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Your friend is developing a computer game. He has already decided how the game world should look like — it should consist of n locations connected by m two-way passages. The passages are designed in such a way that it should be possible to get from any location to any other location.
Of course, some passages should be guarded by the monsters (if you just can go everywhere without any difficulties, then it's not fun, right?). Some crucial passages will be guarded by really fearsome monsters, requiring the hero to prepare for battle and designing his own tactics of defeating them (commonly these kinds of monsters are called bosses). And your friend wants you to help him place these bosses.
The game will start in location s and end in location t, but these locations are not chosen yet. After choosing these locations, your friend will place a boss in each passage such that it is impossible to get from s to t without using this passage. Your friend wants to place as much bosses as possible (because more challenges means more fun, right?), so he asks you to help him determine the maximum possible number of bosses, considering that any location can be chosen as s or as t.
Input
The first line contains two integers n and m (2 ≤ n ≤ 3 ⋅ 10^5, n - 1 ≤ m ≤ 3 ⋅ 10^5) — the number of locations and passages, respectively.
Then m lines follow, each containing two integers x and y (1 ≤ x, y ≤ n, x ≠ y) describing the endpoints of one of the passages.
It is guaranteed that there is no pair of locations directly connected by two or more passages, and that any location is reachable from any other location.
Output
Print one integer — the maximum number of bosses your friend can place, considering all possible choices for s and t.
Examples
Input
5 5
1 2
2 3
3 1
4 1
5 2
Output
2
Input
4 3
1 2
4 3
3 2
Output
3
|
instruction
| 0
| 14,149
| 2
| 28,298
|
Tags: dfs and similar, graphs, trees
Correct Solution:
```
import sys
# sys.stind.readline lee datos el doble de
# rápido que la funcion por defecto input
input = sys.stdin.readline
def get_input():
n, m = [int(x) for x in input().split(' ')]
graph = [[] for _ in range(n + 1)]
for _ in range(m):
u, v = [int(x) for x in input().split(' ')]
graph[u].append(v)
graph[v].append(u)
return graph
def dfs_bridges(graph, node):
n = len(graph)
time = 0
discover_time = [0] * n
low = [0] * n
pi = [None] * n
color = ['white'] * n
ecc = [-1] * n
ecc_number = 0
bridges = []
stack = [node]
discover_stack = []
while stack:
current_node = stack[-1]
if color[current_node] != 'white':
stack.pop()
if color[current_node] == 'grey':
if pi[current_node] is not None:
low[pi[current_node]] = min(low[pi[current_node]], low[current_node])
if low[current_node] == discover_time[current_node]:
bridges.append((pi[current_node], current_node))
while discover_stack:
top = discover_stack.pop()
ecc[top] = ecc_number
if top == current_node:
break
ecc_number += 1
color[current_node] = 'black'
continue
time += 1
color[current_node] = 'grey'
low[current_node] = discover_time[current_node] = time
discover_stack.append(current_node)
for adj in graph[current_node]:
if color[adj] == 'white':
pi[adj] = current_node
stack.append(adj)
elif pi[current_node] != adj:
low[current_node] = min(low[current_node], discover_time[adj])
else:
while discover_stack:
top = discover_stack.pop()
ecc[top] = ecc_number
ecc_number += 1
return ecc_number, ecc, bridges
def build_bridge_tree(ecc_count, ecc, bridges):
n = len(graph)
bridge_tree = [[] for _ in range(ecc_count)]
for u, v in bridges:
if ecc[u] != ecc[v]:
bridge_tree[ecc[u]].append(ecc[v])
bridge_tree[ecc[v]].append(ecc[u])
return bridge_tree
def diameter(tree, root):
n = len(tree)
pi = [None] * n
color = ['white'] * n
dp1, dp2 = [0] * n, [0] * n
stack = [root]
while stack:
current_node = stack[-1]
if color[current_node] != 'white':
stack.pop()
if color[current_node] == 'grey':
parent = pi[current_node]
if parent is not None:
t = dp1[current_node] + 1
if t > dp1[parent]:
t, dp1[parent] = dp1[parent], t
if t > dp2[parent]:
t, dp2[parent] = dp2[parent], t
color[current_node] = 'black'
continue
color[current_node] = 'grey'
for adj in tree[current_node]:
if color[adj] == 'white':
pi[adj] = current_node
stack.append(adj)
root = max(range(n), key=lambda x: dp1[x] + dp2[x])
return dp1[root] + dp2[root]
def dfs_tree(tree, node):
n = len(tree)
visited = [False] * n
distances = [0] * n
current_distance = 0
stack = [node]
while stack:
current_node = stack[-1]
if visited[current_node]:
stack.pop()
current_distance -= 1
continue
visited[current_node] = True
distances[current_node] = current_distance
current_distance += 1
for adj in tree[current_node]:
if not visited[adj]:
stack.append(adj)
return distances
# def diameter(tree):
# distances = dfs_tree(bridge_tree, 0)
# node = max(enumerate(distances), key=lambda t: t[1])[0]
# distances = dfs_tree(bridge_tree, node)
# return max(distances)
if __name__ == "__main__":
graph = get_input()
ecc_count, ecc, bridges = dfs_bridges(graph, 1)
bridge_tree = build_bridge_tree(ecc_count, ecc, bridges)
if ecc_count > 2:
root = [x for x, l in enumerate(bridge_tree) if len(l) > 1][0]
print(diameter(bridge_tree, root))
else:
print(ecc_count - 1)
```
|
output
| 1
| 14,149
| 2
| 28,299
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Your friend is developing a computer game. He has already decided how the game world should look like — it should consist of n locations connected by m two-way passages. The passages are designed in such a way that it should be possible to get from any location to any other location.
Of course, some passages should be guarded by the monsters (if you just can go everywhere without any difficulties, then it's not fun, right?). Some crucial passages will be guarded by really fearsome monsters, requiring the hero to prepare for battle and designing his own tactics of defeating them (commonly these kinds of monsters are called bosses). And your friend wants you to help him place these bosses.
The game will start in location s and end in location t, but these locations are not chosen yet. After choosing these locations, your friend will place a boss in each passage such that it is impossible to get from s to t without using this passage. Your friend wants to place as much bosses as possible (because more challenges means more fun, right?), so he asks you to help him determine the maximum possible number of bosses, considering that any location can be chosen as s or as t.
Input
The first line contains two integers n and m (2 ≤ n ≤ 3 ⋅ 10^5, n - 1 ≤ m ≤ 3 ⋅ 10^5) — the number of locations and passages, respectively.
Then m lines follow, each containing two integers x and y (1 ≤ x, y ≤ n, x ≠ y) describing the endpoints of one of the passages.
It is guaranteed that there is no pair of locations directly connected by two or more passages, and that any location is reachable from any other location.
Output
Print one integer — the maximum number of bosses your friend can place, considering all possible choices for s and t.
Examples
Input
5 5
1 2
2 3
3 1
4 1
5 2
Output
2
Input
4 3
1 2
4 3
3 2
Output
3
Submitted Solution:
```
import sys
def main():
p = input().split()
n = int(p[0]) #number of locations
m = int(p[1]) #number of passages
g = graph(n,m)
t = g.buildBridgeTree()
if n<=5:
t.treeDiameter()
class graph:
n = int() #number of nodes
edges= int() #number of edges
time = int()
conexions = [] #adjacency list
bridges=[] #are we using a removable edge or not for city i?
discovery = [] #time to discover node i
seen = [] #visited or not
cc = [] #index of connected components
low = [] #low[i]=min(discovery(i),discovery(w)) w:any node discoverable from i
pi = [] #index of i's father
def __init__(self, n, m):
self.n = n
self.edges = m
for i in range(self.n):
self.conexions.append([])
self.discovery.append(sys.float_info.max)
self.low.append(sys.float_info.max)
self.seen.append(False)
self.cc.append(-1)
def buildGraph(self):
#this method put every edge in the adjacency list
for i in range(self.edges):
p2=input().split()
self.conexions[int(p2[0])-1].append((int(p2[1])-1,False))
self.conexions[int(p2[1])-1].append((int(p2[0])-1,False))
def searchBridges (self):
self.time = 0
for i in range(self.n):
self.pi.append(-1)
self.searchBridges_(0,-1) #we can start in any node 'cause the graph is connected
def searchBridges_(self,c,index):
self.seen[c]=True #mark as visited
self.time+=1
self.discovery[c]=self.low[c]= self.time
for i in range(len(self.conexions[c])):
pos = self.conexions[c][i][0]
if self.seen[pos]==False:
self.pi[pos]=c #the node that discovered it
self.searchBridges_(pos,i) #search throw its not visited conexions
self.low[c]= min([self.low[c],self.low[pos]]) #definition of low
elif self.pi[c]!=pos: #It is not the node that discovered it
self.low[c]= min([self.low[c],self.discovery[pos]])
if self.pi[c]!=-1 and self.low[c]==self.discovery[c]: #it isn't the root and none of its connections is reacheable earlier than it
self.bridges.append((c,self.pi[c]))
for i in range(len(self.conexions[c])):
if(self.conexions[c][i][0]==self.pi[c]):
self.conexions[c][i]=(self.pi[c],True)
self.conexions[self.pi[c]][index]=(c,True)
break
def findCC(self):
j = 0
for i in range(self.n):
self.pi[i]=-1
self.seen[i]=False
for i in range(self.n):
if self.seen[i]==False:
self.cc[i]=j #assign the index of the new connected component
self.findCC_(i,j) #search throw its not visited conexions
j+=1 #we finished the search in the connected component
def findCC_(self, c, j):
self.seen[c]=True #mark as visited
for i in range(len(self.conexions[c])):
pos = self.conexions[c][i][0]
if(self.seen[pos]==False and self.conexions[c][i][1]==False):
self.cc[pos]=j #assign the index of the connected component
self.pi[pos]=c #the node that discovered it
self.findCC_(pos,j) #search throw its not visited conexions
def treeDiameter(self):
for i in range(self.n):
self.seen[i]=False
self.pi[i]=-1
self.discovery[0]=0
self.treeDiameter_(0) #search the distance from this node, to the others
max = sys.float_info.min
maxIndex = 0
for i in range(self.n):
if self.discovery[i]>max:
max= self.discovery[i] #look for the furthest node
maxIndex=i
for i in range(self.n):
self.seen[i]=False
self.pi[i]=-1
self.discovery[maxIndex]=0
self.treeDiameter_(maxIndex) #search the distance from the furthest node, to the others
max = sys.float_info.min
for i in range(self.n):
if self.discovery[i]>max :
max= self.discovery[i] #look for the furthest node to preview furthest node, and that is the diameter in a tree
print(max)
def treeDiameter_(self, c):
self.seen[c]=True #mark as visited
for i in range(len(self.conexions[c])):
pos = self.conexions[c][i][0]
if self.seen[pos]==False:
self.pi[pos]=c #the node that discovered it
self.discovery[pos]= self.discovery[c]+1 #distance to the node who discover it + 1
#we don't have to compare and search for other paths, since it's a tree and there is only one path between two nodes.
self.treeDiameter_(pos) #search throw its not visited conexions
def buildBridgeTree(self):
if self.n>5:
self.buildGraph()
self.searchBridges()
self.findCC()
print(2)
return
self.buildGraph()
self.searchBridges()
self.findCC()
t = graph(len(self.bridges)+1,len(self.bridges))
for i in range(len(self.bridges)):
t.conexions[self.cc[self.bridges[i][0]]].append((self.cc[self.bridges[i][1]],True))
t.conexions[self.cc[self.bridges[i][1]]].append((self.cc[self.bridges[i][0]],True))
return t
if __name__ == '__main__':
main()
```
|
instruction
| 0
| 14,150
| 2
| 28,300
|
No
|
output
| 1
| 14,150
| 2
| 28,301
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Your friend is developing a computer game. He has already decided how the game world should look like — it should consist of n locations connected by m two-way passages. The passages are designed in such a way that it should be possible to get from any location to any other location.
Of course, some passages should be guarded by the monsters (if you just can go everywhere without any difficulties, then it's not fun, right?). Some crucial passages will be guarded by really fearsome monsters, requiring the hero to prepare for battle and designing his own tactics of defeating them (commonly these kinds of monsters are called bosses). And your friend wants you to help him place these bosses.
The game will start in location s and end in location t, but these locations are not chosen yet. After choosing these locations, your friend will place a boss in each passage such that it is impossible to get from s to t without using this passage. Your friend wants to place as much bosses as possible (because more challenges means more fun, right?), so he asks you to help him determine the maximum possible number of bosses, considering that any location can be chosen as s or as t.
Input
The first line contains two integers n and m (2 ≤ n ≤ 3 ⋅ 10^5, n - 1 ≤ m ≤ 3 ⋅ 10^5) — the number of locations and passages, respectively.
Then m lines follow, each containing two integers x and y (1 ≤ x, y ≤ n, x ≠ y) describing the endpoints of one of the passages.
It is guaranteed that there is no pair of locations directly connected by two or more passages, and that any location is reachable from any other location.
Output
Print one integer — the maximum number of bosses your friend can place, considering all possible choices for s and t.
Examples
Input
5 5
1 2
2 3
3 1
4 1
5 2
Output
2
Input
4 3
1 2
4 3
3 2
Output
3
Submitted Solution:
```
from sys import stdin,stdout
class DFS_General:
def __init__(self,edges,n):
self.n= n
self.pi = [-1 for _ in range(0,n)]
self.visit = [False for _ in range(0,n)]
self.Ady= edges
self.d = [-1 for _ in range(0,n)]
self.low = [-1 for _ in range(0,n)]
self.compo = [-1 for _ in range(0,n )]
self.count = 0
self.time = 0
self.bridges = []
self.queue= []
def DFS_visit_AP(self, u):
self.visit[u] = True
self.time += 1
self.d[u] = self.time
self.low[u] = self.d[u]
for v in self.Ady[u]:
if not self.visit[v]:
self.pi[v]= u
self.DFS_visit_AP(v)
self.low[u]= min(self.low[v], self.low[u])
elif self.visit[v] and self.pi[v] != u:
self.low[u]= min(self.low[u], self.d[v])
self.compo[u]= self.count
if self.pi[u] != -1 and self.low[u]== self.d[u]:
self.bridges.append((self.pi[u], u))
def DFS_AP(self):
for i in range(0,self.n):
if not self.visit[i]:
self.count += 1
self.DFS_visit_AP(i)
def BFS(s,Ady,n):
d = [0 for _ in range(0,n)]
color = [-1 for _ in range(0,n)]
queue = []
queue.append(s)
d[s]= 0
color[s] = 0
while queue:
u = queue.pop(0)
for v in Ady[u]:
if color[v] == -1:
color[v]= 0
d[v] = d[u] + 1
queue.append(v)
return d
def Solution(Ady,n):
DFS_ = DFS_General(Ady,n)
DFS_.DFS_AP()
if len(DFS_.bridges) > 0:
for i in DFS_.bridges:
Ady[i[0]].remove(i[1])
Ady[i[1]].remove(i[0])
DFS_final = DFS_General(Ady,n)
DFS_final.DFS_AP()
Ady = [[] for _ in range(0,DFS_final.count)]
for i in DFS_.bridges:
Ady[DFS_final.compo[i[0]]-1].append(DFS_final.compo[i[1]] -1)
Ady[DFS_final.compo[i[1]] -1].append(DFS_final.compo[i[0]] -1)
d = BFS(0,Ady,len(Ady))
i = d.index(max(d))
d = BFS(i,Ady,len(Ady))
return max(d)
else:
return 0
n_m = stdin.readline().split()
n = int(n_m[0])
m = int(n_m[1])
Ady = [[] for i in range (0,n)]
for i in range(m):
stri= stdin.readline().split()
item = (int(stri[0])-1,int(stri[1])-1)
Ady[item[0]].append(item[1])
Ady[item[1]].append(item[0])
stdout.write(str(Solution(Ady,n)))
```
|
instruction
| 0
| 14,151
| 2
| 28,302
|
No
|
output
| 1
| 14,151
| 2
| 28,303
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Your friend is developing a computer game. He has already decided how the game world should look like — it should consist of n locations connected by m two-way passages. The passages are designed in such a way that it should be possible to get from any location to any other location.
Of course, some passages should be guarded by the monsters (if you just can go everywhere without any difficulties, then it's not fun, right?). Some crucial passages will be guarded by really fearsome monsters, requiring the hero to prepare for battle and designing his own tactics of defeating them (commonly these kinds of monsters are called bosses). And your friend wants you to help him place these bosses.
The game will start in location s and end in location t, but these locations are not chosen yet. After choosing these locations, your friend will place a boss in each passage such that it is impossible to get from s to t without using this passage. Your friend wants to place as much bosses as possible (because more challenges means more fun, right?), so he asks you to help him determine the maximum possible number of bosses, considering that any location can be chosen as s or as t.
Input
The first line contains two integers n and m (2 ≤ n ≤ 3 ⋅ 10^5, n - 1 ≤ m ≤ 3 ⋅ 10^5) — the number of locations and passages, respectively.
Then m lines follow, each containing two integers x and y (1 ≤ x, y ≤ n, x ≠ y) describing the endpoints of one of the passages.
It is guaranteed that there is no pair of locations directly connected by two or more passages, and that any location is reachable from any other location.
Output
Print one integer — the maximum number of bosses your friend can place, considering all possible choices for s and t.
Examples
Input
5 5
1 2
2 3
3 1
4 1
5 2
Output
2
Input
4 3
1 2
4 3
3 2
Output
3
Submitted Solution:
```
import sys
def main():
p = input().split()
n = int(p[0]) #number of locations
m = int(p[1]) #number of passages
g = graph(n,m)
g.buildBridgeTree()
if m==19999:
return
t = graph(len(g.bridges)+1,len(g.bridges))
t.conexions= []
t.pi=[]
t.discovery=[]
t.seen=[]
for i in range(len(g.bridges)+1):
t.conexions.append([])
t.pi.append(-1)
t.discovery.append(sys.float_info.max)
t.seen.append(False)
for i in range(len(g.bridges)):
t.conexions[g.cc[g.bridges[i][0]]].append((g.cc[g.bridges[i][1]],True))
t.conexions[g.cc[g.bridges[i][1]]].append((g.cc[g.bridges[i][0]],True))
t.treeDiameter()
class graph:
n = int() #number of nodes
edges= int() #number of edges
time = int()
conexions = [] #adjacency list
bridges=[] #are we using a removable edge or not for city i?
discovery = [] #time to discover node i
seen = [] #visited or not
cc = [] #index of connected components
low = [] #low[i]=min(discovery(i),discovery(w)) w:any node discoverable from i
pi = [] #index of i's father
def __init__(self, n, m):
self.n = n
self.edges = m
for i in range(self.n):
self.conexions.append([])
self.discovery.append(sys.float_info.max)
self.low.append(sys.float_info.max)
self.seen.append(False)
self.cc.append(-1)
def buildGraph(self):
#this method put every edge in the adjacency list
for i in range(self.edges):
p2=input().split()
self.conexions[int(p2[0])-1].append((int(p2[1])-1,False))
self.conexions[int(p2[1])-1].append((int(p2[0])-1,False))
def searchBridges (self):
self.time = 0
for i in range(self.n):
self.pi.append(-1)
self.searchBridges_(0,-1) #we can start in any node 'cause the graph is connected
def searchBridges_(self,c,index):
self.seen[c]=True #mark as visited
self.time+=1
self.discovery[c]=self.low[c]= self.time
try:
for i in range(len(self.conexions[c])):
pos = self.conexions[c][i][0]
if self.seen[pos]==False:
self.pi[pos]=c #the node that discovered it
self.searchBridges_(pos,i) #search throw its not visited conexions
self.low[c]= min([self.low[c],self.low[pos]]) #definition of low
elif self.pi[c]!=pos: #It is not the node that discovered it
self.low[c]= min([self.low[c],self.discovery[pos]])
except:
print(c)
if self.pi[c]!=-1 and self.low[c]==self.discovery[c]: #it isn't the root and none of its connections is reacheable earlier than it
self.bridges.append((c,self.pi[c]))
for i in range(len(self.conexions[c])):
if(self.conexions[c][i][0]==self.pi[c]):
self.conexions[c][i]=(self.pi[c],True)
self.conexions[self.pi[c]][index]=(c,True)
def findCC(self):
j = 0
for i in range(self.n):
self.pi[i]=-1
self.seen[i]=False
for i in range(self.n):
if self.seen[i]==False:
self.cc[i]=j #assign the index of the new connected component
self.findCC_(i,j) #search throw its not visited conexions
j+=1 #we finished the search in the connected component
def findCC_(self, c, j):
self.seen[c]=True #mark as visited
for i in range(len(self.conexions[c])):
pos = self.conexions[c][i][0]
if(self.seen[pos]==False and self.conexions[c][i][1]==False):
self.cc[pos]=j #assign the index of the connected component
self.pi[pos]=c #the node that discovered it
self.findCC_(pos,j) #search throw its not visited conexions
def treeDiameter(self):
for i in range(self.n):
self.seen[i]=False
self.pi[i]=-1
self.discovery[0]=0
self.treeDiameter_(0) #search the distance from this node, to the others
max = -1
maxIndex = 0
for i in range(self.n):
if self.discovery[i]>max:
max= self.discovery[i] #look for the furthest node
maxIndex=i
for i in range(self.n):
self.seen[i]=False
self.pi[i]=-1
self.discovery[maxIndex]=0
self.treeDiameter_(maxIndex) #search the distance from the furthest node, to the others
max =-1
for i in range(self.n):
if self.discovery[i]>max :
max= self.discovery[i] #look for the furthest node to preview furthest node, and that is the diameter in a tree
print(max)
def treeDiameter_(self, c):
self.seen[c]=True #mark as visited
for i in range(len(self.conexions[c])):
pos = self.conexions[c][i][0]
if self.seen[pos]==False:
self.pi[pos]=c #the node that discovered it
self.discovery[pos]= self.discovery[c]+1 #distance to the node who discover it + 1
#we don't have to compare and search for other paths, since it's a tree and there is only one path between two nodes.
self.treeDiameter_(pos) #search throw its not visited conexions
def buildBridgeTree(self):
self.buildGraph()
self.searchBridges()
self.findCC()
if __name__ == '__main__':
main()
```
|
instruction
| 0
| 14,152
| 2
| 28,304
|
No
|
output
| 1
| 14,152
| 2
| 28,305
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Your friend is developing a computer game. He has already decided how the game world should look like — it should consist of n locations connected by m two-way passages. The passages are designed in such a way that it should be possible to get from any location to any other location.
Of course, some passages should be guarded by the monsters (if you just can go everywhere without any difficulties, then it's not fun, right?). Some crucial passages will be guarded by really fearsome monsters, requiring the hero to prepare for battle and designing his own tactics of defeating them (commonly these kinds of monsters are called bosses). And your friend wants you to help him place these bosses.
The game will start in location s and end in location t, but these locations are not chosen yet. After choosing these locations, your friend will place a boss in each passage such that it is impossible to get from s to t without using this passage. Your friend wants to place as much bosses as possible (because more challenges means more fun, right?), so he asks you to help him determine the maximum possible number of bosses, considering that any location can be chosen as s or as t.
Input
The first line contains two integers n and m (2 ≤ n ≤ 3 ⋅ 10^5, n - 1 ≤ m ≤ 3 ⋅ 10^5) — the number of locations and passages, respectively.
Then m lines follow, each containing two integers x and y (1 ≤ x, y ≤ n, x ≠ y) describing the endpoints of one of the passages.
It is guaranteed that there is no pair of locations directly connected by two or more passages, and that any location is reachable from any other location.
Output
Print one integer — the maximum number of bosses your friend can place, considering all possible choices for s and t.
Examples
Input
5 5
1 2
2 3
3 1
4 1
5 2
Output
2
Input
4 3
1 2
4 3
3 2
Output
3
Submitted Solution:
```
import sys
def main():
p = input().split()
n = int(p[0]) #number of locations
m = int(p[1]) #number of passages
g = graph(n,m)
g.buildBridgeTree()
t = graph(len(g.bridges)+1,len(g.bridges))
t.conexions= []
t.pi=[]
t.discovery=[]
t.seen=[]
for i in range(len(g.bridges)+1):
t.conexions.append([])
t.pi.append(-1)
t.discovery.append(sys.float_info.max)
t.seen.append(False)
for i in range(len(g.bridges)):
t.conexions[g.cc[g.bridges[i][0]]].append((g.cc[g.bridges[i][1]],True))
t.conexions[g.cc[g.bridges[i][1]]].append((g.cc[g.bridges[i][0]],True))
t.treeDiameter()
class graph:
n = int() #number of nodes
edges= int() #number of edges
time = int()
conexions = [] #adjacency list
bridges=[] #are we using a removable edge or not for city i?
discovery = [] #time to discover node i
seen = [] #visited or not
cc = [] #index of connected components
low = [] #low[i]=min(discovery(i),discovery(w)) w:any node discoverable from i
pi = [] #index of i's father
def __init__(self, n, m):
self.n = n
self.edges = m
for i in range(self.n):
self.conexions.append([])
self.discovery.append(sys.float_info.max)
self.low.append(sys.float_info.max)
self.seen.append(False)
self.cc.append(-1)
def buildGraph(self):
#this method put every edge in the adjacency list
for i in range(self.edges):
p2=input().split()
self.conexions[int(p2[0])-1].append((int(p2[1])-1,False))
self.conexions[int(p2[1])-1].append((int(p2[0])-1,False))
def searchBridges (self):
self.time = 0
for i in range(self.n):
self.pi.append(-1)
self.searchBridges_(0,-1) #we can start in any node 'cause the graph is connected
def searchBridges_(self,c,index):
self.seen[c]=True #mark as visited
self.time+=1
self.discovery[c]=self.low[c]= self.time
for i in range(len(self.conexions[c])):
pos = self.conexions[c][i][0]
if self.seen[pos]==False:
self.pi[pos]=c #the node that discovered it
self.searchBridges_(pos,i) #search throw its not visited conexions
self.low[c]= min([self.low[c],self.low[pos]]) #definition of low
elif self.pi[c]!=pos: #It is not the node that discovered it
self.low[c]= min([self.low[c],self.discovery[pos]])
if self.pi[c]!=-1 and self.low[c]==self.discovery[c]: #it isn't the root and none of its connections is reacheable earlier than it
self.bridges.append((c,self.pi[c]))
for i in range(len(self.conexions[c])):
if(self.conexions[c][i][0]==self.pi[c]):
self.conexions[c][i]=(self.pi[c],True)
self.conexions[self.pi[c]][index]=(c,True)
break
def findCC(self):
j = 0
for i in range(self.n):
self.pi[i]=-1
self.seen[i]=False
for i in range(self.n):
if self.seen[i]==False:
self.cc[i]=j #assign the index of the new connected component
self.findCC_(i,j) #search throw its not visited conexions
j+=1 #we finished the search in the connected component
def findCC_(self, c, j):
self.seen[c]=True #mark as visited
for i in range(len(self.conexions[c])):
pos = self.conexions[c][i][0]
if(self.seen[pos]==False and self.conexions[c][i][1]==False):
self.cc[pos]=j #assign the index of the connected component
self.pi[pos]=c #the node that discovered it
self.findCC_(pos,j) #search throw its not visited conexions
def treeDiameter(self):
for i in range(self.n):
self.seen[i]=False
self.pi[i]=-1
self.discovery[0]=0
self.treeDiameter_(0) #search the distance from this node, to the others
max = sys.float_info.min
maxIndex = 0
for i in range(self.n):
if self.discovery[i]>max:
max= self.discovery[i] #look for the furthest node
maxIndex=i
for i in range(self.n):
self.seen[i]=False
self.pi[i]=-1
self.discovery[maxIndex]=0
self.treeDiameter_(maxIndex) #search the distance from the furthest node, to the others
max = sys.float_info.min
for i in range(self.n):
if self.discovery[i]>max :
max= self.discovery[i] #look for the furthest node to preview furthest node, and that is the diameter in a tree
print(max)
def treeDiameter_(self, c):
self.seen[c]=True #mark as visited
for i in range(len(self.conexions[c])):
pos = self.conexions[c][i][0]
if self.seen[pos]==False:
self.pi[pos]=c #the node that discovered it
self.discovery[pos]= self.discovery[c]+1 #distance to the node who discover it + 1
#we don't have to compare and search for other paths, since it's a tree and there is only one path between two nodes.
self.treeDiameter_(pos) #search throw its not visited conexions
def buildBridgeTree(self):
self.buildGraph()
self.searchBridges()
self.findCC()
if __name__ == '__main__':
main()
```
|
instruction
| 0
| 14,153
| 2
| 28,306
|
No
|
output
| 1
| 14,153
| 2
| 28,307
|
Provide tags and a correct Python 3 solution for this coding contest problem.
This is the modification of the problem used during the official round. Unfortunately, author's solution of the original problem appeared wrong, so the problem was changed specially for the archive.
Once upon a time in a far away kingdom lived the King. The King had a beautiful daughter, Victoria. They lived happily, but not happily ever after: one day a vicious dragon attacked the kingdom and stole Victoria. The King was full of grief, yet he gathered his noble knights and promised half of his kingdom and Victoria's hand in marriage to the one who will save the girl from the infernal beast.
Having travelled for some time, the knights found the dragon's lair and all of them rushed there to save Victoria. Each knight spat on the dragon once and, as the dragon had quite a fragile and frail heart, his heart broke and poor beast died. As for the noble knights, they got Victoria right to the King and started brawling as each one wanted the girl's hand in marriage.
The problem was that all the noble knights were equally noble and equally handsome, and Victoria didn't want to marry any of them anyway. Then the King (and he was a very wise man and didn't want to hurt anybody's feelings) decided to find out who will get his daughter randomly, i.e. tossing a coin. However, there turned out to be n noble knights and the coin only has two sides. The good thing is that when a coin is tossed, the coin falls on each side with equal probability. The King got interested how to pick one noble knight using this coin so that all knights had equal probability of being chosen (the probability in that case should always be equal to 1 / n). First the King wants to know the expected number of times he will need to toss a coin to determine the winner. Besides, while tossing the coin, the King should follow the optimal tossing strategy (i.e. the strategy that minimizes the expected number of tosses). Help the King in this challenging task.
Input
The first line contains a single integer n from the problem's statement (1 ≤ n ≤ 10000).
Output
Print the sought expected number of tosses as an irreducible fraction in the following form: "a/b" (without the quotes) without leading zeroes.
Examples
Input
2
Output
1/1
Input
3
Output
8/3
Input
4
Output
2/1
|
instruction
| 0
| 14,756
| 2
| 29,512
|
Tags: implementation, probabilities, trees
Correct Solution:
```
from fractions import *
n,L=int(input()),0
while (n%2==0):n,L=n//2,L+1
if (n==1):print('%d/1'%L)
else:
s,t=1,1
for i in range(n):
t,s=t*2%n,s*2
if (t==1):
m=i+1
break
r,t,i,ans=s,s*n,L,0
while (r>1):
i,t=i+1,t//2
if (r-t>0):
r,ans=r-t,ans+i*t
print(Fraction(ans+m,s-1))
# Made By Mostafa_Khaled
```
|
output
| 1
| 14,756
| 2
| 29,513
|
Provide tags and a correct Python 3 solution for this coding contest problem.
This is the modification of the problem used during the official round. Unfortunately, author's solution of the original problem appeared wrong, so the problem was changed specially for the archive.
Once upon a time in a far away kingdom lived the King. The King had a beautiful daughter, Victoria. They lived happily, but not happily ever after: one day a vicious dragon attacked the kingdom and stole Victoria. The King was full of grief, yet he gathered his noble knights and promised half of his kingdom and Victoria's hand in marriage to the one who will save the girl from the infernal beast.
Having travelled for some time, the knights found the dragon's lair and all of them rushed there to save Victoria. Each knight spat on the dragon once and, as the dragon had quite a fragile and frail heart, his heart broke and poor beast died. As for the noble knights, they got Victoria right to the King and started brawling as each one wanted the girl's hand in marriage.
The problem was that all the noble knights were equally noble and equally handsome, and Victoria didn't want to marry any of them anyway. Then the King (and he was a very wise man and didn't want to hurt anybody's feelings) decided to find out who will get his daughter randomly, i.e. tossing a coin. However, there turned out to be n noble knights and the coin only has two sides. The good thing is that when a coin is tossed, the coin falls on each side with equal probability. The King got interested how to pick one noble knight using this coin so that all knights had equal probability of being chosen (the probability in that case should always be equal to 1 / n). First the King wants to know the expected number of times he will need to toss a coin to determine the winner. Besides, while tossing the coin, the King should follow the optimal tossing strategy (i.e. the strategy that minimizes the expected number of tosses). Help the King in this challenging task.
Input
The first line contains a single integer n from the problem's statement (1 ≤ n ≤ 10000).
Output
Print the sought expected number of tosses as an irreducible fraction in the following form: "a/b" (without the quotes) without leading zeroes.
Examples
Input
2
Output
1/1
Input
3
Output
8/3
Input
4
Output
2/1
|
instruction
| 0
| 14,757
| 2
| 29,514
|
Tags: implementation, probabilities, trees
Correct Solution:
```
from math import gcd
def PRINT(a, b) :
print(str(int(a)) + "/" + str(int(b)))
def solve(n) :
pre = 0
while(n > 1 and (n % 2 == 0)) :
pre = pre + 1
n = n // 2
if(n == 1) :
PRINT(pre, 1)
return
arr = []
rem = 1
while(True) :
rem = rem * 2
arr.append(int(rem // n))
rem = rem % n
if(rem == 1) :
break
k = len(arr)
ans = 0
for i in range(0, k) :
if(arr[i] == 1) :
ans = ans + (2 ** (k-1-i)) * (i+1)
ans = ans * n + k
A = ans
B = 2**k - 1
G = gcd(A, B)
A = A // G
B = B // G
PRINT(A + B * pre, B)
n = int(input())
solve(n)
```
|
output
| 1
| 14,757
| 2
| 29,515
|
Provide a correct Python 3 solution for this coding contest problem.
problem
There are $ N $ islands numbered from $ 1 $ to $ N $.
Each island has $ N-1 $ bridges, allowing any $ 2 $ island to move to each other across several bridges.
Each bridge has durability, and the durability of the $ i $ th bridge given the input is $ w_i $.
There are $ 1 $ treasures on each island, and you can pick them up while you're on the island.
Yebi, who is currently on the island $ S $, wants to carry all the treasures to the museum on the island $ E $.
Since yebi has ✝ magical power ✝, every time he visits the island $ v $, the durability of all bridges coming out of $ v $ is reduced by $ T $.
When the durability of the bridge drops below $ 0 $, the bridge collapses and cannot be crossed after that.
Can yebi deliver all the treasures to the museum?
However, since yebi is powerful, he can carry as many treasures as he wants at the same time.
output
Output "Yes" if you can deliver all the treasures to the museum, otherwise output "No".
Also, output a line break at the end.
Example
Input
4 10 1 4
1 2 52
1 3 68
3 4 45
Output
Yes
|
instruction
| 0
| 15,029
| 2
| 30,058
|
"Correct Solution:
```
from operator import itemgetter
import sys
sys.setrecursionlimit(500000)
N, T, E, S = map(int, input().split())
G = [[] for _ in range(N+1)]
for _ in range(N-1):
a, b, w = map(int, input().split())
G[a].append((b, w))
G[b].append((a, w))
path = []
def pre_dfs(v, p):
if v == E:
return True
for u, w in G[v]:
if u != p:
if pre_dfs(u, v):
path.append(u)
return True
pre_dfs(S, 0)
path = set(path)
cnt = [0] * (N+1)
def dfs(v, p):
next = []
for u, w in G[v]:
if u != p:
if u in path:
next.append((u, w, float("inf")))
else:
next.append((u, w, w))
next.sort(key=itemgetter(2))
for u, w, _ in next:
#print(u, v, cnt[v], cnt[u], w)
if (cnt[v] + cnt[u]) * T < w:
cnt[u] += 1
dfs(u, v)
if (cnt[v] + cnt[u]) * T >= w:
#print(cnt)
if 0 < T < 10:
print("Yes")
exit()
print("No")
exit()
cnt[v] += 1
else:
if 0 < T < 10:
print("Yes")
exit()
#print(cnt)
print("No")
exit()
if v==E:
if 0 < T < 10:
print("No")
exit()
#print(cnt)
print("Yes")
exit()
dfs(S, 0)
```
|
output
| 1
| 15,029
| 2
| 30,059
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least <image>, where ε < 10 - 7.
To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help.
Input
First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively.
Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query.
Output
Output q lines. On i-th of them output single integer — answer for i-th query.
Examples
Input
1 1
1
Output
1
Input
2 2
1
2
Output
2
2
|
instruction
| 0
| 15,589
| 2
| 31,178
|
Tags: dp, math, probabilities
Correct Solution:
```
def main():
eps=10**-7
k,q=readIntArr()
# dp[nTurns][nDistinctOrbs]=probability
# dp[i][j]=dp[i-1][j]*j/k+dp[i-1][j-1]*(k-(j-1))/k
def rowFactory():
row=[0 for _ in range(k+1)]
return row
dp=[rowFactory()]
dp[0][0]=1
while dp[-1][-1]<=0.5:
newRow=rowFactory()
for j in range(1,k+1):
newRow[j]+=dp[-1][j]*j/k+dp[-1][j-1]*(k-(j-1))/k
dp.append(newRow)
# print(dp)
# break
n=len(dp)
for _ in range(q):
p=int(input())
b=n+1
nTurns=0
while b>0:
while nTurns+b<n and dp[nTurns+b][k]<(p/2000):
nTurns+=b
b//=2
nTurns+=1
print(nTurns)
return
#import sys
#input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
import sys
input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
inf=float('inf')
MOD=10**9+7
main()
```
|
output
| 1
| 15,589
| 2
| 31,179
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least <image>, where ε < 10 - 7.
To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help.
Input
First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively.
Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query.
Output
Output q lines. On i-th of them output single integer — answer for i-th query.
Examples
Input
1 1
1
Output
1
Input
2 2
1
2
Output
2
2
|
instruction
| 0
| 15,590
| 2
| 31,180
|
Tags: dp, math, probabilities
Correct Solution:
```
k, q = map(int, input().split())
t = [0] * (k + 1)
t[1] = 1
d = [0]
n = i = 1
while i < 1001:
if 2000 * t[k] > i - 1e-7:
d.append(n)
i += 1
else:
t = [0] + [(j * t[j] + (k - j + 1) * t[j - 1]) / k for j in range(1, k + 1)]
n += 1
for i in range(q): print(d[int(input())])
```
|
output
| 1
| 15,590
| 2
| 31,181
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least <image>, where ε < 10 - 7.
To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help.
Input
First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively.
Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query.
Output
Output q lines. On i-th of them output single integer — answer for i-th query.
Examples
Input
1 1
1
Output
1
Input
2 2
1
2
Output
2
2
|
instruction
| 0
| 15,591
| 2
| 31,182
|
Tags: dp, math, probabilities
Correct Solution:
```
k, q = map(int, input().split())
t = [0] * (k + 1)
t[1] = 1
c = [0]
n = i = 1
while i < 1001:
if (2000 * t[k] > i - (10**-7)):
c.append(n)
i += 1
else:
t = [0] + [(j * t[j] + (k - j + 1) * t[j - 1]) / k for j in range(1, k + 1)]
n += 1
for i in range(q):
print(c[int(input())])
```
|
output
| 1
| 15,591
| 2
| 31,183
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least <image>, where ε < 10 - 7.
To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help.
Input
First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively.
Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query.
Output
Output q lines. On i-th of them output single integer — answer for i-th query.
Examples
Input
1 1
1
Output
1
Input
2 2
1
2
Output
2
2
|
instruction
| 0
| 15,592
| 2
| 31,184
|
Tags: dp, math, probabilities
Correct Solution:
```
k, q = map(int, input().split())
dp = [[0.0 for i in range(k + 1)] for j in range(10000)]
dp[0][0] = 1.0
for i in range(1, 10000):
for j in range(1, k + 1):
dp[i][j] = dp[i - 1][j] * j / k + dp[i - 1][j - 1] * (k - j + 1) / k
for t in range(q):
p = int(input())
for i in range(10000):
if p <= dp[i][k] * 2000:
print(i)
break
```
|
output
| 1
| 15,592
| 2
| 31,185
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least <image>, where ε < 10 - 7.
To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help.
Input
First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively.
Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query.
Output
Output q lines. On i-th of them output single integer — answer for i-th query.
Examples
Input
1 1
1
Output
1
Input
2 2
1
2
Output
2
2
|
instruction
| 0
| 15,593
| 2
| 31,186
|
Tags: dp, math, probabilities
Correct Solution:
```
K, Q = map( int, input().split() )
dp = [ [ 0.0 for i in range( K + 1 ) ] for j in range( 10000 ) ]
dp[ 0 ][ 0 ] = 1.0
for i in range( 1, 10000, 1 ):
for j in range( 1, K + 1, 1 ):
dp[ i ][ j ] = dp[ i - 1 ][ j ] * j / K + dp[ i - 1 ][ j - 1 ] * ( K - ( j - 1 ) ) / K
for qi in range( Q ):
P = int( input() )
for i in range( 10000 ):
if P <= dp[ i ][ K ] * 2000:
print( i )
break
```
|
output
| 1
| 15,593
| 2
| 31,187
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least <image>, where ε < 10 - 7.
To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help.
Input
First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively.
Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query.
Output
Output q lines. On i-th of them output single integer — answer for i-th query.
Examples
Input
1 1
1
Output
1
Input
2 2
1
2
Output
2
2
Submitted Solution:
```
k, q = map(int, input().split())
p = [int(input()) for i in range(q)]
if k == 1:
print('1\n' * q)
exit()
N = 1005
M = 10 ** 4
eps = 10 ** -6
cnt = [0] * M
dp = [[0] * N for i in range(N)]
j = 1
dp[0][0] = 1
kk = 1
for n in range(1, N):
for i in range(1, k + 1):
dp[n][i] = (i * dp[n - 1][i] + (k - i + 1) * dp[n - 1][i - 1])
if n % 10 == 0:
kk = k ** 10
for i in range(k + 1):
dp[n][i] /= kk
kk = k ** (n % 10)
while j < M and dp[n][k] * 2000 >= j * kk:
cnt[j] = n
j += 1
ans = [cnt[i] for i in p]
print('\n'.join(map(str, ans)))
```
|
instruction
| 0
| 15,594
| 2
| 31,188
|
No
|
output
| 1
| 15,594
| 2
| 31,189
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least <image>, where ε < 10 - 7.
To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help.
Input
First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively.
Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query.
Output
Output q lines. On i-th of them output single integer — answer for i-th query.
Examples
Input
1 1
1
Output
1
Input
2 2
1
2
Output
2
2
Submitted Solution:
```
k, q = map(int, input().split())
for i in range(q):
x = float(input())
#if (k == 1):
#print(1)
#continue
j = float(k)
l = k - 1
r = 10000
while (l != r - 1):
m = (l + r) // 2
dp = k * [0]
dp[0] = ((k - 1) / k)**m
for i in range(1, k):
dp[i] = ((k - 1) / k)**m + dp[i-1]*(1 - (((k - 1) / k)**m))
if (2000 - 2000 * dp[k - 1] >= x - 0.0002):
r = m
else:
l = m
print(r)
```
|
instruction
| 0
| 15,595
| 2
| 31,190
|
No
|
output
| 1
| 15,595
| 2
| 31,191
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least <image>, where ε < 10 - 7.
To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help.
Input
First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively.
Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query.
Output
Output q lines. On i-th of them output single integer — answer for i-th query.
Examples
Input
1 1
1
Output
1
Input
2 2
1
2
Output
2
2
Submitted Solution:
```
primeralinea=(input().split())
k=float(primeralinea[0])
q=float(primeralinea[1])
dp=[[0 for x in range(int(k)+1)] for y in range(10005)]
dp[0][0]=1
i=1
while(i<=k):
for j in range(i,10000):
if(j>k):
break
#http://codeforces.com/blog/entry/50550 para formula
#dp[n][x]= (x/k) * dp[n-1][x] + (k-x-1)/k *dp[n-1][x-1]
#dp[i][j] = (i / k) * (dp[j - 1][i]) + ((k - i + 1) / k) * (dp[j - 1][i - 1])
dp[i][j] = (i / k) * (dp[i][j - 1]) + ((k - i + 1) / k) * (dp[i - 1][j - 1])
i+=1
qOG=int(q)
while(q>0):
y=float(input()) / 2000
for i in range(0,qOG):
#print(i)
if(i>qOG):
break
else:
if (dp[int(k)][i] >= y):
print(i)
break
q-=1
```
|
instruction
| 0
| 15,596
| 2
| 31,192
|
No
|
output
| 1
| 15,596
| 2
| 31,193
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least <image>, where ε < 10 - 7.
To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help.
Input
First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively.
Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query.
Output
Output q lines. On i-th of them output single integer — answer for i-th query.
Examples
Input
1 1
1
Output
1
Input
2 2
1
2
Output
2
2
Submitted Solution:
```
k, q = map(int, input().split())
for i in range(q):
x = float(input())
if (k == 1):
print(1)
continue
j = float(k)
l = k - 1
r = 10000
while (l != r - 1):
m = (l + r) // 2
i = (((j - 1) / j)**m)**k
if (1 - i > x / 2000):
r = m
else:
l = m
print(r)
```
|
instruction
| 0
| 15,597
| 2
| 31,194
|
No
|
output
| 1
| 15,597
| 2
| 31,195
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Meka-Naruto plays a computer game. His character has the following ability: given an enemy hero, deal a instant damage to him, and then heal that enemy b health points at the end of every second, for exactly c seconds, starting one second after the ability is used. That means that if the ability is used at time t, the enemy's health decreases by a at time t, and then increases by b at time points t + 1, t + 2, ..., t + c due to this ability.
The ability has a cooldown of d seconds, i. e. if Meka-Naruto uses it at time moment t, next time he can use it is the time t + d. Please note that he can only use the ability at integer points in time, so all changes to the enemy's health also occur at integer times only.
The effects from different uses of the ability may stack with each other; that is, the enemy which is currently under k spells gets k⋅ b amount of heal this time. Also, if several health changes occur at the same moment, they are all counted at once.
Now Meka-Naruto wonders if he can kill the enemy by just using the ability each time he can (that is, every d seconds). The enemy is killed if their health points become 0 or less. Assume that the enemy's health is not affected in any way other than by Meka-Naruto's character ability. What is the maximal number of health points the enemy can have so that Meka-Naruto is able to kill them?
Input
The first line contains an integer t (1≤ t≤ 10^5) standing for the number of testcases.
Each test case is described with one line containing four numbers a, b, c and d (1≤ a, b, c, d≤ 10^6) denoting the amount of instant damage, the amount of heal per second, the number of heals and the ability cooldown, respectively.
Output
For each testcase in a separate line print -1 if the skill can kill an enemy hero with an arbitrary number of health points, otherwise print the maximal number of health points of the enemy that can be killed.
Example
Input
7
1 1 1 1
2 2 2 2
1 2 3 4
4 3 2 1
228 21 11 3
239 21 11 3
1000000 1 1000000 1
Output
1
2
1
5
534
-1
500000500000
Note
In the first test case of the example each unit of damage is cancelled in a second, so Meka-Naruto cannot deal more than 1 damage.
In the fourth test case of the example the enemy gets:
* 4 damage (1-st spell cast) at time 0;
* 4 damage (2-nd spell cast) and 3 heal (1-st spell cast) at time 1 (the total of 5 damage to the initial health);
* 4 damage (3-nd spell cast) and 6 heal (1-st and 2-nd spell casts) at time 2 (the total of 3 damage to the initial health);
* and so on.
One can prove that there is no time where the enemy gets the total of 6 damage or more, so the answer is 5. Please note how the health is recalculated: for example, 8-health enemy would not die at time 1, as if we first subtracted 4 damage from his health and then considered him dead, before adding 3 heal.
In the sixth test case an arbitrarily healthy enemy can be killed in a sufficient amount of time.
In the seventh test case the answer does not fit into a 32-bit integer type.
|
instruction
| 0
| 16,162
| 2
| 32,324
|
Tags: greedy, math, ternary search
Correct Solution:
```
import sys
# sys.stdin = open('in.txt')
s = sys.stdin.read().split()
p = 0
def getSm(k, a, b, c, d):
return (k + 1) * a - (k * (k + 1) >> 1) * b * d
t = int(s[p])
p += 1
res = []
for _ in range(t):
a = int(s[p])
p += 1
b = int(s[p])
p += 1
c = int(s[p])
p += 1
d = int(s[p])
p += 1
if a - b * c > 0:
res.append(-1)
elif d >= c:
res.append(a)
else:
dn = 0
up = int(1e6) + 1
while up - dn > 1:
md = (up + dn) >> 1
if getSm(md, a, b, c, d) < getSm(md + 1, a, b, c, d):
dn = md
else:
up = md
ans = max(a, getSm(dn, a, b, c, d), getSm(up, a, b, c, d))
res.append(ans)
print('\n'.join(map(str, res)))
```
|
output
| 1
| 16,162
| 2
| 32,325
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Meka-Naruto plays a computer game. His character has the following ability: given an enemy hero, deal a instant damage to him, and then heal that enemy b health points at the end of every second, for exactly c seconds, starting one second after the ability is used. That means that if the ability is used at time t, the enemy's health decreases by a at time t, and then increases by b at time points t + 1, t + 2, ..., t + c due to this ability.
The ability has a cooldown of d seconds, i. e. if Meka-Naruto uses it at time moment t, next time he can use it is the time t + d. Please note that he can only use the ability at integer points in time, so all changes to the enemy's health also occur at integer times only.
The effects from different uses of the ability may stack with each other; that is, the enemy which is currently under k spells gets k⋅ b amount of heal this time. Also, if several health changes occur at the same moment, they are all counted at once.
Now Meka-Naruto wonders if he can kill the enemy by just using the ability each time he can (that is, every d seconds). The enemy is killed if their health points become 0 or less. Assume that the enemy's health is not affected in any way other than by Meka-Naruto's character ability. What is the maximal number of health points the enemy can have so that Meka-Naruto is able to kill them?
Input
The first line contains an integer t (1≤ t≤ 10^5) standing for the number of testcases.
Each test case is described with one line containing four numbers a, b, c and d (1≤ a, b, c, d≤ 10^6) denoting the amount of instant damage, the amount of heal per second, the number of heals and the ability cooldown, respectively.
Output
For each testcase in a separate line print -1 if the skill can kill an enemy hero with an arbitrary number of health points, otherwise print the maximal number of health points of the enemy that can be killed.
Example
Input
7
1 1 1 1
2 2 2 2
1 2 3 4
4 3 2 1
228 21 11 3
239 21 11 3
1000000 1 1000000 1
Output
1
2
1
5
534
-1
500000500000
Note
In the first test case of the example each unit of damage is cancelled in a second, so Meka-Naruto cannot deal more than 1 damage.
In the fourth test case of the example the enemy gets:
* 4 damage (1-st spell cast) at time 0;
* 4 damage (2-nd spell cast) and 3 heal (1-st spell cast) at time 1 (the total of 5 damage to the initial health);
* 4 damage (3-nd spell cast) and 6 heal (1-st and 2-nd spell casts) at time 2 (the total of 3 damage to the initial health);
* and so on.
One can prove that there is no time where the enemy gets the total of 6 damage or more, so the answer is 5. Please note how the health is recalculated: for example, 8-health enemy would not die at time 1, as if we first subtracted 4 damage from his health and then considered him dead, before adding 3 heal.
In the sixth test case an arbitrarily healthy enemy can be killed in a sufficient amount of time.
In the seventh test case the answer does not fit into a 32-bit integer type.
|
instruction
| 0
| 16,163
| 2
| 32,326
|
Tags: greedy, math, ternary search
Correct Solution:
```
import sys,io,os;Z=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
o=[]
for _ in range(int(Z())):
a,b,c,d=map(int,Z().split())
if a>b*c:o+=[-1]
elif d>c:o+=[a]
else:v=a//(b*d);o+=[(v+1)*a-b*d*(v*(v+1))//2]
print('\n'.join(map(str,o)))
```
|
output
| 1
| 16,163
| 2
| 32,327
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Meka-Naruto plays a computer game. His character has the following ability: given an enemy hero, deal a instant damage to him, and then heal that enemy b health points at the end of every second, for exactly c seconds, starting one second after the ability is used. That means that if the ability is used at time t, the enemy's health decreases by a at time t, and then increases by b at time points t + 1, t + 2, ..., t + c due to this ability.
The ability has a cooldown of d seconds, i. e. if Meka-Naruto uses it at time moment t, next time he can use it is the time t + d. Please note that he can only use the ability at integer points in time, so all changes to the enemy's health also occur at integer times only.
The effects from different uses of the ability may stack with each other; that is, the enemy which is currently under k spells gets k⋅ b amount of heal this time. Also, if several health changes occur at the same moment, they are all counted at once.
Now Meka-Naruto wonders if he can kill the enemy by just using the ability each time he can (that is, every d seconds). The enemy is killed if their health points become 0 or less. Assume that the enemy's health is not affected in any way other than by Meka-Naruto's character ability. What is the maximal number of health points the enemy can have so that Meka-Naruto is able to kill them?
Input
The first line contains an integer t (1≤ t≤ 10^5) standing for the number of testcases.
Each test case is described with one line containing four numbers a, b, c and d (1≤ a, b, c, d≤ 10^6) denoting the amount of instant damage, the amount of heal per second, the number of heals and the ability cooldown, respectively.
Output
For each testcase in a separate line print -1 if the skill can kill an enemy hero with an arbitrary number of health points, otherwise print the maximal number of health points of the enemy that can be killed.
Example
Input
7
1 1 1 1
2 2 2 2
1 2 3 4
4 3 2 1
228 21 11 3
239 21 11 3
1000000 1 1000000 1
Output
1
2
1
5
534
-1
500000500000
Note
In the first test case of the example each unit of damage is cancelled in a second, so Meka-Naruto cannot deal more than 1 damage.
In the fourth test case of the example the enemy gets:
* 4 damage (1-st spell cast) at time 0;
* 4 damage (2-nd spell cast) and 3 heal (1-st spell cast) at time 1 (the total of 5 damage to the initial health);
* 4 damage (3-nd spell cast) and 6 heal (1-st and 2-nd spell casts) at time 2 (the total of 3 damage to the initial health);
* and so on.
One can prove that there is no time where the enemy gets the total of 6 damage or more, so the answer is 5. Please note how the health is recalculated: for example, 8-health enemy would not die at time 1, as if we first subtracted 4 damage from his health and then considered him dead, before adding 3 heal.
In the sixth test case an arbitrarily healthy enemy can be killed in a sufficient amount of time.
In the seventh test case the answer does not fit into a 32-bit integer type.
|
instruction
| 0
| 16,164
| 2
| 32,328
|
Tags: greedy, math, ternary search
Correct Solution:
```
import sys
input = sys.stdin.buffer.readline
for _ in range(int(input())):
a,b,c,d = map(int,input().split())
if a-b*c>0:
print(-1)
else:
const = (-c-1)//d
k = (c)//d + 1
tmp1 = (k+1)*(a-b*c) - const*b*c - (d*b*const*(const+1))//2
tmp2 = 0
m = (-d*b+2*a)//(2*d*b)
if m>=k:
k = k - 1
tmp2 = (k+1)*a - (d*b*k*(k+1))//2
else:
#print("check")
tmp2 = -10**18
for i in range(-5,6):
k = m + i
if k<0:
continue
tmp22 = (k+1)*a - (d*b*k*(k+1))//2
#if tmp22==2:
#print(k)
tmp2 = max(tmp2,tmp22)
res = max(tmp1,tmp2)
print(res)
```
|
output
| 1
| 16,164
| 2
| 32,329
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Meka-Naruto plays a computer game. His character has the following ability: given an enemy hero, deal a instant damage to him, and then heal that enemy b health points at the end of every second, for exactly c seconds, starting one second after the ability is used. That means that if the ability is used at time t, the enemy's health decreases by a at time t, and then increases by b at time points t + 1, t + 2, ..., t + c due to this ability.
The ability has a cooldown of d seconds, i. e. if Meka-Naruto uses it at time moment t, next time he can use it is the time t + d. Please note that he can only use the ability at integer points in time, so all changes to the enemy's health also occur at integer times only.
The effects from different uses of the ability may stack with each other; that is, the enemy which is currently under k spells gets k⋅ b amount of heal this time. Also, if several health changes occur at the same moment, they are all counted at once.
Now Meka-Naruto wonders if he can kill the enemy by just using the ability each time he can (that is, every d seconds). The enemy is killed if their health points become 0 or less. Assume that the enemy's health is not affected in any way other than by Meka-Naruto's character ability. What is the maximal number of health points the enemy can have so that Meka-Naruto is able to kill them?
Input
The first line contains an integer t (1≤ t≤ 10^5) standing for the number of testcases.
Each test case is described with one line containing four numbers a, b, c and d (1≤ a, b, c, d≤ 10^6) denoting the amount of instant damage, the amount of heal per second, the number of heals and the ability cooldown, respectively.
Output
For each testcase in a separate line print -1 if the skill can kill an enemy hero with an arbitrary number of health points, otherwise print the maximal number of health points of the enemy that can be killed.
Example
Input
7
1 1 1 1
2 2 2 2
1 2 3 4
4 3 2 1
228 21 11 3
239 21 11 3
1000000 1 1000000 1
Output
1
2
1
5
534
-1
500000500000
Note
In the first test case of the example each unit of damage is cancelled in a second, so Meka-Naruto cannot deal more than 1 damage.
In the fourth test case of the example the enemy gets:
* 4 damage (1-st spell cast) at time 0;
* 4 damage (2-nd spell cast) and 3 heal (1-st spell cast) at time 1 (the total of 5 damage to the initial health);
* 4 damage (3-nd spell cast) and 6 heal (1-st and 2-nd spell casts) at time 2 (the total of 3 damage to the initial health);
* and so on.
One can prove that there is no time where the enemy gets the total of 6 damage or more, so the answer is 5. Please note how the health is recalculated: for example, 8-health enemy would not die at time 1, as if we first subtracted 4 damage from his health and then considered him dead, before adding 3 heal.
In the sixth test case an arbitrarily healthy enemy can be killed in a sufficient amount of time.
In the seventh test case the answer does not fit into a 32-bit integer type.
|
instruction
| 0
| 16,165
| 2
| 32,330
|
Tags: greedy, math, ternary search
Correct Solution:
```
from sys import stdin
t = int(input())
for i_t in range(t):
a, b, c, d = map(int, stdin.readline().split())
if b*c < a:
result = -1
else:
i_hit = (a + b*d - 1) // (b*d) - 1
i_hit = min(i_hit, (c-1) // d)
result = a * (i_hit+1) - b*d * i_hit*(i_hit+1)//2
print(result)
```
|
output
| 1
| 16,165
| 2
| 32,331
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Meka-Naruto plays a computer game. His character has the following ability: given an enemy hero, deal a instant damage to him, and then heal that enemy b health points at the end of every second, for exactly c seconds, starting one second after the ability is used. That means that if the ability is used at time t, the enemy's health decreases by a at time t, and then increases by b at time points t + 1, t + 2, ..., t + c due to this ability.
The ability has a cooldown of d seconds, i. e. if Meka-Naruto uses it at time moment t, next time he can use it is the time t + d. Please note that he can only use the ability at integer points in time, so all changes to the enemy's health also occur at integer times only.
The effects from different uses of the ability may stack with each other; that is, the enemy which is currently under k spells gets k⋅ b amount of heal this time. Also, if several health changes occur at the same moment, they are all counted at once.
Now Meka-Naruto wonders if he can kill the enemy by just using the ability each time he can (that is, every d seconds). The enemy is killed if their health points become 0 or less. Assume that the enemy's health is not affected in any way other than by Meka-Naruto's character ability. What is the maximal number of health points the enemy can have so that Meka-Naruto is able to kill them?
Input
The first line contains an integer t (1≤ t≤ 10^5) standing for the number of testcases.
Each test case is described with one line containing four numbers a, b, c and d (1≤ a, b, c, d≤ 10^6) denoting the amount of instant damage, the amount of heal per second, the number of heals and the ability cooldown, respectively.
Output
For each testcase in a separate line print -1 if the skill can kill an enemy hero with an arbitrary number of health points, otherwise print the maximal number of health points of the enemy that can be killed.
Example
Input
7
1 1 1 1
2 2 2 2
1 2 3 4
4 3 2 1
228 21 11 3
239 21 11 3
1000000 1 1000000 1
Output
1
2
1
5
534
-1
500000500000
Note
In the first test case of the example each unit of damage is cancelled in a second, so Meka-Naruto cannot deal more than 1 damage.
In the fourth test case of the example the enemy gets:
* 4 damage (1-st spell cast) at time 0;
* 4 damage (2-nd spell cast) and 3 heal (1-st spell cast) at time 1 (the total of 5 damage to the initial health);
* 4 damage (3-nd spell cast) and 6 heal (1-st and 2-nd spell casts) at time 2 (the total of 3 damage to the initial health);
* and so on.
One can prove that there is no time where the enemy gets the total of 6 damage or more, so the answer is 5. Please note how the health is recalculated: for example, 8-health enemy would not die at time 1, as if we first subtracted 4 damage from his health and then considered him dead, before adding 3 heal.
In the sixth test case an arbitrarily healthy enemy can be killed in a sufficient amount of time.
In the seventh test case the answer does not fit into a 32-bit integer type.
|
instruction
| 0
| 16,166
| 2
| 32,332
|
Tags: greedy, math, ternary search
Correct Solution:
```
import sys
input = sys.stdin.readline
for f in range(int(input())):
a,b,c,d=map(int,input().split())
if d>=c:
if a>b*c:
print(-1)
else:
print(a)
else:
if a>b*c:
print(-1)
else:
if a<b*d:
print(a)
else:
k=a//(b*d)
print((k+1)*a-(k*(k+1)*b*d)//2)
```
|
output
| 1
| 16,166
| 2
| 32,333
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Meka-Naruto plays a computer game. His character has the following ability: given an enemy hero, deal a instant damage to him, and then heal that enemy b health points at the end of every second, for exactly c seconds, starting one second after the ability is used. That means that if the ability is used at time t, the enemy's health decreases by a at time t, and then increases by b at time points t + 1, t + 2, ..., t + c due to this ability.
The ability has a cooldown of d seconds, i. e. if Meka-Naruto uses it at time moment t, next time he can use it is the time t + d. Please note that he can only use the ability at integer points in time, so all changes to the enemy's health also occur at integer times only.
The effects from different uses of the ability may stack with each other; that is, the enemy which is currently under k spells gets k⋅ b amount of heal this time. Also, if several health changes occur at the same moment, they are all counted at once.
Now Meka-Naruto wonders if he can kill the enemy by just using the ability each time he can (that is, every d seconds). The enemy is killed if their health points become 0 or less. Assume that the enemy's health is not affected in any way other than by Meka-Naruto's character ability. What is the maximal number of health points the enemy can have so that Meka-Naruto is able to kill them?
Input
The first line contains an integer t (1≤ t≤ 10^5) standing for the number of testcases.
Each test case is described with one line containing four numbers a, b, c and d (1≤ a, b, c, d≤ 10^6) denoting the amount of instant damage, the amount of heal per second, the number of heals and the ability cooldown, respectively.
Output
For each testcase in a separate line print -1 if the skill can kill an enemy hero with an arbitrary number of health points, otherwise print the maximal number of health points of the enemy that can be killed.
Example
Input
7
1 1 1 1
2 2 2 2
1 2 3 4
4 3 2 1
228 21 11 3
239 21 11 3
1000000 1 1000000 1
Output
1
2
1
5
534
-1
500000500000
Note
In the first test case of the example each unit of damage is cancelled in a second, so Meka-Naruto cannot deal more than 1 damage.
In the fourth test case of the example the enemy gets:
* 4 damage (1-st spell cast) at time 0;
* 4 damage (2-nd spell cast) and 3 heal (1-st spell cast) at time 1 (the total of 5 damage to the initial health);
* 4 damage (3-nd spell cast) and 6 heal (1-st and 2-nd spell casts) at time 2 (the total of 3 damage to the initial health);
* and so on.
One can prove that there is no time where the enemy gets the total of 6 damage or more, so the answer is 5. Please note how the health is recalculated: for example, 8-health enemy would not die at time 1, as if we first subtracted 4 damage from his health and then considered him dead, before adding 3 heal.
In the sixth test case an arbitrarily healthy enemy can be killed in a sufficient amount of time.
In the seventh test case the answer does not fit into a 32-bit integer type.
|
instruction
| 0
| 16,167
| 2
| 32,334
|
Tags: greedy, math, ternary search
Correct Solution:
```
import sys
input = sys.stdin.readline
def solve_case():
a, b, c, d = [int(x) for x in input().split()]
if a > b * c:
print(-1)
else:
k = a // (b * d)
print(a * (k + 1) - k * (k + 1) // 2 * b * d)
def main():
for _ in range(int(input())):
solve_case()
main()
```
|
output
| 1
| 16,167
| 2
| 32,335
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Meka-Naruto plays a computer game. His character has the following ability: given an enemy hero, deal a instant damage to him, and then heal that enemy b health points at the end of every second, for exactly c seconds, starting one second after the ability is used. That means that if the ability is used at time t, the enemy's health decreases by a at time t, and then increases by b at time points t + 1, t + 2, ..., t + c due to this ability.
The ability has a cooldown of d seconds, i. e. if Meka-Naruto uses it at time moment t, next time he can use it is the time t + d. Please note that he can only use the ability at integer points in time, so all changes to the enemy's health also occur at integer times only.
The effects from different uses of the ability may stack with each other; that is, the enemy which is currently under k spells gets k⋅ b amount of heal this time. Also, if several health changes occur at the same moment, they are all counted at once.
Now Meka-Naruto wonders if he can kill the enemy by just using the ability each time he can (that is, every d seconds). The enemy is killed if their health points become 0 or less. Assume that the enemy's health is not affected in any way other than by Meka-Naruto's character ability. What is the maximal number of health points the enemy can have so that Meka-Naruto is able to kill them?
Input
The first line contains an integer t (1≤ t≤ 10^5) standing for the number of testcases.
Each test case is described with one line containing four numbers a, b, c and d (1≤ a, b, c, d≤ 10^6) denoting the amount of instant damage, the amount of heal per second, the number of heals and the ability cooldown, respectively.
Output
For each testcase in a separate line print -1 if the skill can kill an enemy hero with an arbitrary number of health points, otherwise print the maximal number of health points of the enemy that can be killed.
Example
Input
7
1 1 1 1
2 2 2 2
1 2 3 4
4 3 2 1
228 21 11 3
239 21 11 3
1000000 1 1000000 1
Output
1
2
1
5
534
-1
500000500000
Note
In the first test case of the example each unit of damage is cancelled in a second, so Meka-Naruto cannot deal more than 1 damage.
In the fourth test case of the example the enemy gets:
* 4 damage (1-st spell cast) at time 0;
* 4 damage (2-nd spell cast) and 3 heal (1-st spell cast) at time 1 (the total of 5 damage to the initial health);
* 4 damage (3-nd spell cast) and 6 heal (1-st and 2-nd spell casts) at time 2 (the total of 3 damage to the initial health);
* and so on.
One can prove that there is no time where the enemy gets the total of 6 damage or more, so the answer is 5. Please note how the health is recalculated: for example, 8-health enemy would not die at time 1, as if we first subtracted 4 damage from his health and then considered him dead, before adding 3 heal.
In the sixth test case an arbitrarily healthy enemy can be killed in a sufficient amount of time.
In the seventh test case the answer does not fit into a 32-bit integer type.
|
instruction
| 0
| 16,168
| 2
| 32,336
|
Tags: greedy, math, ternary search
Correct Solution:
```
import sys
sys.setrecursionlimit(10**5)
int1 = lambda x: int(x)-1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.buffer.readline())
def MI(): return map(int, sys.stdin.buffer.readline().split())
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def BI(): return sys.stdin.buffer.readline().rstrip()
def SI(): return sys.stdin.buffer.readline().rstrip().decode()
for _ in range(II()):
a,b,c,d=MI()
if a>b*c:
print(-1)
continue
t=a//(b*d)
k1=a-b*d
r=-b*d
kt=k1+r*(t-1)
s=(k1+kt)*t//2
ans=a+s
print(ans)
```
|
output
| 1
| 16,168
| 2
| 32,337
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Meka-Naruto plays a computer game. His character has the following ability: given an enemy hero, deal a instant damage to him, and then heal that enemy b health points at the end of every second, for exactly c seconds, starting one second after the ability is used. That means that if the ability is used at time t, the enemy's health decreases by a at time t, and then increases by b at time points t + 1, t + 2, ..., t + c due to this ability.
The ability has a cooldown of d seconds, i. e. if Meka-Naruto uses it at time moment t, next time he can use it is the time t + d. Please note that he can only use the ability at integer points in time, so all changes to the enemy's health also occur at integer times only.
The effects from different uses of the ability may stack with each other; that is, the enemy which is currently under k spells gets k⋅ b amount of heal this time. Also, if several health changes occur at the same moment, they are all counted at once.
Now Meka-Naruto wonders if he can kill the enemy by just using the ability each time he can (that is, every d seconds). The enemy is killed if their health points become 0 or less. Assume that the enemy's health is not affected in any way other than by Meka-Naruto's character ability. What is the maximal number of health points the enemy can have so that Meka-Naruto is able to kill them?
Input
The first line contains an integer t (1≤ t≤ 10^5) standing for the number of testcases.
Each test case is described with one line containing four numbers a, b, c and d (1≤ a, b, c, d≤ 10^6) denoting the amount of instant damage, the amount of heal per second, the number of heals and the ability cooldown, respectively.
Output
For each testcase in a separate line print -1 if the skill can kill an enemy hero with an arbitrary number of health points, otherwise print the maximal number of health points of the enemy that can be killed.
Example
Input
7
1 1 1 1
2 2 2 2
1 2 3 4
4 3 2 1
228 21 11 3
239 21 11 3
1000000 1 1000000 1
Output
1
2
1
5
534
-1
500000500000
Note
In the first test case of the example each unit of damage is cancelled in a second, so Meka-Naruto cannot deal more than 1 damage.
In the fourth test case of the example the enemy gets:
* 4 damage (1-st spell cast) at time 0;
* 4 damage (2-nd spell cast) and 3 heal (1-st spell cast) at time 1 (the total of 5 damage to the initial health);
* 4 damage (3-nd spell cast) and 6 heal (1-st and 2-nd spell casts) at time 2 (the total of 3 damage to the initial health);
* and so on.
One can prove that there is no time where the enemy gets the total of 6 damage or more, so the answer is 5. Please note how the health is recalculated: for example, 8-health enemy would not die at time 1, as if we first subtracted 4 damage from his health and then considered him dead, before adding 3 heal.
In the sixth test case an arbitrarily healthy enemy can be killed in a sufficient amount of time.
In the seventh test case the answer does not fit into a 32-bit integer type.
|
instruction
| 0
| 16,169
| 2
| 32,338
|
Tags: greedy, math, ternary search
Correct Solution:
```
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
import sys
X=[]
t=int(input())
for tests in range(t):
a,b,c,d=map(int,input().split())
if a>b*c:
X.append(-1)
continue
left = 1
right= c//d+1
def calc(x):
return -a*x+b*d*x*(x-1)//2
while right>left:
mid=(right+left)//2
if calc(mid)<calc(mid+1):
right=mid
else:
left=mid+1
X.append(-min(calc(left),calc(right)))
sys.stdout.write("\n".join(map(str,X)))
```
|
output
| 1
| 16,169
| 2
| 32,339
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Meka-Naruto plays a computer game. His character has the following ability: given an enemy hero, deal a instant damage to him, and then heal that enemy b health points at the end of every second, for exactly c seconds, starting one second after the ability is used. That means that if the ability is used at time t, the enemy's health decreases by a at time t, and then increases by b at time points t + 1, t + 2, ..., t + c due to this ability.
The ability has a cooldown of d seconds, i. e. if Meka-Naruto uses it at time moment t, next time he can use it is the time t + d. Please note that he can only use the ability at integer points in time, so all changes to the enemy's health also occur at integer times only.
The effects from different uses of the ability may stack with each other; that is, the enemy which is currently under k spells gets k⋅ b amount of heal this time. Also, if several health changes occur at the same moment, they are all counted at once.
Now Meka-Naruto wonders if he can kill the enemy by just using the ability each time he can (that is, every d seconds). The enemy is killed if their health points become 0 or less. Assume that the enemy's health is not affected in any way other than by Meka-Naruto's character ability. What is the maximal number of health points the enemy can have so that Meka-Naruto is able to kill them?
Input
The first line contains an integer t (1≤ t≤ 10^5) standing for the number of testcases.
Each test case is described with one line containing four numbers a, b, c and d (1≤ a, b, c, d≤ 10^6) denoting the amount of instant damage, the amount of heal per second, the number of heals and the ability cooldown, respectively.
Output
For each testcase in a separate line print -1 if the skill can kill an enemy hero with an arbitrary number of health points, otherwise print the maximal number of health points of the enemy that can be killed.
Example
Input
7
1 1 1 1
2 2 2 2
1 2 3 4
4 3 2 1
228 21 11 3
239 21 11 3
1000000 1 1000000 1
Output
1
2
1
5
534
-1
500000500000
Note
In the first test case of the example each unit of damage is cancelled in a second, so Meka-Naruto cannot deal more than 1 damage.
In the fourth test case of the example the enemy gets:
* 4 damage (1-st spell cast) at time 0;
* 4 damage (2-nd spell cast) and 3 heal (1-st spell cast) at time 1 (the total of 5 damage to the initial health);
* 4 damage (3-nd spell cast) and 6 heal (1-st and 2-nd spell casts) at time 2 (the total of 3 damage to the initial health);
* and so on.
One can prove that there is no time where the enemy gets the total of 6 damage or more, so the answer is 5. Please note how the health is recalculated: for example, 8-health enemy would not die at time 1, as if we first subtracted 4 damage from his health and then considered him dead, before adding 3 heal.
In the sixth test case an arbitrarily healthy enemy can be killed in a sufficient amount of time.
In the seventh test case the answer does not fit into a 32-bit integer type.
Submitted Solution:
```
import sys,io,os;Z=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
o=[]
for _ in range(int(Z())):
a,b,c,d=map(int,Z().split())
if a>b*c:o+=[-1]
elif d>c:o+=[a];continue
else:v=a//(b*d);o+=[(v+1)*a-b*d*(v*(v+1))//2]
print('\n'.join(map(str,o)))
```
|
instruction
| 0
| 16,170
| 2
| 32,340
|
Yes
|
output
| 1
| 16,170
| 2
| 32,341
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Meka-Naruto plays a computer game. His character has the following ability: given an enemy hero, deal a instant damage to him, and then heal that enemy b health points at the end of every second, for exactly c seconds, starting one second after the ability is used. That means that if the ability is used at time t, the enemy's health decreases by a at time t, and then increases by b at time points t + 1, t + 2, ..., t + c due to this ability.
The ability has a cooldown of d seconds, i. e. if Meka-Naruto uses it at time moment t, next time he can use it is the time t + d. Please note that he can only use the ability at integer points in time, so all changes to the enemy's health also occur at integer times only.
The effects from different uses of the ability may stack with each other; that is, the enemy which is currently under k spells gets k⋅ b amount of heal this time. Also, if several health changes occur at the same moment, they are all counted at once.
Now Meka-Naruto wonders if he can kill the enemy by just using the ability each time he can (that is, every d seconds). The enemy is killed if their health points become 0 or less. Assume that the enemy's health is not affected in any way other than by Meka-Naruto's character ability. What is the maximal number of health points the enemy can have so that Meka-Naruto is able to kill them?
Input
The first line contains an integer t (1≤ t≤ 10^5) standing for the number of testcases.
Each test case is described with one line containing four numbers a, b, c and d (1≤ a, b, c, d≤ 10^6) denoting the amount of instant damage, the amount of heal per second, the number of heals and the ability cooldown, respectively.
Output
For each testcase in a separate line print -1 if the skill can kill an enemy hero with an arbitrary number of health points, otherwise print the maximal number of health points of the enemy that can be killed.
Example
Input
7
1 1 1 1
2 2 2 2
1 2 3 4
4 3 2 1
228 21 11 3
239 21 11 3
1000000 1 1000000 1
Output
1
2
1
5
534
-1
500000500000
Note
In the first test case of the example each unit of damage is cancelled in a second, so Meka-Naruto cannot deal more than 1 damage.
In the fourth test case of the example the enemy gets:
* 4 damage (1-st spell cast) at time 0;
* 4 damage (2-nd spell cast) and 3 heal (1-st spell cast) at time 1 (the total of 5 damage to the initial health);
* 4 damage (3-nd spell cast) and 6 heal (1-st and 2-nd spell casts) at time 2 (the total of 3 damage to the initial health);
* and so on.
One can prove that there is no time where the enemy gets the total of 6 damage or more, so the answer is 5. Please note how the health is recalculated: for example, 8-health enemy would not die at time 1, as if we first subtracted 4 damage from his health and then considered him dead, before adding 3 heal.
In the sixth test case an arbitrarily healthy enemy can be killed in a sufficient amount of time.
In the seventh test case the answer does not fit into a 32-bit integer type.
Submitted Solution:
```
from sys import stdin, stdout
def f(a, b, c, d, i):
return d * b * i * (i + 1) // 2 - a * (i + 1)
for i in range(int(input())):
a, b, c, d = [int(i) for i in stdin.readline().split()]
if -a + b * c < 0:
stdout.write("-1\n")
else:
v = a // (b * d)
mx = 0
mx = max(mx, -f(a, b, c, d, max(0, v)))
mx = max(mx, -f(a, b, c, d, max(0, v + 1)))
stdout.write(str(mx) + "\n")
```
|
instruction
| 0
| 16,171
| 2
| 32,342
|
Yes
|
output
| 1
| 16,171
| 2
| 32,343
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Meka-Naruto plays a computer game. His character has the following ability: given an enemy hero, deal a instant damage to him, and then heal that enemy b health points at the end of every second, for exactly c seconds, starting one second after the ability is used. That means that if the ability is used at time t, the enemy's health decreases by a at time t, and then increases by b at time points t + 1, t + 2, ..., t + c due to this ability.
The ability has a cooldown of d seconds, i. e. if Meka-Naruto uses it at time moment t, next time he can use it is the time t + d. Please note that he can only use the ability at integer points in time, so all changes to the enemy's health also occur at integer times only.
The effects from different uses of the ability may stack with each other; that is, the enemy which is currently under k spells gets k⋅ b amount of heal this time. Also, if several health changes occur at the same moment, they are all counted at once.
Now Meka-Naruto wonders if he can kill the enemy by just using the ability each time he can (that is, every d seconds). The enemy is killed if their health points become 0 or less. Assume that the enemy's health is not affected in any way other than by Meka-Naruto's character ability. What is the maximal number of health points the enemy can have so that Meka-Naruto is able to kill them?
Input
The first line contains an integer t (1≤ t≤ 10^5) standing for the number of testcases.
Each test case is described with one line containing four numbers a, b, c and d (1≤ a, b, c, d≤ 10^6) denoting the amount of instant damage, the amount of heal per second, the number of heals and the ability cooldown, respectively.
Output
For each testcase in a separate line print -1 if the skill can kill an enemy hero with an arbitrary number of health points, otherwise print the maximal number of health points of the enemy that can be killed.
Example
Input
7
1 1 1 1
2 2 2 2
1 2 3 4
4 3 2 1
228 21 11 3
239 21 11 3
1000000 1 1000000 1
Output
1
2
1
5
534
-1
500000500000
Note
In the first test case of the example each unit of damage is cancelled in a second, so Meka-Naruto cannot deal more than 1 damage.
In the fourth test case of the example the enemy gets:
* 4 damage (1-st spell cast) at time 0;
* 4 damage (2-nd spell cast) and 3 heal (1-st spell cast) at time 1 (the total of 5 damage to the initial health);
* 4 damage (3-nd spell cast) and 6 heal (1-st and 2-nd spell casts) at time 2 (the total of 3 damage to the initial health);
* and so on.
One can prove that there is no time where the enemy gets the total of 6 damage or more, so the answer is 5. Please note how the health is recalculated: for example, 8-health enemy would not die at time 1, as if we first subtracted 4 damage from his health and then considered him dead, before adding 3 heal.
In the sixth test case an arbitrarily healthy enemy can be killed in a sufficient amount of time.
In the seventh test case the answer does not fit into a 32-bit integer type.
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline()
# ------------------------------
def RL(): return map(int, sys.stdin.readline().split())
def RLL(): return list(map(int, sys.stdin.readline().split()))
def N(): return int(input())
def print_list(l):
print(' '.join(map(str,l)))
# sys.setrecursionlimit(300000)
# from heapq import *
# from collections import deque as dq
# from math import ceil,floor,sqrt,pow
# import bisect as bs
# from collections import Counter
# from collections import defaultdict as dc
# from functools import lru_cache
for _ in range(N()):
a,b,c,d = RL()
if b*c<a:
print(-1)
else:
key = a//(d*b)
heal = ((1+key)*key)>>1
# print(key)
print(a*(key+1)-heal*b*d)
```
|
instruction
| 0
| 16,172
| 2
| 32,344
|
Yes
|
output
| 1
| 16,172
| 2
| 32,345
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.