text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Provide a correct Python 3 solution for this coding contest problem.
Given is a string S consisting of lowercase English letters. Find the maximum positive integer K that satisfies the following condition:
* There exists a partition of S into K non-empty strings S=S_1S_2...S_K such that S_i \neq S_{i+1} (1 \leq i \leq K-1).
Here S_1S_2...S_K represents the concatenation of S_1,S_2,...,S_K in this order.
Constraints
* 1 \leq |S| \leq 2 \times 10^5
* S consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
S
Output
Print the maximum positive integer K that satisfies the condition.
Examples
Input
aabbaa
Output
4
Input
aaaccacabaababc
Output
12
"Correct Solution:
```
a=0;t=c=""
for i in input():
t+=i
if c!=t:
a+=1;c=t;t=""
print(a)
```
| 99,300 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given is a string S consisting of lowercase English letters. Find the maximum positive integer K that satisfies the following condition:
* There exists a partition of S into K non-empty strings S=S_1S_2...S_K such that S_i \neq S_{i+1} (1 \leq i \leq K-1).
Here S_1S_2...S_K represents the concatenation of S_1,S_2,...,S_K in this order.
Constraints
* 1 \leq |S| \leq 2 \times 10^5
* S consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
S
Output
Print the maximum positive integer K that satisfies the condition.
Examples
Input
aabbaa
Output
4
Input
aaaccacabaababc
Output
12
Submitted Solution:
```
s = input()
t = ''
a = ['-1']
for i in s:
t += i
if t != a[-1]:
a += [t]
t = ''
print(len(a)-1)
```
Yes
| 99,301 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given is a string S consisting of lowercase English letters. Find the maximum positive integer K that satisfies the following condition:
* There exists a partition of S into K non-empty strings S=S_1S_2...S_K such that S_i \neq S_{i+1} (1 \leq i \leq K-1).
Here S_1S_2...S_K represents the concatenation of S_1,S_2,...,S_K in this order.
Constraints
* 1 \leq |S| \leq 2 \times 10^5
* S consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
S
Output
Print the maximum positive integer K that satisfies the condition.
Examples
Input
aabbaa
Output
4
Input
aaaccacabaababc
Output
12
Submitted Solution:
```
s = input()
prev = ''
p = 0
count = 0
for i in range(1, len(s) + 1):
if s[p:i] != prev:
prev = s[p:i]
p = i
count += 1
print(count)
```
Yes
| 99,302 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given is a string S consisting of lowercase English letters. Find the maximum positive integer K that satisfies the following condition:
* There exists a partition of S into K non-empty strings S=S_1S_2...S_K such that S_i \neq S_{i+1} (1 \leq i \leq K-1).
Here S_1S_2...S_K represents the concatenation of S_1,S_2,...,S_K in this order.
Constraints
* 1 \leq |S| \leq 2 \times 10^5
* S consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
S
Output
Print the maximum positive integer K that satisfies the condition.
Examples
Input
aabbaa
Output
4
Input
aaaccacabaababc
Output
12
Submitted Solution:
```
s = input()
f = False
ans = 0
buf = None
for c in s:
if f:
f = False
buf = None
ans += 1
elif c == buf:
f = True
else:
buf = c
ans += 1
print(ans)
```
Yes
| 99,303 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given is a string S consisting of lowercase English letters. Find the maximum positive integer K that satisfies the following condition:
* There exists a partition of S into K non-empty strings S=S_1S_2...S_K such that S_i \neq S_{i+1} (1 \leq i \leq K-1).
Here S_1S_2...S_K represents the concatenation of S_1,S_2,...,S_K in this order.
Constraints
* 1 \leq |S| \leq 2 \times 10^5
* S consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
S
Output
Print the maximum positive integer K that satisfies the condition.
Examples
Input
aabbaa
Output
4
Input
aaaccacabaababc
Output
12
Submitted Solution:
```
s = input()
prev = '1'
count = 0
now = ''
for i in s:
now = now + i
if now != prev:
count+=1
prev = now
now = ''
print(count)
```
Yes
| 99,304 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given is a string S consisting of lowercase English letters. Find the maximum positive integer K that satisfies the following condition:
* There exists a partition of S into K non-empty strings S=S_1S_2...S_K such that S_i \neq S_{i+1} (1 \leq i \leq K-1).
Here S_1S_2...S_K represents the concatenation of S_1,S_2,...,S_K in this order.
Constraints
* 1 \leq |S| \leq 2 \times 10^5
* S consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
S
Output
Print the maximum positive integer K that satisfies the condition.
Examples
Input
aabbaa
Output
4
Input
aaaccacabaababc
Output
12
Submitted Solution:
```
S = input()
count = 0
start = 0
end = 1
hold_value = ""
while end <= len(S):
if hold_value == S[start:end]:
end += 1
else:
hold_value = S[start:end]
print(hold_value)
start = end
end += 1
count += 1
print(count)
```
No
| 99,305 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given is a string S consisting of lowercase English letters. Find the maximum positive integer K that satisfies the following condition:
* There exists a partition of S into K non-empty strings S=S_1S_2...S_K such that S_i \neq S_{i+1} (1 \leq i \leq K-1).
Here S_1S_2...S_K represents the concatenation of S_1,S_2,...,S_K in this order.
Constraints
* 1 \leq |S| \leq 2 \times 10^5
* S consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
S
Output
Print the maximum positive integer K that satisfies the condition.
Examples
Input
aabbaa
Output
4
Input
aaaccacabaababc
Output
12
Submitted Solution:
```
def main():
import itertools
s=itertools.groupby(str(input()))
ans=0
for k,v in s:
l=len(list(v))
if l<=2:
ans+=1
else:
ans+=l//2+1
print(ans)
if __name__=="__main__":
main()
```
No
| 99,306 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given is a string S consisting of lowercase English letters. Find the maximum positive integer K that satisfies the following condition:
* There exists a partition of S into K non-empty strings S=S_1S_2...S_K such that S_i \neq S_{i+1} (1 \leq i \leq K-1).
Here S_1S_2...S_K represents the concatenation of S_1,S_2,...,S_K in this order.
Constraints
* 1 \leq |S| \leq 2 \times 10^5
* S consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
S
Output
Print the maximum positive integer K that satisfies the condition.
Examples
Input
aabbaa
Output
4
Input
aaaccacabaababc
Output
12
Submitted Solution:
```
import numpy as np
s = input().strip()
dp = np.zeros((len(s), 2), dtype=np.int)
# 初期値
dp[0][0] = 0
dp[0][1] = 0
dp[1][0] = 1
dp[1][1] = 0
for i in range(2, len(s)):
d00 = dp[i - 1][0] + 1 if s[i] != s[i - 1] else -1
d01 = dp[i - 1][1] + 1
dp[i][0] = max(d00, d01)
d10 = dp[i - 2][0] + 1
d11 = dp[i - 2][1] + 1 if i < 3 or s[i-1:i+1] != s[i-3:i-1] else -1
dp[i][1] = max(d10, d11)
ans = max(dp[-1][0], dp[-1][1])
print(ans)
```
No
| 99,307 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given is a string S consisting of lowercase English letters. Find the maximum positive integer K that satisfies the following condition:
* There exists a partition of S into K non-empty strings S=S_1S_2...S_K such that S_i \neq S_{i+1} (1 \leq i \leq K-1).
Here S_1S_2...S_K represents the concatenation of S_1,S_2,...,S_K in this order.
Constraints
* 1 \leq |S| \leq 2 \times 10^5
* S consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
S
Output
Print the maximum positive integer K that satisfies the condition.
Examples
Input
aabbaa
Output
4
Input
aaaccacabaababc
Output
12
Submitted Solution:
```
s = list(input())
if len(s) == 1:
print(1)
exit()
elif len(s) == 2:
if s[0] == s[1]:
print(1)
else:
print(2)
exit()
else:
dp = [0]*len(s)
if s[0]==s[1] and s[1]==s[2]:
dp[0:3]=[1,2,2]
elif s[0]==s[1] and s[1]!=s[2]:
dp[0:3]=[1,1,2]
elif s[0]!=s[1] and s[1]==s[2]:
dp[0:3]=[1,2,2]
else:
dp[0:3]=[1,2,3]
for i in range(3, len(s)):
if s[i] != s[i-1]:
dp[i] += dp[i-1]+1
else:
dp[i] += dp[i-3]+2
print(dp[-1])
```
No
| 99,308 |
Provide a correct Python 3 solution for this coding contest problem.
The restaurant AtCoder serves the following five dishes:
* ABC Don (rice bowl): takes A minutes to serve.
* ARC Curry: takes B minutes to serve.
* AGC Pasta: takes C minutes to serve.
* APC Ramen: takes D minutes to serve.
* ATC Hanbagu (hamburger patty): takes E minutes to serve.
Here, the time to serve a dish is the time between when an order is placed and when the dish is delivered.
This restaurant has the following rules on orders:
* An order can only be placed at a time that is a multiple of 10 (time 0, 10, 20, ...).
* Only one dish can be ordered at a time.
* No new order can be placed when an order is already placed and the dish is still not delivered, but a new order can be placed at the exact time when the dish is delivered.
E869120 arrives at this restaurant at time 0. He will order all five dishes. Find the earliest possible time for the last dish to be delivered.
Here, he can order the dishes in any order he likes, and he can place an order already at time 0.
Constraints
* A, B, C, D and E are integers between 1 and 123 (inclusive).
Input
Input is given from Standard Input in the following format:
A
B
C
D
E
Output
Print the earliest possible time for the last dish to be delivered, as an integer.
Examples
Input
29
20
7
35
120
Output
215
Input
101
86
119
108
57
Output
481
Input
123
123
123
123
123
Output
643
"Correct Solution:
```
*a,=map(int,open(0));print(min(~-i%10for i in a)-sum(-i//10*10for i in a)-9)
```
| 99,309 |
Provide a correct Python 3 solution for this coding contest problem.
The restaurant AtCoder serves the following five dishes:
* ABC Don (rice bowl): takes A minutes to serve.
* ARC Curry: takes B minutes to serve.
* AGC Pasta: takes C minutes to serve.
* APC Ramen: takes D minutes to serve.
* ATC Hanbagu (hamburger patty): takes E minutes to serve.
Here, the time to serve a dish is the time between when an order is placed and when the dish is delivered.
This restaurant has the following rules on orders:
* An order can only be placed at a time that is a multiple of 10 (time 0, 10, 20, ...).
* Only one dish can be ordered at a time.
* No new order can be placed when an order is already placed and the dish is still not delivered, but a new order can be placed at the exact time when the dish is delivered.
E869120 arrives at this restaurant at time 0. He will order all five dishes. Find the earliest possible time for the last dish to be delivered.
Here, he can order the dishes in any order he likes, and he can place an order already at time 0.
Constraints
* A, B, C, D and E are integers between 1 and 123 (inclusive).
Input
Input is given from Standard Input in the following format:
A
B
C
D
E
Output
Print the earliest possible time for the last dish to be delivered, as an integer.
Examples
Input
29
20
7
35
120
Output
215
Input
101
86
119
108
57
Output
481
Input
123
123
123
123
123
Output
643
"Correct Solution:
```
dish = [int(input()) for i in range(5)]
reeltime = sorted([10 - (x%10) if x%10 != 0 else (x%10) for x in dish])
print(sum(dish)+sum(reeltime[:-1]))
```
| 99,310 |
Provide a correct Python 3 solution for this coding contest problem.
The restaurant AtCoder serves the following five dishes:
* ABC Don (rice bowl): takes A minutes to serve.
* ARC Curry: takes B minutes to serve.
* AGC Pasta: takes C minutes to serve.
* APC Ramen: takes D minutes to serve.
* ATC Hanbagu (hamburger patty): takes E minutes to serve.
Here, the time to serve a dish is the time between when an order is placed and when the dish is delivered.
This restaurant has the following rules on orders:
* An order can only be placed at a time that is a multiple of 10 (time 0, 10, 20, ...).
* Only one dish can be ordered at a time.
* No new order can be placed when an order is already placed and the dish is still not delivered, but a new order can be placed at the exact time when the dish is delivered.
E869120 arrives at this restaurant at time 0. He will order all five dishes. Find the earliest possible time for the last dish to be delivered.
Here, he can order the dishes in any order he likes, and he can place an order already at time 0.
Constraints
* A, B, C, D and E are integers between 1 and 123 (inclusive).
Input
Input is given from Standard Input in the following format:
A
B
C
D
E
Output
Print the earliest possible time for the last dish to be delivered, as an integer.
Examples
Input
29
20
7
35
120
Output
215
Input
101
86
119
108
57
Output
481
Input
123
123
123
123
123
Output
643
"Correct Solution:
```
abcde = [int(input()) for _ in range(5)]
s = list(map(lambda x: (10-x%10)%10, abcde))
print(sum(abcde)+sum(s)-max(s))
```
| 99,311 |
Provide a correct Python 3 solution for this coding contest problem.
The restaurant AtCoder serves the following five dishes:
* ABC Don (rice bowl): takes A minutes to serve.
* ARC Curry: takes B minutes to serve.
* AGC Pasta: takes C minutes to serve.
* APC Ramen: takes D minutes to serve.
* ATC Hanbagu (hamburger patty): takes E minutes to serve.
Here, the time to serve a dish is the time between when an order is placed and when the dish is delivered.
This restaurant has the following rules on orders:
* An order can only be placed at a time that is a multiple of 10 (time 0, 10, 20, ...).
* Only one dish can be ordered at a time.
* No new order can be placed when an order is already placed and the dish is still not delivered, but a new order can be placed at the exact time when the dish is delivered.
E869120 arrives at this restaurant at time 0. He will order all five dishes. Find the earliest possible time for the last dish to be delivered.
Here, he can order the dishes in any order he likes, and he can place an order already at time 0.
Constraints
* A, B, C, D and E are integers between 1 and 123 (inclusive).
Input
Input is given from Standard Input in the following format:
A
B
C
D
E
Output
Print the earliest possible time for the last dish to be delivered, as an integer.
Examples
Input
29
20
7
35
120
Output
215
Input
101
86
119
108
57
Output
481
Input
123
123
123
123
123
Output
643
"Correct Solution:
```
a=[int(input()) for _ in [0]*5]
b=[-(-i//10)*10-i for i in a]
print(sum(b)+sum(a)-max(b))
```
| 99,312 |
Provide a correct Python 3 solution for this coding contest problem.
The restaurant AtCoder serves the following five dishes:
* ABC Don (rice bowl): takes A minutes to serve.
* ARC Curry: takes B minutes to serve.
* AGC Pasta: takes C minutes to serve.
* APC Ramen: takes D minutes to serve.
* ATC Hanbagu (hamburger patty): takes E minutes to serve.
Here, the time to serve a dish is the time between when an order is placed and when the dish is delivered.
This restaurant has the following rules on orders:
* An order can only be placed at a time that is a multiple of 10 (time 0, 10, 20, ...).
* Only one dish can be ordered at a time.
* No new order can be placed when an order is already placed and the dish is still not delivered, but a new order can be placed at the exact time when the dish is delivered.
E869120 arrives at this restaurant at time 0. He will order all five dishes. Find the earliest possible time for the last dish to be delivered.
Here, he can order the dishes in any order he likes, and he can place an order already at time 0.
Constraints
* A, B, C, D and E are integers between 1 and 123 (inclusive).
Input
Input is given from Standard Input in the following format:
A
B
C
D
E
Output
Print the earliest possible time for the last dish to be delivered, as an integer.
Examples
Input
29
20
7
35
120
Output
215
Input
101
86
119
108
57
Output
481
Input
123
123
123
123
123
Output
643
"Correct Solution:
```
import math
l = [int(input()) for _ in range(5)]
l2 = [math.ceil(i/10)*10 for i in l]
diff = max([i-j for i,j in zip(l2,l)])
print(sum(l2) - diff)
```
| 99,313 |
Provide a correct Python 3 solution for this coding contest problem.
The restaurant AtCoder serves the following five dishes:
* ABC Don (rice bowl): takes A minutes to serve.
* ARC Curry: takes B minutes to serve.
* AGC Pasta: takes C minutes to serve.
* APC Ramen: takes D minutes to serve.
* ATC Hanbagu (hamburger patty): takes E minutes to serve.
Here, the time to serve a dish is the time between when an order is placed and when the dish is delivered.
This restaurant has the following rules on orders:
* An order can only be placed at a time that is a multiple of 10 (time 0, 10, 20, ...).
* Only one dish can be ordered at a time.
* No new order can be placed when an order is already placed and the dish is still not delivered, but a new order can be placed at the exact time when the dish is delivered.
E869120 arrives at this restaurant at time 0. He will order all five dishes. Find the earliest possible time for the last dish to be delivered.
Here, he can order the dishes in any order he likes, and he can place an order already at time 0.
Constraints
* A, B, C, D and E are integers between 1 and 123 (inclusive).
Input
Input is given from Standard Input in the following format:
A
B
C
D
E
Output
Print the earliest possible time for the last dish to be delivered, as an integer.
Examples
Input
29
20
7
35
120
Output
215
Input
101
86
119
108
57
Output
481
Input
123
123
123
123
123
Output
643
"Correct Solution:
```
Time = [int(input()) for X in range(0,5)]
Loss = [(10-X%10)%10 for X in Time]
print(sum(Time)+sum(sorted(Loss)[:4]))
```
| 99,314 |
Provide a correct Python 3 solution for this coding contest problem.
The restaurant AtCoder serves the following five dishes:
* ABC Don (rice bowl): takes A minutes to serve.
* ARC Curry: takes B minutes to serve.
* AGC Pasta: takes C minutes to serve.
* APC Ramen: takes D minutes to serve.
* ATC Hanbagu (hamburger patty): takes E minutes to serve.
Here, the time to serve a dish is the time between when an order is placed and when the dish is delivered.
This restaurant has the following rules on orders:
* An order can only be placed at a time that is a multiple of 10 (time 0, 10, 20, ...).
* Only one dish can be ordered at a time.
* No new order can be placed when an order is already placed and the dish is still not delivered, but a new order can be placed at the exact time when the dish is delivered.
E869120 arrives at this restaurant at time 0. He will order all five dishes. Find the earliest possible time for the last dish to be delivered.
Here, he can order the dishes in any order he likes, and he can place an order already at time 0.
Constraints
* A, B, C, D and E are integers between 1 and 123 (inclusive).
Input
Input is given from Standard Input in the following format:
A
B
C
D
E
Output
Print the earliest possible time for the last dish to be delivered, as an integer.
Examples
Input
29
20
7
35
120
Output
215
Input
101
86
119
108
57
Output
481
Input
123
123
123
123
123
Output
643
"Correct Solution:
```
lis = [int(input()) for _ in range(5)]
times = [(l + 9) // 10 * 10 for l in lis]
loss = [(10 - l % 10) % 10 for l in lis]
print(sum(times) - max(loss))
```
| 99,315 |
Provide a correct Python 3 solution for this coding contest problem.
The restaurant AtCoder serves the following five dishes:
* ABC Don (rice bowl): takes A minutes to serve.
* ARC Curry: takes B minutes to serve.
* AGC Pasta: takes C minutes to serve.
* APC Ramen: takes D minutes to serve.
* ATC Hanbagu (hamburger patty): takes E minutes to serve.
Here, the time to serve a dish is the time between when an order is placed and when the dish is delivered.
This restaurant has the following rules on orders:
* An order can only be placed at a time that is a multiple of 10 (time 0, 10, 20, ...).
* Only one dish can be ordered at a time.
* No new order can be placed when an order is already placed and the dish is still not delivered, but a new order can be placed at the exact time when the dish is delivered.
E869120 arrives at this restaurant at time 0. He will order all five dishes. Find the earliest possible time for the last dish to be delivered.
Here, he can order the dishes in any order he likes, and he can place an order already at time 0.
Constraints
* A, B, C, D and E are integers between 1 and 123 (inclusive).
Input
Input is given from Standard Input in the following format:
A
B
C
D
E
Output
Print the earliest possible time for the last dish to be delivered, as an integer.
Examples
Input
29
20
7
35
120
Output
215
Input
101
86
119
108
57
Output
481
Input
123
123
123
123
123
Output
643
"Correct Solution:
```
a=[int(input()) for _ in range(5)]
import math
b=[math.ceil(i/10)*10-i for i in a]
print(sum(a)+sum(b)-max(b))
```
| 99,316 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The restaurant AtCoder serves the following five dishes:
* ABC Don (rice bowl): takes A minutes to serve.
* ARC Curry: takes B minutes to serve.
* AGC Pasta: takes C minutes to serve.
* APC Ramen: takes D minutes to serve.
* ATC Hanbagu (hamburger patty): takes E minutes to serve.
Here, the time to serve a dish is the time between when an order is placed and when the dish is delivered.
This restaurant has the following rules on orders:
* An order can only be placed at a time that is a multiple of 10 (time 0, 10, 20, ...).
* Only one dish can be ordered at a time.
* No new order can be placed when an order is already placed and the dish is still not delivered, but a new order can be placed at the exact time when the dish is delivered.
E869120 arrives at this restaurant at time 0. He will order all five dishes. Find the earliest possible time for the last dish to be delivered.
Here, he can order the dishes in any order he likes, and he can place an order already at time 0.
Constraints
* A, B, C, D and E are integers between 1 and 123 (inclusive).
Input
Input is given from Standard Input in the following format:
A
B
C
D
E
Output
Print the earliest possible time for the last dish to be delivered, as an integer.
Examples
Input
29
20
7
35
120
Output
215
Input
101
86
119
108
57
Output
481
Input
123
123
123
123
123
Output
643
Submitted Solution:
```
x = [int(input()) for i in range(5)]
ans = 0
gap = []
for i in x:
y = -i//10 * -10
ans += y
gap.append(y-i)
ans = ans - max(gap)
print(ans)
```
Yes
| 99,317 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The restaurant AtCoder serves the following five dishes:
* ABC Don (rice bowl): takes A minutes to serve.
* ARC Curry: takes B minutes to serve.
* AGC Pasta: takes C minutes to serve.
* APC Ramen: takes D minutes to serve.
* ATC Hanbagu (hamburger patty): takes E minutes to serve.
Here, the time to serve a dish is the time between when an order is placed and when the dish is delivered.
This restaurant has the following rules on orders:
* An order can only be placed at a time that is a multiple of 10 (time 0, 10, 20, ...).
* Only one dish can be ordered at a time.
* No new order can be placed when an order is already placed and the dish is still not delivered, but a new order can be placed at the exact time when the dish is delivered.
E869120 arrives at this restaurant at time 0. He will order all five dishes. Find the earliest possible time for the last dish to be delivered.
Here, he can order the dishes in any order he likes, and he can place an order already at time 0.
Constraints
* A, B, C, D and E are integers between 1 and 123 (inclusive).
Input
Input is given from Standard Input in the following format:
A
B
C
D
E
Output
Print the earliest possible time for the last dish to be delivered, as an integer.
Examples
Input
29
20
7
35
120
Output
215
Input
101
86
119
108
57
Output
481
Input
123
123
123
123
123
Output
643
Submitted Solution:
```
e,*a=sorted(eval('int(input()),'*5),key=lambda x:~-x%10);print(e-sum(-i//10*10for i in a))
```
Yes
| 99,318 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The restaurant AtCoder serves the following five dishes:
* ABC Don (rice bowl): takes A minutes to serve.
* ARC Curry: takes B minutes to serve.
* AGC Pasta: takes C minutes to serve.
* APC Ramen: takes D minutes to serve.
* ATC Hanbagu (hamburger patty): takes E minutes to serve.
Here, the time to serve a dish is the time between when an order is placed and when the dish is delivered.
This restaurant has the following rules on orders:
* An order can only be placed at a time that is a multiple of 10 (time 0, 10, 20, ...).
* Only one dish can be ordered at a time.
* No new order can be placed when an order is already placed and the dish is still not delivered, but a new order can be placed at the exact time when the dish is delivered.
E869120 arrives at this restaurant at time 0. He will order all five dishes. Find the earliest possible time for the last dish to be delivered.
Here, he can order the dishes in any order he likes, and he can place an order already at time 0.
Constraints
* A, B, C, D and E are integers between 1 and 123 (inclusive).
Input
Input is given from Standard Input in the following format:
A
B
C
D
E
Output
Print the earliest possible time for the last dish to be delivered, as an integer.
Examples
Input
29
20
7
35
120
Output
215
Input
101
86
119
108
57
Output
481
Input
123
123
123
123
123
Output
643
Submitted Solution:
```
time=[]
ans=0
for i in range(5):
A=int(input())
a=10-A%10
ans+=A+a%10
time.append(a%10)
time.sort()
ans-=time[-1]
print(ans)
```
Yes
| 99,319 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The restaurant AtCoder serves the following five dishes:
* ABC Don (rice bowl): takes A minutes to serve.
* ARC Curry: takes B minutes to serve.
* AGC Pasta: takes C minutes to serve.
* APC Ramen: takes D minutes to serve.
* ATC Hanbagu (hamburger patty): takes E minutes to serve.
Here, the time to serve a dish is the time between when an order is placed and when the dish is delivered.
This restaurant has the following rules on orders:
* An order can only be placed at a time that is a multiple of 10 (time 0, 10, 20, ...).
* Only one dish can be ordered at a time.
* No new order can be placed when an order is already placed and the dish is still not delivered, but a new order can be placed at the exact time when the dish is delivered.
E869120 arrives at this restaurant at time 0. He will order all five dishes. Find the earliest possible time for the last dish to be delivered.
Here, he can order the dishes in any order he likes, and he can place an order already at time 0.
Constraints
* A, B, C, D and E are integers between 1 and 123 (inclusive).
Input
Input is given from Standard Input in the following format:
A
B
C
D
E
Output
Print the earliest possible time for the last dish to be delivered, as an integer.
Examples
Input
29
20
7
35
120
Output
215
Input
101
86
119
108
57
Output
481
Input
123
123
123
123
123
Output
643
Submitted Solution:
```
time = list(int(input()) for i in range(5))
def f(x):
return (10-x%10)%10
b = list(map(f, time))
ans = sum(time) + sum(b) - max(b)
print(ans)
```
Yes
| 99,320 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The restaurant AtCoder serves the following five dishes:
* ABC Don (rice bowl): takes A minutes to serve.
* ARC Curry: takes B minutes to serve.
* AGC Pasta: takes C minutes to serve.
* APC Ramen: takes D minutes to serve.
* ATC Hanbagu (hamburger patty): takes E minutes to serve.
Here, the time to serve a dish is the time between when an order is placed and when the dish is delivered.
This restaurant has the following rules on orders:
* An order can only be placed at a time that is a multiple of 10 (time 0, 10, 20, ...).
* Only one dish can be ordered at a time.
* No new order can be placed when an order is already placed and the dish is still not delivered, but a new order can be placed at the exact time when the dish is delivered.
E869120 arrives at this restaurant at time 0. He will order all five dishes. Find the earliest possible time for the last dish to be delivered.
Here, he can order the dishes in any order he likes, and he can place an order already at time 0.
Constraints
* A, B, C, D and E are integers between 1 and 123 (inclusive).
Input
Input is given from Standard Input in the following format:
A
B
C
D
E
Output
Print the earliest possible time for the last dish to be delivered, as an integer.
Examples
Input
29
20
7
35
120
Output
215
Input
101
86
119
108
57
Output
481
Input
123
123
123
123
123
Output
643
Submitted Solution:
```
import numpy as np
A = int(input())
B = int(input())
C = int(input())
D = int(input())
E = int(input())
a = A % 10
b = B % 10
c = C % 10
d = D % 10
e = E % 10
aa = A // 10
bb = B // 10
cc = C // 10
dd = D // 10
ee = E // 10
r = np.array([a, b, c, d, e])
k = (r > 0).sum()
l = r[r != 0].min()
print((aa + bb + cc + dd + ee) * 10 + 10*(k-1) + l)
```
No
| 99,321 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The restaurant AtCoder serves the following five dishes:
* ABC Don (rice bowl): takes A minutes to serve.
* ARC Curry: takes B minutes to serve.
* AGC Pasta: takes C minutes to serve.
* APC Ramen: takes D minutes to serve.
* ATC Hanbagu (hamburger patty): takes E minutes to serve.
Here, the time to serve a dish is the time between when an order is placed and when the dish is delivered.
This restaurant has the following rules on orders:
* An order can only be placed at a time that is a multiple of 10 (time 0, 10, 20, ...).
* Only one dish can be ordered at a time.
* No new order can be placed when an order is already placed and the dish is still not delivered, but a new order can be placed at the exact time when the dish is delivered.
E869120 arrives at this restaurant at time 0. He will order all five dishes. Find the earliest possible time for the last dish to be delivered.
Here, he can order the dishes in any order he likes, and he can place an order already at time 0.
Constraints
* A, B, C, D and E are integers between 1 and 123 (inclusive).
Input
Input is given from Standard Input in the following format:
A
B
C
D
E
Output
Print the earliest possible time for the last dish to be delivered, as an integer.
Examples
Input
29
20
7
35
120
Output
215
Input
101
86
119
108
57
Output
481
Input
123
123
123
123
123
Output
643
Submitted Solution:
```
d=[int(input()) for i in range(5)]
d2=[j+(10-j%10) for j in d]
d_mod=[10-k%10 for k in d]
ans=sum(d2)-max(d_mod)
print(ans)
```
No
| 99,322 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The restaurant AtCoder serves the following five dishes:
* ABC Don (rice bowl): takes A minutes to serve.
* ARC Curry: takes B minutes to serve.
* AGC Pasta: takes C minutes to serve.
* APC Ramen: takes D minutes to serve.
* ATC Hanbagu (hamburger patty): takes E minutes to serve.
Here, the time to serve a dish is the time between when an order is placed and when the dish is delivered.
This restaurant has the following rules on orders:
* An order can only be placed at a time that is a multiple of 10 (time 0, 10, 20, ...).
* Only one dish can be ordered at a time.
* No new order can be placed when an order is already placed and the dish is still not delivered, but a new order can be placed at the exact time when the dish is delivered.
E869120 arrives at this restaurant at time 0. He will order all five dishes. Find the earliest possible time for the last dish to be delivered.
Here, he can order the dishes in any order he likes, and he can place an order already at time 0.
Constraints
* A, B, C, D and E are integers between 1 and 123 (inclusive).
Input
Input is given from Standard Input in the following format:
A
B
C
D
E
Output
Print the earliest possible time for the last dish to be delivered, as an integer.
Examples
Input
29
20
7
35
120
Output
215
Input
101
86
119
108
57
Output
481
Input
123
123
123
123
123
Output
643
Submitted Solution:
```
order_time = [0, 0, 0, 0, 0]
order = len(order_time)
time = 0
last_order = 9
count_change = 0
for i in range(0, order):
order_time[i] = int(input())
if (order_time[i] % 10 != 0) and (order_time[i] % 10 <= last_order % 10):
last_order = order_time[i]
count_change += 1
if count_change == 0:
last_order = order_time[i]
for i in range(0, order):
if order_time[i] % 10 != 0:
time += order_time[i] // 10 * 10 + 10
else:
time += order_time[i]
time -= last_order // 10 * 10 + 10
time += last_order
print(time)
order_time = [0, 0, 0, 0, 0]
order = len(order_time)
time = 0
last_order = 9
count_change = 0
for i in range(0, order):
order_time[i] = int(input())
if (order_time[i] % 10 != 0) and (order_time[i] % 10 <= last_order % 10):
last_order = order_time[i]
count_change += 1
for i in range(0, order):
if order_time[i] % 10 != 0:
time += order_time[i] // 10 * 10 + 10
else:
time += order_time[i]
if count_change == 0:
last_order = order_time[i]
else:
time -= last_order // 10 * 10 + 10
time += last_order
print(time)
```
No
| 99,323 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The restaurant AtCoder serves the following five dishes:
* ABC Don (rice bowl): takes A minutes to serve.
* ARC Curry: takes B minutes to serve.
* AGC Pasta: takes C minutes to serve.
* APC Ramen: takes D minutes to serve.
* ATC Hanbagu (hamburger patty): takes E minutes to serve.
Here, the time to serve a dish is the time between when an order is placed and when the dish is delivered.
This restaurant has the following rules on orders:
* An order can only be placed at a time that is a multiple of 10 (time 0, 10, 20, ...).
* Only one dish can be ordered at a time.
* No new order can be placed when an order is already placed and the dish is still not delivered, but a new order can be placed at the exact time when the dish is delivered.
E869120 arrives at this restaurant at time 0. He will order all five dishes. Find the earliest possible time for the last dish to be delivered.
Here, he can order the dishes in any order he likes, and he can place an order already at time 0.
Constraints
* A, B, C, D and E are integers between 1 and 123 (inclusive).
Input
Input is given from Standard Input in the following format:
A
B
C
D
E
Output
Print the earliest possible time for the last dish to be delivered, as an integer.
Examples
Input
29
20
7
35
120
Output
215
Input
101
86
119
108
57
Output
481
Input
123
123
123
123
123
Output
643
Submitted Solution:
```
# ABC123
# Five Dishes
#B=A R=B G=C P=D T=E
Ryori = [input() for _ in range(5)]
O = []
t = 0
for i in Ryori:
print(i)
if int(i[-1]) == 0:
x = Ryori.pop(Ryori.index(i))
O.append(x)
Ryori = sorted(Ryori,key=lambda x: x[-1], reverse=True)
for i in range(len(Ryori)-1):
for j in range(10):
if (int(Ryori[i]) + j) % 10 == 0:
t += int(Ryori[i]) + j
t += int(Ryori[-1])
for i in O:
t += int(i)
print(t)
```
No
| 99,324 |
Provide a correct Python 3 solution for this coding contest problem.
Niwango-kun has \\(N\\) chickens as his pets. The chickens are identified by numbers \\(1\\) to \\(N\\), and the size of the \\(i\\)-th chicken is a positive integer \\(a_i\\).
\\(N\\) chickens decided to take each other's hand (wing) and form some cycles. The way to make cycles is represented by a permutation \\(p\\) of \\(1, \ldots , N\\). Chicken \\(i\\) takes chicken \\(p_i\\)'s left hand by its right hand. Chickens may take their own hand.
Let us define the cycle containing chicken \\(i\\) as the set consisting of chickens \\(p_i, p_{p_i}, \ldots, p_{\ddots_i} = i\\). It can be proven that after each chicken takes some chicken's hand, the \\(N\\) chickens can be decomposed into cycles.
The beauty \\(f(p)\\) of a way of forming cycles is defined as the product of the size of the smallest chicken in each cycle. Let \\(b_i \ (1 \leq i \leq N)\\) be the sum of \\(f(p)\\) among all possible permutations \\(p\\) for which \\(i\\) cycles are formed in the procedure above.
Find the greatest common divisor of \\(b_1, b_2, \ldots, b_N\\) and print it \\({\rm mod} \ 998244353\\).
Constraints
* \\(1 \leq N \leq 10^5\\)
* \\(1 \leq a_i \leq 10^9\\)
* All numbers given in input are integers
Input
Input is given from Standard Input in the following format:
\(N\)
\(a_1\) \(a_2\) \(\ldots\) \(a_N\)
Output
Print the answer.
Examples
Input
2
4 3
Output
3
Input
4
2 5 2 5
Output
2
"Correct Solution:
```
from math import gcd
mod=998244353
N=int(input())
a=list(map(int,input().split()))
a.sort()
ans=1
for i in range(N):
g=gcd(i,a[i])
ans=(ans*g)%mod
print(ans)
```
| 99,325 |
Provide a correct Python 3 solution for this coding contest problem.
Niwango-kun has \\(N\\) chickens as his pets. The chickens are identified by numbers \\(1\\) to \\(N\\), and the size of the \\(i\\)-th chicken is a positive integer \\(a_i\\).
\\(N\\) chickens decided to take each other's hand (wing) and form some cycles. The way to make cycles is represented by a permutation \\(p\\) of \\(1, \ldots , N\\). Chicken \\(i\\) takes chicken \\(p_i\\)'s left hand by its right hand. Chickens may take their own hand.
Let us define the cycle containing chicken \\(i\\) as the set consisting of chickens \\(p_i, p_{p_i}, \ldots, p_{\ddots_i} = i\\). It can be proven that after each chicken takes some chicken's hand, the \\(N\\) chickens can be decomposed into cycles.
The beauty \\(f(p)\\) of a way of forming cycles is defined as the product of the size of the smallest chicken in each cycle. Let \\(b_i \ (1 \leq i \leq N)\\) be the sum of \\(f(p)\\) among all possible permutations \\(p\\) for which \\(i\\) cycles are formed in the procedure above.
Find the greatest common divisor of \\(b_1, b_2, \ldots, b_N\\) and print it \\({\rm mod} \ 998244353\\).
Constraints
* \\(1 \leq N \leq 10^5\\)
* \\(1 \leq a_i \leq 10^9\\)
* All numbers given in input are integers
Input
Input is given from Standard Input in the following format:
\(N\)
\(a_1\) \(a_2\) \(\ldots\) \(a_N\)
Output
Print the answer.
Examples
Input
2
4 3
Output
3
Input
4
2 5 2 5
Output
2
"Correct Solution:
```
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)
from fractions import gcd
from functools import reduce
MOD = 998244353
N,*A = map(int,read().split())
A.sort()
"""
安い鳥から追加していく。(サイクルの個数 -> 美しさ)が多項式倍で遷移する。
Gaussの補題より、最大個数かけるだけ
"""
answer = reduce(lambda x,y: x*y%MOD, (gcd(i,x) for i,x in enumerate(A)))
print(answer)
```
| 99,326 |
Provide a correct Python 3 solution for this coding contest problem.
Niwango-kun has \\(N\\) chickens as his pets. The chickens are identified by numbers \\(1\\) to \\(N\\), and the size of the \\(i\\)-th chicken is a positive integer \\(a_i\\).
\\(N\\) chickens decided to take each other's hand (wing) and form some cycles. The way to make cycles is represented by a permutation \\(p\\) of \\(1, \ldots , N\\). Chicken \\(i\\) takes chicken \\(p_i\\)'s left hand by its right hand. Chickens may take their own hand.
Let us define the cycle containing chicken \\(i\\) as the set consisting of chickens \\(p_i, p_{p_i}, \ldots, p_{\ddots_i} = i\\). It can be proven that after each chicken takes some chicken's hand, the \\(N\\) chickens can be decomposed into cycles.
The beauty \\(f(p)\\) of a way of forming cycles is defined as the product of the size of the smallest chicken in each cycle. Let \\(b_i \ (1 \leq i \leq N)\\) be the sum of \\(f(p)\\) among all possible permutations \\(p\\) for which \\(i\\) cycles are formed in the procedure above.
Find the greatest common divisor of \\(b_1, b_2, \ldots, b_N\\) and print it \\({\rm mod} \ 998244353\\).
Constraints
* \\(1 \leq N \leq 10^5\\)
* \\(1 \leq a_i \leq 10^9\\)
* All numbers given in input are integers
Input
Input is given from Standard Input in the following format:
\(N\)
\(a_1\) \(a_2\) \(\ldots\) \(a_N\)
Output
Print the answer.
Examples
Input
2
4 3
Output
3
Input
4
2 5 2 5
Output
2
"Correct Solution:
```
N = int(input())
a = list(map(int,input().split()))
Mod = 998244353
def gcd(a, b):
while b:
a, b = b, a % b
return a
a.sort()
ans = 1
for i in range(N):
ans *= gcd(a[i],i)
ans %= Mod
print(ans)
```
| 99,327 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Niwango-kun has \\(N\\) chickens as his pets. The chickens are identified by numbers \\(1\\) to \\(N\\), and the size of the \\(i\\)-th chicken is a positive integer \\(a_i\\).
\\(N\\) chickens decided to take each other's hand (wing) and form some cycles. The way to make cycles is represented by a permutation \\(p\\) of \\(1, \ldots , N\\). Chicken \\(i\\) takes chicken \\(p_i\\)'s left hand by its right hand. Chickens may take their own hand.
Let us define the cycle containing chicken \\(i\\) as the set consisting of chickens \\(p_i, p_{p_i}, \ldots, p_{\ddots_i} = i\\). It can be proven that after each chicken takes some chicken's hand, the \\(N\\) chickens can be decomposed into cycles.
The beauty \\(f(p)\\) of a way of forming cycles is defined as the product of the size of the smallest chicken in each cycle. Let \\(b_i \ (1 \leq i \leq N)\\) be the sum of \\(f(p)\\) among all possible permutations \\(p\\) for which \\(i\\) cycles are formed in the procedure above.
Find the greatest common divisor of \\(b_1, b_2, \ldots, b_N\\) and print it \\({\rm mod} \ 998244353\\).
Constraints
* \\(1 \leq N \leq 10^5\\)
* \\(1 \leq a_i \leq 10^9\\)
* All numbers given in input are integers
Input
Input is given from Standard Input in the following format:
\(N\)
\(a_1\) \(a_2\) \(\ldots\) \(a_N\)
Output
Print the answer.
Examples
Input
2
4 3
Output
3
Input
4
2 5 2 5
Output
2
Submitted Solution:
```
N=int(input())
L=list(map(int,input().split()))
print(min(L))
```
No
| 99,328 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Niwango-kun has \\(N\\) chickens as his pets. The chickens are identified by numbers \\(1\\) to \\(N\\), and the size of the \\(i\\)-th chicken is a positive integer \\(a_i\\).
\\(N\\) chickens decided to take each other's hand (wing) and form some cycles. The way to make cycles is represented by a permutation \\(p\\) of \\(1, \ldots , N\\). Chicken \\(i\\) takes chicken \\(p_i\\)'s left hand by its right hand. Chickens may take their own hand.
Let us define the cycle containing chicken \\(i\\) as the set consisting of chickens \\(p_i, p_{p_i}, \ldots, p_{\ddots_i} = i\\). It can be proven that after each chicken takes some chicken's hand, the \\(N\\) chickens can be decomposed into cycles.
The beauty \\(f(p)\\) of a way of forming cycles is defined as the product of the size of the smallest chicken in each cycle. Let \\(b_i \ (1 \leq i \leq N)\\) be the sum of \\(f(p)\\) among all possible permutations \\(p\\) for which \\(i\\) cycles are formed in the procedure above.
Find the greatest common divisor of \\(b_1, b_2, \ldots, b_N\\) and print it \\({\rm mod} \ 998244353\\).
Constraints
* \\(1 \leq N \leq 10^5\\)
* \\(1 \leq a_i \leq 10^9\\)
* All numbers given in input are integers
Input
Input is given from Standard Input in the following format:
\(N\)
\(a_1\) \(a_2\) \(\ldots\) \(a_N\)
Output
Print the answer.
Examples
Input
2
4 3
Output
3
Input
4
2 5 2 5
Output
2
Submitted Solution:
```
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")
n = int(input())
a = list(map(int, input().split()))
ans = min(a)
print(ans)
```
No
| 99,329 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Niwango-kun has \\(N\\) chickens as his pets. The chickens are identified by numbers \\(1\\) to \\(N\\), and the size of the \\(i\\)-th chicken is a positive integer \\(a_i\\).
\\(N\\) chickens decided to take each other's hand (wing) and form some cycles. The way to make cycles is represented by a permutation \\(p\\) of \\(1, \ldots , N\\). Chicken \\(i\\) takes chicken \\(p_i\\)'s left hand by its right hand. Chickens may take their own hand.
Let us define the cycle containing chicken \\(i\\) as the set consisting of chickens \\(p_i, p_{p_i}, \ldots, p_{\ddots_i} = i\\). It can be proven that after each chicken takes some chicken's hand, the \\(N\\) chickens can be decomposed into cycles.
The beauty \\(f(p)\\) of a way of forming cycles is defined as the product of the size of the smallest chicken in each cycle. Let \\(b_i \ (1 \leq i \leq N)\\) be the sum of \\(f(p)\\) among all possible permutations \\(p\\) for which \\(i\\) cycles are formed in the procedure above.
Find the greatest common divisor of \\(b_1, b_2, \ldots, b_N\\) and print it \\({\rm mod} \ 998244353\\).
Constraints
* \\(1 \leq N \leq 10^5\\)
* \\(1 \leq a_i \leq 10^9\\)
* All numbers given in input are integers
Input
Input is given from Standard Input in the following format:
\(N\)
\(a_1\) \(a_2\) \(\ldots\) \(a_N\)
Output
Print the answer.
Examples
Input
2
4 3
Output
3
Input
4
2 5 2 5
Output
2
Submitted Solution:
```
N=int(input())
a=list(map(int,input().split()))
print(min(a))
```
No
| 99,330 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Niwango-kun has \\(N\\) chickens as his pets. The chickens are identified by numbers \\(1\\) to \\(N\\), and the size of the \\(i\\)-th chicken is a positive integer \\(a_i\\).
\\(N\\) chickens decided to take each other's hand (wing) and form some cycles. The way to make cycles is represented by a permutation \\(p\\) of \\(1, \ldots , N\\). Chicken \\(i\\) takes chicken \\(p_i\\)'s left hand by its right hand. Chickens may take their own hand.
Let us define the cycle containing chicken \\(i\\) as the set consisting of chickens \\(p_i, p_{p_i}, \ldots, p_{\ddots_i} = i\\). It can be proven that after each chicken takes some chicken's hand, the \\(N\\) chickens can be decomposed into cycles.
The beauty \\(f(p)\\) of a way of forming cycles is defined as the product of the size of the smallest chicken in each cycle. Let \\(b_i \ (1 \leq i \leq N)\\) be the sum of \\(f(p)\\) among all possible permutations \\(p\\) for which \\(i\\) cycles are formed in the procedure above.
Find the greatest common divisor of \\(b_1, b_2, \ldots, b_N\\) and print it \\({\rm mod} \ 998244353\\).
Constraints
* \\(1 \leq N \leq 10^5\\)
* \\(1 \leq a_i \leq 10^9\\)
* All numbers given in input are integers
Input
Input is given from Standard Input in the following format:
\(N\)
\(a_1\) \(a_2\) \(\ldots\) \(a_N\)
Output
Print the answer.
Examples
Input
2
4 3
Output
3
Input
4
2 5 2 5
Output
2
Submitted Solution:
```
import numpy as np
def main():
n = int(input())
a = list(map(int, input().split()))
m = np.mean(a)
r = a[np.argmin((a-m)**2)]
print(r)
main()
```
No
| 99,331 |
Provide a correct Python 3 solution for this coding contest problem.
Consider the following game:
* The game is played using a row of N squares and many stones.
* First, a_i stones are put in Square i\ (1 \leq i \leq N).
* A player can perform the following operation as many time as desired: "Select an integer i such that Square i contains exactly i stones. Remove all the stones from Square i, and add one stone to each of the i-1 squares from Square 1 to Square i-1."
* The final score of the player is the total number of the stones remaining in the squares.
For a sequence a of length N, let f(a) be the minimum score that can be obtained when the game is played on a.
Find the sum of f(a) over all sequences a of length N where each element is between 0 and K (inclusive). Since it can be extremely large, find the answer modulo 1000000007 (= 10^9+7).
Constraints
* 1 \leq N \leq 100
* 1 \leq K \leq N
Input
Input is given from Standard Input in the following format:
N K
Output
Print the sum of f(a) modulo 1000000007 (= 10^9+7).
Examples
Input
2 2
Output
10
Input
20 17
Output
983853488
"Correct Solution:
```
"""
https://atcoder.jp/contests/cf17-final/tasks/cf17_final_g
1回の操作で捨てられる石は1個
いくつ捨てられるかを考えた方がいいだろう
大きい方から?→そんなことはない
小さいほうから?→そんなことはない
今i=aiを満たしている中で最小のものからやるべき?→これはそう
数え上げなので…? → X回とれる盤面は何通りあるか(1)
または、あるindexより右をX回選択できるindexより右側の数列は何通りか(2) → 左は自由
(2)の方がやりやすそう(Nはでかいとする)
→ 右端は1通り (Nのみ)
→ 右から2番目は 1回選択が N-1,A / 2回選択が N-2,N
→ 右から3番目は 1回選択が N-2,(0回選択)
右から順番に見てく?
100*100→10000個しか取れない
毎回何の数字か全探索したとしても 100^3で間に合う
取れる個数は100log100
3300 * 100 * 100 = 3.3*10^7
間に合いそう
"""
N,K = map(int,input().split())
mod = 10**9+7
lis = [0] * 3300
lis[0] = 1
for i in range(N,0,-1):
nlis = [0] * 3300
for j in range(K+1):
for last in range(3300):
if i < j:
nlis[last] += lis[last]
nlis[last] %= mod
elif (last+j)//i + last < 3300:
nlis[last+(last+j)//i] += lis[last]
nlis[last+(last+j)//i] %= mod
lis = nlis
#print (lis[:20])
ans = K * (K+1) // 2 * pow(K+1,N-1,mod) * N
#print (ans)
for i in range(3300):
ans -= lis[i] * i
ans %= mod
print (ans)
"""
#test
ans = 0
for i in range(100,0,-1):
ans += (ans//i) + 1
print (ans)
"""
```
| 99,332 |
Provide a correct Python 3 solution for this coding contest problem.
There is a sequence of length N: a = (a_1, a_2, ..., a_N). Here, each a_i is a non-negative integer.
Snuke can repeatedly perform the following operation:
* Let the XOR of all the elements in a be x. Select an integer i (1 ≤ i ≤ N) and replace a_i with x.
Snuke's objective is to match a with another sequence b = (b_1, b_2, ..., b_N). Here, each b_i is a non-negative integer.
Determine whether the objective is achievable, and find the minimum necessary number of operations if the answer is positive.
Constraints
* 2 ≤ N ≤ 10^5
* a_i and b_i are integers.
* 0 ≤ a_i, b_i < 2^{30}
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
b_1 b_2 ... b_N
Output
If the objective is achievable, print the minimum necessary number of operations. Otherwise, print `-1` instead.
Examples
Input
3
0 1 2
3 1 0
Output
2
Input
3
0 1 2
0 1 2
Output
0
Input
2
1 1
0 0
Output
-1
Input
4
0 1 2 3
1 0 3 2
Output
5
"Correct Solution:
```
n,a,b=int(input()),list(map(int,input().split()))+[0],list(map(int,input().split()))+[0]
for i in range(n):
a[n]^=a[i]
b[n]^=b[i]
na,nb=sorted(a),sorted(b)
if na!=nb:
print("-1")
exit()
f=dict()
def find(x):
if f[x]==x:
return x
else:
f[x]=find(f[x])
return f[x]
ans=0
for i in range(n):
if a[i]!=b[i]:
f[a[i]]=a[i]
f[a[n]]=a[n]
for i in range(n):
if a[i]!=b[i]:
ans+=1
f[find(b[i])]=find(a[i])
for i in f:
if i==f[i]:
ans+=1
print(ans-1)
```
| 99,333 |
Provide a correct Python 3 solution for this coding contest problem.
There is a sequence of length N: a = (a_1, a_2, ..., a_N). Here, each a_i is a non-negative integer.
Snuke can repeatedly perform the following operation:
* Let the XOR of all the elements in a be x. Select an integer i (1 ≤ i ≤ N) and replace a_i with x.
Snuke's objective is to match a with another sequence b = (b_1, b_2, ..., b_N). Here, each b_i is a non-negative integer.
Determine whether the objective is achievable, and find the minimum necessary number of operations if the answer is positive.
Constraints
* 2 ≤ N ≤ 10^5
* a_i and b_i are integers.
* 0 ≤ a_i, b_i < 2^{30}
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
b_1 b_2 ... b_N
Output
If the objective is achievable, print the minimum necessary number of operations. Otherwise, print `-1` instead.
Examples
Input
3
0 1 2
3 1 0
Output
2
Input
3
0 1 2
0 1 2
Output
0
Input
2
1 1
0 0
Output
-1
Input
4
0 1 2 3
1 0 3 2
Output
5
"Correct Solution:
```
class UnionFindVerSize():
def __init__(self, N):
self._parent = [n for n in range(0, N)]
self._size = [1] * N
def find_root(self, x):
if self._parent[x] == x: return x
self._parent[x] = self.find_root(self._parent[x])
return self._parent[x]
def unite(self, x, y):
gx = self.find_root(x)
gy = self.find_root(y)
if gx == gy: return
if self._size[gx] < self._size[gy]:
self._parent[gx] = gy
self._size[gy] += self._size[gx]
else:
self._parent[gy] = gx
self._size[gx] += self._size[gy]
def get_size(self, x):
return self._size[self.find_root(x)]
def is_same_group(self, x, y):
return self.find_root(x) == self.find_root(y)
def calc_group_num(self):
N = len(self._parent)
ans = 0
for i in range(N):
if self.find_root(i) == i:
ans += 1
return ans
from collections import Counter
N=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
A=0
for i in range(N):
A^=a[i]
B=0
for i in range(N):
B^=b[i]
a.append(A)
b.append(B)
if Counter(a)!=Counter(b):
exit(print(-1))
val=set([])
for i in range(N+1):
if a[i]!=b[i]:
val.add(a[i])
if not val:
exit(print(0))
val=list(val)
val.sort()
comp={i:e for e,i in enumerate(val)}
n=max(comp[d] for d in comp)+1
uf=UnionFindVerSize(n)
check=False
cnt=0
for i in range(N):
if a[i]!=b[i]:
uf.unite(comp[a[i]],comp[b[i]])
if a[i]==b[-1]:
check=True
cnt+=1
print(cnt+uf.calc_group_num()-int(check))
```
| 99,334 |
Provide a correct Python 3 solution for this coding contest problem.
There is a sequence of length N: a = (a_1, a_2, ..., a_N). Here, each a_i is a non-negative integer.
Snuke can repeatedly perform the following operation:
* Let the XOR of all the elements in a be x. Select an integer i (1 ≤ i ≤ N) and replace a_i with x.
Snuke's objective is to match a with another sequence b = (b_1, b_2, ..., b_N). Here, each b_i is a non-negative integer.
Determine whether the objective is achievable, and find the minimum necessary number of operations if the answer is positive.
Constraints
* 2 ≤ N ≤ 10^5
* a_i and b_i are integers.
* 0 ≤ a_i, b_i < 2^{30}
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
b_1 b_2 ... b_N
Output
If the objective is achievable, print the minimum necessary number of operations. Otherwise, print `-1` instead.
Examples
Input
3
0 1 2
3 1 0
Output
2
Input
3
0 1 2
0 1 2
Output
0
Input
2
1 1
0 0
Output
-1
Input
4
0 1 2 3
1 0 3 2
Output
5
"Correct Solution:
```
def examA():
N = I()
ans = 0
print(ans)
return
def examB():
ans = 0
print(ans)
return
def examC():
ans = 0
print(ans)
return
def examD():
class UnionFind():
def __init__(self, n):
self.parent = [-1 for _ in range(n)]
# 正==子: 根の頂点番号 / 負==根: 連結頂点数
def find(self, x):
# 要素xが属するグループの根を返す
if self.parent[x] < 0:
return x
else:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def unite(self, x, y):
# 要素xが属するグループと要素yが属するグループとを併合する
x, y = self.find(x), self.find(y)
if x == y:
return False
else:
if self.size(x) < self.size(y):
x, y = y, x
self.parent[x] += self.parent[y]
self.parent[y] = x
def same(self, x, y):
# 要素x, yが同じグループに属するかどうかを返す
return self.find(x) == self.find(y)
def size(self, x):
# 要素xが属するグループのサイズ(要素数)を返す
x = self.find(x)
return -self.parent[x]
def is_root(self, x):
# 要素の根をリストで返す
return self.parent[x] < 0
def roots(self):
# すべての根の要素をリストで返す
return [i for i, x in enumerate(self.parent) if x < 0]
def members(self, x):
# 要素xが属するグループに属する要素をリストで返す
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def group_count(self):
# グループの数を返す
return len(self.roots())
def all_group_members(self):
# {ルート要素: [そのグループに含まれる要素のリスト], ...}の辞書を返す
return {r: self.members(r) for r in self.roots()}
N = I()
A = LI()
B = LI()
uf = UnionFind(N+1)
Da = defaultdict(list)
Db = defaultdict(list)
bita = 0
same = [False]*(N+1)
for i in range(N):
if A[i]==B[i]:
same[i] = True
if sum(same)==N:
print(0)
return
for i,a in enumerate(A):
bita ^= a
if same[i]:
continue
Da[a].append(i)
Da[bita].append(N)
bitb = 0
for i,b in enumerate(B):
bitb ^= b
if same[i]:
continue
Db[b].append(i)
Db[bitb].append(N)
#print(Da)
#print(Db)
for key,a in Da.items():
if len(Db[key])!=len(a):
print(-1)
return
for key,a in Da.items():
uf.unite(a[0],Db[key][0])
if len(a)==1:
continue
for i in a[1:]:
uf.unite(a[0],i)
for b in Db.values():
if len(b)==1:
continue
for i in b[1:]:
uf.unite(b[0],i)
if uf.size(N)==N-sum(same):
ans = uf.size(N)
if bita!=bitb:
ans -= 1
print(ans)
return
ans = 0
used = [False]*(N+1)
for i in range(N):
#print(ans)
if same[i]:
continue
p = uf.find(i)
if used[p]:
continue
used[p] = True
ans += (-uf.parent[p]+1)
#print(ans)
#if sum(used)>1:
# ans += 1
if uf.size(N)>1:
ans -= 1
if bita!=bitb or len(Da[bita])>1:
ans -= 1
print(ans)
return
def examE():
ans = 0
print(ans)
return
def examF():
ans = 0
print(ans)
return
def test():
i = I()
li = LI()
lsi = LSI()
si = LS()
print(i)
print(li)
print(lsi)
print(si)
return
from decimal import Decimal as dec
import sys,bisect,itertools,heapq,math,random
from copy import deepcopy
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
def I(): return int(input())
def LI(): return list(map(int,sys.stdin.readline().split()))
def DI(): return dec(input())
def LDI(): return list(map(dec,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = 10**(-12)
alphabet = [chr(ord('a') + i) for i in range(26)]
sys.setrecursionlimit(10**7)
if __name__ == '__main__':
examD()
"""
5
0 2 3 6 9
2 9 0 6 3
5
0 2 3 6 9
2 9 0 6 14
# 4
5
0 2 3 6 9
2 3 0 6 14
# 5
5
0 2 3 6 9
2 0 3 9 14
# 5
4
1 2 4 8
2 1 8 4
# 6
"""
```
| 99,335 |
Provide a correct Python 3 solution for this coding contest problem.
There is a sequence of length N: a = (a_1, a_2, ..., a_N). Here, each a_i is a non-negative integer.
Snuke can repeatedly perform the following operation:
* Let the XOR of all the elements in a be x. Select an integer i (1 ≤ i ≤ N) and replace a_i with x.
Snuke's objective is to match a with another sequence b = (b_1, b_2, ..., b_N). Here, each b_i is a non-negative integer.
Determine whether the objective is achievable, and find the minimum necessary number of operations if the answer is positive.
Constraints
* 2 ≤ N ≤ 10^5
* a_i and b_i are integers.
* 0 ≤ a_i, b_i < 2^{30}
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
b_1 b_2 ... b_N
Output
If the objective is achievable, print the minimum necessary number of operations. Otherwise, print `-1` instead.
Examples
Input
3
0 1 2
3 1 0
Output
2
Input
3
0 1 2
0 1 2
Output
0
Input
2
1 1
0 0
Output
-1
Input
4
0 1 2 3
1 0 3 2
Output
5
"Correct Solution:
```
from collections import defaultdict
from functools import reduce
from operator import xor
def dfs(s, links, fixed):
q = [s]
while q:
v = q.pop()
if fixed[v]:
continue
fixed[v] = True
q.extend(links[v])
def solve(n, aaa, bbb):
a0 = reduce(xor, aaa, 0)
b0 = reduce(xor, bbb, 0)
aaa.append(a0)
bbb.append(b0)
ad = defaultdict(set)
bd = defaultdict(set)
for i, a in enumerate(aaa):
ad[a].add(i)
for i, b in enumerate(bbb):
bd[b].add(i)
ac = {a: len(s) for a, s in ad.items()}
bc = {b: len(s) for b, s in bd.items()}
if ac != bc:
return -1
links = defaultdict(set)
ans = 0
for a, b in zip(aaa, bbb):
if a == b:
continue
ans += 1
links[a].add(b)
if not ans:
return 0
if a0 == b0:
links[a0].add(b0)
else:
ans -= 1
fixed = {a: False for a in links}
for a in links:
if fixed[a]:
continue
ans += 1
dfs(a, links, fixed)
return ans - 1
n = int(input())
aaa = list(map(int, input().split()))
bbb = list(map(int, input().split()))
print(solve(n, aaa, bbb))
```
| 99,336 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a sequence of length N: a = (a_1, a_2, ..., a_N). Here, each a_i is a non-negative integer.
Snuke can repeatedly perform the following operation:
* Let the XOR of all the elements in a be x. Select an integer i (1 ≤ i ≤ N) and replace a_i with x.
Snuke's objective is to match a with another sequence b = (b_1, b_2, ..., b_N). Here, each b_i is a non-negative integer.
Determine whether the objective is achievable, and find the minimum necessary number of operations if the answer is positive.
Constraints
* 2 ≤ N ≤ 10^5
* a_i and b_i are integers.
* 0 ≤ a_i, b_i < 2^{30}
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
b_1 b_2 ... b_N
Output
If the objective is achievable, print the minimum necessary number of operations. Otherwise, print `-1` instead.
Examples
Input
3
0 1 2
3 1 0
Output
2
Input
3
0 1 2
0 1 2
Output
0
Input
2
1 1
0 0
Output
-1
Input
4
0 1 2 3
1 0 3 2
Output
5
Submitted Solution:
```
print(-1)
```
No
| 99,337 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a sequence of length N: a = (a_1, a_2, ..., a_N). Here, each a_i is a non-negative integer.
Snuke can repeatedly perform the following operation:
* Let the XOR of all the elements in a be x. Select an integer i (1 ≤ i ≤ N) and replace a_i with x.
Snuke's objective is to match a with another sequence b = (b_1, b_2, ..., b_N). Here, each b_i is a non-negative integer.
Determine whether the objective is achievable, and find the minimum necessary number of operations if the answer is positive.
Constraints
* 2 ≤ N ≤ 10^5
* a_i and b_i are integers.
* 0 ≤ a_i, b_i < 2^{30}
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
b_1 b_2 ... b_N
Output
If the objective is achievable, print the minimum necessary number of operations. Otherwise, print `-1` instead.
Examples
Input
3
0 1 2
3 1 0
Output
2
Input
3
0 1 2
0 1 2
Output
0
Input
2
1 1
0 0
Output
-1
Input
4
0 1 2 3
1 0 3 2
Output
5
Submitted Solution:
```
def examA():
N = I()
ans = 0
print(ans)
return
def examB():
ans = 0
print(ans)
return
def examC():
ans = 0
print(ans)
return
def examD():
class UnionFind():
def __init__(self, n):
self.parent = [-1 for _ in range(n)]
# 正==子: 根の頂点番号 / 負==根: 連結頂点数
def find(self, x):
# 要素xが属するグループの根を返す
if self.parent[x] < 0:
return x
else:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def unite(self, x, y):
# 要素xが属するグループと要素yが属するグループとを併合する
x, y = self.find(x), self.find(y)
if x == y:
return False
else:
if self.size(x) < self.size(y):
x, y = y, x
self.parent[x] += self.parent[y]
self.parent[y] = x
def same(self, x, y):
# 要素x, yが同じグループに属するかどうかを返す
return self.find(x) == self.find(y)
def size(self, x):
# 要素xが属するグループのサイズ(要素数)を返す
x = self.find(x)
return -self.parent[x]
def is_root(self, x):
# 要素の根をリストで返す
return self.parent[x] < 0
def roots(self):
# すべての根の要素をリストで返す
return [i for i, x in enumerate(self.parent) if x < 0]
def members(self, x):
# 要素xが属するグループに属する要素をリストで返す
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def group_count(self):
# グループの数を返す
return len(self.roots())
def all_group_members(self):
# {ルート要素: [そのグループに含まれる要素のリスト], ...}の辞書を返す
return {r: self.members(r) for r in self.roots()}
N = I()
A = LI()
B = LI()
uf = UnionFind(N+1)
Da = defaultdict(list)
Db = defaultdict(list)
bita = 0
same = [False]*(N+1)
for i in range(N):
if A[i]==B[i]:
same[i] = True
if sum(same)==N:
print(0)
return
for i,a in enumerate(A):
bita ^= a
if same[i]:
continue
Da[a].append(i)
Da[bita].append(N)
bitb = 0
for i,b in enumerate(B):
bitb ^= b
if same[i]:
continue
Db[b].append(i)
Db[bitb].append(N)
#print(Da)
#print(Db)
for key,a in Da.items():
if len(Db[key])!=len(a):
print(-1)
return
for key,a in Da.items():
uf.unite(a[0],Db[key][0])
if len(a)==1:
continue
for i in a[1:]:
uf.unite(a[0],i)
for b in Db.values():
if len(b)==1:
continue
for i in b[1:]:
uf.unite(b[0],i)
if uf.size(N)==N-sum(same):
ans = uf.size(N)
if bita!=bitb:
ans -= 1
print(ans)
return
ans = -1
used = [False]*(N+1)
for i in range(N+1):
#print(ans)
if same[i]:
continue
p = uf.find(i)
if used[p]:
continue
used[p] = True
ans += (-uf.parent[p]+1)
#print(ans)
#if sum(used)>1:
# ans += 1
if uf.size(N)>1 or bita!=bitb:
ans -= 1
print(ans)
return
def examE():
ans = 0
print(ans)
return
def examF():
ans = 0
print(ans)
return
def test():
i = I()
li = LI()
lsi = LSI()
si = LS()
print(i)
print(li)
print(lsi)
print(si)
return
from decimal import Decimal as dec
import sys,bisect,itertools,heapq,math,random
from copy import deepcopy
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
def I(): return int(input())
def LI(): return list(map(int,sys.stdin.readline().split()))
def DI(): return dec(input())
def LDI(): return list(map(dec,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = 10**(-12)
alphabet = [chr(ord('a') + i) for i in range(26)]
sys.setrecursionlimit(10**7)
if __name__ == '__main__':
examD()
"""
5
0 2 3 6 9
2 9 0 6 3
5
0 2 3 6 9
2 9 0 6 14
# 4
5
0 2 3 6 9
2 3 0 6 14
# 5
5
0 2 3 6 9
2 0 3 9 14
# 5
"""
```
No
| 99,338 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a sequence of length N: a = (a_1, a_2, ..., a_N). Here, each a_i is a non-negative integer.
Snuke can repeatedly perform the following operation:
* Let the XOR of all the elements in a be x. Select an integer i (1 ≤ i ≤ N) and replace a_i with x.
Snuke's objective is to match a with another sequence b = (b_1, b_2, ..., b_N). Here, each b_i is a non-negative integer.
Determine whether the objective is achievable, and find the minimum necessary number of operations if the answer is positive.
Constraints
* 2 ≤ N ≤ 10^5
* a_i and b_i are integers.
* 0 ≤ a_i, b_i < 2^{30}
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
b_1 b_2 ... b_N
Output
If the objective is achievable, print the minimum necessary number of operations. Otherwise, print `-1` instead.
Examples
Input
3
0 1 2
3 1 0
Output
2
Input
3
0 1 2
0 1 2
Output
0
Input
2
1 1
0 0
Output
-1
Input
4
0 1 2 3
1 0 3 2
Output
5
Submitted Solution:
```
from collections import Counter
n = int(input())
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
bonusNumber = 0
for i in range(n):
bonusNumber ^= a[i]
aa = Counter({bonusNumber: 1})
bb = Counter()
for i in range(n):
aa[a[i]] += 1
bb[b[i]] += 1
for x in bb.keys():
if bb[x] > aa[x]:
print(-1)
exit()
#############################
ans = 0
tmp = []
first = True
for i in range(n):
if first and b[i] == bonusNumber and b[i] != a[i]:
bonusNumber = a[i]
a[i] = b[i]
ans += 1
first = False
elif b[i] != a[i]:
tmp.append(b[i])
while bonusNumber in tmp:
tmp.remove(bonusNumber)
bonusNumber = a[b.index(bonusNumber)]
ans += 1
if len(tmp) == 0:
print(ans)
else:
ans += len(tmp) + 1
print(ans)
```
No
| 99,339 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a sequence of length N: a = (a_1, a_2, ..., a_N). Here, each a_i is a non-negative integer.
Snuke can repeatedly perform the following operation:
* Let the XOR of all the elements in a be x. Select an integer i (1 ≤ i ≤ N) and replace a_i with x.
Snuke's objective is to match a with another sequence b = (b_1, b_2, ..., b_N). Here, each b_i is a non-negative integer.
Determine whether the objective is achievable, and find the minimum necessary number of operations if the answer is positive.
Constraints
* 2 ≤ N ≤ 10^5
* a_i and b_i are integers.
* 0 ≤ a_i, b_i < 2^{30}
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
b_1 b_2 ... b_N
Output
If the objective is achievable, print the minimum necessary number of operations. Otherwise, print `-1` instead.
Examples
Input
3
0 1 2
3 1 0
Output
2
Input
3
0 1 2
0 1 2
Output
0
Input
2
1 1
0 0
Output
-1
Input
4
0 1 2 3
1 0 3 2
Output
5
Submitted Solution:
```
n,a,b=int(input()),list(map(int,input().split()))+[0],list(map(int,input().split()))+[0]
for i in range(n):
a[n]^=a[i]
b[n]^=b[i]
na,nb=sorted(a),sorted(b)
if sum([na[i]!=nb[i] for i in range(n+1)]):
print("-1")
exit()
f=dict()
def find(x):
if f[x]==x:
return x
else:
f[x]=find(f[x])
return f[x]
ans=0
for i in range(n):
if a[i]!=b[i]:
f[a[i]]=a[i]
f[a[n]]=a[n]
for i in range(n):
if a[i]!=b[i]:
ans+=1
f[find(b[i])]=find(a[i])
for i,j in f:
if i==j:
ans+=1
print(ans-1)
```
No
| 99,340 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a tree with N vertices. The vertices are numbered 1 through N. For each 1 ≤ i ≤ N - 1, the i-th edge connects vertices a_i and b_i. The lengths of all the edges are 1.
Snuke likes some of the vertices. The information on his favorite vertices are given to you as a string s of length N. For each 1 ≤ i ≤ N, s_i is `1` if Snuke likes vertex i, and `0` if he does not like vertex i.
Initially, all the vertices are white. Snuke will perform the following operation exactly once:
* Select a vertex v that he likes, and a non-negative integer d. Then, paint all the vertices black whose distances from v are at most d.
Find the number of the possible combinations of colors of the vertices after the operation.
Constraints
* 2 ≤ N ≤ 2×10^5
* 1 ≤ a_i, b_i ≤ N
* The given graph is a tree.
* |s| = N
* s consists of `0` and `1`.
* s contains at least one occurrence of `1`.
Input
The input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N - 1} b_{N - 1}
s
Output
Print the number of the possible combinations of colors of the vertices after the operation.
Examples
Input
4
1 2
1 3
1 4
1100
Output
4
Input
5
1 2
1 3
1 4
4 5
11111
Output
11
Input
6
1 2
1 3
1 4
2 5
2 6
100011
Output
8
Submitted Solution:
```
def solve():
n = int(input())
g = [[] for _ in range(n)]
for _ in range(n - 1):
a, b = [int(x) for x in input().split()]
a -= 1
b -= 1
g[a].append(b)
g[b].append(a)
ds = dict()
parent = [-1] * n
dfs_order = [0]
for i in range(n):
a = dfs_order[i]
for b in g[a]:
if b == parent[a]:
continue
dfs_order.append(b)
parent[b] = a
vd = [-1] * n
for a in reversed(dfs_order):
vd[a] = 0
for b in g[a]:
if b == parent[a]:
continue
ds[(a, b)] = vd[b]
vd[a] = max(vd[a], vd[b])
vd[a] = vd[a] + 1
ans = 0
d_parent = [0] * n
for a in dfs_order:
cd = [(d_parent[a], parent[a])]
for b in g[a]:
if b == parent[a]:
continue
cd.append((ds[(a, b)], b))
cd.sort()
cd.reverse()
cur = (cd[1][0] + 1) if (len(cd) > 1) else 1
cur = min(cur, cd[0][0] - 1)
ans += cur + 1
for b in g[a]:
if b == parent[a]:
continue
x = cd[0][0]
if cd[0][1] == b:
x = cd[1][0]
d_parent[b] = x + 1
print(ans + 1)
if __name__ == '__main__':
# t = int(input())
t=1
for _ in range(t):
solve()
```
No
| 99,341 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a tree with N vertices. The vertices are numbered 1 through N. For each 1 ≤ i ≤ N - 1, the i-th edge connects vertices a_i and b_i. The lengths of all the edges are 1.
Snuke likes some of the vertices. The information on his favorite vertices are given to you as a string s of length N. For each 1 ≤ i ≤ N, s_i is `1` if Snuke likes vertex i, and `0` if he does not like vertex i.
Initially, all the vertices are white. Snuke will perform the following operation exactly once:
* Select a vertex v that he likes, and a non-negative integer d. Then, paint all the vertices black whose distances from v are at most d.
Find the number of the possible combinations of colors of the vertices after the operation.
Constraints
* 2 ≤ N ≤ 2×10^5
* 1 ≤ a_i, b_i ≤ N
* The given graph is a tree.
* |s| = N
* s consists of `0` and `1`.
* s contains at least one occurrence of `1`.
Input
The input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N - 1} b_{N - 1}
s
Output
Print the number of the possible combinations of colors of the vertices after the operation.
Examples
Input
4
1 2
1 3
1 4
1100
Output
4
Input
5
1 2
1 3
1 4
4 5
11111
Output
11
Input
6
1 2
1 3
1 4
2 5
2 6
100011
Output
8
Submitted Solution:
```
def solve():
n = int(input())
g = [[] for _ in range(n)]
for _ in range(n - 1):
a, b = [int(x) for x in input().split()]
a -= 1
b -= 1
g[a].append(b)
g[b].append(a)
ds = dict()
def dfs1(g, a, fr):
res = 0
for b in g[a]:
if b == fr:
continue
x = dfs1(g, b, a)
ds[(a, b)] = x
res = max(res, x)
return res + 1
dfs1(g, 0, -1)
# print(ds)
ans = 0
def dfs2(g, a, fr, d_fr):
nonlocal ans
# print(a, fr, d_fr)
cd = [(d_fr, fr)]
for b in g[a]:
if b == fr:
continue
cd.append((ds[(a, b)], b))
cd.sort()
cd.reverse()
# print(cd)
cur = (cd[1][0] + 1) if (len(cd) > 1) else 1
cur = min(cur, cd[0][0] - 1)
# print(cur)
ans += cur + 1
for b in g[a]:
if b == fr:
continue
x = cd[0][0]
if cd[0][1] == b:
x = cd[1][0]
dfs2(g, b, a, x + 1)
dfs2(g, 0, -1, 0)
print(ans + 1)
if __name__ == '__main__':
# t = int(input())
t = 1
for _ in range(t):
solve()
```
No
| 99,342 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a tree with N vertices. The vertices are numbered 1 through N. For each 1 ≤ i ≤ N - 1, the i-th edge connects vertices a_i and b_i. The lengths of all the edges are 1.
Snuke likes some of the vertices. The information on his favorite vertices are given to you as a string s of length N. For each 1 ≤ i ≤ N, s_i is `1` if Snuke likes vertex i, and `0` if he does not like vertex i.
Initially, all the vertices are white. Snuke will perform the following operation exactly once:
* Select a vertex v that he likes, and a non-negative integer d. Then, paint all the vertices black whose distances from v are at most d.
Find the number of the possible combinations of colors of the vertices after the operation.
Constraints
* 2 ≤ N ≤ 2×10^5
* 1 ≤ a_i, b_i ≤ N
* The given graph is a tree.
* |s| = N
* s consists of `0` and `1`.
* s contains at least one occurrence of `1`.
Input
The input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N - 1} b_{N - 1}
s
Output
Print the number of the possible combinations of colors of the vertices after the operation.
Examples
Input
4
1 2
1 3
1 4
1100
Output
4
Input
5
1 2
1 3
1 4
4 5
11111
Output
11
Input
6
1 2
1 3
1 4
2 5
2 6
100011
Output
8
Submitted Solution:
```
def solve():
n = int(input())
g = [[] for _ in range(n)]
for _ in range(n - 1):
a, b = [int(x) for x in input().split()]
a -= 1
b -= 1
g[a].append(b)
g[b].append(a)
ds = dict()
def dfs1(g, a, fr):
res = 0
for b in g[a]:
if b == fr:
continue
x = dfs1(g, b, a)
ds[(a, b)] = x
res = max(res, x)
return res + 1
dfs1(g, 0, -1)
# print(ds)
ans = 0
def dfs2(g, a, fr, d_fr):
nonlocal ans
# print(a, fr, d_fr)
cd = [(d_fr, fr)]
for b in g[a]:
if b == fr:
continue
cd.append((ds[(a, b)], b))
cd.sort()
cd.reverse()
# print(cd)
cur = (cd[1][0] + 1) if (len(cd) > 1) else 1
cur = min(cur, cd[0][0] - 1)
# print(cur)
ans += cur + 1
for b in g[a]:
if b == fr:
continue
x = cd[0][0]
if cd[0][1] == b:
x = cd[1][0]
dfs2(g, b, a, x + 1)
dfs2(g, 0, -1, 0)
print(ans + 1)
if __name__ == '__main__':
t = int(input())
for _ in range(t):
solve()
```
No
| 99,343 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected graph with N vertices and M edges. Here, N-1≤M≤N holds and the graph is connected. There are no self-loops or multiple edges in this graph.
The vertices are numbered 1 through N, and the edges are numbered 1 through M. Edge i connects vertices a_i and b_i.
The color of each vertex can be either white or black. Initially, all the vertices are white. Snuke is trying to turn all the vertices black by performing the following operation some number of times:
* Select a pair of adjacent vertices with the same color, and invert the colors of those vertices. That is, if the vertices are both white, then turn them black, and vice versa.
Determine if it is possible to turn all the vertices black. If the answer is positive, find the minimum number of times the operation needs to be performed in order to achieve the objective.
Constraints
* 2≤N≤10^5
* N-1≤M≤N
* 1≤a_i,b_i≤N
* There are no self-loops or multiple edges in the given graph.
* The given graph is connected.
Input
The input is given from Standard Input in the following format:
N M
a_1 b_1
a_2 b_2
:
a_M b_M
Output
If it is possible to turn all the vertices black, print the minimum number of times the operation needs to be performed in order to achieve the objective. Otherwise, print `-1` instead.
Examples
Input
6 5
1 2
1 3
1 4
2 5
2 6
Output
5
Input
3 2
1 2
2 3
Output
-1
Input
4 4
1 2
2 3
3 4
4 1
Output
2
Input
6 6
1 2
2 3
3 1
1 4
1 5
1 6
Output
7
Submitted Solution:
```
print(-1)
```
No
| 99,344 |
Provide a correct Python 3 solution for this coding contest problem.
Enter a positive integer n of 4,000 or less, with a pair of integers a, b, c, d in the range 0-1000.
a + b + c + d = n
Create a program that outputs the number of combinations that satisfy the conditions.
Input
Given multiple datasets. Each dataset is given n on one row. Please process until the end of the input.
The number of datasets does not exceed 50.
Output
For each data set, output the number of combinations of a, b, c, and d on one line.
Example
Input
2
3
35
Output
10
20
8436
"Correct Solution:
```
import sys
m=1000;n=m*4
a=[0]*-~n
for i in range(2001):a[i]=a[n-i]=(i+3)*(i+2)*(i+1)//6-a[~-i-m]*4*(i>~-m)
for e in sys.stdin:print(a[int(e)])
```
| 99,345 |
Provide a correct Python 3 solution for this coding contest problem.
Enter a positive integer n of 4,000 or less, with a pair of integers a, b, c, d in the range 0-1000.
a + b + c + d = n
Create a program that outputs the number of combinations that satisfy the conditions.
Input
Given multiple datasets. Each dataset is given n on one row. Please process until the end of the input.
The number of datasets does not exceed 50.
Output
For each data set, output the number of combinations of a, b, c, and d on one line.
Example
Input
2
3
35
Output
10
20
8436
"Correct Solution:
```
while True:
try:
n = int(input())
if n > 2000:
n = 4000 - n
ans = (n+1)*(n+2)*(n+3)/6
if n >= 1001:
n = n - 1001
ans = ans - 2*(n+1)*(n+2)*(n+3)/3
print(int(ans))
except EOFError:
break
```
| 99,346 |
Provide a correct Python 3 solution for this coding contest problem.
Enter a positive integer n of 4,000 or less, with a pair of integers a, b, c, d in the range 0-1000.
a + b + c + d = n
Create a program that outputs the number of combinations that satisfy the conditions.
Input
Given multiple datasets. Each dataset is given n on one row. Please process until the end of the input.
The number of datasets does not exceed 50.
Output
For each data set, output the number of combinations of a, b, c, and d on one line.
Example
Input
2
3
35
Output
10
20
8436
"Correct Solution:
```
import sys
a=[0]*4001
for i in range(1999):a[i]=a[4000-i]=(i+3)*(i+2)*(i+1)//6-a[i-1001]*4*(i>999)
for e in sys.stdin:print(a[int(e)])
```
| 99,347 |
Provide a correct Python 3 solution for this coding contest problem.
Enter a positive integer n of 4,000 or less, with a pair of integers a, b, c, d in the range 0-1000.
a + b + c + d = n
Create a program that outputs the number of combinations that satisfy the conditions.
Input
Given multiple datasets. Each dataset is given n on one row. Please process until the end of the input.
The number of datasets does not exceed 50.
Output
For each data set, output the number of combinations of a, b, c, and d on one line.
Example
Input
2
3
35
Output
10
20
8436
"Correct Solution:
```
# -*- coding: utf-8 -*-
import sys
import os
import math
T = [0] * 2001
for a in range(1001):
for b in range(1001):
T[a + b] += 1
for s in sys.stdin:
n = int(s)
sum_n_num = 0
for a_b_sum in range(0, n+1):
c_d_sum = n - a_b_sum
if a_b_sum <= 2000 and c_d_sum <= 2000:
sum_n_num += T[a_b_sum] * T[c_d_sum]
print(sum_n_num)
```
| 99,348 |
Provide a correct Python 3 solution for this coding contest problem.
Enter a positive integer n of 4,000 or less, with a pair of integers a, b, c, d in the range 0-1000.
a + b + c + d = n
Create a program that outputs the number of combinations that satisfy the conditions.
Input
Given multiple datasets. Each dataset is given n on one row. Please process until the end of the input.
The number of datasets does not exceed 50.
Output
For each data set, output the number of combinations of a, b, c, and d on one line.
Example
Input
2
3
35
Output
10
20
8436
"Correct Solution:
```
A = [0 for i in range(2001)]
for i in range(1001) :
for j in range(1001) :
A[i + j] += 1
while True :
try :
n = int(input())
cnt = 0
if(n > 4000) :
print(0)
elif(n > 2000) :
for i in range(n - 2000, 2001) :
cnt += A[i] * A[n - i]
print(cnt)
else :
for i in range(n + 1) :
cnt += A[i] * A[n - i]
print(cnt)
except :
break
```
| 99,349 |
Provide a correct Python 3 solution for this coding contest problem.
Enter a positive integer n of 4,000 or less, with a pair of integers a, b, c, d in the range 0-1000.
a + b + c + d = n
Create a program that outputs the number of combinations that satisfy the conditions.
Input
Given multiple datasets. Each dataset is given n on one row. Please process until the end of the input.
The number of datasets does not exceed 50.
Output
For each data set, output the number of combinations of a, b, c, and d on one line.
Example
Input
2
3
35
Output
10
20
8436
"Correct Solution:
```
s = list(range(1,1001)) + list(range(1001,0,-1))
while True:
try:
n = int(input())
except:
break
ans = 0
for i in range(min(n+1,2001)):
if 0 <= n-i <= 2000:
ans += s[i] * s[n-i]
print(ans)
```
| 99,350 |
Provide a correct Python 3 solution for this coding contest problem.
Enter a positive integer n of 4,000 or less, with a pair of integers a, b, c, d in the range 0-1000.
a + b + c + d = n
Create a program that outputs the number of combinations that satisfy the conditions.
Input
Given multiple datasets. Each dataset is given n on one row. Please process until the end of the input.
The number of datasets does not exceed 50.
Output
For each data set, output the number of combinations of a, b, c, and d on one line.
Example
Input
2
3
35
Output
10
20
8436
"Correct Solution:
```
from collections import Counter
pair_dict = Counter()
for i in range(2001):
pair_dict[i] = min(i, 2000 - i) + 1
while True:
try:
n = int(input())
ans = 0
for i in range(n + 1):
ans += pair_dict[i] * pair_dict[n - i]
print(ans)
except EOFError:
break
```
| 99,351 |
Provide a correct Python 3 solution for this coding contest problem.
Enter a positive integer n of 4,000 or less, with a pair of integers a, b, c, d in the range 0-1000.
a + b + c + d = n
Create a program that outputs the number of combinations that satisfy the conditions.
Input
Given multiple datasets. Each dataset is given n on one row. Please process until the end of the input.
The number of datasets does not exceed 50.
Output
For each data set, output the number of combinations of a, b, c, and d on one line.
Example
Input
2
3
35
Output
10
20
8436
"Correct Solution:
```
import sys
for line in sys.stdin.readlines():
n = int(line.rstrip())
count = 0
for i in range(1001):
if 0 <= n - i <= 1000:
count += (n-i+1)*(i+1)
elif 1001 <= n-i <= 2000 :
count += (2000-(n-i)+1)*(i+1)
for i in range(1001,2001):
if 0 <= n - i <= 1000:
count += (n-i+1)*(2000-i+1)
elif 1001 <= n-i <= 2000:
count += (2000-(n-i)+1)*(2000-i+1)
print(count)
```
| 99,352 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Enter a positive integer n of 4,000 or less, with a pair of integers a, b, c, d in the range 0-1000.
a + b + c + d = n
Create a program that outputs the number of combinations that satisfy the conditions.
Input
Given multiple datasets. Each dataset is given n on one row. Please process until the end of the input.
The number of datasets does not exceed 50.
Output
For each data set, output the number of combinations of a, b, c, and d on one line.
Example
Input
2
3
35
Output
10
20
8436
Submitted Solution:
```
def Kosuu(n,sak):
if n <= sak:
kazu = n + 1
sta = 0
end = n
else:
kazu = sak * 2 + 1 - n
sta = n - sak
end = sak
return [kazu,sta,end]
while True:
try:
Sum = 0
n = int(input())
ABl = Kosuu(n,2000)
for i in range(ABl[1],ABl[2] + 1):
Sum += Kosuu(i,1000)[0] * Kosuu(n -i,1000)[0]
print(Sum)
except EOFError:
break
```
Yes
| 99,353 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Enter a positive integer n of 4,000 or less, with a pair of integers a, b, c, d in the range 0-1000.
a + b + c + d = n
Create a program that outputs the number of combinations that satisfy the conditions.
Input
Given multiple datasets. Each dataset is given n on one row. Please process until the end of the input.
The number of datasets does not exceed 50.
Output
For each data set, output the number of combinations of a, b, c, and d on one line.
Example
Input
2
3
35
Output
10
20
8436
Submitted Solution:
```
ab = [0 for _ in range(2001)]
for a in range(1001):
for b in range(1001):
ab[a+b] += 1
while True:
try:
n = int(input())
except:
break
ans = sum(ab[i]*ab[n-i] for i in range(2001) if n-i >= 0 and n-i <= 2000)
print(ans)
```
Yes
| 99,354 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Enter a positive integer n of 4,000 or less, with a pair of integers a, b, c, d in the range 0-1000.
a + b + c + d = n
Create a program that outputs the number of combinations that satisfy the conditions.
Input
Given multiple datasets. Each dataset is given n on one row. Please process until the end of the input.
The number of datasets does not exceed 50.
Output
For each data set, output the number of combinations of a, b, c, and d on one line.
Example
Input
2
3
35
Output
10
20
8436
Submitted Solution:
```
s=[0]*4001
for i in range(2001):
a=a+2*(i-999)*(i-1000) if i>1000 else 0
s[i]=(i+3)*(i+2)*-~i//6-a
s[4000-i]=s[i]
while 1:
try:print(s[int(input())])
except:break
```
Yes
| 99,355 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Enter a positive integer n of 4,000 or less, with a pair of integers a, b, c, d in the range 0-1000.
a + b + c + d = n
Create a program that outputs the number of combinations that satisfy the conditions.
Input
Given multiple datasets. Each dataset is given n on one row. Please process until the end of the input.
The number of datasets does not exceed 50.
Output
For each data set, output the number of combinations of a, b, c, and d on one line.
Example
Input
2
3
35
Output
10
20
8436
Submitted Solution:
```
import sys
hist = [0 for i in range(4001)]
for i in range(1001):
for j in range(1001):
hist[i + j] += 1
for line in sys.stdin:
ans = 0
n = int(line)
for i in range(min(n, 2000) + 1):
ans += (hist[i] * hist[n-i])
print(ans)
```
Yes
| 99,356 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Enter a positive integer n of 4,000 or less, with a pair of integers a, b, c, d in the range 0-1000.
a + b + c + d = n
Create a program that outputs the number of combinations that satisfy the conditions.
Input
Given multiple datasets. Each dataset is given n on one row. Please process until the end of the input.
The number of datasets does not exceed 50.
Output
For each data set, output the number of combinations of a, b, c, and d on one line.
Example
Input
2
3
35
Output
10
20
8436
Submitted Solution:
```
while True:
m = 0
try:
n = int(input().strip())
for a in range(10001):
if n - a <0:
break
for b in range(10001):
if n - (a+b) <0:
break
for c in range(10001):
if n - (a+b+c) <0:
break
for d in range(10001):
if n - (a+b+c+d) <0:
break
if a+b+c+d == n:
m += 1
print(m)
except EOFError:
break
```
No
| 99,357 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Enter a positive integer n of 4,000 or less, with a pair of integers a, b, c, d in the range 0-1000.
a + b + c + d = n
Create a program that outputs the number of combinations that satisfy the conditions.
Input
Given multiple datasets. Each dataset is given n on one row. Please process until the end of the input.
The number of datasets does not exceed 50.
Output
For each data set, output the number of combinations of a, b, c, and d on one line.
Example
Input
2
3
35
Output
10
20
8436
Submitted Solution:
```
import sys
for line in sys.stdin.readlines():
n = int(line.rstrip())
count = 0
for i in range(min(2001,n+1)):
if n - i >= 0:
count += (i+1)*(n-i+1)
print(count)
```
No
| 99,358 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Enter a positive integer n of 4,000 or less, with a pair of integers a, b, c, d in the range 0-1000.
a + b + c + d = n
Create a program that outputs the number of combinations that satisfy the conditions.
Input
Given multiple datasets. Each dataset is given n on one row. Please process until the end of the input.
The number of datasets does not exceed 50.
Output
For each data set, output the number of combinations of a, b, c, and d on one line.
Example
Input
2
3
35
Output
10
20
8436
Submitted Solution:
```
def solve(n):
ans=0
for a in range(n+1):
for b in range(n+1):
if a+b>n:
break
for c in range(n+1):
if n-(a+b+c)>=0:
ans+=1
else:
break
return ans
while True:
try:
n=int(input())
print(solve(n))
except EOFError:
break
```
No
| 99,359 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Enter a positive integer n of 4,000 or less, with a pair of integers a, b, c, d in the range 0-1000.
a + b + c + d = n
Create a program that outputs the number of combinations that satisfy the conditions.
Input
Given multiple datasets. Each dataset is given n on one row. Please process until the end of the input.
The number of datasets does not exceed 50.
Output
For each data set, output the number of combinations of a, b, c, and d on one line.
Example
Input
2
3
35
Output
10
20
8436
Submitted Solution:
```
while True:
try:
N = int(input())
except EOFError:
break
ans = (N + 3) * (N + 2) * (N + 1) // 6
print(ans)
```
No
| 99,360 |
Provide a correct Python 3 solution for this coding contest problem.
The screen that displays digital numbers that you often see on calculators is called a "7-segment display" because the digital numbers consist of seven parts (segments).
The new product to be launched by Wakamatsu will incorporate a 7-segment display into the product, and as an employee, you will create a program to display the given number on the 7-segment display.
This 7-segment display will not change until the next switch instruction is sent. By sending a signal consisting of 7 bits, the display information of each corresponding segment can be switched. Bits have a value of 1 or 0, where 1 stands for "switch" and 0 stands for "as is".
The correspondence between each bit and segment is shown in the figure below. The signal sends 7 bits in the order of "gfedcba". For example, in order to display "0" from the hidden state, "0111111" must be sent to the display as a signal. To change from "0" to "5", send "1010010". If you want to change "5" to "1" in succession, send "1101011".
<image>
Create a program that takes n (1 ≤ n ≤ 100) numbers that you want to display and outputs the signal sequence required to correctly display those numbers di (0 ≤ di ≤ 9) on the 7-segment display. please. It is assumed that the initial state of the 7-segment display is all hidden.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of -1. Each dataset is given in the following format:
n
d1
d2
::
dn
The number of datasets does not exceed 120.
Output
For each input dataset, output the sequence of signals needed to properly output the numbers to the display.
Example
Input
3
0
5
1
1
0
-1
Output
0111111
1010010
1101011
0111111
"Correct Solution:
```
#!/usr/bin/env python3
seven_seg = {
0: '0111111',
1: '0000110',
2: '1011011',
3: '1001111',
4: '1100110',
5: '1101101',
6: '1111101',
7: '0100111',
8: '1111111',
9: '1101111'
}
while True:
seven_seg_state = ['0'] * 7
n = int(input())
if n == -1:
break
for _ in range(n):
in_data = int(input())
for i in range(7):
if seven_seg[in_data][i] == seven_seg_state[i]:
print("0", end="")
else:
print("1", end="")
seven_seg_state[i] = seven_seg[in_data][i]
print()
```
| 99,361 |
Provide a correct Python 3 solution for this coding contest problem.
The screen that displays digital numbers that you often see on calculators is called a "7-segment display" because the digital numbers consist of seven parts (segments).
The new product to be launched by Wakamatsu will incorporate a 7-segment display into the product, and as an employee, you will create a program to display the given number on the 7-segment display.
This 7-segment display will not change until the next switch instruction is sent. By sending a signal consisting of 7 bits, the display information of each corresponding segment can be switched. Bits have a value of 1 or 0, where 1 stands for "switch" and 0 stands for "as is".
The correspondence between each bit and segment is shown in the figure below. The signal sends 7 bits in the order of "gfedcba". For example, in order to display "0" from the hidden state, "0111111" must be sent to the display as a signal. To change from "0" to "5", send "1010010". If you want to change "5" to "1" in succession, send "1101011".
<image>
Create a program that takes n (1 ≤ n ≤ 100) numbers that you want to display and outputs the signal sequence required to correctly display those numbers di (0 ≤ di ≤ 9) on the 7-segment display. please. It is assumed that the initial state of the 7-segment display is all hidden.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of -1. Each dataset is given in the following format:
n
d1
d2
::
dn
The number of datasets does not exceed 120.
Output
For each input dataset, output the sequence of signals needed to properly output the numbers to the display.
Example
Input
3
0
5
1
1
0
-1
Output
0111111
1010010
1101011
0111111
"Correct Solution:
```
NUM = (
0b0111111,
0b0000110,
0b1011011,
0b1001111,
0b1100110,
0b1101101,
0b1111101,
0b0100111,
0b1111111,
0b1101111,
)
while 1:
n = int(input())
if n == -1:break
current = 0
for i in range(n):
num = NUM[int(input())]
print(format(current ^ num,'b').zfill(7))
current = num
```
| 99,362 |
Provide a correct Python 3 solution for this coding contest problem.
The screen that displays digital numbers that you often see on calculators is called a "7-segment display" because the digital numbers consist of seven parts (segments).
The new product to be launched by Wakamatsu will incorporate a 7-segment display into the product, and as an employee, you will create a program to display the given number on the 7-segment display.
This 7-segment display will not change until the next switch instruction is sent. By sending a signal consisting of 7 bits, the display information of each corresponding segment can be switched. Bits have a value of 1 or 0, where 1 stands for "switch" and 0 stands for "as is".
The correspondence between each bit and segment is shown in the figure below. The signal sends 7 bits in the order of "gfedcba". For example, in order to display "0" from the hidden state, "0111111" must be sent to the display as a signal. To change from "0" to "5", send "1010010". If you want to change "5" to "1" in succession, send "1101011".
<image>
Create a program that takes n (1 ≤ n ≤ 100) numbers that you want to display and outputs the signal sequence required to correctly display those numbers di (0 ≤ di ≤ 9) on the 7-segment display. please. It is assumed that the initial state of the 7-segment display is all hidden.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of -1. Each dataset is given in the following format:
n
d1
d2
::
dn
The number of datasets does not exceed 120.
Output
For each input dataset, output the sequence of signals needed to properly output the numbers to the display.
Example
Input
3
0
5
1
1
0
-1
Output
0111111
1010010
1101011
0111111
"Correct Solution:
```
dic = {0:"0111111", 1:"0000110", 2:"1011011", 3:"1001111", 4:"1100110",
5:"1101101", 6:"1111101", 7:"0100111", 8:"1111111", 9:"1101111"}
while True:
n = int(input())
if n == -1:
break
dig = "0" * 7
for _ in range(n):
d = dic[int(input())]
put = ""
for i in range(7):
if dig[i] != d[i]:
put += "1"
else:
put += "0"
print(put)
dig = d
```
| 99,363 |
Provide a correct Python 3 solution for this coding contest problem.
The screen that displays digital numbers that you often see on calculators is called a "7-segment display" because the digital numbers consist of seven parts (segments).
The new product to be launched by Wakamatsu will incorporate a 7-segment display into the product, and as an employee, you will create a program to display the given number on the 7-segment display.
This 7-segment display will not change until the next switch instruction is sent. By sending a signal consisting of 7 bits, the display information of each corresponding segment can be switched. Bits have a value of 1 or 0, where 1 stands for "switch" and 0 stands for "as is".
The correspondence between each bit and segment is shown in the figure below. The signal sends 7 bits in the order of "gfedcba". For example, in order to display "0" from the hidden state, "0111111" must be sent to the display as a signal. To change from "0" to "5", send "1010010". If you want to change "5" to "1" in succession, send "1101011".
<image>
Create a program that takes n (1 ≤ n ≤ 100) numbers that you want to display and outputs the signal sequence required to correctly display those numbers di (0 ≤ di ≤ 9) on the 7-segment display. please. It is assumed that the initial state of the 7-segment display is all hidden.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of -1. Each dataset is given in the following format:
n
d1
d2
::
dn
The number of datasets does not exceed 120.
Output
For each input dataset, output the sequence of signals needed to properly output the numbers to the display.
Example
Input
3
0
5
1
1
0
-1
Output
0111111
1010010
1101011
0111111
"Correct Solution:
```
Num_seg = [[0,1,1,1,1,1,1],[0,0,0,0,1,1,0],[1,0,1,1,0,1,1],[1,0,0,1,1,1,1],[1,1,0,0,1,1,0],[1,1,0,1,1,0,1],[1,1,1,1,1,0,1],[0,1,0,0,1,1,1],[1,1,1,1,1,1,1],[1,1,0,1,1,1,1]]
while True:
n = int(input())
if n == -1:
break
num_b = int(input())
seg = ""
for h in range(7):
seg = seg + str(Num_seg[num_b][h])
print(seg)
for i in range(n - 1):
num_a = int(input())
seg = ""
for j in range(7):
if Num_seg[num_b][j] == Num_seg[num_a][j]:
seg = seg + "0"
else:
seg = seg + "1"
num_b = num_a
print(seg)
```
| 99,364 |
Provide a correct Python 3 solution for this coding contest problem.
The screen that displays digital numbers that you often see on calculators is called a "7-segment display" because the digital numbers consist of seven parts (segments).
The new product to be launched by Wakamatsu will incorporate a 7-segment display into the product, and as an employee, you will create a program to display the given number on the 7-segment display.
This 7-segment display will not change until the next switch instruction is sent. By sending a signal consisting of 7 bits, the display information of each corresponding segment can be switched. Bits have a value of 1 or 0, where 1 stands for "switch" and 0 stands for "as is".
The correspondence between each bit and segment is shown in the figure below. The signal sends 7 bits in the order of "gfedcba". For example, in order to display "0" from the hidden state, "0111111" must be sent to the display as a signal. To change from "0" to "5", send "1010010". If you want to change "5" to "1" in succession, send "1101011".
<image>
Create a program that takes n (1 ≤ n ≤ 100) numbers that you want to display and outputs the signal sequence required to correctly display those numbers di (0 ≤ di ≤ 9) on the 7-segment display. please. It is assumed that the initial state of the 7-segment display is all hidden.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of -1. Each dataset is given in the following format:
n
d1
d2
::
dn
The number of datasets does not exceed 120.
Output
For each input dataset, output the sequence of signals needed to properly output the numbers to the display.
Example
Input
3
0
5
1
1
0
-1
Output
0111111
1010010
1101011
0111111
"Correct Solution:
```
s=[0b0111111,0b0000110,0b1011011,0b1001111,0b1100110,0b1101101,0b1111101,0b0100111,0b1111111,0b1101111]
while 1:
n=int(input())
if n<0:break
a=0
for _ in range(n):
b=int(input())
print(bin(a^s[b])[2:].zfill(7))
a=s[b]
```
| 99,365 |
Provide a correct Python 3 solution for this coding contest problem.
The screen that displays digital numbers that you often see on calculators is called a "7-segment display" because the digital numbers consist of seven parts (segments).
The new product to be launched by Wakamatsu will incorporate a 7-segment display into the product, and as an employee, you will create a program to display the given number on the 7-segment display.
This 7-segment display will not change until the next switch instruction is sent. By sending a signal consisting of 7 bits, the display information of each corresponding segment can be switched. Bits have a value of 1 or 0, where 1 stands for "switch" and 0 stands for "as is".
The correspondence between each bit and segment is shown in the figure below. The signal sends 7 bits in the order of "gfedcba". For example, in order to display "0" from the hidden state, "0111111" must be sent to the display as a signal. To change from "0" to "5", send "1010010". If you want to change "5" to "1" in succession, send "1101011".
<image>
Create a program that takes n (1 ≤ n ≤ 100) numbers that you want to display and outputs the signal sequence required to correctly display those numbers di (0 ≤ di ≤ 9) on the 7-segment display. please. It is assumed that the initial state of the 7-segment display is all hidden.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of -1. Each dataset is given in the following format:
n
d1
d2
::
dn
The number of datasets does not exceed 120.
Output
For each input dataset, output the sequence of signals needed to properly output the numbers to the display.
Example
Input
3
0
5
1
1
0
-1
Output
0111111
1010010
1101011
0111111
"Correct Solution:
```
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0228
"""
import sys
from sys import stdin
input = stdin.readline
LED_pattern = [
##-gfedcba
0b0111111, # 0
0b0000110, # 1
0b1011011, # 2
0b1001111, # 3
0b1100110, # 4
0b1101101, # 5
0b1111101, # 6
0b0100111, # 7
0b1111111, # 8
0b1101111, # 9
0b0000000 # all OFF
]
def solve(cp, np):
a = LED_pattern[cp]
b = LED_pattern[np]
return bin(a ^ b)[2:].zfill(7)
def main(args):
while True:
n = int(input())
if n == -1:
break
cp = 10 # all OFF
for _ in range(n):
d = int(input())
ans = solve(cp, d)
cp = d
print(ans)
if __name__ == '__main__':
main(sys.argv[1:])
```
| 99,366 |
Provide a correct Python 3 solution for this coding contest problem.
The screen that displays digital numbers that you often see on calculators is called a "7-segment display" because the digital numbers consist of seven parts (segments).
The new product to be launched by Wakamatsu will incorporate a 7-segment display into the product, and as an employee, you will create a program to display the given number on the 7-segment display.
This 7-segment display will not change until the next switch instruction is sent. By sending a signal consisting of 7 bits, the display information of each corresponding segment can be switched. Bits have a value of 1 or 0, where 1 stands for "switch" and 0 stands for "as is".
The correspondence between each bit and segment is shown in the figure below. The signal sends 7 bits in the order of "gfedcba". For example, in order to display "0" from the hidden state, "0111111" must be sent to the display as a signal. To change from "0" to "5", send "1010010". If you want to change "5" to "1" in succession, send "1101011".
<image>
Create a program that takes n (1 ≤ n ≤ 100) numbers that you want to display and outputs the signal sequence required to correctly display those numbers di (0 ≤ di ≤ 9) on the 7-segment display. please. It is assumed that the initial state of the 7-segment display is all hidden.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of -1. Each dataset is given in the following format:
n
d1
d2
::
dn
The number of datasets does not exceed 120.
Output
For each input dataset, output the sequence of signals needed to properly output the numbers to the display.
Example
Input
3
0
5
1
1
0
-1
Output
0111111
1010010
1101011
0111111
"Correct Solution:
```
nums = ["0111111", "0000110", "1011011", "1001111", "1100110",
"1101101", "1111101", "0100111", "1111111", "1101111"]
while 1:
n = int(input())
if n == -1:
break
sig = "0000000"
for _ in range(n):
d = int(input())
num = nums[d]
out = ""
for s, n in zip(sig, num):
if s == n:
out += "0"
else:
out += "1"
print(out)
sig = num
```
| 99,367 |
Provide a correct Python 3 solution for this coding contest problem.
The screen that displays digital numbers that you often see on calculators is called a "7-segment display" because the digital numbers consist of seven parts (segments).
The new product to be launched by Wakamatsu will incorporate a 7-segment display into the product, and as an employee, you will create a program to display the given number on the 7-segment display.
This 7-segment display will not change until the next switch instruction is sent. By sending a signal consisting of 7 bits, the display information of each corresponding segment can be switched. Bits have a value of 1 or 0, where 1 stands for "switch" and 0 stands for "as is".
The correspondence between each bit and segment is shown in the figure below. The signal sends 7 bits in the order of "gfedcba". For example, in order to display "0" from the hidden state, "0111111" must be sent to the display as a signal. To change from "0" to "5", send "1010010". If you want to change "5" to "1" in succession, send "1101011".
<image>
Create a program that takes n (1 ≤ n ≤ 100) numbers that you want to display and outputs the signal sequence required to correctly display those numbers di (0 ≤ di ≤ 9) on the 7-segment display. please. It is assumed that the initial state of the 7-segment display is all hidden.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of -1. Each dataset is given in the following format:
n
d1
d2
::
dn
The number of datasets does not exceed 120.
Output
For each input dataset, output the sequence of signals needed to properly output the numbers to the display.
Example
Input
3
0
5
1
1
0
-1
Output
0111111
1010010
1101011
0111111
"Correct Solution:
```
import sys
f = sys.stdin
segment =[0b0111111,
0b0000110,
0b1011011,
0b1001111,
0b1100110,
0b1101101,
0b1111101,
0b0100111,
0b1111111,
0b1101111]
while True:
n = int(f.readline())
if n == -1:
break
display = 0
for i in [int(f.readline()) for _ in range(n)]:
print(bin(display ^ segment[i])[2:].zfill(7))
display = segment[i]
```
| 99,368 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The screen that displays digital numbers that you often see on calculators is called a "7-segment display" because the digital numbers consist of seven parts (segments).
The new product to be launched by Wakamatsu will incorporate a 7-segment display into the product, and as an employee, you will create a program to display the given number on the 7-segment display.
This 7-segment display will not change until the next switch instruction is sent. By sending a signal consisting of 7 bits, the display information of each corresponding segment can be switched. Bits have a value of 1 or 0, where 1 stands for "switch" and 0 stands for "as is".
The correspondence between each bit and segment is shown in the figure below. The signal sends 7 bits in the order of "gfedcba". For example, in order to display "0" from the hidden state, "0111111" must be sent to the display as a signal. To change from "0" to "5", send "1010010". If you want to change "5" to "1" in succession, send "1101011".
<image>
Create a program that takes n (1 ≤ n ≤ 100) numbers that you want to display and outputs the signal sequence required to correctly display those numbers di (0 ≤ di ≤ 9) on the 7-segment display. please. It is assumed that the initial state of the 7-segment display is all hidden.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of -1. Each dataset is given in the following format:
n
d1
d2
::
dn
The number of datasets does not exceed 120.
Output
For each input dataset, output the sequence of signals needed to properly output the numbers to the display.
Example
Input
3
0
5
1
1
0
-1
Output
0111111
1010010
1101011
0111111
Submitted Solution:
```
seg = [[0, 1, 1, 1, 1, 1, 1],
[0, 0, 0, 0, 1, 1, 0],
[1, 0, 1, 1, 0, 1, 1],
[1, 0, 0, 1, 1, 1, 1],
[1, 1, 0, 0, 1, 1, 0],
[1, 1, 0, 1, 1, 0, 1],
[1, 1, 1, 1, 1, 0, 1],
[0, 1, 0, 0, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 0, 1, 1, 1, 1]]
while True :
n = int(input())
if n == -1 :
break
pre = [0]*7
for i in range(n) :
num = int(input())
post = seg[num]
for j in range(7) :
if pre[j] == post[j] :
print(0, end='')
else :
print(1, end='')
print()
pre = post
```
Yes
| 99,369 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The screen that displays digital numbers that you often see on calculators is called a "7-segment display" because the digital numbers consist of seven parts (segments).
The new product to be launched by Wakamatsu will incorporate a 7-segment display into the product, and as an employee, you will create a program to display the given number on the 7-segment display.
This 7-segment display will not change until the next switch instruction is sent. By sending a signal consisting of 7 bits, the display information of each corresponding segment can be switched. Bits have a value of 1 or 0, where 1 stands for "switch" and 0 stands for "as is".
The correspondence between each bit and segment is shown in the figure below. The signal sends 7 bits in the order of "gfedcba". For example, in order to display "0" from the hidden state, "0111111" must be sent to the display as a signal. To change from "0" to "5", send "1010010". If you want to change "5" to "1" in succession, send "1101011".
<image>
Create a program that takes n (1 ≤ n ≤ 100) numbers that you want to display and outputs the signal sequence required to correctly display those numbers di (0 ≤ di ≤ 9) on the 7-segment display. please. It is assumed that the initial state of the 7-segment display is all hidden.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of -1. Each dataset is given in the following format:
n
d1
d2
::
dn
The number of datasets does not exceed 120.
Output
For each input dataset, output the sequence of signals needed to properly output the numbers to the display.
Example
Input
3
0
5
1
1
0
-1
Output
0111111
1010010
1101011
0111111
Submitted Solution:
```
# AOJ 0228: Seven Segments
# Python3 2018.6.25 bal4u
p = [[1,1,1,1,1,1,0], [0,1,1,0,0,0,0], [1,1,0,1,1,0,1], [1,1,1,1,0,0,1], [0,1,1,0,0,1,1], \
[1,0,1,1,0,1,1], [1,0,1,1,1,1,1], [1,1,1,0,0,1,0], [1,1,1,1,1,1,1], [1,1,1,1,0,1,1]]
while True:
n = int(input())
if n < 0: break
a = [0]*7
for i in range(n):
d = int(input())
ans = ''
for j in range(6,-1,-1):
k = (a[j] ^ p[d][j]) & 1
ans += '1' if k else '0'
if k: a[j] = 1-a[j]
print(ans)
```
Yes
| 99,370 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The screen that displays digital numbers that you often see on calculators is called a "7-segment display" because the digital numbers consist of seven parts (segments).
The new product to be launched by Wakamatsu will incorporate a 7-segment display into the product, and as an employee, you will create a program to display the given number on the 7-segment display.
This 7-segment display will not change until the next switch instruction is sent. By sending a signal consisting of 7 bits, the display information of each corresponding segment can be switched. Bits have a value of 1 or 0, where 1 stands for "switch" and 0 stands for "as is".
The correspondence between each bit and segment is shown in the figure below. The signal sends 7 bits in the order of "gfedcba". For example, in order to display "0" from the hidden state, "0111111" must be sent to the display as a signal. To change from "0" to "5", send "1010010". If you want to change "5" to "1" in succession, send "1101011".
<image>
Create a program that takes n (1 ≤ n ≤ 100) numbers that you want to display and outputs the signal sequence required to correctly display those numbers di (0 ≤ di ≤ 9) on the 7-segment display. please. It is assumed that the initial state of the 7-segment display is all hidden.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of -1. Each dataset is given in the following format:
n
d1
d2
::
dn
The number of datasets does not exceed 120.
Output
For each input dataset, output the sequence of signals needed to properly output the numbers to the display.
Example
Input
3
0
5
1
1
0
-1
Output
0111111
1010010
1101011
0111111
Submitted Solution:
```
# Aizu Problem 0228: Seven Segments
import sys, math, os, bisect
# read input:
PYDEV = os.environ.get('PYDEV')
if PYDEV=="True":
sys.stdin = open("sample-input.txt", "rt")
digits = [63, 6, 91, 79, 102, 109, 125, 39, 127, 111]
while True:
n = int(input())
if n == -1:
break
e = 0
for i in range(n):
a = digits[int(input())]
print("{:07b}".format(a^e))
e = a
```
Yes
| 99,371 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The screen that displays digital numbers that you often see on calculators is called a "7-segment display" because the digital numbers consist of seven parts (segments).
The new product to be launched by Wakamatsu will incorporate a 7-segment display into the product, and as an employee, you will create a program to display the given number on the 7-segment display.
This 7-segment display will not change until the next switch instruction is sent. By sending a signal consisting of 7 bits, the display information of each corresponding segment can be switched. Bits have a value of 1 or 0, where 1 stands for "switch" and 0 stands for "as is".
The correspondence between each bit and segment is shown in the figure below. The signal sends 7 bits in the order of "gfedcba". For example, in order to display "0" from the hidden state, "0111111" must be sent to the display as a signal. To change from "0" to "5", send "1010010". If you want to change "5" to "1" in succession, send "1101011".
<image>
Create a program that takes n (1 ≤ n ≤ 100) numbers that you want to display and outputs the signal sequence required to correctly display those numbers di (0 ≤ di ≤ 9) on the 7-segment display. please. It is assumed that the initial state of the 7-segment display is all hidden.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of -1. Each dataset is given in the following format:
n
d1
d2
::
dn
The number of datasets does not exceed 120.
Output
For each input dataset, output the sequence of signals needed to properly output the numbers to the display.
Example
Input
3
0
5
1
1
0
-1
Output
0111111
1010010
1101011
0111111
Submitted Solution:
```
#!/usr/bin/env python3
seven_seg = {
0: '0111111',
1: '0000110',
2: '1011011',
3: '1001111',
4: '1100110',
5: '1101101',
6: '1111101',
7: '0100111',
8: '1111111',
9: '1101111'
}
while True:
seven_seg_state = ['0'] * 7
n = int(input())
if n == -1:
break
for _ in range(n):
in_data = int(input())
for i, s in enumerate(seven_seg_state):
if seven_seg[in_data][i] == s:
print("0", end="")
else:
print("1", end="")
s = seven_seg[in_data][i]
print()
```
No
| 99,372 |
Provide a correct Python 3 solution for this coding contest problem.
$N$ sages are sitting around a round table with $N$ seats. Each sage holds chopsticks with his dominant hand to eat his dinner. The following happens in this situation.
* If sage $i$ is right-handed and a left-handed sage sits on his right, a level of frustration $w_i$ occurs to him. A right-handed sage on his right does not cause such frustration at all.
* If sage $i$ is left-handed and a right-handed sage sits on his left, a level of frustration $w_i$ occurs to him. A left-handed sage on his left does not cause such frustration at all.
You wish you could minimize the total amount of frustration by clever sitting order arrangement.
Given the number of sages with his dominant hand information, make a program to evaluate the minimum frustration achievable.
Input
The input is given in the following format.
$N$
$a_1$ $a_2$ $...$ $a_N$
$w_1$ $w_2$ $...$ $w_N$
The first line provides the number of sages $N$ ($3 \leq N \leq 10$). The second line provides an array of integers $a_i$ (0 or 1) which indicate if the $i$-th sage is right-handed (0) or left-handed (1). The third line provides an array of integers $w_i$ ($1 \leq w_i \leq 1000$) which indicate the level of frustration the $i$-th sage bears.
Output
Output the minimum total frustration the sages bear.
Examples
Input
5
1 0 0 1 0
2 3 5 1 2
Output
3
Input
3
0 0 0
1 2 3
Output
0
"Correct Solution:
```
N = int(input())
a = [int(i) for i in input().split()]
w = [int(i) for i in input().split()]
rightMin = 1001
leftMin = 1001
for i in range(N):
if a[i] == 0:
rightMin = min(rightMin, w[i])
else:
leftMin = min(leftMin, w[i])
if rightMin == 1001 or leftMin == 1001:
print(0)
else:
print(rightMin + leftMin)
```
| 99,373 |
Provide a correct Python 3 solution for this coding contest problem.
$N$ sages are sitting around a round table with $N$ seats. Each sage holds chopsticks with his dominant hand to eat his dinner. The following happens in this situation.
* If sage $i$ is right-handed and a left-handed sage sits on his right, a level of frustration $w_i$ occurs to him. A right-handed sage on his right does not cause such frustration at all.
* If sage $i$ is left-handed and a right-handed sage sits on his left, a level of frustration $w_i$ occurs to him. A left-handed sage on his left does not cause such frustration at all.
You wish you could minimize the total amount of frustration by clever sitting order arrangement.
Given the number of sages with his dominant hand information, make a program to evaluate the minimum frustration achievable.
Input
The input is given in the following format.
$N$
$a_1$ $a_2$ $...$ $a_N$
$w_1$ $w_2$ $...$ $w_N$
The first line provides the number of sages $N$ ($3 \leq N \leq 10$). The second line provides an array of integers $a_i$ (0 or 1) which indicate if the $i$-th sage is right-handed (0) or left-handed (1). The third line provides an array of integers $w_i$ ($1 \leq w_i \leq 1000$) which indicate the level of frustration the $i$-th sage bears.
Output
Output the minimum total frustration the sages bear.
Examples
Input
5
1 0 0 1 0
2 3 5 1 2
Output
3
Input
3
0 0 0
1 2 3
Output
0
"Correct Solution:
```
n = int(input())
a = list(map(int,input().split()))
w = list(map(int,input().split()))
INF = 10**9
x = [INF]*2
for i in range(n):
x[a[i]] = min(x[a[i]], w[i])
ans = sum(x)
if ans >= INF:
ans = 0
print(ans)
```
| 99,374 |
Provide a correct Python 3 solution for this coding contest problem.
$N$ sages are sitting around a round table with $N$ seats. Each sage holds chopsticks with his dominant hand to eat his dinner. The following happens in this situation.
* If sage $i$ is right-handed and a left-handed sage sits on his right, a level of frustration $w_i$ occurs to him. A right-handed sage on his right does not cause such frustration at all.
* If sage $i$ is left-handed and a right-handed sage sits on his left, a level of frustration $w_i$ occurs to him. A left-handed sage on his left does not cause such frustration at all.
You wish you could minimize the total amount of frustration by clever sitting order arrangement.
Given the number of sages with his dominant hand information, make a program to evaluate the minimum frustration achievable.
Input
The input is given in the following format.
$N$
$a_1$ $a_2$ $...$ $a_N$
$w_1$ $w_2$ $...$ $w_N$
The first line provides the number of sages $N$ ($3 \leq N \leq 10$). The second line provides an array of integers $a_i$ (0 or 1) which indicate if the $i$-th sage is right-handed (0) or left-handed (1). The third line provides an array of integers $w_i$ ($1 \leq w_i \leq 1000$) which indicate the level of frustration the $i$-th sage bears.
Output
Output the minimum total frustration the sages bear.
Examples
Input
5
1 0 0 1 0
2 3 5 1 2
Output
3
Input
3
0 0 0
1 2 3
Output
0
"Correct Solution:
```
N = input()
a = [int(x) for x in input().split()]
w = [int(x) for x in input().split()]
R = [w for a, w in zip(a, w) if a == 0]
L = [w for a, w in zip(a, w) if a == 1]
if R and L:
print(min(R) + min(L))
else:
print(0)
```
| 99,375 |
Provide a correct Python 3 solution for this coding contest problem.
$N$ sages are sitting around a round table with $N$ seats. Each sage holds chopsticks with his dominant hand to eat his dinner. The following happens in this situation.
* If sage $i$ is right-handed and a left-handed sage sits on his right, a level of frustration $w_i$ occurs to him. A right-handed sage on his right does not cause such frustration at all.
* If sage $i$ is left-handed and a right-handed sage sits on his left, a level of frustration $w_i$ occurs to him. A left-handed sage on his left does not cause such frustration at all.
You wish you could minimize the total amount of frustration by clever sitting order arrangement.
Given the number of sages with his dominant hand information, make a program to evaluate the minimum frustration achievable.
Input
The input is given in the following format.
$N$
$a_1$ $a_2$ $...$ $a_N$
$w_1$ $w_2$ $...$ $w_N$
The first line provides the number of sages $N$ ($3 \leq N \leq 10$). The second line provides an array of integers $a_i$ (0 or 1) which indicate if the $i$-th sage is right-handed (0) or left-handed (1). The third line provides an array of integers $w_i$ ($1 \leq w_i \leq 1000$) which indicate the level of frustration the $i$-th sage bears.
Output
Output the minimum total frustration the sages bear.
Examples
Input
5
1 0 0 1 0
2 3 5 1 2
Output
3
Input
3
0 0 0
1 2 3
Output
0
"Correct Solution:
```
n = int(input())
alst = list(map(int, input().split()))
wlst = list(map(int, input().split()))
right = [w for a, w in zip(alst, wlst) if a == 0]
left = [w for a, w in zip(alst, wlst) if a == 1]
if right and left:
print(min(right) + min(left))
else:
print(0)
```
| 99,376 |
Provide a correct Python 3 solution for this coding contest problem.
$N$ sages are sitting around a round table with $N$ seats. Each sage holds chopsticks with his dominant hand to eat his dinner. The following happens in this situation.
* If sage $i$ is right-handed and a left-handed sage sits on his right, a level of frustration $w_i$ occurs to him. A right-handed sage on his right does not cause such frustration at all.
* If sage $i$ is left-handed and a right-handed sage sits on his left, a level of frustration $w_i$ occurs to him. A left-handed sage on his left does not cause such frustration at all.
You wish you could minimize the total amount of frustration by clever sitting order arrangement.
Given the number of sages with his dominant hand information, make a program to evaluate the minimum frustration achievable.
Input
The input is given in the following format.
$N$
$a_1$ $a_2$ $...$ $a_N$
$w_1$ $w_2$ $...$ $w_N$
The first line provides the number of sages $N$ ($3 \leq N \leq 10$). The second line provides an array of integers $a_i$ (0 or 1) which indicate if the $i$-th sage is right-handed (0) or left-handed (1). The third line provides an array of integers $w_i$ ($1 \leq w_i \leq 1000$) which indicate the level of frustration the $i$-th sage bears.
Output
Output the minimum total frustration the sages bear.
Examples
Input
5
1 0 0 1 0
2 3 5 1 2
Output
3
Input
3
0 0 0
1 2 3
Output
0
"Correct Solution:
```
N = int(input())
*A, = map(int, input().split())
*W, = map(int, input().split())
INF = 10**9
l = r = INF
for a, w in zip(A, W):
if a:
r = min(w, r)
else:
l = min(w, l)
if l == INF or r == INF:
print(0)
else:
print(l+r)
```
| 99,377 |
Provide a correct Python 3 solution for this coding contest problem.
$N$ sages are sitting around a round table with $N$ seats. Each sage holds chopsticks with his dominant hand to eat his dinner. The following happens in this situation.
* If sage $i$ is right-handed and a left-handed sage sits on his right, a level of frustration $w_i$ occurs to him. A right-handed sage on his right does not cause such frustration at all.
* If sage $i$ is left-handed and a right-handed sage sits on his left, a level of frustration $w_i$ occurs to him. A left-handed sage on his left does not cause such frustration at all.
You wish you could minimize the total amount of frustration by clever sitting order arrangement.
Given the number of sages with his dominant hand information, make a program to evaluate the minimum frustration achievable.
Input
The input is given in the following format.
$N$
$a_1$ $a_2$ $...$ $a_N$
$w_1$ $w_2$ $...$ $w_N$
The first line provides the number of sages $N$ ($3 \leq N \leq 10$). The second line provides an array of integers $a_i$ (0 or 1) which indicate if the $i$-th sage is right-handed (0) or left-handed (1). The third line provides an array of integers $w_i$ ($1 \leq w_i \leq 1000$) which indicate the level of frustration the $i$-th sage bears.
Output
Output the minimum total frustration the sages bear.
Examples
Input
5
1 0 0 1 0
2 3 5 1 2
Output
3
Input
3
0 0 0
1 2 3
Output
0
"Correct Solution:
```
n = int(input())
a = [int(_) for _ in input().split()]
w = [int(_) for _ in input().split()]
if sum(a) == n or sum(a) == 0:
print(0)
quit()
lia = []
lib = []
for i in range(n):
if a[i] == 0:
lia.append(w[i])
else:
lib.append(w[i])
print(min(lia)+min(lib))
```
| 99,378 |
Provide a correct Python 3 solution for this coding contest problem.
$N$ sages are sitting around a round table with $N$ seats. Each sage holds chopsticks with his dominant hand to eat his dinner. The following happens in this situation.
* If sage $i$ is right-handed and a left-handed sage sits on his right, a level of frustration $w_i$ occurs to him. A right-handed sage on his right does not cause such frustration at all.
* If sage $i$ is left-handed and a right-handed sage sits on his left, a level of frustration $w_i$ occurs to him. A left-handed sage on his left does not cause such frustration at all.
You wish you could minimize the total amount of frustration by clever sitting order arrangement.
Given the number of sages with his dominant hand information, make a program to evaluate the minimum frustration achievable.
Input
The input is given in the following format.
$N$
$a_1$ $a_2$ $...$ $a_N$
$w_1$ $w_2$ $...$ $w_N$
The first line provides the number of sages $N$ ($3 \leq N \leq 10$). The second line provides an array of integers $a_i$ (0 or 1) which indicate if the $i$-th sage is right-handed (0) or left-handed (1). The third line provides an array of integers $w_i$ ($1 \leq w_i \leq 1000$) which indicate the level of frustration the $i$-th sage bears.
Output
Output the minimum total frustration the sages bear.
Examples
Input
5
1 0 0 1 0
2 3 5 1 2
Output
3
Input
3
0 0 0
1 2 3
Output
0
"Correct Solution:
```
n = int(input())
aw = [[0,0] for i in range(n)]
for i, a in enumerate(map(int, input().split())): aw[i][0] = a
for i, w in enumerate(map(int, input().split())): aw[i][1] = w
migimin = 1001
hidarimin = 1001
for a,w in aw:
if a: hidarimin = min(hidarimin, w)
else: migimin = min(migimin, w)
if hidarimin>1000 or migimin>1000: print(0)
else: print(hidarimin+migimin)
```
| 99,379 |
Provide a correct Python 3 solution for this coding contest problem.
Dr. Asimov, a robotics researcher, loves to research, but hates houseworks and his house were really dirty. So, he has developed a cleaning robot.
As shown in the following figure, his house has 9 rooms, where each room is identified by an alphabet:
<image>
The robot he developed operates as follows:
* If the battery runs down, the robot stops.
* If not so, the robot chooses a direction from four cardinal points with the equal probability, and moves to the room in that direction. Then, the robot clean the room and consumes 1 point of the battery.
* However, if there is no room in that direction, the robot does not move and remains the same room. In addition, there is a junk room in the house where the robot can not enter, and the robot also remains when it tries to enter the junk room. The robot also consumes 1 point of the battery when it remains the same place.
A battery charger for the robot is in a room. It would be convenient for Dr. Asimov if the robot stops at the battery room when its battery run down.
Your task is to write a program which computes the probability of the robot stopping at the battery room.
Constraints
* Judge data includes at most 100 data sets.
* n ≤ 15
* s, t, b are distinct.
Input
The input consists of several datasets. Each dataset consists of:
n
s t b
n is an integer that indicates the initial battery point. s, t, b are alphabets respectively represent the room where the robot is initially, the battery room, and the junk room.
The input ends with a dataset which consists of single 0 for n. Your program should not output for this dataset.
Output
For each dataset, print the probability as a floating point number in a line. The answer may not have an error greater than 0.000001.
Example
Input
1
E A C
1
E B C
2
E A B
0
Output
0.00000000
0.25000000
0.06250000
"Correct Solution:
```
while True:
n = int(input())
if n == 0:
break
s, t, b = input().split()
base = ord("A")
blank = ord(b) - base
dp = [[0] * 9 for _ in range(n + 1)]
dp[0][ord(s) - base] = 1
to = {0:(0, 0, 1, 3), 1:(0, 1, 2, 4), 2:(1, 2, 2, 5), 3:(0, 3, 4, 6),
4:(1, 3, 5, 7), 5:(2, 4, 5, 8), 6:(3, 6, 6, 7), 7:(4, 6, 7, 8), 8:(5, 7, 8, 8)}
def update(x, i):
for nex in to[x]:
if nex == blank:
dp[i][x] += dp[i - 1][x] / 4
else:
dp[i][nex] += dp[i - 1][x] / 4
for i in range(1, n + 1):
for x in range(9):
update(x, i)
print(dp[n][ord(t) - base])
```
| 99,380 |
Provide a correct Python 3 solution for this coding contest problem.
Dr. Asimov, a robotics researcher, loves to research, but hates houseworks and his house were really dirty. So, he has developed a cleaning robot.
As shown in the following figure, his house has 9 rooms, where each room is identified by an alphabet:
<image>
The robot he developed operates as follows:
* If the battery runs down, the robot stops.
* If not so, the robot chooses a direction from four cardinal points with the equal probability, and moves to the room in that direction. Then, the robot clean the room and consumes 1 point of the battery.
* However, if there is no room in that direction, the robot does not move and remains the same room. In addition, there is a junk room in the house where the robot can not enter, and the robot also remains when it tries to enter the junk room. The robot also consumes 1 point of the battery when it remains the same place.
A battery charger for the robot is in a room. It would be convenient for Dr. Asimov if the robot stops at the battery room when its battery run down.
Your task is to write a program which computes the probability of the robot stopping at the battery room.
Constraints
* Judge data includes at most 100 data sets.
* n ≤ 15
* s, t, b are distinct.
Input
The input consists of several datasets. Each dataset consists of:
n
s t b
n is an integer that indicates the initial battery point. s, t, b are alphabets respectively represent the room where the robot is initially, the battery room, and the junk room.
The input ends with a dataset which consists of single 0 for n. Your program should not output for this dataset.
Output
For each dataset, print the probability as a floating point number in a line. The answer may not have an error greater than 0.000001.
Example
Input
1
E A C
1
E B C
2
E A B
0
Output
0.00000000
0.25000000
0.06250000
"Correct Solution:
```
# AOJ 1020: Cleaning Robot
# Python3 2018.7.5 bal4u
mv = ((-1,0),(0,1),(1,0),(0,-1))
while True:
n = int(input())
if n == 0: break
t1, t2, t3 = input().split()
s, t, b = ord(t1)-ord('A'), ord(t2)-ord('A'), ord(t3)-ord('A')
f = [[[0.0 for a in range(3)] for c in range(3)] for r in range(17)]
f[0][s//3][s%3] = 1
for j in range(1, n+1):
for r in range(3):
for c in range(3):
for i in range(4):
r2, c2 = r + mv[i][0], c + mv[i][1]
if r2 < 0 or r2 >= 3 or c2 < 0 or c2 >= 3 or 3*r2+c2 == b:
r2, c2 = r, c
f[j][r2][c2] += f[j-1][r][c]/4
print(f[n][t//3][t%3])
```
| 99,381 |
Provide a correct Python 3 solution for this coding contest problem.
Dr. Asimov, a robotics researcher, loves to research, but hates houseworks and his house were really dirty. So, he has developed a cleaning robot.
As shown in the following figure, his house has 9 rooms, where each room is identified by an alphabet:
<image>
The robot he developed operates as follows:
* If the battery runs down, the robot stops.
* If not so, the robot chooses a direction from four cardinal points with the equal probability, and moves to the room in that direction. Then, the robot clean the room and consumes 1 point of the battery.
* However, if there is no room in that direction, the robot does not move and remains the same room. In addition, there is a junk room in the house where the robot can not enter, and the robot also remains when it tries to enter the junk room. The robot also consumes 1 point of the battery when it remains the same place.
A battery charger for the robot is in a room. It would be convenient for Dr. Asimov if the robot stops at the battery room when its battery run down.
Your task is to write a program which computes the probability of the robot stopping at the battery room.
Constraints
* Judge data includes at most 100 data sets.
* n ≤ 15
* s, t, b are distinct.
Input
The input consists of several datasets. Each dataset consists of:
n
s t b
n is an integer that indicates the initial battery point. s, t, b are alphabets respectively represent the room where the robot is initially, the battery room, and the junk room.
The input ends with a dataset which consists of single 0 for n. Your program should not output for this dataset.
Output
For each dataset, print the probability as a floating point number in a line. The answer may not have an error greater than 0.000001.
Example
Input
1
E A C
1
E B C
2
E A B
0
Output
0.00000000
0.25000000
0.06250000
"Correct Solution:
```
index = "ABCDEFGHI".index
dd = ((-1, 0), (0, -1), (1, 0), (0, 1))
while 1:
N = int(input())
if N == 0:
break
s, t, b = map(index, input().split())
S = [[0]*3 for i in range(3)]
sy, sx = divmod(s, 3)
ty, tx = divmod(t, 3)
by, bx = divmod(b, 3)
T = [[0]*3 for i in range(3)]
S[sy][sx] = 1
for i in range(N):
for y in range(3):
for x in range(3):
if x == bx and y == by:
T[y][x] = 0
continue
r = 0
for dx, dy in dd:
nx = x + dx; ny = y + dy
if not 0 <= nx < 3 or not 0 <= ny < 3 or (bx == nx and by == ny):
nx = x; ny = y
r += S[ny][nx]
T[y][x] = r
S, T = T, S
su = sum(sum(e) for e in S)
print("%.15f" % (S[ty][tx] / su))
```
| 99,382 |
Provide a correct Python 3 solution for this coding contest problem.
Consider car trips in a country where there is no friction. Cars in this country do not have engines. Once a car started to move at a speed, it keeps moving at the same speed. There are acceleration devices on some points on the road, where a car can increase or decrease its speed by 1. It can also keep its speed there. Your job in this problem is to write a program which determines the route with the shortest time to travel from a starting city to a goal city.
There are several cities in the country, and a road network connecting them. Each city has an acceleration device. As mentioned above, if a car arrives at a city at a speed v , it leaves the city at one of v - 1, v , or v + 1. The first road leaving the starting city must be run at the speed 1. Similarly, the last road arriving at the goal city must be run at the speed 1.
The starting city and the goal city are given. The problem is to find the best route which leads to the goal city going through several cities on the road network. When the car arrives at a city, it cannot immediately go back the road it used to reach the city. No U-turns are allowed. Except this constraint, one can choose any route on the road network. It is allowed to visit the same city or use the same road multiple times. The starting city and the goal city may be visited during the trip.
For each road on the network, its distance and speed limit are given. A car must run a road at a speed less than or equal to its speed limit. The time needed to run a road is the distance divided by the speed. The time needed within cities including that for acceleration or deceleration should be ignored.
Input
The input consists of multiple datasets, each in the following format.
> n m
> s g
> x 1 y 1 d 1 c 1
> ...
> xm ym dm cm
>
Every input item in a dataset is a non-negative integer. Input items in the same line are separated by a space.
The first line gives the size of the road network. n is the number of cities in the network. You can assume that the number of cities is between 2 and 30, inclusive. m is the number of roads between cities, which may be zero.
The second line gives the trip. s is the city index of the starting city. g is the city index of the goal city. s is not equal to g . You can assume that all city indices in a dataset (including the above two) are between 1 and n , inclusive.
The following m lines give the details of roads between cities. The i -th road connects two cities with city indices xi and yi , and has a distance di (1 ≤ i ≤ m ). You can assume that the distance is between 1 and 100, inclusive. The speed limit of the road is specified by ci . You can assume that the speed limit is between 1 and 30, inclusive.
No two roads connect the same pair of cities. A road never connects a city with itself. Each road can be traveled in both directions.
The last dataset is followed by a line containing two zeros (separated by a space).
Output
For each dataset in the input, one line should be output as specified below. An output line should not contain extra characters such as spaces.
If one can travel from the starting city to the goal city, the time needed for the best route (a route with the shortest time) should be printed. The answer should not have an error greater than 0.001. You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied.
If it is impossible to reach the goal city, the string "`unreachable`" should be printed. Note that all the letters of "`unreachable`" are in lowercase.
Sample Input
2 0
1 2
5 4
1 5
1 2 1 1
2 3 2 2
3 4 2 2
4 5 1 1
6 6
1 6
1 2 2 1
2 3 2 1
3 6 2 1
1 4 2 30
4 5 3 30
5 6 2 30
6 7
1 6
1 2 1 30
2 3 1 30
3 1 1 30
3 4 100 30
4 5 1 30
5 6 1 30
6 4 1 30
0 0
Output for the Sample Input
unreachable
4.00000
5.50000
11.25664
Example
Input
2 0
1 2
5 4
1 5
1 2 1 1
2 3 2 2
3 4 2 2
4 5 1 1
6 6
1 6
1 2 2 1
2 3 2 1
3 6 2 1
1 4 2 30
4 5 3 30
5 6 2 30
6 7
1 6
1 2 1 30
2 3 1 30
3 1 1 30
3 4 100 30
4 5 1 30
5 6 1 30
6 4 1 30
0 0
Output
unreachable
4.00000
5.50000
11.25664
"Correct Solution:
```
import sys
import heapq
if sys.version[0] == '2':
range, input = xrange, raw_input
MAX_SPEED = 30
dvs = (-1, 0, 1)
while True:
N, M = map(int, input().split())
if not (N | M):
break
S, G = map(lambda x: int(x) - 1, input().split())
edge = [[] for _ in range(N)]
for _ in range(M):
x, y, d, c = map(int, input().split())
edge[x - 1].append((y - 1, d, c))
edge[y - 1].append((x - 1, d, c))
INF = 1e9
dist = [[[INF for _ in range(N)] for _ in range(MAX_SPEED + 1)] for _ in range(N)]
que = [(0.0, S, 0, S)]
while que:
cost, now, v, prev = heapq.heappop(que)
if cost > dist[now][v][prev]:
continue
if now == G and v == 1:
print("{:.20f}".format(cost))
break
dist[now][v][prev] = cost
for x, d, c in edge[now]:
if x == prev:
continue
for dv in dvs:
nv = v + dv
if 0 < nv <= c and dist[x][nv][now] > dist[now][v][prev] + d / nv:
dist[x][nv][now] = dist[now][v][prev] + d / nv
heapq.heappush(que, (dist[x][nv][now], x, nv, now))
else:
print("unreachable")
```
| 99,383 |
Provide a correct Python 3 solution for this coding contest problem.
Consider car trips in a country where there is no friction. Cars in this country do not have engines. Once a car started to move at a speed, it keeps moving at the same speed. There are acceleration devices on some points on the road, where a car can increase or decrease its speed by 1. It can also keep its speed there. Your job in this problem is to write a program which determines the route with the shortest time to travel from a starting city to a goal city.
There are several cities in the country, and a road network connecting them. Each city has an acceleration device. As mentioned above, if a car arrives at a city at a speed v , it leaves the city at one of v - 1, v , or v + 1. The first road leaving the starting city must be run at the speed 1. Similarly, the last road arriving at the goal city must be run at the speed 1.
The starting city and the goal city are given. The problem is to find the best route which leads to the goal city going through several cities on the road network. When the car arrives at a city, it cannot immediately go back the road it used to reach the city. No U-turns are allowed. Except this constraint, one can choose any route on the road network. It is allowed to visit the same city or use the same road multiple times. The starting city and the goal city may be visited during the trip.
For each road on the network, its distance and speed limit are given. A car must run a road at a speed less than or equal to its speed limit. The time needed to run a road is the distance divided by the speed. The time needed within cities including that for acceleration or deceleration should be ignored.
Input
The input consists of multiple datasets, each in the following format.
> n m
> s g
> x 1 y 1 d 1 c 1
> ...
> xm ym dm cm
>
Every input item in a dataset is a non-negative integer. Input items in the same line are separated by a space.
The first line gives the size of the road network. n is the number of cities in the network. You can assume that the number of cities is between 2 and 30, inclusive. m is the number of roads between cities, which may be zero.
The second line gives the trip. s is the city index of the starting city. g is the city index of the goal city. s is not equal to g . You can assume that all city indices in a dataset (including the above two) are between 1 and n , inclusive.
The following m lines give the details of roads between cities. The i -th road connects two cities with city indices xi and yi , and has a distance di (1 ≤ i ≤ m ). You can assume that the distance is between 1 and 100, inclusive. The speed limit of the road is specified by ci . You can assume that the speed limit is between 1 and 30, inclusive.
No two roads connect the same pair of cities. A road never connects a city with itself. Each road can be traveled in both directions.
The last dataset is followed by a line containing two zeros (separated by a space).
Output
For each dataset in the input, one line should be output as specified below. An output line should not contain extra characters such as spaces.
If one can travel from the starting city to the goal city, the time needed for the best route (a route with the shortest time) should be printed. The answer should not have an error greater than 0.001. You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied.
If it is impossible to reach the goal city, the string "`unreachable`" should be printed. Note that all the letters of "`unreachable`" are in lowercase.
Sample Input
2 0
1 2
5 4
1 5
1 2 1 1
2 3 2 2
3 4 2 2
4 5 1 1
6 6
1 6
1 2 2 1
2 3 2 1
3 6 2 1
1 4 2 30
4 5 3 30
5 6 2 30
6 7
1 6
1 2 1 30
2 3 1 30
3 1 1 30
3 4 100 30
4 5 1 30
5 6 1 30
6 4 1 30
0 0
Output for the Sample Input
unreachable
4.00000
5.50000
11.25664
Example
Input
2 0
1 2
5 4
1 5
1 2 1 1
2 3 2 2
3 4 2 2
4 5 1 1
6 6
1 6
1 2 2 1
2 3 2 1
3 6 2 1
1 4 2 30
4 5 3 30
5 6 2 30
6 7
1 6
1 2 1 30
2 3 1 30
3 1 1 30
3 4 100 30
4 5 1 30
5 6 1 30
6 4 1 30
0 0
Output
unreachable
4.00000
5.50000
11.25664
"Correct Solution:
```
from collections import defaultdict
from heapq import heappop, heappush
while True:
n, m = map(int, input().split())
if n==0 and m==0:
break
s, g = map(int, input().split())
graph = defaultdict(list)
for _ in range(m):
x, y, d, c = map(int, input().split())
graph[x].append((y, d, c))
graph[y].append((x, d, c))
def dijkstra(s):
d = defaultdict(lambda:float("INF"))
d[(s, 0, -1)] = 0
used = defaultdict(bool)
q = []
heappush(q, (0, (s, 0, -1)))
while len(q):
elapsed, v = heappop(q)
cur, vel1, prev1 = v[0], v[1], v[2]
if cur==g and vel1 == 1:
return elapsed
if used[v]:
continue
used[v] = True
for to, dist, ct in graph[cur]:
if to==prev1:
continue
for vel2 in range(vel1-1, vel1+2):
if vel2<1 or ct<vel2:
continue
nxt = (to, vel2, cur)
if used[nxt]:
continue
elapsed2 = elapsed+dist/vel2
if d[nxt] > elapsed2:
d[nxt] = elapsed2
heappush(q, (elapsed2, nxt))
return "unreachable"
print(dijkstra(s))
```
| 99,384 |
Provide a correct Python 3 solution for this coding contest problem.
Consider car trips in a country where there is no friction. Cars in this country do not have engines. Once a car started to move at a speed, it keeps moving at the same speed. There are acceleration devices on some points on the road, where a car can increase or decrease its speed by 1. It can also keep its speed there. Your job in this problem is to write a program which determines the route with the shortest time to travel from a starting city to a goal city.
There are several cities in the country, and a road network connecting them. Each city has an acceleration device. As mentioned above, if a car arrives at a city at a speed v , it leaves the city at one of v - 1, v , or v + 1. The first road leaving the starting city must be run at the speed 1. Similarly, the last road arriving at the goal city must be run at the speed 1.
The starting city and the goal city are given. The problem is to find the best route which leads to the goal city going through several cities on the road network. When the car arrives at a city, it cannot immediately go back the road it used to reach the city. No U-turns are allowed. Except this constraint, one can choose any route on the road network. It is allowed to visit the same city or use the same road multiple times. The starting city and the goal city may be visited during the trip.
For each road on the network, its distance and speed limit are given. A car must run a road at a speed less than or equal to its speed limit. The time needed to run a road is the distance divided by the speed. The time needed within cities including that for acceleration or deceleration should be ignored.
Input
The input consists of multiple datasets, each in the following format.
> n m
> s g
> x 1 y 1 d 1 c 1
> ...
> xm ym dm cm
>
Every input item in a dataset is a non-negative integer. Input items in the same line are separated by a space.
The first line gives the size of the road network. n is the number of cities in the network. You can assume that the number of cities is between 2 and 30, inclusive. m is the number of roads between cities, which may be zero.
The second line gives the trip. s is the city index of the starting city. g is the city index of the goal city. s is not equal to g . You can assume that all city indices in a dataset (including the above two) are between 1 and n , inclusive.
The following m lines give the details of roads between cities. The i -th road connects two cities with city indices xi and yi , and has a distance di (1 ≤ i ≤ m ). You can assume that the distance is between 1 and 100, inclusive. The speed limit of the road is specified by ci . You can assume that the speed limit is between 1 and 30, inclusive.
No two roads connect the same pair of cities. A road never connects a city with itself. Each road can be traveled in both directions.
The last dataset is followed by a line containing two zeros (separated by a space).
Output
For each dataset in the input, one line should be output as specified below. An output line should not contain extra characters such as spaces.
If one can travel from the starting city to the goal city, the time needed for the best route (a route with the shortest time) should be printed. The answer should not have an error greater than 0.001. You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied.
If it is impossible to reach the goal city, the string "`unreachable`" should be printed. Note that all the letters of "`unreachable`" are in lowercase.
Sample Input
2 0
1 2
5 4
1 5
1 2 1 1
2 3 2 2
3 4 2 2
4 5 1 1
6 6
1 6
1 2 2 1
2 3 2 1
3 6 2 1
1 4 2 30
4 5 3 30
5 6 2 30
6 7
1 6
1 2 1 30
2 3 1 30
3 1 1 30
3 4 100 30
4 5 1 30
5 6 1 30
6 4 1 30
0 0
Output for the Sample Input
unreachable
4.00000
5.50000
11.25664
Example
Input
2 0
1 2
5 4
1 5
1 2 1 1
2 3 2 2
3 4 2 2
4 5 1 1
6 6
1 6
1 2 2 1
2 3 2 1
3 6 2 1
1 4 2 30
4 5 3 30
5 6 2 30
6 7
1 6
1 2 1 30
2 3 1 30
3 1 1 30
3 4 100 30
4 5 1 30
5 6 1 30
6 4 1 30
0 0
Output
unreachable
4.00000
5.50000
11.25664
"Correct Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def main():
rr = []
while True:
n,m = LI()
if n == 0:
break
s,g = LI()
a = [LI() for _ in range(m)]
e = collections.defaultdict(list)
for x,y,d,c in a:
e[x].append((y,d,c))
e[y].append((x,d,c))
def search(s):
d = collections.defaultdict(lambda: inf)
d[(s,0,-1)] = 0
q = []
heapq.heappush(q, (0, (s, 0, -1)))
v = collections.defaultdict(bool)
while len(q):
k, u = heapq.heappop(q)
if v[u]:
continue
v[u] = True
if u[0] == g and u[1] == 1:
return '{:0.9f}'.format(k)
c = u[1]
b = u[2]
for uv, ud, uc in e[u[0]]:
if uv == b:
continue
for tc in range(max(c-1,1),min(uc+1,c+2)):
nuv = (uv, tc, u[0])
if v[nuv]:
continue
vd = k + ud / tc
if d[nuv] > vd:
d[nuv] = vd
heapq.heappush(q, (vd, nuv))
return 'unreachable'
rr.append(search(s))
return '\n'.join(map(str, rr))
print(main())
```
| 99,385 |
Provide a correct Python 3 solution for this coding contest problem.
Consider car trips in a country where there is no friction. Cars in this country do not have engines. Once a car started to move at a speed, it keeps moving at the same speed. There are acceleration devices on some points on the road, where a car can increase or decrease its speed by 1. It can also keep its speed there. Your job in this problem is to write a program which determines the route with the shortest time to travel from a starting city to a goal city.
There are several cities in the country, and a road network connecting them. Each city has an acceleration device. As mentioned above, if a car arrives at a city at a speed v , it leaves the city at one of v - 1, v , or v + 1. The first road leaving the starting city must be run at the speed 1. Similarly, the last road arriving at the goal city must be run at the speed 1.
The starting city and the goal city are given. The problem is to find the best route which leads to the goal city going through several cities on the road network. When the car arrives at a city, it cannot immediately go back the road it used to reach the city. No U-turns are allowed. Except this constraint, one can choose any route on the road network. It is allowed to visit the same city or use the same road multiple times. The starting city and the goal city may be visited during the trip.
For each road on the network, its distance and speed limit are given. A car must run a road at a speed less than or equal to its speed limit. The time needed to run a road is the distance divided by the speed. The time needed within cities including that for acceleration or deceleration should be ignored.
Input
The input consists of multiple datasets, each in the following format.
> n m
> s g
> x 1 y 1 d 1 c 1
> ...
> xm ym dm cm
>
Every input item in a dataset is a non-negative integer. Input items in the same line are separated by a space.
The first line gives the size of the road network. n is the number of cities in the network. You can assume that the number of cities is between 2 and 30, inclusive. m is the number of roads between cities, which may be zero.
The second line gives the trip. s is the city index of the starting city. g is the city index of the goal city. s is not equal to g . You can assume that all city indices in a dataset (including the above two) are between 1 and n , inclusive.
The following m lines give the details of roads between cities. The i -th road connects two cities with city indices xi and yi , and has a distance di (1 ≤ i ≤ m ). You can assume that the distance is between 1 and 100, inclusive. The speed limit of the road is specified by ci . You can assume that the speed limit is between 1 and 30, inclusive.
No two roads connect the same pair of cities. A road never connects a city with itself. Each road can be traveled in both directions.
The last dataset is followed by a line containing two zeros (separated by a space).
Output
For each dataset in the input, one line should be output as specified below. An output line should not contain extra characters such as spaces.
If one can travel from the starting city to the goal city, the time needed for the best route (a route with the shortest time) should be printed. The answer should not have an error greater than 0.001. You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied.
If it is impossible to reach the goal city, the string "`unreachable`" should be printed. Note that all the letters of "`unreachable`" are in lowercase.
Sample Input
2 0
1 2
5 4
1 5
1 2 1 1
2 3 2 2
3 4 2 2
4 5 1 1
6 6
1 6
1 2 2 1
2 3 2 1
3 6 2 1
1 4 2 30
4 5 3 30
5 6 2 30
6 7
1 6
1 2 1 30
2 3 1 30
3 1 1 30
3 4 100 30
4 5 1 30
5 6 1 30
6 4 1 30
0 0
Output for the Sample Input
unreachable
4.00000
5.50000
11.25664
Example
Input
2 0
1 2
5 4
1 5
1 2 1 1
2 3 2 2
3 4 2 2
4 5 1 1
6 6
1 6
1 2 2 1
2 3 2 1
3 6 2 1
1 4 2 30
4 5 3 30
5 6 2 30
6 7
1 6
1 2 1 30
2 3 1 30
3 1 1 30
3 4 100 30
4 5 1 30
5 6 1 30
6 4 1 30
0 0
Output
unreachable
4.00000
5.50000
11.25664
"Correct Solution:
```
def solve():
import sys
from heapq import heappush, heappop
file_input = sys.stdin
inf = float('inf')
while True:
n, m = map(int, file_input.readline().split())
if n == 0:
break
s, g = map(int, file_input.readline().split())
adj_list = [[] for i in range(n)]
for i in range(m):
x, y, d, c = map(int, file_input.readline().split())
x -= 1
y -= 1
adj_list[x].append((y, d, c))
adj_list[y].append((x, d, c))
# Dijkstra's algorithm
s -= 1
g -= 1
time_rec = [[[inf] * 31 for j in range(n)] for i in range(n)]
time_rec[s][s][1] = 0
# pq element: (time, current city, previous city, speed)
pq = [(0, s, s, 0)]
while pq:
t, c, p, s = heappop(pq)
if time_rec[p][c][s] < t:
continue
if c == g and s == 1:
print(t)
break
for next_city, d, s_limit in adj_list[c]:
if next_city == p:
continue
if s <= 1:
lower_limit = 1
else:
lower_limit = s - 1
for shifted_s in range(lower_limit, s + 2):
if shifted_s > s_limit:
continue
next_t = t + d / shifted_s
if time_rec[c][next_city][shifted_s] <= next_t:
continue
else:
heappush(pq, (next_t, next_city, c, shifted_s))
time_rec[c][next_city][shifted_s] = next_t
else:
print('unreachable')
solve()
```
| 99,386 |
Provide a correct Python 3 solution for this coding contest problem.
Consider car trips in a country where there is no friction. Cars in this country do not have engines. Once a car started to move at a speed, it keeps moving at the same speed. There are acceleration devices on some points on the road, where a car can increase or decrease its speed by 1. It can also keep its speed there. Your job in this problem is to write a program which determines the route with the shortest time to travel from a starting city to a goal city.
There are several cities in the country, and a road network connecting them. Each city has an acceleration device. As mentioned above, if a car arrives at a city at a speed v , it leaves the city at one of v - 1, v , or v + 1. The first road leaving the starting city must be run at the speed 1. Similarly, the last road arriving at the goal city must be run at the speed 1.
The starting city and the goal city are given. The problem is to find the best route which leads to the goal city going through several cities on the road network. When the car arrives at a city, it cannot immediately go back the road it used to reach the city. No U-turns are allowed. Except this constraint, one can choose any route on the road network. It is allowed to visit the same city or use the same road multiple times. The starting city and the goal city may be visited during the trip.
For each road on the network, its distance and speed limit are given. A car must run a road at a speed less than or equal to its speed limit. The time needed to run a road is the distance divided by the speed. The time needed within cities including that for acceleration or deceleration should be ignored.
Input
The input consists of multiple datasets, each in the following format.
> n m
> s g
> x 1 y 1 d 1 c 1
> ...
> xm ym dm cm
>
Every input item in a dataset is a non-negative integer. Input items in the same line are separated by a space.
The first line gives the size of the road network. n is the number of cities in the network. You can assume that the number of cities is between 2 and 30, inclusive. m is the number of roads between cities, which may be zero.
The second line gives the trip. s is the city index of the starting city. g is the city index of the goal city. s is not equal to g . You can assume that all city indices in a dataset (including the above two) are between 1 and n , inclusive.
The following m lines give the details of roads between cities. The i -th road connects two cities with city indices xi and yi , and has a distance di (1 ≤ i ≤ m ). You can assume that the distance is between 1 and 100, inclusive. The speed limit of the road is specified by ci . You can assume that the speed limit is between 1 and 30, inclusive.
No two roads connect the same pair of cities. A road never connects a city with itself. Each road can be traveled in both directions.
The last dataset is followed by a line containing two zeros (separated by a space).
Output
For each dataset in the input, one line should be output as specified below. An output line should not contain extra characters such as spaces.
If one can travel from the starting city to the goal city, the time needed for the best route (a route with the shortest time) should be printed. The answer should not have an error greater than 0.001. You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied.
If it is impossible to reach the goal city, the string "`unreachable`" should be printed. Note that all the letters of "`unreachable`" are in lowercase.
Sample Input
2 0
1 2
5 4
1 5
1 2 1 1
2 3 2 2
3 4 2 2
4 5 1 1
6 6
1 6
1 2 2 1
2 3 2 1
3 6 2 1
1 4 2 30
4 5 3 30
5 6 2 30
6 7
1 6
1 2 1 30
2 3 1 30
3 1 1 30
3 4 100 30
4 5 1 30
5 6 1 30
6 4 1 30
0 0
Output for the Sample Input
unreachable
4.00000
5.50000
11.25664
Example
Input
2 0
1 2
5 4
1 5
1 2 1 1
2 3 2 2
3 4 2 2
4 5 1 1
6 6
1 6
1 2 2 1
2 3 2 1
3 6 2 1
1 4 2 30
4 5 3 30
5 6 2 30
6 7
1 6
1 2 1 30
2 3 1 30
3 1 1 30
3 4 100 30
4 5 1 30
5 6 1 30
6 4 1 30
0 0
Output
unreachable
4.00000
5.50000
11.25664
"Correct Solution:
```
import sys
import heapq
if sys.version[0] == '2':
range, input = xrange, raw_input
MAX_SPEED = 30
while True:
N, M = map(int, input().split())
if not (N | M):
break
S, G = map(lambda x: int(x) - 1, input().split())
edge = [[] for _ in range(N)]
for _ in range(M):
x, y, d, c = map(int, input().split())
edge[x - 1].append((y - 1, d, c))
edge[y - 1].append((x - 1, d, c))
INF = float('inf')
dist = [[[INF for _ in range(N)] for _ in range(MAX_SPEED + 1)] for _ in range(N)]
que = [(0.0, S, 0, S)]
while que:
cost, now, v, prev = heapq.heappop(que)
if cost > dist[now][v][prev]:
continue
if now == G and v == 1:
print("{:.20f}".format(cost))
break
dist[now][v][prev] = cost
for x, d, c in edge[now]:
if x == prev:
continue
for dv in (-1, 0, 1):
nv = v + dv
if 0 < nv <= c and dist[x][nv][now] > dist[now][v][prev] + d / nv:
dist[x][nv][now] = dist[now][v][prev] + d / nv
heapq.heappush(que, (dist[x][nv][now], x, nv, now))
else:
print("unreachable")
```
| 99,387 |
Provide a correct Python 3 solution for this coding contest problem.
Consider car trips in a country where there is no friction. Cars in this country do not have engines. Once a car started to move at a speed, it keeps moving at the same speed. There are acceleration devices on some points on the road, where a car can increase or decrease its speed by 1. It can also keep its speed there. Your job in this problem is to write a program which determines the route with the shortest time to travel from a starting city to a goal city.
There are several cities in the country, and a road network connecting them. Each city has an acceleration device. As mentioned above, if a car arrives at a city at a speed v , it leaves the city at one of v - 1, v , or v + 1. The first road leaving the starting city must be run at the speed 1. Similarly, the last road arriving at the goal city must be run at the speed 1.
The starting city and the goal city are given. The problem is to find the best route which leads to the goal city going through several cities on the road network. When the car arrives at a city, it cannot immediately go back the road it used to reach the city. No U-turns are allowed. Except this constraint, one can choose any route on the road network. It is allowed to visit the same city or use the same road multiple times. The starting city and the goal city may be visited during the trip.
For each road on the network, its distance and speed limit are given. A car must run a road at a speed less than or equal to its speed limit. The time needed to run a road is the distance divided by the speed. The time needed within cities including that for acceleration or deceleration should be ignored.
Input
The input consists of multiple datasets, each in the following format.
> n m
> s g
> x 1 y 1 d 1 c 1
> ...
> xm ym dm cm
>
Every input item in a dataset is a non-negative integer. Input items in the same line are separated by a space.
The first line gives the size of the road network. n is the number of cities in the network. You can assume that the number of cities is between 2 and 30, inclusive. m is the number of roads between cities, which may be zero.
The second line gives the trip. s is the city index of the starting city. g is the city index of the goal city. s is not equal to g . You can assume that all city indices in a dataset (including the above two) are between 1 and n , inclusive.
The following m lines give the details of roads between cities. The i -th road connects two cities with city indices xi and yi , and has a distance di (1 ≤ i ≤ m ). You can assume that the distance is between 1 and 100, inclusive. The speed limit of the road is specified by ci . You can assume that the speed limit is between 1 and 30, inclusive.
No two roads connect the same pair of cities. A road never connects a city with itself. Each road can be traveled in both directions.
The last dataset is followed by a line containing two zeros (separated by a space).
Output
For each dataset in the input, one line should be output as specified below. An output line should not contain extra characters such as spaces.
If one can travel from the starting city to the goal city, the time needed for the best route (a route with the shortest time) should be printed. The answer should not have an error greater than 0.001. You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied.
If it is impossible to reach the goal city, the string "`unreachable`" should be printed. Note that all the letters of "`unreachable`" are in lowercase.
Sample Input
2 0
1 2
5 4
1 5
1 2 1 1
2 3 2 2
3 4 2 2
4 5 1 1
6 6
1 6
1 2 2 1
2 3 2 1
3 6 2 1
1 4 2 30
4 5 3 30
5 6 2 30
6 7
1 6
1 2 1 30
2 3 1 30
3 1 1 30
3 4 100 30
4 5 1 30
5 6 1 30
6 4 1 30
0 0
Output for the Sample Input
unreachable
4.00000
5.50000
11.25664
Example
Input
2 0
1 2
5 4
1 5
1 2 1 1
2 3 2 2
3 4 2 2
4 5 1 1
6 6
1 6
1 2 2 1
2 3 2 1
3 6 2 1
1 4 2 30
4 5 3 30
5 6 2 30
6 7
1 6
1 2 1 30
2 3 1 30
3 1 1 30
3 4 100 30
4 5 1 30
5 6 1 30
6 4 1 30
0 0
Output
unreachable
4.00000
5.50000
11.25664
"Correct Solution:
```
from heapq import heappush, heappop
def main():
while True:
n, m = map(int, input().split())
if n == 0:
break
s, g = map(int, input().split())
s -= 1
g -= 1
edges = [[] for _ in range(n)]
for _ in range(m):
x, y, d, c = map(int, input().split())
x -= 1
y -= 1
edges[x].append((y, d, c))
edges[y].append((x, d, c))
que = []
heappush(que, (0, 1, s, None))
dic = {}
dic[(1, None, s, None)] = 0
INF = 10 ** 20
ans = INF
while que:
score, speed, node, pre_node= heappop(que)
if score >= ans:break
for to, dist, limit in edges[node]:
if to == pre_node or speed > limit:continue
new_score = score + dist / speed
if speed == 1 and to == g and ans > new_score:ans = new_score
for new_speed in (speed - 1, speed, speed + 1):
if new_speed <= 0:continue
if (new_speed, to, node) not in dic or dic[(new_speed, to, node)] > new_score:
dic[(new_speed, to, node)] = new_score
heappush(que, (new_score, new_speed, to, node))
if ans == INF:
print("unreachable")
else:
print(ans)
main()
```
| 99,388 |
Provide a correct Python 3 solution for this coding contest problem.
Consider car trips in a country where there is no friction. Cars in this country do not have engines. Once a car started to move at a speed, it keeps moving at the same speed. There are acceleration devices on some points on the road, where a car can increase or decrease its speed by 1. It can also keep its speed there. Your job in this problem is to write a program which determines the route with the shortest time to travel from a starting city to a goal city.
There are several cities in the country, and a road network connecting them. Each city has an acceleration device. As mentioned above, if a car arrives at a city at a speed v , it leaves the city at one of v - 1, v , or v + 1. The first road leaving the starting city must be run at the speed 1. Similarly, the last road arriving at the goal city must be run at the speed 1.
The starting city and the goal city are given. The problem is to find the best route which leads to the goal city going through several cities on the road network. When the car arrives at a city, it cannot immediately go back the road it used to reach the city. No U-turns are allowed. Except this constraint, one can choose any route on the road network. It is allowed to visit the same city or use the same road multiple times. The starting city and the goal city may be visited during the trip.
For each road on the network, its distance and speed limit are given. A car must run a road at a speed less than or equal to its speed limit. The time needed to run a road is the distance divided by the speed. The time needed within cities including that for acceleration or deceleration should be ignored.
Input
The input consists of multiple datasets, each in the following format.
> n m
> s g
> x 1 y 1 d 1 c 1
> ...
> xm ym dm cm
>
Every input item in a dataset is a non-negative integer. Input items in the same line are separated by a space.
The first line gives the size of the road network. n is the number of cities in the network. You can assume that the number of cities is between 2 and 30, inclusive. m is the number of roads between cities, which may be zero.
The second line gives the trip. s is the city index of the starting city. g is the city index of the goal city. s is not equal to g . You can assume that all city indices in a dataset (including the above two) are between 1 and n , inclusive.
The following m lines give the details of roads between cities. The i -th road connects two cities with city indices xi and yi , and has a distance di (1 ≤ i ≤ m ). You can assume that the distance is between 1 and 100, inclusive. The speed limit of the road is specified by ci . You can assume that the speed limit is between 1 and 30, inclusive.
No two roads connect the same pair of cities. A road never connects a city with itself. Each road can be traveled in both directions.
The last dataset is followed by a line containing two zeros (separated by a space).
Output
For each dataset in the input, one line should be output as specified below. An output line should not contain extra characters such as spaces.
If one can travel from the starting city to the goal city, the time needed for the best route (a route with the shortest time) should be printed. The answer should not have an error greater than 0.001. You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied.
If it is impossible to reach the goal city, the string "`unreachable`" should be printed. Note that all the letters of "`unreachable`" are in lowercase.
Sample Input
2 0
1 2
5 4
1 5
1 2 1 1
2 3 2 2
3 4 2 2
4 5 1 1
6 6
1 6
1 2 2 1
2 3 2 1
3 6 2 1
1 4 2 30
4 5 3 30
5 6 2 30
6 7
1 6
1 2 1 30
2 3 1 30
3 1 1 30
3 4 100 30
4 5 1 30
5 6 1 30
6 4 1 30
0 0
Output for the Sample Input
unreachable
4.00000
5.50000
11.25664
Example
Input
2 0
1 2
5 4
1 5
1 2 1 1
2 3 2 2
3 4 2 2
4 5 1 1
6 6
1 6
1 2 2 1
2 3 2 1
3 6 2 1
1 4 2 30
4 5 3 30
5 6 2 30
6 7
1 6
1 2 1 30
2 3 1 30
3 1 1 30
3 4 100 30
4 5 1 30
5 6 1 30
6 4 1 30
0 0
Output
unreachable
4.00000
5.50000
11.25664
"Correct Solution:
```
#2006_D
"""
import sys
from collections import defaultdict
def dfs(d,y,x,f):
global ans
if d >= 10:
return
f_ = defaultdict(int)
for i in f.keys():
f_[i] = f[i]
for t,s in vr[(y,x)]:
if a[t][s] == 3:
ans = min(ans,d+1)
break
elif f[(t,s)]:
if s == x+1:
break
f_[(t,s)] = 0
dfs(d+1,t,s-1,f_)
f_[(t,s)] = 1
break
for t,s in vl[(y,x)]:
if a[t][s] == 3:
ans = min(ans,d+1)
break
elif f[(t,s)]:
if s == x-1:
break
f_[(t,s)] = 0
dfs(d+1,t,s+1,f_)
f_[(t,s)] = 1
break
for t,s in vd[(y,x)]:
if a[t][s] == 3:
ans = min(ans,d+1)
break
elif f[(t,s)]:
if t == y+1:
break
f_[(t,s)] = 0
dfs(d+1,t-1,s,f_)
f_[(t,s)] = 1
break
for t,s in vu[(y,x)]:
if a[t][s] == 3:
ans = min(ans,d+1)
break
elif f[(t,s)]:
if t == y-1:
break
f_[(t,s)] = 0
dfs(d+1,t+1,s,f_)
f_[(t,s)] = 1
break
return
while 1:
w,h = map(int, sys.stdin.readline()[:-1].split())
if w == h == 0:
break
a = [list(map(int, sys.stdin.readline()[:-1].split())) for i in range(h)]
vr = defaultdict(list)
vl = defaultdict(list)
vd = defaultdict(list)
vu = defaultdict(list)
f = defaultdict(int)
for y in range(h):
for x in range(w):
if a[y][x] == 1:
f[(y,x)] = 1
if a[y][x] in [1,3]:
for x_ in range(x):
vr[(y,x_)].append((y,x))
elif a[y][x] == 2:
sy,sx = y,x
for y in range(h):
for x in range(w)[::-1]:
if a[y][x] in (1,3):
for x_ in range(x+1,w):
vl[(y,x_)].append((y,x))
for x in range(w):
for y in range(h):
if a[y][x] in (1,3):
for y_ in range(y):
vd[(y_,x)].append((y,x))
for x in range(w):
for y in range(h)[::-1]:
if a[y][x] in (1,3):
for y_ in range(y+1,h):
vu[(y_,x)].append((y,x))
ind = [[[0]*4 for i in range(w)] for j in range(h)]
ans = 11
dfs(0,sy,sx,f)
ans = ans if ans < 11 else -1
print(ans)
"""
#2018_D
"""
import sys
from collections import defaultdict
sys.setrecursionlimit(1000000)
def dfs(d,s,l,v,dic):
s_ = tuple(s)
if dic[(d,s_)] != None:
return dic[(d,s_)]
if d == l:
dic[(d,s_)] = 1
for x in s:
if x > (n>>1):
dic[(d,s_)] = 0
return 0
return 1
else:
res = 0
i,j = v[d]
if s[i] < (n>>1):
s[i] += 1
res += dfs(d+1,s,l,v,dic)
s[i] -= 1
if s[j] < (n>>1):
s[j] += 1
res += dfs(d+1,s,l,v,dic)
s[j] -= 1
dic[(d,s_)] = res
return res
def solve(n):
dic = defaultdict(lambda : None)
m = int(sys.stdin.readline())
s = [0]*n
f = [[1]*n for i in range(n)]
for i in range(n):
f[i][i] = 0
for i in range(m):
x,y = [int(x) for x in sys.stdin.readline().split()]
x -= 1
y -= 1
s[x] += 1
f[x][y] = 0
f[y][x] = 0
v = []
for i in range(n):
for j in range(i+1,n):
if f[i][j]:
v.append((i,j))
l = len(v)
print(dfs(0,s,l,v,dic))
while 1:
n = int(sys.stdin.readline())
if n == 0:
break
solve(n)
"""
#2011_D
"""
import sys
def dfs(s,d,f,v):
global ans
if ans == n-n%2:
return
if d > ans:
ans = d
for i in range(n):
if s[i] == 0:
for j in range(i+1,n):
if s[j] == 0:
if f[i] == f[j]:
s[i] = -1
s[j] = -1
for k in v[i]:
s[k] -= 1
for k in v[j]:
s[k] -= 1
dfs(s,d+2,f,v)
s[i] = 0
s[j] = 0
for k in v[i]:
s[k] += 1
for k in v[j]:
s[k] += 1
def solve(n):
p = [[int(x) for x in sys.stdin.readline().split()] for i in range(n)]
v = [[] for i in range(n)]
f = [0]*n
s = [0]*n
for i in range(n):
x,y,r,f[i] = p[i]
for j in range(i+1,n):
xj,yj,rj,c = p[j]
if (x-xj)**2+(y-yj)**2 < (r+rj)**2:
v[i].append(j)
s[j] += 1
dfs(s,0,f,v)
print(ans)
while 1:
n = int(sys.stdin.readline())
ans = 0
if n == 0:
break
solve(n)
"""
#2003_D
"""
import sys
def root(x,par):
if par[x] == x:
return x
par[x] = root(par[x],par)
return par[x]
def unite(x,y,par,rank):
x = root(x,par)
y = root(y,par)
if rank[x] < rank[y]:
par[x] = y
else:
par[y] = x
if rank[x] == rank[y]:
rank[x] += 1
def solve(n):
p = [[float(x) for x in sys.stdin.readline().split()] for i in range(n)]
v = []
for i in range(n):
for j in range(i):
xi,yi,zi,ri = p[i]
xj,yj,zj,rj = p[j]
d = max(0,((xi-xj)**2+(yi-yj)**2+(zi-zj)**2)**0.5-(ri+rj))
v.append((i,j,d))
par = [i for i in range(n)]
rank = [0]*n
v.sort(key = lambda x:x[2])
ans = 0
for x,y,d in v:
if root(x,par) != root(y,par):
unite(x,y,par,rank)
ans += d
print("{:.3f}".format(round(ans,3)))
while 1:
n = int(sys.stdin.readline())
if n == 0:
break
solve(n)
"""
#2009_D
import sys
from heapq import heappop,heappush
from collections import defaultdict
def solve(n,m):
s,g = [int(x) for x in sys.stdin.readline().split()]
s -= 1
g -= 1
e = [[] for i in range(n)]
for i in range(m):
a,b,d,c = [int(x) for x in sys.stdin.readline().split()]
a -= 1
b -= 1
e[a].append((b,d,c))
e[b].append((a,d,c))
dist = defaultdict(lambda : float("inf"))
dist[(s,0,-1)] = 0
q = [(0,s,0,-1)]
while q:
dx,x,v,p = heappop(q)
if x == g and v == 1:
print(dx)
return
for i in range(-1,2):
v_ = v+i
if v_ < 1 :continue
for y,d,c in e[x]:
if p == y:
continue
if v_ > c:
continue
z = d/v_
if dx+z < dist[(y,v_,x)]:
dist[(y,v_,x)] = dx+z
heappush(q,(dist[(y,v_,x)],y,v_,x))
print("unreachable")
return
while 1:
n,m = [int(x) for x in sys.stdin.readline().split()]
if n == 0:
break
solve(n,m)
```
| 99,389 |
Provide a correct Python 3 solution for this coding contest problem.
Consider car trips in a country where there is no friction. Cars in this country do not have engines. Once a car started to move at a speed, it keeps moving at the same speed. There are acceleration devices on some points on the road, where a car can increase or decrease its speed by 1. It can also keep its speed there. Your job in this problem is to write a program which determines the route with the shortest time to travel from a starting city to a goal city.
There are several cities in the country, and a road network connecting them. Each city has an acceleration device. As mentioned above, if a car arrives at a city at a speed v , it leaves the city at one of v - 1, v , or v + 1. The first road leaving the starting city must be run at the speed 1. Similarly, the last road arriving at the goal city must be run at the speed 1.
The starting city and the goal city are given. The problem is to find the best route which leads to the goal city going through several cities on the road network. When the car arrives at a city, it cannot immediately go back the road it used to reach the city. No U-turns are allowed. Except this constraint, one can choose any route on the road network. It is allowed to visit the same city or use the same road multiple times. The starting city and the goal city may be visited during the trip.
For each road on the network, its distance and speed limit are given. A car must run a road at a speed less than or equal to its speed limit. The time needed to run a road is the distance divided by the speed. The time needed within cities including that for acceleration or deceleration should be ignored.
Input
The input consists of multiple datasets, each in the following format.
> n m
> s g
> x 1 y 1 d 1 c 1
> ...
> xm ym dm cm
>
Every input item in a dataset is a non-negative integer. Input items in the same line are separated by a space.
The first line gives the size of the road network. n is the number of cities in the network. You can assume that the number of cities is between 2 and 30, inclusive. m is the number of roads between cities, which may be zero.
The second line gives the trip. s is the city index of the starting city. g is the city index of the goal city. s is not equal to g . You can assume that all city indices in a dataset (including the above two) are between 1 and n , inclusive.
The following m lines give the details of roads between cities. The i -th road connects two cities with city indices xi and yi , and has a distance di (1 ≤ i ≤ m ). You can assume that the distance is between 1 and 100, inclusive. The speed limit of the road is specified by ci . You can assume that the speed limit is between 1 and 30, inclusive.
No two roads connect the same pair of cities. A road never connects a city with itself. Each road can be traveled in both directions.
The last dataset is followed by a line containing two zeros (separated by a space).
Output
For each dataset in the input, one line should be output as specified below. An output line should not contain extra characters such as spaces.
If one can travel from the starting city to the goal city, the time needed for the best route (a route with the shortest time) should be printed. The answer should not have an error greater than 0.001. You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied.
If it is impossible to reach the goal city, the string "`unreachable`" should be printed. Note that all the letters of "`unreachable`" are in lowercase.
Sample Input
2 0
1 2
5 4
1 5
1 2 1 1
2 3 2 2
3 4 2 2
4 5 1 1
6 6
1 6
1 2 2 1
2 3 2 1
3 6 2 1
1 4 2 30
4 5 3 30
5 6 2 30
6 7
1 6
1 2 1 30
2 3 1 30
3 1 1 30
3 4 100 30
4 5 1 30
5 6 1 30
6 4 1 30
0 0
Output for the Sample Input
unreachable
4.00000
5.50000
11.25664
Example
Input
2 0
1 2
5 4
1 5
1 2 1 1
2 3 2 2
3 4 2 2
4 5 1 1
6 6
1 6
1 2 2 1
2 3 2 1
3 6 2 1
1 4 2 30
4 5 3 30
5 6 2 30
6 7
1 6
1 2 1 30
2 3 1 30
3 1 1 30
3 4 100 30
4 5 1 30
5 6 1 30
6 4 1 30
0 0
Output
unreachable
4.00000
5.50000
11.25664
"Correct Solution:
```
# AOJ 1162: Discrete Speed
# Python3 2018.7.15 bal4u
INF = 10e8
import heapq
def dijkstra(V, to, start, goal):
node = [[[INF for k in range(31)] for j in range(V)] for i in range(V)]
Q = []
node[start][0][0] = 0
heapq.heappush(Q, (0, start, -1, 0))
while Q:
t, s, p, v = heapq.heappop(Q)
if s == goal and v == 1: return t
for e, d, c in to[s]:
if e == p: continue # Uターン禁止
for i in range(-1, 2):
nv = v+i
if nv > c or nv <= 0: continue
nt = t + d/nv
if nt < node[e][s][nv]:
node[e][s][nv] = nt
heapq.heappush(Q, (nt, e, s, nv))
return -1
while True:
n, m = map(int, input().split())
if n == 0: break
s, g = map(int, input().split())
s -= 1; g -= 1
to = [[] for i in range(n)]
for i in range(m):
x, y, d, c = map(int, input().split())
x -= 1; y -= 1
to[x].append((y, d, c))
to[y].append((x, d, c))
ans = dijkstra(n, to, s, g)
print(ans if ans >= 0 else "unreachable")
```
| 99,390 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider car trips in a country where there is no friction. Cars in this country do not have engines. Once a car started to move at a speed, it keeps moving at the same speed. There are acceleration devices on some points on the road, where a car can increase or decrease its speed by 1. It can also keep its speed there. Your job in this problem is to write a program which determines the route with the shortest time to travel from a starting city to a goal city.
There are several cities in the country, and a road network connecting them. Each city has an acceleration device. As mentioned above, if a car arrives at a city at a speed v , it leaves the city at one of v - 1, v , or v + 1. The first road leaving the starting city must be run at the speed 1. Similarly, the last road arriving at the goal city must be run at the speed 1.
The starting city and the goal city are given. The problem is to find the best route which leads to the goal city going through several cities on the road network. When the car arrives at a city, it cannot immediately go back the road it used to reach the city. No U-turns are allowed. Except this constraint, one can choose any route on the road network. It is allowed to visit the same city or use the same road multiple times. The starting city and the goal city may be visited during the trip.
For each road on the network, its distance and speed limit are given. A car must run a road at a speed less than or equal to its speed limit. The time needed to run a road is the distance divided by the speed. The time needed within cities including that for acceleration or deceleration should be ignored.
Input
The input consists of multiple datasets, each in the following format.
> n m
> s g
> x 1 y 1 d 1 c 1
> ...
> xm ym dm cm
>
Every input item in a dataset is a non-negative integer. Input items in the same line are separated by a space.
The first line gives the size of the road network. n is the number of cities in the network. You can assume that the number of cities is between 2 and 30, inclusive. m is the number of roads between cities, which may be zero.
The second line gives the trip. s is the city index of the starting city. g is the city index of the goal city. s is not equal to g . You can assume that all city indices in a dataset (including the above two) are between 1 and n , inclusive.
The following m lines give the details of roads between cities. The i -th road connects two cities with city indices xi and yi , and has a distance di (1 ≤ i ≤ m ). You can assume that the distance is between 1 and 100, inclusive. The speed limit of the road is specified by ci . You can assume that the speed limit is between 1 and 30, inclusive.
No two roads connect the same pair of cities. A road never connects a city with itself. Each road can be traveled in both directions.
The last dataset is followed by a line containing two zeros (separated by a space).
Output
For each dataset in the input, one line should be output as specified below. An output line should not contain extra characters such as spaces.
If one can travel from the starting city to the goal city, the time needed for the best route (a route with the shortest time) should be printed. The answer should not have an error greater than 0.001. You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied.
If it is impossible to reach the goal city, the string "`unreachable`" should be printed. Note that all the letters of "`unreachable`" are in lowercase.
Sample Input
2 0
1 2
5 4
1 5
1 2 1 1
2 3 2 2
3 4 2 2
4 5 1 1
6 6
1 6
1 2 2 1
2 3 2 1
3 6 2 1
1 4 2 30
4 5 3 30
5 6 2 30
6 7
1 6
1 2 1 30
2 3 1 30
3 1 1 30
3 4 100 30
4 5 1 30
5 6 1 30
6 4 1 30
0 0
Output for the Sample Input
unreachable
4.00000
5.50000
11.25664
Example
Input
2 0
1 2
5 4
1 5
1 2 1 1
2 3 2 2
3 4 2 2
4 5 1 1
6 6
1 6
1 2 2 1
2 3 2 1
3 6 2 1
1 4 2 30
4 5 3 30
5 6 2 30
6 7
1 6
1 2 1 30
2 3 1 30
3 1 1 30
3 4 100 30
4 5 1 30
5 6 1 30
6 4 1 30
0 0
Output
unreachable
4.00000
5.50000
11.25664
Submitted Solution:
```
import sys
import heapq
if sys.version[0] == '2':
range, input = xrange, raw_input
MAX_SPEED = 30
while True:
N, M = map(int, input().split())
if not (N | M):
break
S, G = map(lambda x: int(x) - 1, input().split())
edge = [[] for _ in range(N)]
for _ in range(M):
x, y, d, c = map(int, input().split())
edge[x - 1].append((y - 1, d, c))
edge[y - 1].append((x - 1, d, c))
INF = float('inf')
dist = [[[INF for _ in range(N)] for _ in range(MAX_SPEED + 1)] for _ in range(N)]
que = [(0.0, S, 0, S)]
while que:
cost, now, v, prev = heapq.heappop(que)
if cost > dist[now][v][prev]:
continue
if now == G and v == 1:
print("{:.20f}".format(cost))
break
dist[now][v][prev] = cost
for x, d, c in edge[now]:
if x == prev:
continue
if 0 < v <= c and dist[x][v][now] > dist[now][v][prev] + d / v:
dist[x][v][now] = dist[now][v][prev] + d / v
heapq.heappush(que, (dist[x][v][now], x, v, now))
if v < c and dist[x][v + 1][now] > dist[now][v][prev] + d / (v + 1):
dist[x][v + 1][now] = dist[now][v][prev] + d / (v + 1)
heapq.heappush(que, (dist[x][v + 1][now], x, v + 1, now))
if 1 < v <= c + 1 and dist[x][v - 1][now] > dist[now][v][prev] + d / (v - 1):
dist[x][v - 1][now] = dist[now][v][prev] + d / (v - 1)
heapq.heappush(que, (dist[x][v - 1][now], x, v - 1, now))
else:
print("unreachable")
```
Yes
| 99,391 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider car trips in a country where there is no friction. Cars in this country do not have engines. Once a car started to move at a speed, it keeps moving at the same speed. There are acceleration devices on some points on the road, where a car can increase or decrease its speed by 1. It can also keep its speed there. Your job in this problem is to write a program which determines the route with the shortest time to travel from a starting city to a goal city.
There are several cities in the country, and a road network connecting them. Each city has an acceleration device. As mentioned above, if a car arrives at a city at a speed v , it leaves the city at one of v - 1, v , or v + 1. The first road leaving the starting city must be run at the speed 1. Similarly, the last road arriving at the goal city must be run at the speed 1.
The starting city and the goal city are given. The problem is to find the best route which leads to the goal city going through several cities on the road network. When the car arrives at a city, it cannot immediately go back the road it used to reach the city. No U-turns are allowed. Except this constraint, one can choose any route on the road network. It is allowed to visit the same city or use the same road multiple times. The starting city and the goal city may be visited during the trip.
For each road on the network, its distance and speed limit are given. A car must run a road at a speed less than or equal to its speed limit. The time needed to run a road is the distance divided by the speed. The time needed within cities including that for acceleration or deceleration should be ignored.
Input
The input consists of multiple datasets, each in the following format.
> n m
> s g
> x 1 y 1 d 1 c 1
> ...
> xm ym dm cm
>
Every input item in a dataset is a non-negative integer. Input items in the same line are separated by a space.
The first line gives the size of the road network. n is the number of cities in the network. You can assume that the number of cities is between 2 and 30, inclusive. m is the number of roads between cities, which may be zero.
The second line gives the trip. s is the city index of the starting city. g is the city index of the goal city. s is not equal to g . You can assume that all city indices in a dataset (including the above two) are between 1 and n , inclusive.
The following m lines give the details of roads between cities. The i -th road connects two cities with city indices xi and yi , and has a distance di (1 ≤ i ≤ m ). You can assume that the distance is between 1 and 100, inclusive. The speed limit of the road is specified by ci . You can assume that the speed limit is between 1 and 30, inclusive.
No two roads connect the same pair of cities. A road never connects a city with itself. Each road can be traveled in both directions.
The last dataset is followed by a line containing two zeros (separated by a space).
Output
For each dataset in the input, one line should be output as specified below. An output line should not contain extra characters such as spaces.
If one can travel from the starting city to the goal city, the time needed for the best route (a route with the shortest time) should be printed. The answer should not have an error greater than 0.001. You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied.
If it is impossible to reach the goal city, the string "`unreachable`" should be printed. Note that all the letters of "`unreachable`" are in lowercase.
Sample Input
2 0
1 2
5 4
1 5
1 2 1 1
2 3 2 2
3 4 2 2
4 5 1 1
6 6
1 6
1 2 2 1
2 3 2 1
3 6 2 1
1 4 2 30
4 5 3 30
5 6 2 30
6 7
1 6
1 2 1 30
2 3 1 30
3 1 1 30
3 4 100 30
4 5 1 30
5 6 1 30
6 4 1 30
0 0
Output for the Sample Input
unreachable
4.00000
5.50000
11.25664
Example
Input
2 0
1 2
5 4
1 5
1 2 1 1
2 3 2 2
3 4 2 2
4 5 1 1
6 6
1 6
1 2 2 1
2 3 2 1
3 6 2 1
1 4 2 30
4 5 3 30
5 6 2 30
6 7
1 6
1 2 1 30
2 3 1 30
3 1 1 30
3 4 100 30
4 5 1 30
5 6 1 30
6 4 1 30
0 0
Output
unreachable
4.00000
5.50000
11.25664
Submitted Solution:
```
from collections import deque
from heapq import heappop, heappush
def inpl(): return list(map(int, input().split()))
INF = 50000
N, M = inpl()
while N:
s, g = inpl()
G = [[] for _ in range(N+1)]
for _ in range(M):
a, b, d, c = inpl()
G[a].append([b, c, d])
G[b].append([a, c, d])
DP = [[[INF]*(N+1) for _ in range(31)] for _ in range(N+1)]
DP[s][0][0] = 0
Q = [[0, 0, s, 0]] # time, speed, where, pre
while Q:
t, v, p, bp = heappop(Q)
if DP[p][v][bp] < t:
continue
for q, c, d in G[p]:
if q == bp:
continue
for dv in range(-1, 2):
nv = v+dv
if not (0 < nv <= c):
continue
nt = t + d/(nv)
if DP[q][nv][p] > nt:
DP[q][nv][p] = nt
heappush(Q, [nt, nv, q, p])
ans = min(DP[g][1])
if ans == INF:
print("unreachable")
else:
print(ans)
N, M = inpl()
```
Yes
| 99,392 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider car trips in a country where there is no friction. Cars in this country do not have engines. Once a car started to move at a speed, it keeps moving at the same speed. There are acceleration devices on some points on the road, where a car can increase or decrease its speed by 1. It can also keep its speed there. Your job in this problem is to write a program which determines the route with the shortest time to travel from a starting city to a goal city.
There are several cities in the country, and a road network connecting them. Each city has an acceleration device. As mentioned above, if a car arrives at a city at a speed v , it leaves the city at one of v - 1, v , or v + 1. The first road leaving the starting city must be run at the speed 1. Similarly, the last road arriving at the goal city must be run at the speed 1.
The starting city and the goal city are given. The problem is to find the best route which leads to the goal city going through several cities on the road network. When the car arrives at a city, it cannot immediately go back the road it used to reach the city. No U-turns are allowed. Except this constraint, one can choose any route on the road network. It is allowed to visit the same city or use the same road multiple times. The starting city and the goal city may be visited during the trip.
For each road on the network, its distance and speed limit are given. A car must run a road at a speed less than or equal to its speed limit. The time needed to run a road is the distance divided by the speed. The time needed within cities including that for acceleration or deceleration should be ignored.
Input
The input consists of multiple datasets, each in the following format.
> n m
> s g
> x 1 y 1 d 1 c 1
> ...
> xm ym dm cm
>
Every input item in a dataset is a non-negative integer. Input items in the same line are separated by a space.
The first line gives the size of the road network. n is the number of cities in the network. You can assume that the number of cities is between 2 and 30, inclusive. m is the number of roads between cities, which may be zero.
The second line gives the trip. s is the city index of the starting city. g is the city index of the goal city. s is not equal to g . You can assume that all city indices in a dataset (including the above two) are between 1 and n , inclusive.
The following m lines give the details of roads between cities. The i -th road connects two cities with city indices xi and yi , and has a distance di (1 ≤ i ≤ m ). You can assume that the distance is between 1 and 100, inclusive. The speed limit of the road is specified by ci . You can assume that the speed limit is between 1 and 30, inclusive.
No two roads connect the same pair of cities. A road never connects a city with itself. Each road can be traveled in both directions.
The last dataset is followed by a line containing two zeros (separated by a space).
Output
For each dataset in the input, one line should be output as specified below. An output line should not contain extra characters such as spaces.
If one can travel from the starting city to the goal city, the time needed for the best route (a route with the shortest time) should be printed. The answer should not have an error greater than 0.001. You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied.
If it is impossible to reach the goal city, the string "`unreachable`" should be printed. Note that all the letters of "`unreachable`" are in lowercase.
Sample Input
2 0
1 2
5 4
1 5
1 2 1 1
2 3 2 2
3 4 2 2
4 5 1 1
6 6
1 6
1 2 2 1
2 3 2 1
3 6 2 1
1 4 2 30
4 5 3 30
5 6 2 30
6 7
1 6
1 2 1 30
2 3 1 30
3 1 1 30
3 4 100 30
4 5 1 30
5 6 1 30
6 4 1 30
0 0
Output for the Sample Input
unreachable
4.00000
5.50000
11.25664
Example
Input
2 0
1 2
5 4
1 5
1 2 1 1
2 3 2 2
3 4 2 2
4 5 1 1
6 6
1 6
1 2 2 1
2 3 2 1
3 6 2 1
1 4 2 30
4 5 3 30
5 6 2 30
6 7
1 6
1 2 1 30
2 3 1 30
3 1 1 30
3 4 100 30
4 5 1 30
5 6 1 30
6 4 1 30
0 0
Output
unreachable
4.00000
5.50000
11.25664
Submitted Solution:
```
import sys
import heapq
if sys.version[0] == '2':
range, input = xrange, raw_input
MAX_SPEED = 30
while True:
N, M = map(int, input().split())
if not (N | M):
break
S, G = map(lambda x: int(x) - 1, input().split())
edge = [[] for _ in range(N)]
for _ in range(M):
x, y, d, c = map(int, input().split())
edge[x - 1].append((y - 1, d, c))
edge[y - 1].append((x - 1, d, c))
INF = 1e18
dist = [[[INF for _ in range(N)] for _ in range(MAX_SPEED + 1)] for _ in range(N)]
que = [(0.0, S, 0, S)]
while que:
cost, now, v, prev = heapq.heappop(que)
if cost > dist[now][v][prev]:
continue
if now == G and v == 1:
print("{:.20f}".format(cost))
break
dist[now][v][prev] = cost
for x, d, c in edge[now]:
if x == prev:
continue
for dv in (-1, 0, 1):
nv = v + dv
if 0 < nv <= c and dist[x][nv][now] > dist[now][v][prev] + d / nv:
dist[x][nv][now] = dist[now][v][prev] + d / nv
heapq.heappush(que, (dist[x][nv][now], x, nv, now))
else:
print("unreachable")
```
Yes
| 99,393 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider car trips in a country where there is no friction. Cars in this country do not have engines. Once a car started to move at a speed, it keeps moving at the same speed. There are acceleration devices on some points on the road, where a car can increase or decrease its speed by 1. It can also keep its speed there. Your job in this problem is to write a program which determines the route with the shortest time to travel from a starting city to a goal city.
There are several cities in the country, and a road network connecting them. Each city has an acceleration device. As mentioned above, if a car arrives at a city at a speed v , it leaves the city at one of v - 1, v , or v + 1. The first road leaving the starting city must be run at the speed 1. Similarly, the last road arriving at the goal city must be run at the speed 1.
The starting city and the goal city are given. The problem is to find the best route which leads to the goal city going through several cities on the road network. When the car arrives at a city, it cannot immediately go back the road it used to reach the city. No U-turns are allowed. Except this constraint, one can choose any route on the road network. It is allowed to visit the same city or use the same road multiple times. The starting city and the goal city may be visited during the trip.
For each road on the network, its distance and speed limit are given. A car must run a road at a speed less than or equal to its speed limit. The time needed to run a road is the distance divided by the speed. The time needed within cities including that for acceleration or deceleration should be ignored.
Input
The input consists of multiple datasets, each in the following format.
> n m
> s g
> x 1 y 1 d 1 c 1
> ...
> xm ym dm cm
>
Every input item in a dataset is a non-negative integer. Input items in the same line are separated by a space.
The first line gives the size of the road network. n is the number of cities in the network. You can assume that the number of cities is between 2 and 30, inclusive. m is the number of roads between cities, which may be zero.
The second line gives the trip. s is the city index of the starting city. g is the city index of the goal city. s is not equal to g . You can assume that all city indices in a dataset (including the above two) are between 1 and n , inclusive.
The following m lines give the details of roads between cities. The i -th road connects two cities with city indices xi and yi , and has a distance di (1 ≤ i ≤ m ). You can assume that the distance is between 1 and 100, inclusive. The speed limit of the road is specified by ci . You can assume that the speed limit is between 1 and 30, inclusive.
No two roads connect the same pair of cities. A road never connects a city with itself. Each road can be traveled in both directions.
The last dataset is followed by a line containing two zeros (separated by a space).
Output
For each dataset in the input, one line should be output as specified below. An output line should not contain extra characters such as spaces.
If one can travel from the starting city to the goal city, the time needed for the best route (a route with the shortest time) should be printed. The answer should not have an error greater than 0.001. You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied.
If it is impossible to reach the goal city, the string "`unreachable`" should be printed. Note that all the letters of "`unreachable`" are in lowercase.
Sample Input
2 0
1 2
5 4
1 5
1 2 1 1
2 3 2 2
3 4 2 2
4 5 1 1
6 6
1 6
1 2 2 1
2 3 2 1
3 6 2 1
1 4 2 30
4 5 3 30
5 6 2 30
6 7
1 6
1 2 1 30
2 3 1 30
3 1 1 30
3 4 100 30
4 5 1 30
5 6 1 30
6 4 1 30
0 0
Output for the Sample Input
unreachable
4.00000
5.50000
11.25664
Example
Input
2 0
1 2
5 4
1 5
1 2 1 1
2 3 2 2
3 4 2 2
4 5 1 1
6 6
1 6
1 2 2 1
2 3 2 1
3 6 2 1
1 4 2 30
4 5 3 30
5 6 2 30
6 7
1 6
1 2 1 30
2 3 1 30
3 1 1 30
3 4 100 30
4 5 1 30
5 6 1 30
6 4 1 30
0 0
Output
unreachable
4.00000
5.50000
11.25664
Submitted Solution:
```
from collections import deque
from heapq import heappop, heappush
def inpl(): return list(map(int, input().split()))
INF = 50000
N, M = inpl()
while N:
s, g = inpl()
G = [[] for _ in range(N+1)]
for _ in range(M):
a, b, d, c = inpl()
G[a].append([b, c, d])
G[b].append([a, c, d])
DP = [[INF]*(31) for _ in range(N+1)]
DP[s][1] = 0
Q = [[0, 0, s]] # time, speed, where
while Q:
t, v, p = heappop(Q)
if DP[p][v] < t:
continue
for q, c, d in G[p]:
for dv in range(-1, 2):
nv = v+dv
if not (0 < nv <= min(30, c)):
continue
nt = t + d/(nv)
if DP[q][nv] > nt:
DP[q][nv] = nt
heappush(Q, [nt, nv, q])
if DP[g][1] == INF:
print("unreachable")
else:
print(DP[g][1])
N, M = inpl()
```
No
| 99,394 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider car trips in a country where there is no friction. Cars in this country do not have engines. Once a car started to move at a speed, it keeps moving at the same speed. There are acceleration devices on some points on the road, where a car can increase or decrease its speed by 1. It can also keep its speed there. Your job in this problem is to write a program which determines the route with the shortest time to travel from a starting city to a goal city.
There are several cities in the country, and a road network connecting them. Each city has an acceleration device. As mentioned above, if a car arrives at a city at a speed v , it leaves the city at one of v - 1, v , or v + 1. The first road leaving the starting city must be run at the speed 1. Similarly, the last road arriving at the goal city must be run at the speed 1.
The starting city and the goal city are given. The problem is to find the best route which leads to the goal city going through several cities on the road network. When the car arrives at a city, it cannot immediately go back the road it used to reach the city. No U-turns are allowed. Except this constraint, one can choose any route on the road network. It is allowed to visit the same city or use the same road multiple times. The starting city and the goal city may be visited during the trip.
For each road on the network, its distance and speed limit are given. A car must run a road at a speed less than or equal to its speed limit. The time needed to run a road is the distance divided by the speed. The time needed within cities including that for acceleration or deceleration should be ignored.
Input
The input consists of multiple datasets, each in the following format.
> n m
> s g
> x 1 y 1 d 1 c 1
> ...
> xm ym dm cm
>
Every input item in a dataset is a non-negative integer. Input items in the same line are separated by a space.
The first line gives the size of the road network. n is the number of cities in the network. You can assume that the number of cities is between 2 and 30, inclusive. m is the number of roads between cities, which may be zero.
The second line gives the trip. s is the city index of the starting city. g is the city index of the goal city. s is not equal to g . You can assume that all city indices in a dataset (including the above two) are between 1 and n , inclusive.
The following m lines give the details of roads between cities. The i -th road connects two cities with city indices xi and yi , and has a distance di (1 ≤ i ≤ m ). You can assume that the distance is between 1 and 100, inclusive. The speed limit of the road is specified by ci . You can assume that the speed limit is between 1 and 30, inclusive.
No two roads connect the same pair of cities. A road never connects a city with itself. Each road can be traveled in both directions.
The last dataset is followed by a line containing two zeros (separated by a space).
Output
For each dataset in the input, one line should be output as specified below. An output line should not contain extra characters such as spaces.
If one can travel from the starting city to the goal city, the time needed for the best route (a route with the shortest time) should be printed. The answer should not have an error greater than 0.001. You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied.
If it is impossible to reach the goal city, the string "`unreachable`" should be printed. Note that all the letters of "`unreachable`" are in lowercase.
Sample Input
2 0
1 2
5 4
1 5
1 2 1 1
2 3 2 2
3 4 2 2
4 5 1 1
6 6
1 6
1 2 2 1
2 3 2 1
3 6 2 1
1 4 2 30
4 5 3 30
5 6 2 30
6 7
1 6
1 2 1 30
2 3 1 30
3 1 1 30
3 4 100 30
4 5 1 30
5 6 1 30
6 4 1 30
0 0
Output for the Sample Input
unreachable
4.00000
5.50000
11.25664
Example
Input
2 0
1 2
5 4
1 5
1 2 1 1
2 3 2 2
3 4 2 2
4 5 1 1
6 6
1 6
1 2 2 1
2 3 2 1
3 6 2 1
1 4 2 30
4 5 3 30
5 6 2 30
6 7
1 6
1 2 1 30
2 3 1 30
3 1 1 30
3 4 100 30
4 5 1 30
5 6 1 30
6 4 1 30
0 0
Output
unreachable
4.00000
5.50000
11.25664
Submitted Solution:
```
# AOJ 1162: Discrete Speed
# Python3 2018.7.15 bal4u
INF = 0x7fffffff
import heapq
def dijkstra(V, to, start, goal):
node = [[[INF for k in range(32)] for j in range(V)] for i in range(V)]
Q = []
node[start][0][0] = 0
heapq.heappush(Q, (0, start, 0, 0))
while Q:
t, s, v, p = heapq.heappop(Q)
if s == goal and v == 1: return node[goal][p][v]
for e, d, c in to[s]:
if e == p: continue
for i in range(-1, 2):
nv = v+i
if nv > c or nv <= 0: continue
nt = node[s][p][v]+d/nv
if nt < node[e][s][nv]:
node[e][s][nv] = nt
heapq.heappush(Q, (nt, e, nv, s))
return -1
while True:
n, m = map(int, input().split())
if n == 0: break
s, g = map(int, input().split())
s -= 1; g -= 1
to = [[] for i in range(n)]
for i in range(m):
x, y, d, c = map(int, input().split())
x -= 1; y -= 1
to[x].append((y, d, c))
to[y].append((x, d, c))
ans = dijkstra(n, to, s, g)
print(ans if ans >= 0 else "unreachable")
```
No
| 99,395 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider car trips in a country where there is no friction. Cars in this country do not have engines. Once a car started to move at a speed, it keeps moving at the same speed. There are acceleration devices on some points on the road, where a car can increase or decrease its speed by 1. It can also keep its speed there. Your job in this problem is to write a program which determines the route with the shortest time to travel from a starting city to a goal city.
There are several cities in the country, and a road network connecting them. Each city has an acceleration device. As mentioned above, if a car arrives at a city at a speed v , it leaves the city at one of v - 1, v , or v + 1. The first road leaving the starting city must be run at the speed 1. Similarly, the last road arriving at the goal city must be run at the speed 1.
The starting city and the goal city are given. The problem is to find the best route which leads to the goal city going through several cities on the road network. When the car arrives at a city, it cannot immediately go back the road it used to reach the city. No U-turns are allowed. Except this constraint, one can choose any route on the road network. It is allowed to visit the same city or use the same road multiple times. The starting city and the goal city may be visited during the trip.
For each road on the network, its distance and speed limit are given. A car must run a road at a speed less than or equal to its speed limit. The time needed to run a road is the distance divided by the speed. The time needed within cities including that for acceleration or deceleration should be ignored.
Input
The input consists of multiple datasets, each in the following format.
> n m
> s g
> x 1 y 1 d 1 c 1
> ...
> xm ym dm cm
>
Every input item in a dataset is a non-negative integer. Input items in the same line are separated by a space.
The first line gives the size of the road network. n is the number of cities in the network. You can assume that the number of cities is between 2 and 30, inclusive. m is the number of roads between cities, which may be zero.
The second line gives the trip. s is the city index of the starting city. g is the city index of the goal city. s is not equal to g . You can assume that all city indices in a dataset (including the above two) are between 1 and n , inclusive.
The following m lines give the details of roads between cities. The i -th road connects two cities with city indices xi and yi , and has a distance di (1 ≤ i ≤ m ). You can assume that the distance is between 1 and 100, inclusive. The speed limit of the road is specified by ci . You can assume that the speed limit is between 1 and 30, inclusive.
No two roads connect the same pair of cities. A road never connects a city with itself. Each road can be traveled in both directions.
The last dataset is followed by a line containing two zeros (separated by a space).
Output
For each dataset in the input, one line should be output as specified below. An output line should not contain extra characters such as spaces.
If one can travel from the starting city to the goal city, the time needed for the best route (a route with the shortest time) should be printed. The answer should not have an error greater than 0.001. You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied.
If it is impossible to reach the goal city, the string "`unreachable`" should be printed. Note that all the letters of "`unreachable`" are in lowercase.
Sample Input
2 0
1 2
5 4
1 5
1 2 1 1
2 3 2 2
3 4 2 2
4 5 1 1
6 6
1 6
1 2 2 1
2 3 2 1
3 6 2 1
1 4 2 30
4 5 3 30
5 6 2 30
6 7
1 6
1 2 1 30
2 3 1 30
3 1 1 30
3 4 100 30
4 5 1 30
5 6 1 30
6 4 1 30
0 0
Output for the Sample Input
unreachable
4.00000
5.50000
11.25664
Example
Input
2 0
1 2
5 4
1 5
1 2 1 1
2 3 2 2
3 4 2 2
4 5 1 1
6 6
1 6
1 2 2 1
2 3 2 1
3 6 2 1
1 4 2 30
4 5 3 30
5 6 2 30
6 7
1 6
1 2 1 30
2 3 1 30
3 1 1 30
3 4 100 30
4 5 1 30
5 6 1 30
6 4 1 30
0 0
Output
unreachable
4.00000
5.50000
11.25664
Submitted Solution:
```
MAX_SPEED = 30
while True:
N, M = map(int, input().split())
if not (N | M):
break
S, G = map(lambda x: int(x) - 1, input().split())
edge = []
for _ in range(M):
x, y, d, c = map(int, input().split())
edge.append((x - 1, y - 1, d, c))
edge.append((y - 1, x - 1, d, c))
INF = float('inf')
dist = [[[INF for _ in range(N)] for _ in range(MAX_SPEED + 1)] for _ in range(N)]
dist[S][0][S] = 0.0
while True:
flag = False
for x, y, d, c in edge:
for j in range(min(MAX_SPEED + 1, c + 2)):
for k in range(N):
if k == y or (j <= c and dist[x][j][k] == INF):
continue
# print(x, y, d, c, j, k, dist[x][j][k])
if j > 1 and dist[y][j - 1][x] > dist[x][j][k] + d / (j - 1):
dist[y][j - 1][x] = dist[x][j][k] + d / (j - 1)
flag = True
if 0 < j <= c and dist[y][j][x] > dist[x][j][k] + d / j:
dist[y][j][x] = dist[x][j][k] + d / j
flag = True
if j < c and dist[y][j + 1][x] > dist[x][j][k] + d / (j + 1):
dist[y][j + 1][x] = dist[x][j][k] + d / (j + 1)
flag = True
if not flag:
break
"""
for i in range(N):
print(*dist[i], sep='\n')
print()
"""
ans = min(dist[G][1][j] for j in range(N))
print("unreachable" if ans == INF else "{:.20f}".format(ans))
```
No
| 99,396 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider car trips in a country where there is no friction. Cars in this country do not have engines. Once a car started to move at a speed, it keeps moving at the same speed. There are acceleration devices on some points on the road, where a car can increase or decrease its speed by 1. It can also keep its speed there. Your job in this problem is to write a program which determines the route with the shortest time to travel from a starting city to a goal city.
There are several cities in the country, and a road network connecting them. Each city has an acceleration device. As mentioned above, if a car arrives at a city at a speed v , it leaves the city at one of v - 1, v , or v + 1. The first road leaving the starting city must be run at the speed 1. Similarly, the last road arriving at the goal city must be run at the speed 1.
The starting city and the goal city are given. The problem is to find the best route which leads to the goal city going through several cities on the road network. When the car arrives at a city, it cannot immediately go back the road it used to reach the city. No U-turns are allowed. Except this constraint, one can choose any route on the road network. It is allowed to visit the same city or use the same road multiple times. The starting city and the goal city may be visited during the trip.
For each road on the network, its distance and speed limit are given. A car must run a road at a speed less than or equal to its speed limit. The time needed to run a road is the distance divided by the speed. The time needed within cities including that for acceleration or deceleration should be ignored.
Input
The input consists of multiple datasets, each in the following format.
> n m
> s g
> x 1 y 1 d 1 c 1
> ...
> xm ym dm cm
>
Every input item in a dataset is a non-negative integer. Input items in the same line are separated by a space.
The first line gives the size of the road network. n is the number of cities in the network. You can assume that the number of cities is between 2 and 30, inclusive. m is the number of roads between cities, which may be zero.
The second line gives the trip. s is the city index of the starting city. g is the city index of the goal city. s is not equal to g . You can assume that all city indices in a dataset (including the above two) are between 1 and n , inclusive.
The following m lines give the details of roads between cities. The i -th road connects two cities with city indices xi and yi , and has a distance di (1 ≤ i ≤ m ). You can assume that the distance is between 1 and 100, inclusive. The speed limit of the road is specified by ci . You can assume that the speed limit is between 1 and 30, inclusive.
No two roads connect the same pair of cities. A road never connects a city with itself. Each road can be traveled in both directions.
The last dataset is followed by a line containing two zeros (separated by a space).
Output
For each dataset in the input, one line should be output as specified below. An output line should not contain extra characters such as spaces.
If one can travel from the starting city to the goal city, the time needed for the best route (a route with the shortest time) should be printed. The answer should not have an error greater than 0.001. You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied.
If it is impossible to reach the goal city, the string "`unreachable`" should be printed. Note that all the letters of "`unreachable`" are in lowercase.
Sample Input
2 0
1 2
5 4
1 5
1 2 1 1
2 3 2 2
3 4 2 2
4 5 1 1
6 6
1 6
1 2 2 1
2 3 2 1
3 6 2 1
1 4 2 30
4 5 3 30
5 6 2 30
6 7
1 6
1 2 1 30
2 3 1 30
3 1 1 30
3 4 100 30
4 5 1 30
5 6 1 30
6 4 1 30
0 0
Output for the Sample Input
unreachable
4.00000
5.50000
11.25664
Example
Input
2 0
1 2
5 4
1 5
1 2 1 1
2 3 2 2
3 4 2 2
4 5 1 1
6 6
1 6
1 2 2 1
2 3 2 1
3 6 2 1
1 4 2 30
4 5 3 30
5 6 2 30
6 7
1 6
1 2 1 30
2 3 1 30
3 1 1 30
3 4 100 30
4 5 1 30
5 6 1 30
6 4 1 30
0 0
Output
unreachable
4.00000
5.50000
11.25664
Submitted Solution:
```
from fractions import Fraction
MAX_SPEED = 30
while True:
N, M = map(int, input().split())
if not (N | M):
break
S, G = map(lambda x: int(x) - 1, input().split())
edge = []
for _ in range(M):
x, y, d, c = map(int, input().split())
edge.append((x - 1, y - 1, d, c))
edge.append((y - 1, x - 1, d, c))
INF = float('inf')
dist = [[[INF for _ in range(N)] for _ in range(MAX_SPEED + 1)] for _ in range(N)]
dist[S][0][S] = Fraction()
while True:
flag = False
for x, y, d, c in edge:
for j in range(min(MAX_SPEED + 1, c + 2)):
for k in range(N):
if k == y or (j <= c and dist[x][j][k] == INF):
continue
# print(x, y, d, c, j, k, dist[x][j][k])
if j > 1 and dist[y][j - 1][x] > dist[x][j][k] + Fraction(d, j - 1):
dist[y][j - 1][x] = dist[x][j][k] + Fraction(d, j - 1)
flag = True
if 0 < j <= c and dist[y][j][x] > dist[x][j][k] + Fraction(d, j):
dist[y][j][x] = dist[x][j][k] + Fraction(d, j)
flag = True
if j < c and dist[y][j + 1][x] > dist[x][j][k] + Fraction(d, j + 1):
dist[y][j + 1][x] = dist[x][j][k] + Fraction(d, j + 1)
flag = True
if not flag:
break
"""
for i in range(N):
print(*dist[i], sep='\n')
print()
"""
ans = min(dist[G][1][j] for j in range(N))
print("unreachable" if ans == INF else "{:.20f}".format(float(ans)))
```
No
| 99,397 |
Provide a correct Python 3 solution for this coding contest problem.
Princess in Danger
Princess crisis
English text is not available in this practice contest.
A brave princess in a poor country's tomboy is married to another country for a political marriage. However, a villain who was trying to kill the princess attacked him on the way to his wife, and the princess was seriously injured and was taken to a nearby hospital. However, the villain used a special poison to make sure the princess was dead. Therefore, in order to help the princess, she had to hurry to bring special medicine and frozen relatives' blood from her home country.
This blood is transported frozen, but must be re-frozen in a blood freezing facility within up to M minutes of the previous freezing to keep it fresh. However, there are only a few places where refrigeration facilities are installed.
Blood is safe for M minutes from a fully frozen state without refreezing. If the remaining time without refrigeration is S minutes and the product is transported without freezing for T minutes, the remaining time without refrigeration is S-T minutes. The remaining time that does not require refreezing can be restored up to M minutes by refreezing. The time it takes to refreeze blood depends on how much it is frozen. Every minute the blood is frozen in a freezing facility, the remaining time that does not need to be re-frozen recovers by 1 minute.
At the time of departure from the capital of the home country, the remaining time without refrigerating the blood is M minutes.
As a princess's servant, you must calculate the route to keep the blood fresh from the capital of your home country to the hospital where the princess was transported, in order to save the life of your precious lord. Yes, your mission is to figure out the shortest route from your home capital to the hospital and find the shortest time.
Input
The input consists of multiple datasets. The first row of each dataset contains six non-negative integers N (2 ≤ N ≤ 100), M (1 ≤ M ≤ 100), L (0 ≤ L ≤ N-2), K, A (0 ≤). A <N) and H (0 ≤ H <N) are given. These are the number of towns, the time limit for refrigeration, the number of towns with freezing facilities, the number of roads connecting towns directly, the number representing the capital of the home country, and the hospital where the princess was transported. Represents the town number. The capital of the home country and the hospital where the princess was transported are different towns. It is assumed that the towns are assigned numbers from 0 to N-1. The following lines are given L non-negative integers separated by a single space. These represent the numbers of the towns where the freezing facilities are located. The capital of the home country and the hospital where the princess was transported are not included in this list, but it can be considered that there is a freezing facility. The following line K gives information on the roads connecting the towns. In the i-th line, three non-negative integers X, Y, and T are given separated by one space, which means that there is a direct connection between town X and town Y, and it takes time T to move. Represents that. This road is bidirectional. Also, there is at most one road that directly connects town X and town Y.
The input ends when N = M = L = K = A = H = 0, which is not included in the dataset.
Output
For each dataset, output the shortest time that blood can be delivered while maintaining its freshness. If it cannot be delivered, output "Help!".
Sample Input
2 1 0 1 0 1
0 1 2
3 1 1 2 0 1
2
0 2 1
1 2 1
3 2 1 2 0 1
2
0 2 1
1 2 1
4 4 1 4 1 3
2
0 1 2
1 2 4
0 2 1
3 0 3
5 3 2 6 0 3
1 2
2 1 2
1 0 1
3 4 1
2 4 1
4 1 2
2 0 2
5 4 2 6 0 3
1 2
4 2 4
2 1 2
4 3 1
0 1 5
1 4 2
2 0 3
0 0 0 0 0 0
Output for the Sample Input
Help!
3
2
Ten
Five
12
Example
Input
2 1 0 1 0 1
0 1 2
3 1 1 2 0 1
2
0 2 1
1 2 1
3 2 1 2 0 1
2
0 2 1
1 2 1
4 4 1 4 1 3
2
0 1 2
1 2 4
0 2 1
3 0 3
5 3 2 6 0 3
1 2
2 1 2
1 0 1
3 4 1
2 4 1
4 1 2
2 0 2
5 4 2 6 0 3
1 2
4 2 4
2 1 2
4 3 1
0 1 5
1 4 2
2 0 3
0 0 0 0 0 0
Output
Help!
3
2
10
5
12
"Correct Solution:
```
from heapq import heappop, heappush
def dijkstra(links, n, m, freezables, s, t):
queue = [(0, 0, s, m)]
visited = [0] * n
while queue:
link_cost, cost, node, remain = heappop(queue)
if node == t:
# Congratulations!
if link_cost <= m:
return link_cost
return cost - remain
if visited[node] >= remain:
continue
visited[node] = remain
for cost2, node2 in links[node]:
if remain < cost2:
continue
if node2 in freezables:
heappush(queue, (link_cost + cost2, cost + cost2 * 2 + m - remain, node2, m))
else:
heappush(queue, (link_cost + cost2, cost + cost2, node2, remain - cost2))
return 'Help!'
while True:
n, m, l, k, a, h = map(int, input().split())
if n == 0:
break
freezables = set(map(int, input().split())) if l > 0 else set()
links = [set() for _ in range(n)]
for _ in range(k):
x, y, t = map(int, input().split())
links[x].add((t, y))
links[y].add((t, x))
print(dijkstra(links, n, m, freezables, a, h))
```
| 99,398 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Princess in Danger
Princess crisis
English text is not available in this practice contest.
A brave princess in a poor country's tomboy is married to another country for a political marriage. However, a villain who was trying to kill the princess attacked him on the way to his wife, and the princess was seriously injured and was taken to a nearby hospital. However, the villain used a special poison to make sure the princess was dead. Therefore, in order to help the princess, she had to hurry to bring special medicine and frozen relatives' blood from her home country.
This blood is transported frozen, but must be re-frozen in a blood freezing facility within up to M minutes of the previous freezing to keep it fresh. However, there are only a few places where refrigeration facilities are installed.
Blood is safe for M minutes from a fully frozen state without refreezing. If the remaining time without refrigeration is S minutes and the product is transported without freezing for T minutes, the remaining time without refrigeration is S-T minutes. The remaining time that does not require refreezing can be restored up to M minutes by refreezing. The time it takes to refreeze blood depends on how much it is frozen. Every minute the blood is frozen in a freezing facility, the remaining time that does not need to be re-frozen recovers by 1 minute.
At the time of departure from the capital of the home country, the remaining time without refrigerating the blood is M minutes.
As a princess's servant, you must calculate the route to keep the blood fresh from the capital of your home country to the hospital where the princess was transported, in order to save the life of your precious lord. Yes, your mission is to figure out the shortest route from your home capital to the hospital and find the shortest time.
Input
The input consists of multiple datasets. The first row of each dataset contains six non-negative integers N (2 ≤ N ≤ 100), M (1 ≤ M ≤ 100), L (0 ≤ L ≤ N-2), K, A (0 ≤). A <N) and H (0 ≤ H <N) are given. These are the number of towns, the time limit for refrigeration, the number of towns with freezing facilities, the number of roads connecting towns directly, the number representing the capital of the home country, and the hospital where the princess was transported. Represents the town number. The capital of the home country and the hospital where the princess was transported are different towns. It is assumed that the towns are assigned numbers from 0 to N-1. The following lines are given L non-negative integers separated by a single space. These represent the numbers of the towns where the freezing facilities are located. The capital of the home country and the hospital where the princess was transported are not included in this list, but it can be considered that there is a freezing facility. The following line K gives information on the roads connecting the towns. In the i-th line, three non-negative integers X, Y, and T are given separated by one space, which means that there is a direct connection between town X and town Y, and it takes time T to move. Represents that. This road is bidirectional. Also, there is at most one road that directly connects town X and town Y.
The input ends when N = M = L = K = A = H = 0, which is not included in the dataset.
Output
For each dataset, output the shortest time that blood can be delivered while maintaining its freshness. If it cannot be delivered, output "Help!".
Sample Input
2 1 0 1 0 1
0 1 2
3 1 1 2 0 1
2
0 2 1
1 2 1
3 2 1 2 0 1
2
0 2 1
1 2 1
4 4 1 4 1 3
2
0 1 2
1 2 4
0 2 1
3 0 3
5 3 2 6 0 3
1 2
2 1 2
1 0 1
3 4 1
2 4 1
4 1 2
2 0 2
5 4 2 6 0 3
1 2
4 2 4
2 1 2
4 3 1
0 1 5
1 4 2
2 0 3
0 0 0 0 0 0
Output for the Sample Input
Help!
3
2
Ten
Five
12
Example
Input
2 1 0 1 0 1
0 1 2
3 1 1 2 0 1
2
0 2 1
1 2 1
3 2 1 2 0 1
2
0 2 1
1 2 1
4 4 1 4 1 3
2
0 1 2
1 2 4
0 2 1
3 0 3
5 3 2 6 0 3
1 2
2 1 2
1 0 1
3 4 1
2 4 1
4 1 2
2 0 2
5 4 2 6 0 3
1 2
4 2 4
2 1 2
4 3 1
0 1 5
1 4 2
2 0 3
0 0 0 0 0 0
Output
Help!
3
2
10
5
12
Submitted Solution:
```
from heapq import heappush, heappop
INF = 10 ** 20
def main():
while True:
n, m, l, k, a, h = map(int, input().split())
if n == 0:
break
if l != 0:
sisetu = list(map(int, input().split())) + [a, h]
else:
input()
sisetu = [a, h]
costs = [[INF] * n for _ in range(n)]
for _ in range(k):
x, y, t = map(int, input().split())
costs[x][y] = t
costs[y][x] = t
for k in range(n):
costsk = costs[k]
for i in range(n):
costsi = costs[i]
costsik = costsi[k]
for j in range(i + 1, n):
costsij = costsi[j]
costsikj = costsik + costsk[j]
if costsij > costsikj:
costsi[j] = costsikj
costs[j][i] = costsikj
edges = [[] for _ in range(n)]
for i in range(n):
for j in range(i + 1, n):
if i in sisetu and j in sisetu and costs[i][j] <= m:
edges[i].append((costs[i][j], j))
edges[j].append((costs[i][j], i))
que = []
heappush(que, (0, a))
cost = [INF] * n
cost[a] = 0
while que:
total, node = heappop(que)
for dist, to in edges[node]:
if total + dist < cost[to]:
cost[to] = total + dist
heappush(que, (total + dist, to))
if cost[h] == INF:
print("Help!")
else:
print(cost[h] + max(0, (cost[h] - m)))
main()
```
No
| 99,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.