message stringlengths 2 22.8k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 16 109k | cluster float64 1 1 | __index_level_0__ int64 32 217k |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of n stations, enumerated from 1 through n. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit after station i is station i+1 if 1 ≤ i < n or station 1 if i = n. It takes the train 1 second to travel to its next station as described.
Bob gave Alice a fun task before he left: to deliver m candies that are initially at some stations to their independent destinations using the train. The candies are enumerated from 1 through m. Candy i (1 ≤ i ≤ m), now at station a_i, should be delivered to station b_i (a_i ≠ b_i).
<image> The blue numbers on the candies correspond to b_i values. The image corresponds to the 1-st example.
The train has infinite capacity, and it is possible to load off any number of candies at a station. However, only at most one candy can be loaded from a station onto the train before it leaves the station. You can choose any candy at this station. The time it takes to move the candies is negligible.
Now, Alice wonders how much time is needed for the train to deliver all candies. Your task is to find, for each station, the minimum time the train would need to deliver all the candies were it to start from there.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 5 000; 1 ≤ m ≤ 20 000) — the number of stations and the number of candies, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 ≤ a_i, b_i ≤ n; a_i ≠ b_i) — the station that initially contains candy i and the destination station of the candy, respectively.
Output
In the first and only line, print n space-separated integers, the i-th of which is the minimum time, in seconds, the train would need to deliver all the candies were it to start from station i.
Examples
Input
5 7
2 4
5 1
2 3
3 4
4 1
5 3
3 5
Output
10 9 10 10 9
Input
2 3
1 2
1 2
1 2
Output
5 6
Note
Consider the second sample.
If the train started at station 1, the optimal strategy is as follows.
1. Load the first candy onto the train.
2. Proceed to station 2. This step takes 1 second.
3. Deliver the first candy.
4. Proceed to station 1. This step takes 1 second.
5. Load the second candy onto the train.
6. Proceed to station 2. This step takes 1 second.
7. Deliver the second candy.
8. Proceed to station 1. This step takes 1 second.
9. Load the third candy onto the train.
10. Proceed to station 2. This step takes 1 second.
11. Deliver the third candy.
Hence, the train needs 5 seconds to complete the tasks.
If the train were to start at station 2, however, it would need to move to station 1 before it could load the first candy, which would take one additional second. Thus, the answer in this scenario is 5+1 = 6 seconds.
Submitted Solution:
```
if __name__ == "__main__":
from sys import stdin
n, m = list(map(int, stdin.readline().split()))
c = {}
for _ in range(m):
a, b = list(map(int, stdin.readline().split()))
if (a-1) not in c.keys():
c[a-1] = []
x = b-a + (n if b<a else 0)
c[a-1].append(x)
for k, l in c.items():
c[k] = min(l) + ((len(l)-1)*n)
toprint = []
for x in range(n):
res = 0
for y, v in c.items():
s = y-x + (n if y<x else 0)
res = max(res, v+s)
toprint.append(res)
print(*toprint)
``` | instruction | 0 | 48,884 | 1 | 97,768 |
Yes | output | 1 | 48,884 | 1 | 97,769 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of n stations, enumerated from 1 through n. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit after station i is station i+1 if 1 ≤ i < n or station 1 if i = n. It takes the train 1 second to travel to its next station as described.
Bob gave Alice a fun task before he left: to deliver m candies that are initially at some stations to their independent destinations using the train. The candies are enumerated from 1 through m. Candy i (1 ≤ i ≤ m), now at station a_i, should be delivered to station b_i (a_i ≠ b_i).
<image> The blue numbers on the candies correspond to b_i values. The image corresponds to the 1-st example.
The train has infinite capacity, and it is possible to load off any number of candies at a station. However, only at most one candy can be loaded from a station onto the train before it leaves the station. You can choose any candy at this station. The time it takes to move the candies is negligible.
Now, Alice wonders how much time is needed for the train to deliver all candies. Your task is to find, for each station, the minimum time the train would need to deliver all the candies were it to start from there.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 5 000; 1 ≤ m ≤ 20 000) — the number of stations and the number of candies, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 ≤ a_i, b_i ≤ n; a_i ≠ b_i) — the station that initially contains candy i and the destination station of the candy, respectively.
Output
In the first and only line, print n space-separated integers, the i-th of which is the minimum time, in seconds, the train would need to deliver all the candies were it to start from station i.
Examples
Input
5 7
2 4
5 1
2 3
3 4
4 1
5 3
3 5
Output
10 9 10 10 9
Input
2 3
1 2
1 2
1 2
Output
5 6
Note
Consider the second sample.
If the train started at station 1, the optimal strategy is as follows.
1. Load the first candy onto the train.
2. Proceed to station 2. This step takes 1 second.
3. Deliver the first candy.
4. Proceed to station 1. This step takes 1 second.
5. Load the second candy onto the train.
6. Proceed to station 2. This step takes 1 second.
7. Deliver the second candy.
8. Proceed to station 1. This step takes 1 second.
9. Load the third candy onto the train.
10. Proceed to station 2. This step takes 1 second.
11. Deliver the third candy.
Hence, the train needs 5 seconds to complete the tasks.
If the train were to start at station 2, however, it would need to move to station 1 before it could load the first candy, which would take one additional second. Thus, the answer in this scenario is 5+1 = 6 seconds.
Submitted Solution:
```
from collections import defaultdict as dd
n,m=[int(i) for i in input().split(' ')]
a=[]
b=[]
def fnx(i,j):
if i<j:
return(j-i)
else:
return(n-i+j)
def fnr(r):
if r%n==0:
return(n)
else:
return(r%n)
for i in range(m):
x,y=[int(i) for i in input().split(' ')]
a.append(x)
b.append(y)
ANS=[]
ii=1
s=[[] for i in range(n+1)]
d=dd(list)
r=[ -1 for i in range(n+1)]
y=[-1]
for i in range(m):
x,yy=a[i],b[i]
s[x].append([fnx(x,yy),x,yy])
d[yy].append(x)
for i in range(1,n+1):
rt=s[i].copy()
rt.sort()
r[i]=rt
y.append(len(s[i]))
#print(r)
p=max(y)
A=(p-2)*n
ans1=[]
ans2=[]
for i in range(1,n+1):
if y[i]==p:
if p==1:
ans2.append(r[i][0])
continue
ans1.append(r[i][1])
ans2.append(r[i][0])
if y[i]==p-1:
if p-1==0:
continue
ans1.append(r[i][0])
tr=0
for ij in range(1,n+1):
for i in range(len(ans1)):
re=ans1[i][0]+fnr(ans1[i][1]-ij+1)-1
tr=max(tr,re)
trf=0
for i in range(len(ans2)):
re=ans2[i][0]+fnr(ans2[i][1]-ij+1)-1
trf=max(trf,re)
er=max(A+tr,A+trf+n)
#print(er)
ANS.append(er)
print(*ANS)
``` | instruction | 0 | 48,885 | 1 | 97,770 |
No | output | 1 | 48,885 | 1 | 97,771 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of n stations, enumerated from 1 through n. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit after station i is station i+1 if 1 ≤ i < n or station 1 if i = n. It takes the train 1 second to travel to its next station as described.
Bob gave Alice a fun task before he left: to deliver m candies that are initially at some stations to their independent destinations using the train. The candies are enumerated from 1 through m. Candy i (1 ≤ i ≤ m), now at station a_i, should be delivered to station b_i (a_i ≠ b_i).
<image> The blue numbers on the candies correspond to b_i values. The image corresponds to the 1-st example.
The train has infinite capacity, and it is possible to load off any number of candies at a station. However, only at most one candy can be loaded from a station onto the train before it leaves the station. You can choose any candy at this station. The time it takes to move the candies is negligible.
Now, Alice wonders how much time is needed for the train to deliver all candies. Your task is to find, for each station, the minimum time the train would need to deliver all the candies were it to start from there.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 5 000; 1 ≤ m ≤ 20 000) — the number of stations and the number of candies, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 ≤ a_i, b_i ≤ n; a_i ≠ b_i) — the station that initially contains candy i and the destination station of the candy, respectively.
Output
In the first and only line, print n space-separated integers, the i-th of which is the minimum time, in seconds, the train would need to deliver all the candies were it to start from station i.
Examples
Input
5 7
2 4
5 1
2 3
3 4
4 1
5 3
3 5
Output
10 9 10 10 9
Input
2 3
1 2
1 2
1 2
Output
5 6
Note
Consider the second sample.
If the train started at station 1, the optimal strategy is as follows.
1. Load the first candy onto the train.
2. Proceed to station 2. This step takes 1 second.
3. Deliver the first candy.
4. Proceed to station 1. This step takes 1 second.
5. Load the second candy onto the train.
6. Proceed to station 2. This step takes 1 second.
7. Deliver the second candy.
8. Proceed to station 1. This step takes 1 second.
9. Load the third candy onto the train.
10. Proceed to station 2. This step takes 1 second.
11. Deliver the third candy.
Hence, the train needs 5 seconds to complete the tasks.
If the train were to start at station 2, however, it would need to move to station 1 before it could load the first candy, which would take one additional second. Thus, the answer in this scenario is 5+1 = 6 seconds.
Submitted Solution:
```
N, M = map(int, input().split())
candies = [[] for _ in [0]*N]
c_count = [0]*N
for a, b in (map(int, input().split()) for _ in [0]*M):
candies[a-1].append(b-1)
c_count[a-1] += 1
for i in range(N):
candies[i] = sorted(n+N if n < i else n for n in candies[i])
ans = []
for start in range(N):
max_i, max_n = 0, 0
amari = 10**9
for i in range(start, N):
if c_count[i] and c_count[i] >= max_n and amari > (max_i-start) + candies[i][0] - i:
max_n = c_count[i]
max_i = i
amari = max_i-start + candies[i][0] - i
for i in range(start):
if c_count[i] and c_count[i] >= max_n and amari > (max_i+N-start) + candies[i][0] - i:
max_n = c_count[i]
max_i = i+N
amari = max_i-start + candies[i][0] - i
ans.append((max_n-1)*N + amari)
print(*ans)
``` | instruction | 0 | 48,886 | 1 | 97,772 |
No | output | 1 | 48,886 | 1 | 97,773 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of n stations, enumerated from 1 through n. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit after station i is station i+1 if 1 ≤ i < n or station 1 if i = n. It takes the train 1 second to travel to its next station as described.
Bob gave Alice a fun task before he left: to deliver m candies that are initially at some stations to their independent destinations using the train. The candies are enumerated from 1 through m. Candy i (1 ≤ i ≤ m), now at station a_i, should be delivered to station b_i (a_i ≠ b_i).
<image> The blue numbers on the candies correspond to b_i values. The image corresponds to the 1-st example.
The train has infinite capacity, and it is possible to load off any number of candies at a station. However, only at most one candy can be loaded from a station onto the train before it leaves the station. You can choose any candy at this station. The time it takes to move the candies is negligible.
Now, Alice wonders how much time is needed for the train to deliver all candies. Your task is to find, for each station, the minimum time the train would need to deliver all the candies were it to start from there.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 5 000; 1 ≤ m ≤ 20 000) — the number of stations and the number of candies, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 ≤ a_i, b_i ≤ n; a_i ≠ b_i) — the station that initially contains candy i and the destination station of the candy, respectively.
Output
In the first and only line, print n space-separated integers, the i-th of which is the minimum time, in seconds, the train would need to deliver all the candies were it to start from station i.
Examples
Input
5 7
2 4
5 1
2 3
3 4
4 1
5 3
3 5
Output
10 9 10 10 9
Input
2 3
1 2
1 2
1 2
Output
5 6
Note
Consider the second sample.
If the train started at station 1, the optimal strategy is as follows.
1. Load the first candy onto the train.
2. Proceed to station 2. This step takes 1 second.
3. Deliver the first candy.
4. Proceed to station 1. This step takes 1 second.
5. Load the second candy onto the train.
6. Proceed to station 2. This step takes 1 second.
7. Deliver the second candy.
8. Proceed to station 1. This step takes 1 second.
9. Load the third candy onto the train.
10. Proceed to station 2. This step takes 1 second.
11. Deliver the third candy.
Hence, the train needs 5 seconds to complete the tasks.
If the train were to start at station 2, however, it would need to move to station 1 before it could load the first candy, which would take one additional second. Thus, the answer in this scenario is 5+1 = 6 seconds.
Submitted Solution:
```
n, m = list(map(int, input().split()))
a = []
for i in range(m):
a.append(list(map(int, input().split())))
locs = []
for i in range(n+1):
locs.append([])
for i in range(m):
locs[a[i][0]].append(a[i][1])
ans = [0]*(n+1)
for i in range(1, n+1):
mini = 2**n
for j in locs[i]:
if(j > i):
mini = min(mini, j-i)
else:
mini = min(mini, n-i+j)
if(mini == 2**n):
ans[i] = 0
else:
ans[i] = max(0, n*(len(locs[i])-1) + mini)
# print(*ans[1:])
for start in range(1, n+1):
maxi = 0
for j in range(1, n+1):
if(j >= start):
maxi = max(maxi, j-start + ans[j])
else:
maxi = max(maxi, n - start + j + ans[j])
print(maxi, end=" ")
``` | instruction | 0 | 48,887 | 1 | 97,774 |
No | output | 1 | 48,887 | 1 | 97,775 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of n stations, enumerated from 1 through n. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit after station i is station i+1 if 1 ≤ i < n or station 1 if i = n. It takes the train 1 second to travel to its next station as described.
Bob gave Alice a fun task before he left: to deliver m candies that are initially at some stations to their independent destinations using the train. The candies are enumerated from 1 through m. Candy i (1 ≤ i ≤ m), now at station a_i, should be delivered to station b_i (a_i ≠ b_i).
<image> The blue numbers on the candies correspond to b_i values. The image corresponds to the 1-st example.
The train has infinite capacity, and it is possible to load off any number of candies at a station. However, only at most one candy can be loaded from a station onto the train before it leaves the station. You can choose any candy at this station. The time it takes to move the candies is negligible.
Now, Alice wonders how much time is needed for the train to deliver all candies. Your task is to find, for each station, the minimum time the train would need to deliver all the candies were it to start from there.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 5 000; 1 ≤ m ≤ 20 000) — the number of stations and the number of candies, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 ≤ a_i, b_i ≤ n; a_i ≠ b_i) — the station that initially contains candy i and the destination station of the candy, respectively.
Output
In the first and only line, print n space-separated integers, the i-th of which is the minimum time, in seconds, the train would need to deliver all the candies were it to start from station i.
Examples
Input
5 7
2 4
5 1
2 3
3 4
4 1
5 3
3 5
Output
10 9 10 10 9
Input
2 3
1 2
1 2
1 2
Output
5 6
Note
Consider the second sample.
If the train started at station 1, the optimal strategy is as follows.
1. Load the first candy onto the train.
2. Proceed to station 2. This step takes 1 second.
3. Deliver the first candy.
4. Proceed to station 1. This step takes 1 second.
5. Load the second candy onto the train.
6. Proceed to station 2. This step takes 1 second.
7. Deliver the second candy.
8. Proceed to station 1. This step takes 1 second.
9. Load the third candy onto the train.
10. Proceed to station 2. This step takes 1 second.
11. Deliver the third candy.
Hence, the train needs 5 seconds to complete the tasks.
If the train were to start at station 2, however, it would need to move to station 1 before it could load the first candy, which would take one additional second. Thus, the answer in this scenario is 5+1 = 6 seconds.
Submitted Solution:
```
from collections import defaultdict as dd
n,m=[int(i) for i in input().split(' ')]
a=[]
b=[]
def fnx(i,j):
if i<j:
return(j-i)
else:
return(n-i+j)
def fnr(r):
if r%n==0:
return(n)
else:
return(r%n)
for i in range(m):
x,y=[int(i) for i in input().split(' ')]
a.append(x)
b.append(y)
ANS=[]
ii=1
s=[[] for i in range(n+1)]
d=dd(list)
r=[ -1 for i in range(n+1)]
y=[-1]
for i in range(m):
x,yy=a[i],b[i]
s[x].append([fnx(x,yy),x,yy])
d[yy].append(x)
for i in range(1,n+1):
rt=s[i].copy()
rt.sort()
r[i]=rt
y.append(len(s[i]))
#print(r)
p=max(y)
A=(p-2)*n
ans1=[]
ans2=[]
for i in range(1,n+1):
if y[i]==p:
if p==1:
ans2.append(r[i][0])
continue
ans1.append(r[i][1])
ans2.append(r[i][0])
if y[i]==p-1:
if p-1==0:
continue
ans1.append(r[i][0])
tr=0
for ii in range(1,n+1):
for i in range(len(ans1)):
re=ans1[i][0]+fnr(ans1[i][1]-ii+1)-1
tr=max(tr,re)
trf=0
for i in range(len(ans2)):
re=ans2[i][0]+fnr(ans2[i][1]-ii+1)-1
trf=max(trf,re)
er=max(A+tr,A+trf+n)
#print(er)
ANS.append(er)
print(*ANS)
``` | instruction | 0 | 48,888 | 1 | 97,776 |
No | output | 1 | 48,888 | 1 | 97,777 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Koala Land consists of m bidirectional roads connecting n cities. The roads are numbered from 1 to m by order in input. It is guaranteed, that one can reach any city from every other city.
Koala starts traveling from city 1. Whenever he travels on a road, he writes its number down in his notebook. He doesn't put spaces between the numbers, so they all get concatenated into a single number.
Before embarking on his trip, Koala is curious about the resulting number for all possible destinations. For each possible destination, what is the smallest number he could have written for it?
Since these numbers may be quite large, print their remainders modulo 10^9+7. Please note, that you need to compute the remainder of the minimum possible number, not the minimum possible remainder.
Input
The first line contains two integers n and m (2 ≤ n ≤ 10^5, n - 1 ≤ m ≤ 10^5), the number of cities and the number of roads, respectively.
The i-th of the following m lines contains integers x_i and y_i (1 ≤ x_i, y_i ≤ n, x_i ≠ y_i), representing a bidirectional road between cities x_i and y_i.
It is guaranteed, that for any pair of cities there is at most one road connecting them, and that one can reach any city from every other city.
Output
Print n - 1 integers, the answer for every city except for the first city.
The i-th integer should be equal to the smallest number he could have written for destination i+1. Since this number may be large, output its remainder modulo 10^9+7.
Examples
Input
11 10
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
10 11
Output
1
12
123
1234
12345
123456
1234567
12345678
123456789
345678826
Input
12 19
1 2
2 3
2 4
2 5
2 6
2 7
2 8
2 9
2 10
3 11
11 12
1 3
1 4
1 5
1 6
1 7
1 8
1 9
1 10
Output
1
12
13
14
15
16
17
18
19
1210
121011
Input
12 14
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
10 11
11 12
1 3
1 4
1 10
Output
1
12
13
134
1345
13456
1498
149
14
1410
141011
Submitted Solution:
```
import heapq
import math
graph = []
nv = 0
mod = 10**9 + 7
def number_of_digits(n):
if n != 0:
return int(math.log10(n)) + 1#for negative numbers if you want the - sign add one more digit
else:
return 1
def Dijikstra():
global graph
inf = 10**11
visited = [False]*nv
dist = [inf]*nv
dist[1] = 0
seen = 0
heap = []
for i in range(2,nv + 1):
heapq.heappush(heap,(inf,i))
heapq.heappush(heap,(0,1))
current_vertex = -1
adj = -1
cost = -1
new_cost = -1
while(heap and seen < nv):
current_tuple = heapq.heappop(heap)
current_vertex = current_tuple[1]
visited[current_vertex] = True
seen +=1
for edge in graph[current_vertex]:
adj = edge[0]
cost = edge[1]
cost_digits = number_of_digits(cost)#numero de digitos
new_cost = ((dist[current_vertex]*(10**cost_digits))% mod + cost % mod ) % mod
if(not visited[adj] and new_cost < dist[adj]):
dist[adj] = new_cost
# parent[adj] = current_vertex
heapq.heappush(heap,(dist[adj],adj))
for i in range(2,nv):
print("{}\n".format(dist[i]))
#input:
#line1: n, m number of cities and roads(2<=n<=10^5; n-1<=m<=10^5)
#m lines:
# line i: <xi,yi> edge between vertices xi and yi
def main_method():
n, m = map(int, input().split())
global graph
graph = [0]*(n+1)
global nv
nv = n + 1
for i in range(1,m+1):
x, y = map(int, input().split())
try:
graph[x].append((y,i))
except:
graph[x] = [(y,i)]
try:
graph[y].append((x,i))
except:
graph[y] = [(x,i)]
Dijikstra()
main_method()
``` | instruction | 0 | 48,923 | 1 | 97,846 |
No | output | 1 | 48,923 | 1 | 97,847 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Koala Land consists of m bidirectional roads connecting n cities. The roads are numbered from 1 to m by order in input. It is guaranteed, that one can reach any city from every other city.
Koala starts traveling from city 1. Whenever he travels on a road, he writes its number down in his notebook. He doesn't put spaces between the numbers, so they all get concatenated into a single number.
Before embarking on his trip, Koala is curious about the resulting number for all possible destinations. For each possible destination, what is the smallest number he could have written for it?
Since these numbers may be quite large, print their remainders modulo 10^9+7. Please note, that you need to compute the remainder of the minimum possible number, not the minimum possible remainder.
Input
The first line contains two integers n and m (2 ≤ n ≤ 10^5, n - 1 ≤ m ≤ 10^5), the number of cities and the number of roads, respectively.
The i-th of the following m lines contains integers x_i and y_i (1 ≤ x_i, y_i ≤ n, x_i ≠ y_i), representing a bidirectional road between cities x_i and y_i.
It is guaranteed, that for any pair of cities there is at most one road connecting them, and that one can reach any city from every other city.
Output
Print n - 1 integers, the answer for every city except for the first city.
The i-th integer should be equal to the smallest number he could have written for destination i+1. Since this number may be large, output its remainder modulo 10^9+7.
Examples
Input
11 10
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
10 11
Output
1
12
123
1234
12345
123456
1234567
12345678
123456789
345678826
Input
12 19
1 2
2 3
2 4
2 5
2 6
2 7
2 8
2 9
2 10
3 11
11 12
1 3
1 4
1 5
1 6
1 7
1 8
1 9
1 10
Output
1
12
13
14
15
16
17
18
19
1210
121011
Input
12 14
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
10 11
11 12
1 3
1 4
1 10
Output
1
12
13
134
1345
13456
1498
149
14
1410
141011
Submitted Solution:
```
import heapq
from heapq import *
from fractions import Fraction
n, ne = map(int, input().split())
tr = [[] for __ in range(n + 1)]
for m in range(1, 1+ne):
u, v = map(int, input().split())
tr[u].append((v, m))
tr[v].append((u, m))
for a in tr: a.sort(key=lambda z:Fraction(z[1], 10**len(str(z[1]))-1))
dist = [9e999] * (1 + n)
dist[1] = 0
q = [(0, 1)]
while q:
d, u = heappop(q)
if d > dist[u]: continue
for v, m in tr[u]:
nd = d + len(str(m))
if nd < dist[v]:
dist[v] = nd
heappush(q, (nd, v))
prv = [0] * (n + 1)
visited = [0] * (n + 1)
MOD = 10**9+7
q = [1]; visited[1] = 1
for u in q:
for v, m in tr[u]:
if visited[v]: continue
if dist[u] + len(str(m)) != dist[v]: continue
visited [v] = True
prv[v] = int(str(prv[u]) + str(m)) % MOD
q.append(v)
for i in range(2, n+1):print(prv[i])
``` | instruction | 0 | 48,924 | 1 | 97,848 |
No | output | 1 | 48,924 | 1 | 97,849 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Koala Land consists of m bidirectional roads connecting n cities. The roads are numbered from 1 to m by order in input. It is guaranteed, that one can reach any city from every other city.
Koala starts traveling from city 1. Whenever he travels on a road, he writes its number down in his notebook. He doesn't put spaces between the numbers, so they all get concatenated into a single number.
Before embarking on his trip, Koala is curious about the resulting number for all possible destinations. For each possible destination, what is the smallest number he could have written for it?
Since these numbers may be quite large, print their remainders modulo 10^9+7. Please note, that you need to compute the remainder of the minimum possible number, not the minimum possible remainder.
Input
The first line contains two integers n and m (2 ≤ n ≤ 10^5, n - 1 ≤ m ≤ 10^5), the number of cities and the number of roads, respectively.
The i-th of the following m lines contains integers x_i and y_i (1 ≤ x_i, y_i ≤ n, x_i ≠ y_i), representing a bidirectional road between cities x_i and y_i.
It is guaranteed, that for any pair of cities there is at most one road connecting them, and that one can reach any city from every other city.
Output
Print n - 1 integers, the answer for every city except for the first city.
The i-th integer should be equal to the smallest number he could have written for destination i+1. Since this number may be large, output its remainder modulo 10^9+7.
Examples
Input
11 10
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
10 11
Output
1
12
123
1234
12345
123456
1234567
12345678
123456789
345678826
Input
12 19
1 2
2 3
2 4
2 5
2 6
2 7
2 8
2 9
2 10
3 11
11 12
1 3
1 4
1 5
1 6
1 7
1 8
1 9
1 10
Output
1
12
13
14
15
16
17
18
19
1210
121011
Input
12 14
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
10 11
11 12
1 3
1 4
1 10
Output
1
12
13
134
1345
13456
1498
149
14
1410
141011
Submitted Solution:
```
from sys import stdin, stdout
from collections import deque
graph = []
dist = []
nv = 0
reg = 10**9+7
def modified_bfs():
global graph
global dist
dist = [-1] * (nv+1)#dist[i] stores shortest number from the 1 to i
visited = [False] * (nv + 1)#boolean array to register vertices already seen
q = deque()
q.append(1)#the travel starts from vertex 1
dist[1] = 0
visited[1] = True
while q:
vertex = q.popleft()
graph[vertex].sort(key= lambda x: x[1])#adjacents list is sorted according to edge's cost
for adj in graph[vertex]:
next_vertex = adj[0]
if(not visited[next_vertex]):#if not visited update values
visited[next_vertex] = True
dist[next_vertex] = (dist[vertex] * 10 + adj[1]) % reg
q.append(next_vertex)
def split_edge(x,y,i):
global graph
global nv
previous_vertext = y
while(i>9):
rest = i%10
nv+=1#augment number of edges
graph.append([(previous_vertext,rest)])#initially graph contains only the first n vertices
#so artifial edges are numbered in ascending order according to discovering moment
i//=10
previous_vertext = nv
try:#add to x's adjacents list previous_vertex with cost i
graph[x].append((previous_vertext,i))
except AttributeError:#Create x's adjacents list with previous_vertex with cost i
graph[x] = [(previous_vertext,i)]
#input:
#line1: n, m number of cities and roads(2<=n<=10^5; n-1<=m<=10^5)
#m lines:
# line i: <xi,yi> edge between vertices xi and yi
def main_method():
n, m = map(int, stdin.readline().split())
global graph
graph = [0]*(n+1)
#graph[i] stores a list of tuples:
#(j,w) meaning i is conected with j via and edge with cost w
global nv
nv = n
#This variable will represent the number of total vertices in the graph,
#since extra vertices will be added
for i in range(1,m+1):
x, y = map(int, stdin.readline().split())
split_edge(x,y,i)#split edge into multiples edges with one digit cost
split_edge(y,x,i)
modified_bfs()
global dist
# reg = 10**9+7
for i in range(2,n+1):
stdout.write("{}\n".format(dist[i]))
# stdout.write("{}\n".format(dist[i]%reg))
main_method()
``` | instruction | 0 | 48,925 | 1 | 97,850 |
No | output | 1 | 48,925 | 1 | 97,851 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Koala Land consists of m bidirectional roads connecting n cities. The roads are numbered from 1 to m by order in input. It is guaranteed, that one can reach any city from every other city.
Koala starts traveling from city 1. Whenever he travels on a road, he writes its number down in his notebook. He doesn't put spaces between the numbers, so they all get concatenated into a single number.
Before embarking on his trip, Koala is curious about the resulting number for all possible destinations. For each possible destination, what is the smallest number he could have written for it?
Since these numbers may be quite large, print their remainders modulo 10^9+7. Please note, that you need to compute the remainder of the minimum possible number, not the minimum possible remainder.
Input
The first line contains two integers n and m (2 ≤ n ≤ 10^5, n - 1 ≤ m ≤ 10^5), the number of cities and the number of roads, respectively.
The i-th of the following m lines contains integers x_i and y_i (1 ≤ x_i, y_i ≤ n, x_i ≠ y_i), representing a bidirectional road between cities x_i and y_i.
It is guaranteed, that for any pair of cities there is at most one road connecting them, and that one can reach any city from every other city.
Output
Print n - 1 integers, the answer for every city except for the first city.
The i-th integer should be equal to the smallest number he could have written for destination i+1. Since this number may be large, output its remainder modulo 10^9+7.
Examples
Input
11 10
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
10 11
Output
1
12
123
1234
12345
123456
1234567
12345678
123456789
345678826
Input
12 19
1 2
2 3
2 4
2 5
2 6
2 7
2 8
2 9
2 10
3 11
11 12
1 3
1 4
1 5
1 6
1 7
1 8
1 9
1 10
Output
1
12
13
14
15
16
17
18
19
1210
121011
Input
12 14
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
10 11
11 12
1 3
1 4
1 10
Output
1
12
13
134
1345
13456
1498
149
14
1410
141011
Submitted Solution:
```
from sys import stdin, stdout
from collections import deque
graph = []
dist = []
nv = 0
reg = 10**9+7
def modified_bfs():
global graph
global dist
dist = [-1] * (nv+1)#dist[i] stores shortest number from the 1 to i
visited = [False] * (nv + 1)#boolean array to register vertices already seen
q = deque()
q.append(1)#the travel starts from vertex 1
dist[1] = 0
visited[1] = True
while q:
vertex = q.popleft()
graph[vertex].sort(key= lambda x: x[1])#adjacents list is sorted according to edge's cost
for adj in graph[vertex]:
next_vertex = adj[0]
if(not visited[next_vertex]):#if not visited update values
visited[next_vertex] = True
dist[next_vertex] = ((dist[vertex] * 10)%reg + adj[1]%reg) % reg
q.append(next_vertex)
def split_edge(x,y,i):
global graph
global nv
previous_vertext = y
while(i>9):
rest = i%10
nv+=1#augment number of edges
graph.append([(previous_vertext,rest)])#initially graph contains only the first n vertices
#so artifial edges are numbered in ascending order according to discovering moment
i//=10
previous_vertext = nv
try:#add to x's adjacents list previous_vertex with cost i
graph[x].append((previous_vertext,i))
except AttributeError:#Create x's adjacents list with previous_vertex with cost i
graph[x] = [(previous_vertext,i)]
#input:
#line1: n, m number of cities and roads(2<=n<=10^5; n-1<=m<=10^5)
#m lines:
# line i: <xi,yi> edge between vertices xi and yi
def main_method():
n, m = map(int, stdin.readline().split())
global graph
graph = [0]*(n+1)
#graph[i] stores a list of tuples:
#(j,w) meaning i is conected with j via and edge with cost w
global nv
nv = n
#This variable will represent the number of total vertices in the graph,
#since extra vertices will be added
for i in range(1,m+1):
x, y = map(int, stdin.readline().split())
split_edge(x,y,i)#split edge into multiples edges with one digit cost
split_edge(y,x,i)
modified_bfs()
global dist
for i in range(2,n+1):
stdout.write("{}\n".format(dist[i]))
main_method()
``` | instruction | 0 | 48,926 | 1 | 97,852 |
No | output | 1 | 48,926 | 1 | 97,853 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.
<image>
There are n cities and n-1 two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from 1 to n, and the city 1 is the capital of the kingdom. So, the kingdom has a tree structure.
As the queen, Linova plans to choose exactly k cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.
A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).
Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.
In order to be a queen loved by people, Linova wants to choose k cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
Input
The first line contains two integers n and k (2≤ n≤ 2 ⋅ 10^5, 1≤ k< n) — the number of cities and industry cities respectively.
Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is a road connecting city u and city v.
It is guaranteed that from any city, you can reach any other city by the roads.
Output
Print the only line containing a single integer — the maximum possible sum of happinesses of all envoys.
Examples
Input
7 4
1 2
1 3
1 4
3 5
3 6
4 7
Output
7
Input
4 1
1 2
1 3
2 4
Output
2
Input
8 5
7 5
1 7
6 1
3 7
8 3
2 1
4 5
Output
9
Note
<image>
In the first example, Linova can choose cities 2, 5, 6, 7 to develop industry, then the happiness of the envoy from city 2 is 1, the happiness of envoys from cities 5, 6, 7 is 2. The sum of happinesses is 7, and it can be proved to be the maximum one.
<image>
In the second example, choosing cities 3, 4 developing industry can reach a sum of 3, but remember that Linova plans to choose exactly k cities developing industry, then the maximum sum is 2. | instruction | 0 | 48,969 | 1 | 97,938 |
Tags: dfs and similar, dp, greedy, sortings, trees
Correct Solution:
```
from sys import stdin
import sys, threading
def Soln(node, parent, depth, depthArr, treeArr, sizeArr):
depthArr[node] = depth
sizeArr[node] = 1
for child in treeArr[node]:
if child != parent:
sizeArr[node] += Soln(child, node, depth + 1, depthArr, treeArr, sizeArr)
return sizeArr[node]
def main():
n, k = list(map(int, stdin.readline().rstrip().split(" ")))
happinessArr = [0] * n
treeArr = [[] for i in range(n + 1)]
depthArr = [0] * (n + 1)
sizeArr = [0] * (n + 1)
for _ in range(n - 1):
x, y = map(int, input().rstrip().split(" "))
treeArr[x].append(y)
treeArr[y].append(x)
Soln(1, -1, 0, depthArr, treeArr, sizeArr)
for i in range(n):
happinessArr[i] = sizeArr[i + 1] - 1 - depthArr[i + 1]
happinessArr = sorted(happinessArr, reverse=True)
happiness = 0
for i in range(n - k):
happiness += happinessArr[i]
print(happiness)
if __name__ == "__main__":
sys.setrecursionlimit(2 * (10 ** 5) + 1)
threading.stack_size(128000000)
thread = threading.Thread(target=main)
thread.start()
``` | output | 1 | 48,969 | 1 | 97,939 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.
<image>
There are n cities and n-1 two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from 1 to n, and the city 1 is the capital of the kingdom. So, the kingdom has a tree structure.
As the queen, Linova plans to choose exactly k cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.
A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).
Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.
In order to be a queen loved by people, Linova wants to choose k cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
Input
The first line contains two integers n and k (2≤ n≤ 2 ⋅ 10^5, 1≤ k< n) — the number of cities and industry cities respectively.
Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is a road connecting city u and city v.
It is guaranteed that from any city, you can reach any other city by the roads.
Output
Print the only line containing a single integer — the maximum possible sum of happinesses of all envoys.
Examples
Input
7 4
1 2
1 3
1 4
3 5
3 6
4 7
Output
7
Input
4 1
1 2
1 3
2 4
Output
2
Input
8 5
7 5
1 7
6 1
3 7
8 3
2 1
4 5
Output
9
Note
<image>
In the first example, Linova can choose cities 2, 5, 6, 7 to develop industry, then the happiness of the envoy from city 2 is 1, the happiness of envoys from cities 5, 6, 7 is 2. The sum of happinesses is 7, and it can be proved to be the maximum one.
<image>
In the second example, choosing cities 3, 4 developing industry can reach a sum of 3, but remember that Linova plans to choose exactly k cities developing industry, then the maximum sum is 2. | instruction | 0 | 48,970 | 1 | 97,940 |
Tags: dfs and similar, dp, greedy, sortings, trees
Correct Solution:
```
from collections import deque
def process():
q = deque()
q.append(0)
s = []
seen = [0] * n
while len(q) > 0:
node = q.popleft()
s.append(node)
seen[node] = 1
flag = False
for c in connections[node]:
if not seen[c]:
q.append(c)
distance[c] = distance[node] + 1
seen = [0] * n
while len(s) > 0:
node = s.pop()
seen[node] = 1
for c in connections[node]:
if not seen[c]:
children[c] += children[node] + 1
for i in range(n):
scores[i] = distance[i] - children[i]
#print(distance,children,scores)
n, k = list(map(int, input().split()))
connections = [[] for _ in range(n)]
for i in range(n - 1):
u, v = list(map(int, input().split()))
connections[u - 1].append(v - 1)
connections[v - 1].append(u - 1)
scores = [0] * n
distance = [0] * n
children = [0] * n
process()
scores.sort()
# print("distance {}\n children {}\n".format(distance, children))
print(sum(scores[-k:]))
``` | output | 1 | 48,970 | 1 | 97,941 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.
<image>
There are n cities and n-1 two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from 1 to n, and the city 1 is the capital of the kingdom. So, the kingdom has a tree structure.
As the queen, Linova plans to choose exactly k cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.
A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).
Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.
In order to be a queen loved by people, Linova wants to choose k cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
Input
The first line contains two integers n and k (2≤ n≤ 2 ⋅ 10^5, 1≤ k< n) — the number of cities and industry cities respectively.
Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is a road connecting city u and city v.
It is guaranteed that from any city, you can reach any other city by the roads.
Output
Print the only line containing a single integer — the maximum possible sum of happinesses of all envoys.
Examples
Input
7 4
1 2
1 3
1 4
3 5
3 6
4 7
Output
7
Input
4 1
1 2
1 3
2 4
Output
2
Input
8 5
7 5
1 7
6 1
3 7
8 3
2 1
4 5
Output
9
Note
<image>
In the first example, Linova can choose cities 2, 5, 6, 7 to develop industry, then the happiness of the envoy from city 2 is 1, the happiness of envoys from cities 5, 6, 7 is 2. The sum of happinesses is 7, and it can be proved to be the maximum one.
<image>
In the second example, choosing cities 3, 4 developing industry can reach a sum of 3, but remember that Linova plans to choose exactly k cities developing industry, then the maximum sum is 2. | instruction | 0 | 48,971 | 1 | 97,942 |
Tags: dfs and similar, dp, greedy, sortings, trees
Correct Solution:
```
N,K=map(int,input().split())
graph=[[]for i in range(N+1)]
for i in range(N-1):
a,b=map(int,input().split())
graph[a].append(b)
graph[b].append(a)
from collections import deque
d=deque()
e=deque()
visited=[False for _ in range(N+1)]
distance=[-1 for i in range(N+1)]
distance[1]=0
par=[-1 for i in range(N+1)]
visited[1]=True
d.append(1)
while d:
while d:
x=d.popleft()
for node in graph[x]:
if visited[node]==False:
visited[node]=True
distance[node]=distance[x]+1
par[node]=x
e.append(node)
if e:
d=e
e=deque()
node=[]
for i in range(1,N+1):
node.append((i,distance[i]))
node.sort(key=lambda x:-x[1])
cnt=[1 for i in range(N+1)]
for some in node:
node,dis=some
if par[node]>0:
cnt[par[node]]+=cnt[node]
for i in range(N+1):
cnt[i]-=1
P=[]
for i in range(1,N+1):
P.append(cnt[i]-distance[i])
P.sort(reverse=True)
print(sum(P[:N-K]))
``` | output | 1 | 48,971 | 1 | 97,943 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.
<image>
There are n cities and n-1 two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from 1 to n, and the city 1 is the capital of the kingdom. So, the kingdom has a tree structure.
As the queen, Linova plans to choose exactly k cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.
A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).
Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.
In order to be a queen loved by people, Linova wants to choose k cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
Input
The first line contains two integers n and k (2≤ n≤ 2 ⋅ 10^5, 1≤ k< n) — the number of cities and industry cities respectively.
Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is a road connecting city u and city v.
It is guaranteed that from any city, you can reach any other city by the roads.
Output
Print the only line containing a single integer — the maximum possible sum of happinesses of all envoys.
Examples
Input
7 4
1 2
1 3
1 4
3 5
3 6
4 7
Output
7
Input
4 1
1 2
1 3
2 4
Output
2
Input
8 5
7 5
1 7
6 1
3 7
8 3
2 1
4 5
Output
9
Note
<image>
In the first example, Linova can choose cities 2, 5, 6, 7 to develop industry, then the happiness of the envoy from city 2 is 1, the happiness of envoys from cities 5, 6, 7 is 2. The sum of happinesses is 7, and it can be proved to be the maximum one.
<image>
In the second example, choosing cities 3, 4 developing industry can reach a sum of 3, but remember that Linova plans to choose exactly k cities developing industry, then the maximum sum is 2. | instruction | 0 | 48,972 | 1 | 97,944 |
Tags: dfs and similar, dp, greedy, sortings, trees
Correct Solution:
```
import sys
from collections import deque
def bfs_search(adj_list, visited, queue, P, d, bfs):
node = queue.popleft()
if visited[node]:
return
visited[node] = True
for e in adj_list[node]:
if visited[e] == False:
queue.append(e)
d[e] = d[node] + 1
P[e] = node
bfs.append(e)
return
def answer(n, k, u, v):
adj_list = [[] for _ in range(n+1)] #first [] will never fill in.
visited = [False for _ in range(n+1)] #[0] will never change.
for i in range(n-1):
adj_list[v[i]].append(u[i])
adj_list[u[i]].append(v[i])
queue = deque([1])
P = [0 for _ in range(n+1)]
d = [1 for _ in range(n+1)]
bfs = [1]
while len(queue) > 0:
bfs_search(adj_list, visited, queue, P, d, bfs)
SZ = [1 for _ in range(n+1)]
for i in range(n-1, -1, -1):
c_node = bfs[i]
SZ[P[c_node]] += SZ[c_node]
SZmd = []
for i in range(1, n+1):
SZmd.append(SZ[i] - d[i])
SZmd.sort(reverse=True)
summ = sum(SZmd[:(n-k)])
return summ
def main():
n, k = map(int, sys.stdin.readline().split())
u = [0 for _ in range(n-1)]
v = [0 for _ in range(n-1)]
for i in range(n-1):
u[i], v[i] = map(int, sys.stdin.readline().split())
print(answer(n, k, u, v))
return
main()
``` | output | 1 | 48,972 | 1 | 97,945 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.
<image>
There are n cities and n-1 two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from 1 to n, and the city 1 is the capital of the kingdom. So, the kingdom has a tree structure.
As the queen, Linova plans to choose exactly k cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.
A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).
Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.
In order to be a queen loved by people, Linova wants to choose k cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
Input
The first line contains two integers n and k (2≤ n≤ 2 ⋅ 10^5, 1≤ k< n) — the number of cities and industry cities respectively.
Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is a road connecting city u and city v.
It is guaranteed that from any city, you can reach any other city by the roads.
Output
Print the only line containing a single integer — the maximum possible sum of happinesses of all envoys.
Examples
Input
7 4
1 2
1 3
1 4
3 5
3 6
4 7
Output
7
Input
4 1
1 2
1 3
2 4
Output
2
Input
8 5
7 5
1 7
6 1
3 7
8 3
2 1
4 5
Output
9
Note
<image>
In the first example, Linova can choose cities 2, 5, 6, 7 to develop industry, then the happiness of the envoy from city 2 is 1, the happiness of envoys from cities 5, 6, 7 is 2. The sum of happinesses is 7, and it can be proved to be the maximum one.
<image>
In the second example, choosing cities 3, 4 developing industry can reach a sum of 3, but remember that Linova plans to choose exactly k cities developing industry, then the maximum sum is 2. | instruction | 0 | 48,973 | 1 | 97,946 |
Tags: dfs and similar, dp, greedy, sortings, trees
Correct Solution:
```
import sys
from collections import defaultdict,deque
input=sys.stdin.readline
def bfs(node):
depth[node]=1
q=deque([node])
vis[node]=1
arr=[]
while q:
x=q.popleft()
arr.append(x)
for j in edge[x]:
if vis[j]==0:
vis[j]=1
depth[j]=depth[x]+1
child[x].append(j)
q.append(j)
arr.reverse()
return arr
n,k=list(map(int,input().split()))
edge=defaultdict(list)
child=defaultdict(list)
vis=[0]*(n+1)
depth=[0]*(n+1)
for i in range(n-1):
u,v=list(map(int,input().split()))
edge[u].append(v)
edge[v].append(u)
subTreeSize=[1]*(n+1)
arr=bfs(1)
for i in arr:
for j in child[i]:
subTreeSize[i]+=subTreeSize[j]
lis=[]
for i in range(1,n+1):
lis.append(subTreeSize[i]-depth[i])
lis.sort(reverse=True)
ans=0
for i in range(n-k):
ans+=lis[i]
print(ans)
``` | output | 1 | 48,973 | 1 | 97,947 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.
<image>
There are n cities and n-1 two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from 1 to n, and the city 1 is the capital of the kingdom. So, the kingdom has a tree structure.
As the queen, Linova plans to choose exactly k cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.
A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).
Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.
In order to be a queen loved by people, Linova wants to choose k cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
Input
The first line contains two integers n and k (2≤ n≤ 2 ⋅ 10^5, 1≤ k< n) — the number of cities and industry cities respectively.
Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is a road connecting city u and city v.
It is guaranteed that from any city, you can reach any other city by the roads.
Output
Print the only line containing a single integer — the maximum possible sum of happinesses of all envoys.
Examples
Input
7 4
1 2
1 3
1 4
3 5
3 6
4 7
Output
7
Input
4 1
1 2
1 3
2 4
Output
2
Input
8 5
7 5
1 7
6 1
3 7
8 3
2 1
4 5
Output
9
Note
<image>
In the first example, Linova can choose cities 2, 5, 6, 7 to develop industry, then the happiness of the envoy from city 2 is 1, the happiness of envoys from cities 5, 6, 7 is 2. The sum of happinesses is 7, and it can be proved to be the maximum one.
<image>
In the second example, choosing cities 3, 4 developing industry can reach a sum of 3, but remember that Linova plans to choose exactly k cities developing industry, then the maximum sum is 2. | instruction | 0 | 48,974 | 1 | 97,948 |
Tags: dfs and similar, dp, greedy, sortings, trees
Correct Solution:
```
import heapq
import io,os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n, k = map(int,input().split())
neigh = [[] for i in range(n)]
for i in range(n-1):
u,v = map(int,input().split())
neigh[u-1].append(v-1)
neigh[v-1].append(u-1)
visited = [0 for i in range(n)]
visited[0] = 1
depth = [1]*n
subtree = [0]*n
seq = [0]
stack = [[0,1]]
visited = [0]*n
visited[0] = 1
while stack:
temp = stack.pop()
[index,d] = temp
depth[index] = d
for ele in neigh[index]:
if visited[ele]==1: continue
visited[ele] = 1
stack.append([ele,d+1])
seq.append(ele)
heap = []
ans = 0
seq.reverse()
for index in seq:
subtree[index] = 1
for ele in neigh[index]:
subtree[index] += subtree[ele]
heapq.heappush(heap,depth[index]-subtree[index])
ans += depth[index]-subtree[index]
if len(heap)>k:
ans -= heapq.heappop(heap)
#print(depth)
#print(subtree)
print(ans)
``` | output | 1 | 48,974 | 1 | 97,949 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.
<image>
There are n cities and n-1 two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from 1 to n, and the city 1 is the capital of the kingdom. So, the kingdom has a tree structure.
As the queen, Linova plans to choose exactly k cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.
A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).
Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.
In order to be a queen loved by people, Linova wants to choose k cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
Input
The first line contains two integers n and k (2≤ n≤ 2 ⋅ 10^5, 1≤ k< n) — the number of cities and industry cities respectively.
Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is a road connecting city u and city v.
It is guaranteed that from any city, you can reach any other city by the roads.
Output
Print the only line containing a single integer — the maximum possible sum of happinesses of all envoys.
Examples
Input
7 4
1 2
1 3
1 4
3 5
3 6
4 7
Output
7
Input
4 1
1 2
1 3
2 4
Output
2
Input
8 5
7 5
1 7
6 1
3 7
8 3
2 1
4 5
Output
9
Note
<image>
In the first example, Linova can choose cities 2, 5, 6, 7 to develop industry, then the happiness of the envoy from city 2 is 1, the happiness of envoys from cities 5, 6, 7 is 2. The sum of happinesses is 7, and it can be proved to be the maximum one.
<image>
In the second example, choosing cities 3, 4 developing industry can reach a sum of 3, but remember that Linova plans to choose exactly k cities developing industry, then the maximum sum is 2. | instruction | 0 | 48,975 | 1 | 97,950 |
Tags: dfs and similar, dp, greedy, sortings, trees
Correct Solution:
```
from collections import defaultdict, deque
import os
def get_neighbors(edges):
neighbors = defaultdict(set, {})
for v1, v2 in edges:
if v1 != v2:
neighbors[v1].add(v2)
neighbors[v2].add(v1)
return dict(neighbors)
def solve(edges, n, k):
if k == 0:
return 0
adj = get_neighbors(edges)
counts = [1] * (n + 1)
depths = [0] * (n + 1)
depths[1] = 0
stack = [(1, 0, 0)]
while stack:
node, parent, depth = stack[-1]
if adj[node]:
n1 = adj[node].pop()
adj[n1].remove(node)
stack.append((n1, node, depth + 1))
else:
stack.pop()
counts[parent] += counts[node]
depths[node] = depth
return sum(
sorted([s - d - 1 for s, d in zip(counts, depths)][1:], reverse=True)[: (n - k)]
)
def pp(input):
n, k = map(int, input().split())
edges = [
tuple(map(lambda x: x, map(int, input().split(" ")))) for _ in range(n - 1)
]
print(solve(edges, n, k))
if "paalto" in os.getcwd():
from string_source import string_source
pp(
string_source(
"""7 4
1 2
1 3
1 4
3 5
3 6
4 7"""
)
)
pp(
string_source(
"""4 1
1 2
1 3
2 4"""
)
)
pp(
string_source(
"""8 5
7 5
1 7
6 1
3 7
8 3
2 1
4 5"""
)
)
else:
pp(input)
``` | output | 1 | 48,975 | 1 | 97,951 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.
<image>
There are n cities and n-1 two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from 1 to n, and the city 1 is the capital of the kingdom. So, the kingdom has a tree structure.
As the queen, Linova plans to choose exactly k cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.
A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).
Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.
In order to be a queen loved by people, Linova wants to choose k cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
Input
The first line contains two integers n and k (2≤ n≤ 2 ⋅ 10^5, 1≤ k< n) — the number of cities and industry cities respectively.
Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is a road connecting city u and city v.
It is guaranteed that from any city, you can reach any other city by the roads.
Output
Print the only line containing a single integer — the maximum possible sum of happinesses of all envoys.
Examples
Input
7 4
1 2
1 3
1 4
3 5
3 6
4 7
Output
7
Input
4 1
1 2
1 3
2 4
Output
2
Input
8 5
7 5
1 7
6 1
3 7
8 3
2 1
4 5
Output
9
Note
<image>
In the first example, Linova can choose cities 2, 5, 6, 7 to develop industry, then the happiness of the envoy from city 2 is 1, the happiness of envoys from cities 5, 6, 7 is 2. The sum of happinesses is 7, and it can be proved to be the maximum one.
<image>
In the second example, choosing cities 3, 4 developing industry can reach a sum of 3, but remember that Linova plans to choose exactly k cities developing industry, then the maximum sum is 2. | instruction | 0 | 48,976 | 1 | 97,952 |
Tags: dfs and similar, dp, greedy, sortings, trees
Correct Solution:
```
import sys
input = sys.stdin.readline
n, k = map(int, input().split())
# n, k = 2 * 10**5, 1
g = [[] for _ in range(n)]
for i in range(n - 1):
u, v = map(lambda x: int(x) - 1, input().split())
# u, v = i, i + 1
g[u].append(v)
g[v].append(u)
lvl = {}
stack = [(0, 0)]
children = [[] for _ in range(n)]
while stack:
node, l = stack.pop()
lvl[node] = l
for ne in g[node]:
if ne not in lvl:
stack.append((ne, l + 1))
children[node].append(ne)
subtree = [0] * n
for i in sorted(range(n), key=lambda i: -lvl[i]):
subtree[i] += 1
for ch in children[i]:
subtree[i] += subtree[ch]
# print(lvl)
# print(subtree)
print(sum(sorted([lvl[i] - subtree[i] + 1 for i in range(n)], reverse=True)[:k]))
``` | output | 1 | 48,976 | 1 | 97,953 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.
<image>
There are n cities and n-1 two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from 1 to n, and the city 1 is the capital of the kingdom. So, the kingdom has a tree structure.
As the queen, Linova plans to choose exactly k cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.
A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).
Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.
In order to be a queen loved by people, Linova wants to choose k cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
Input
The first line contains two integers n and k (2≤ n≤ 2 ⋅ 10^5, 1≤ k< n) — the number of cities and industry cities respectively.
Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is a road connecting city u and city v.
It is guaranteed that from any city, you can reach any other city by the roads.
Output
Print the only line containing a single integer — the maximum possible sum of happinesses of all envoys.
Examples
Input
7 4
1 2
1 3
1 4
3 5
3 6
4 7
Output
7
Input
4 1
1 2
1 3
2 4
Output
2
Input
8 5
7 5
1 7
6 1
3 7
8 3
2 1
4 5
Output
9
Note
<image>
In the first example, Linova can choose cities 2, 5, 6, 7 to develop industry, then the happiness of the envoy from city 2 is 1, the happiness of envoys from cities 5, 6, 7 is 2. The sum of happinesses is 7, and it can be proved to be the maximum one.
<image>
In the second example, choosing cities 3, 4 developing industry can reach a sum of 3, but remember that Linova plans to choose exactly k cities developing industry, then the maximum sum is 2.
Submitted Solution:
```
from heapq import *
from sys import stdin
class Node:
def __init__(self,val):
self.val=val
self.forw=set()
self.cou=0
self.depth = 0
def __lt__(self, node):
return self.cou-self.depth > node.cou-node.depth
def __str__(self):
return f'{self.val} {self.forw} {self.cou} {self.depth}'
n,k=map(int,stdin.readline().split())
lst1=[Node(i) for i in range(1,n+1)]
lst = [Node(i) for i in range(1,n+1)]
for _ in range(n-1):
u,v=map(int,stdin.readline().split())
lst1[u-1].forw.add(v)
lst1[v-1].forw.add(u)
lst[u-1].forw.add(v)
lst[v-1].forw.add(u)
to=n-k
arr = [1]
while len(arr):
fl = 0
for i in lst[arr[-1]-1].forw:
lst[i-1].forw.remove(arr[-1])
arr.append(i)
fl = 1
break
if fl:
lst[arr[-2]-1].forw.remove(i)
if not fl:
lst[arr[-1]-1].depth = len(arr)-1
k=lst[arr.pop()-1].cou+1
if len(arr):lst[arr[-1]-1].cou+=k
l = [lst[0]]
heapify(l)
ans = 0
se = set()
while to:
y = heappop(l)
se.add(y.val)
ans += y.cou-y.depth
for t in lst1[y.val-1].forw:
if t not in se:
heappush(l,lst[t-1])
to -= 1
print(ans)
``` | instruction | 0 | 48,977 | 1 | 97,954 |
Yes | output | 1 | 48,977 | 1 | 97,955 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.
<image>
There are n cities and n-1 two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from 1 to n, and the city 1 is the capital of the kingdom. So, the kingdom has a tree structure.
As the queen, Linova plans to choose exactly k cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.
A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).
Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.
In order to be a queen loved by people, Linova wants to choose k cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
Input
The first line contains two integers n and k (2≤ n≤ 2 ⋅ 10^5, 1≤ k< n) — the number of cities and industry cities respectively.
Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is a road connecting city u and city v.
It is guaranteed that from any city, you can reach any other city by the roads.
Output
Print the only line containing a single integer — the maximum possible sum of happinesses of all envoys.
Examples
Input
7 4
1 2
1 3
1 4
3 5
3 6
4 7
Output
7
Input
4 1
1 2
1 3
2 4
Output
2
Input
8 5
7 5
1 7
6 1
3 7
8 3
2 1
4 5
Output
9
Note
<image>
In the first example, Linova can choose cities 2, 5, 6, 7 to develop industry, then the happiness of the envoy from city 2 is 1, the happiness of envoys from cities 5, 6, 7 is 2. The sum of happinesses is 7, and it can be proved to be the maximum one.
<image>
In the second example, choosing cities 3, 4 developing industry can reach a sum of 3, but remember that Linova plans to choose exactly k cities developing industry, then the maximum sum is 2.
Submitted Solution:
```
import sys
readline = sys.stdin.readline
class Segtree:
def __init__(self, A, intv, initialize = True):
self.N = len(A)
self.N0 = 2**(self.N-1).bit_length()
self.intv = intv
if initialize:
self.data = [intv]*self.N0 + A + [intv]*(self.N0 - self.N)
for i in range(self.N0-1, 0, -1):
self.data[i] = self.segf(self.data[2*i], self.data[2*i+1])
else:
self.data = [intv]*(2*self.N0)
def segf(self, x, y):
if table[x] > table[y]:
return x
else:
return y
def update(self, k):
k += self.N0
while k > 0 :
k = k >> 1
self.data[k] = self.segf(self.data[2*k], self.data[2*k+1])
def query(self, l, r):
L, R = l+self.N0, r+self.N0
s = self.intv
while L < R:
if R & 1:
R -= 1
s = self.segf(s, self.data[R])
if L & 1:
s = self.segf(s, self.data[L])
L += 1
L >>= 1
R >>= 1
return s
def binsearch(self, l, r, check, reverse = False):
L, R = l+self.N0, r+self.N0
SL, SR = [], []
while L < R:
if R & 1:
R -= 1
SR.append(R)
if L & 1:
SL.append(L)
L += 1
L >>= 1
R >>= 1
if reverse:
for idx in (SR + SL[::-1]):
if check(self.data[idx]):
break
else:
return -1
while idx < self.N0:
if check(self.data[2*idx+1]):
idx = 2*idx + 1
else:
idx = 2*idx
return idx - self.N0
else:
for idx in (SL + SR[::-1]):
if check(self.data[idx]):
break
else:
return -1
while idx < self.N0:
if check(self.data[2*idx]):
idx = 2*idx
else:
idx = 2*idx + 1
return idx - self.N0
def parorder(Edge, p):
N = len(Edge)
par = [0]*N
par[p] = -1
stack = [p]
order = []
visited = set([p])
ast = stack.append
apo = order.append
while stack:
vn = stack.pop()
apo(vn)
for vf in Edge[vn]:
if vf in visited:
continue
visited.add(vf)
par[vf] = vn
ast(vf)
return par, order
def getcld(p):
res = [[] for _ in range(len(p))]
for i, v in enumerate(p[1:], 1):
res[v].append(i)
return res
INF = 10**9+7
N, K = map(int, readline().split())
Edge = [[] for _ in range(N)]
Dim = [0]*N
for _ in range(N-1):
a, b = map(int, readline().split())
a -= 1
b -= 1
Edge[a].append(b)
Edge[b].append(a)
Dim[a] += 1
Dim[b] += 1
Dim[0] += 1
P, L = parorder(Edge, 0)
dist = [0]*N
for l in L[1:]:
p = P[l]
dist[l] = 1 + dist[p]
table = [-INF]*(N+1)
for i in range(1, N):
if len(Edge[i]) == 1:
table[i] = dist[i]
debt = [0]*N
T = Segtree(list(range(N)), N, initialize = True)
ans = 0
N0 = T.N0
for _ in range(K):
idx = T.query(0, N0)
ans += table[idx]
table[idx] = -INF
T.update(idx)
if idx == 0:
break
p = P[idx]
Dim[p] -= 1
debt[p] += -1 + debt[idx]
if Dim[p] == 1:
table[p] = dist[p] + debt[p]
T.update(p)
print(ans)
``` | instruction | 0 | 48,978 | 1 | 97,956 |
Yes | output | 1 | 48,978 | 1 | 97,957 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.
<image>
There are n cities and n-1 two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from 1 to n, and the city 1 is the capital of the kingdom. So, the kingdom has a tree structure.
As the queen, Linova plans to choose exactly k cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.
A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).
Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.
In order to be a queen loved by people, Linova wants to choose k cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
Input
The first line contains two integers n and k (2≤ n≤ 2 ⋅ 10^5, 1≤ k< n) — the number of cities and industry cities respectively.
Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is a road connecting city u and city v.
It is guaranteed that from any city, you can reach any other city by the roads.
Output
Print the only line containing a single integer — the maximum possible sum of happinesses of all envoys.
Examples
Input
7 4
1 2
1 3
1 4
3 5
3 6
4 7
Output
7
Input
4 1
1 2
1 3
2 4
Output
2
Input
8 5
7 5
1 7
6 1
3 7
8 3
2 1
4 5
Output
9
Note
<image>
In the first example, Linova can choose cities 2, 5, 6, 7 to develop industry, then the happiness of the envoy from city 2 is 1, the happiness of envoys from cities 5, 6, 7 is 2. The sum of happinesses is 7, and it can be proved to be the maximum one.
<image>
In the second example, choosing cities 3, 4 developing industry can reach a sum of 3, but remember that Linova plans to choose exactly k cities developing industry, then the maximum sum is 2.
Submitted Solution:
```
import sys
import threading
from collections import defaultdict
n,k=list(map(int,input().split()))
adj=defaultdict(list)
for _ in range(n-1):
a,b=list(map(int,input().split()))
adj[a].append(b)
adj[b].append(a)
li=[]
def fun(node,par,ht):
size=1
for ch in adj[node]:
if ch != par:
size+=fun(ch,node,ht+1)
li.append(ht-size)
return size
def main():
fun(1,-1,1)
li.sort(reverse=True)
print(sum(li[:k]))
if __name__=="__main__":
sys.setrecursionlimit(10**6)
threading.stack_size(10**8)
t = threading.Thread(target=main)
t.start()
t.join()
``` | instruction | 0 | 48,979 | 1 | 97,958 |
Yes | output | 1 | 48,979 | 1 | 97,959 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.
<image>
There are n cities and n-1 two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from 1 to n, and the city 1 is the capital of the kingdom. So, the kingdom has a tree structure.
As the queen, Linova plans to choose exactly k cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.
A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).
Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.
In order to be a queen loved by people, Linova wants to choose k cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
Input
The first line contains two integers n and k (2≤ n≤ 2 ⋅ 10^5, 1≤ k< n) — the number of cities and industry cities respectively.
Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is a road connecting city u and city v.
It is guaranteed that from any city, you can reach any other city by the roads.
Output
Print the only line containing a single integer — the maximum possible sum of happinesses of all envoys.
Examples
Input
7 4
1 2
1 3
1 4
3 5
3 6
4 7
Output
7
Input
4 1
1 2
1 3
2 4
Output
2
Input
8 5
7 5
1 7
6 1
3 7
8 3
2 1
4 5
Output
9
Note
<image>
In the first example, Linova can choose cities 2, 5, 6, 7 to develop industry, then the happiness of the envoy from city 2 is 1, the happiness of envoys from cities 5, 6, 7 is 2. The sum of happinesses is 7, and it can be proved to be the maximum one.
<image>
In the second example, choosing cities 3, 4 developing industry can reach a sum of 3, but remember that Linova plans to choose exactly k cities developing industry, then the maximum sum is 2.
Submitted Solution:
```
import sys
import threading
sys.setrecursionlimit(10**6)
threading.stack_size(10**8)
class node:
def __init__(self):
self.dist = 0
self.count = 0
visited = []
edges = []
tree = []
def dfs(pos):
global visited
global edges
global tree
cnt = 0
visited[pos] = True
if edges[pos]:
for child in edges[pos]:
if not visited[child]:
tree[child][0] = tree[pos][0] + 1
cnt += dfs(child)
tree[pos][1] = cnt
return cnt + 1
def main():
n, k = list(map(int, input().split()))
global visited
global edges
global tree
visited = [False] * (n+1)
edges = [[] for i in range(n+1)]
tree = [[0,0] for i in range(n+1)]
for i in range(n - 1):
a, b = list(map(int, input().split()))
edges[a].append(b)
edges[b].append(a)
dfs(1)
ans = sum(sorted([tree[i][0] - tree[i][1] for i in range(1, n + 1)], reverse=True)[:k])
print(ans)
t = threading.Thread(target =main)
t.start()
t.join()
``` | instruction | 0 | 48,980 | 1 | 97,960 |
Yes | output | 1 | 48,980 | 1 | 97,961 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.
<image>
There are n cities and n-1 two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from 1 to n, and the city 1 is the capital of the kingdom. So, the kingdom has a tree structure.
As the queen, Linova plans to choose exactly k cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.
A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).
Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.
In order to be a queen loved by people, Linova wants to choose k cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
Input
The first line contains two integers n and k (2≤ n≤ 2 ⋅ 10^5, 1≤ k< n) — the number of cities and industry cities respectively.
Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is a road connecting city u and city v.
It is guaranteed that from any city, you can reach any other city by the roads.
Output
Print the only line containing a single integer — the maximum possible sum of happinesses of all envoys.
Examples
Input
7 4
1 2
1 3
1 4
3 5
3 6
4 7
Output
7
Input
4 1
1 2
1 3
2 4
Output
2
Input
8 5
7 5
1 7
6 1
3 7
8 3
2 1
4 5
Output
9
Note
<image>
In the first example, Linova can choose cities 2, 5, 6, 7 to develop industry, then the happiness of the envoy from city 2 is 1, the happiness of envoys from cities 5, 6, 7 is 2. The sum of happinesses is 7, and it can be proved to be the maximum one.
<image>
In the second example, choosing cities 3, 4 developing industry can reach a sum of 3, but remember that Linova plans to choose exactly k cities developing industry, then the maximum sum is 2.
Submitted Solution:
```
from sys import stdin, stdout
import heapq
def main():
n,k = list(map(int, stdin.readline().split()))
tree = [[] for _ in range(n+1)]
visited = [0] * (n+1)
lev = []
p = [0] * (n+1)
minus = [0] * (n+1)
for _ in range(n-1):
a,b = list(map(int, stdin.readline().split()))
tree[a].append(b)
tree[b].append(a)
stack = [1]
visited[1] = 1
level = 1
while stack:
temp = []
for x in stack:
for y in tree[x]:
if visited[y] == 0:
temp.append(y)
visited[y] = 1
p[y] = x
heapq.heappush(lev, (-level + len(tree[y])-1, y))
stack = temp
level += 1
cnt = 0
res = 0
while cnt < k:
l,x = heapq.heappop(lev)
cnt += 1
res -= l
stdout.write(str(res))
main()
``` | instruction | 0 | 48,981 | 1 | 97,962 |
No | output | 1 | 48,981 | 1 | 97,963 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.
<image>
There are n cities and n-1 two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from 1 to n, and the city 1 is the capital of the kingdom. So, the kingdom has a tree structure.
As the queen, Linova plans to choose exactly k cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.
A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).
Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.
In order to be a queen loved by people, Linova wants to choose k cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
Input
The first line contains two integers n and k (2≤ n≤ 2 ⋅ 10^5, 1≤ k< n) — the number of cities and industry cities respectively.
Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is a road connecting city u and city v.
It is guaranteed that from any city, you can reach any other city by the roads.
Output
Print the only line containing a single integer — the maximum possible sum of happinesses of all envoys.
Examples
Input
7 4
1 2
1 3
1 4
3 5
3 6
4 7
Output
7
Input
4 1
1 2
1 3
2 4
Output
2
Input
8 5
7 5
1 7
6 1
3 7
8 3
2 1
4 5
Output
9
Note
<image>
In the first example, Linova can choose cities 2, 5, 6, 7 to develop industry, then the happiness of the envoy from city 2 is 1, the happiness of envoys from cities 5, 6, 7 is 2. The sum of happinesses is 7, and it can be proved to be the maximum one.
<image>
In the second example, choosing cities 3, 4 developing industry can reach a sum of 3, but remember that Linova plans to choose exactly k cities developing industry, then the maximum sum is 2.
Submitted Solution:
```
import sys
input = lambda: sys.stdin.readline().rstrip()
from collections import deque
# mod = 10 ** 9 + 7
N, K = map(int, input().split())
X = [[] for i in range(N)]
for i in range(N-1):
x, y = map(int, input().split())
X[x-1].append(y-1)
X[y-1].append(x-1)
P = [-1] * N
Q = deque([0])
R = []
while Q:
i = deque.popleft(Q)
R.append(i)
for a in X[i]:
if a != P[i]:
P[a] = i
X[a].remove(i)
deque.append(Q, a)
SIZE = [1] * N
for i in R[1:][::-1]:
SIZE[P[i]] += SIZE[i]
A = [0] * N
DE = [0] * N
for i in R[1:]:
DE[i] = DE[P[i]] + 1
for i in R:
A[i] = (SIZE[i] - DE[i] << 18) + i
# print("SIZE =", SIZE)
# print("DE =", DE)
# print("A =", A)
A = sorted(A)
T = [0] * N
m = (1 << 17) - 1
for i in A[:K]:
T[i & m] = 1
# print("T =", T)
ans = 0
B = [0] * N
for i in R[::-1]:
if T[i]:
B[P[i]] += B[i] + 1
else:
B[P[i]] += B[i]
ans += B[i]
print(ans)
``` | instruction | 0 | 48,982 | 1 | 97,964 |
No | output | 1 | 48,982 | 1 | 97,965 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.
<image>
There are n cities and n-1 two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from 1 to n, and the city 1 is the capital of the kingdom. So, the kingdom has a tree structure.
As the queen, Linova plans to choose exactly k cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.
A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).
Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.
In order to be a queen loved by people, Linova wants to choose k cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
Input
The first line contains two integers n and k (2≤ n≤ 2 ⋅ 10^5, 1≤ k< n) — the number of cities and industry cities respectively.
Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is a road connecting city u and city v.
It is guaranteed that from any city, you can reach any other city by the roads.
Output
Print the only line containing a single integer — the maximum possible sum of happinesses of all envoys.
Examples
Input
7 4
1 2
1 3
1 4
3 5
3 6
4 7
Output
7
Input
4 1
1 2
1 3
2 4
Output
2
Input
8 5
7 5
1 7
6 1
3 7
8 3
2 1
4 5
Output
9
Note
<image>
In the first example, Linova can choose cities 2, 5, 6, 7 to develop industry, then the happiness of the envoy from city 2 is 1, the happiness of envoys from cities 5, 6, 7 is 2. The sum of happinesses is 7, and it can be proved to be the maximum one.
<image>
In the second example, choosing cities 3, 4 developing industry can reach a sum of 3, but remember that Linova plans to choose exactly k cities developing industry, then the maximum sum is 2.
Submitted Solution:
```
from heapq import *
class Node:
def __init__(self,val):
self.val=val
self.forw=[]
self.cou=0
self.depth = 0
def __lt__(self, node):
return self.cou > node.cou
def __str__(self):
return f'{self.val} {self.forw} {self.cou} {self.depth}'
def dfs(x,lst,visited,depth):
lst[x-1].cou=0
for j in lst[x-1].forw:
if j not in visited:
visited.add(j)
lst[j-1].depth = depth + 1
lst[x-1].cou+=dfs(j,lst,visited,depth+1)+1
return lst[x-1].cou
n,k=map(int,input().split())
lst=[Node(i) for i in range(1,n+1)]
for _ in range(n-1):
u,v=map(int,input().split())
lst[u-1].forw.append(v)
lst[v-1].forw.append(u)
to=n-k
visited=set([1])
dfs(1,lst,visited,0)
l = [lst[0]]
heapify(l)
ans = 0
se = set()
while to:
y = heappop(l)
se.add(y.val)
ans += y.cou-y.depth
for t in y.forw:
if t not in se:
heappush(l,lst[t-1])
to -= 1
print(ans)
``` | instruction | 0 | 48,983 | 1 | 97,966 |
No | output | 1 | 48,983 | 1 | 97,967 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.
<image>
There are n cities and n-1 two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from 1 to n, and the city 1 is the capital of the kingdom. So, the kingdom has a tree structure.
As the queen, Linova plans to choose exactly k cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.
A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).
Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.
In order to be a queen loved by people, Linova wants to choose k cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
Input
The first line contains two integers n and k (2≤ n≤ 2 ⋅ 10^5, 1≤ k< n) — the number of cities and industry cities respectively.
Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is a road connecting city u and city v.
It is guaranteed that from any city, you can reach any other city by the roads.
Output
Print the only line containing a single integer — the maximum possible sum of happinesses of all envoys.
Examples
Input
7 4
1 2
1 3
1 4
3 5
3 6
4 7
Output
7
Input
4 1
1 2
1 3
2 4
Output
2
Input
8 5
7 5
1 7
6 1
3 7
8 3
2 1
4 5
Output
9
Note
<image>
In the first example, Linova can choose cities 2, 5, 6, 7 to develop industry, then the happiness of the envoy from city 2 is 1, the happiness of envoys from cities 5, 6, 7 is 2. The sum of happinesses is 7, and it can be proved to be the maximum one.
<image>
In the second example, choosing cities 3, 4 developing industry can reach a sum of 3, but remember that Linova plans to choose exactly k cities developing industry, then the maximum sum is 2.
Submitted Solution:
```
from sys import stdin, stdout
def main():
n,k = list(map(int, stdin.readline().split()))
tree = [[] for _ in range(n+1)]
visited = [0] * (n+1)
indust = [0] * (n+1)
for _ in range(n-1):
a,b = list(map(int, stdin.readline().split()))
tree[a].append(b)
tree[b].append(a)
stack = [1]
visited[1] = 1
level = 0
cnt = 0
res = 0
while stack:
temp = []
t2 = []
for x in stack:
t2.append((x, len(tree[x])))
t2.sort(key=lambda x: x[1], reverse = True)
for x,l in t2:
cnt += 1
if cnt > n - k:
res += level - indust[x]
indust[x] = indust[x] + 1
for y in tree[x]:
if visited[y] == 0:
temp.append(y)
visited[y] = 1
indust[y] = indust[x]
stack = temp
level += 1
stdout.write(str(res))
main()
``` | instruction | 0 | 48,984 | 1 | 97,968 |
No | output | 1 | 48,984 | 1 | 97,969 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The pandemic is upon us, and the world is in shortage of the most important resource: toilet paper. As one of the best prepared nations for this crisis, BubbleLand promised to help all other world nations with this valuable resource. To do that, the country will send airplanes to other countries carrying toilet paper.
In BubbleLand, there are N toilet paper factories, and N airports. Because of how much it takes to build a road, and of course legal issues, every factory must send paper to only one airport, and every airport can only take toilet paper from one factory.
Also, a road can't be built between all airport-factory pairs, again because of legal issues. Every possible road has number d given, number of days it takes to build that road.
Your job is to choose N factory-airport pairs, such that if the country starts building all roads at the same time, it takes the least amount of days to complete them.
Input
The first line contains two integers N (1 ≤ N ≤ 10^4) - number of airports/factories, and M (1 ≤ M ≤ 10^5) - number of available pairs to build a road between.
On next M lines, there are three integers u, v (1 ≤ u,v ≤ N), d (1 ≤ d ≤ 10^9) - meaning that you can build a road between airport u and factory v for d days.
Output
If there are no solutions, output -1. If there exists a solution, output the minimal number of days to complete all roads, equal to maximal d among all chosen roads.
Example
Input
3 5
1 2 1
2 3 2
3 3 3
2 1 4
2 2 5
Output
4 | instruction | 0 | 49,019 | 1 | 98,038 |
Tags: binary search, flows, graph matchings, graphs
Correct Solution:
```
def hopcroft_karp(graph, n, m):
"""
Maximum bipartite matching using Hopcroft-Karp algorithm, running in O(|E| sqrt(|V|))
"""
assert (n == len(graph))
match1 = [-1] * n
match2 = [-1] * m
# Find a greedy match for possible speed up
for node in range(n):
for nei in graph[node]:
if match2[nei] == -1:
match1[node] = nei
match2[nei] = node
break
while 1:
bfs = [node for node in range(n) if match1[node] == -1]
depth = [-1] * n
for node in bfs:
depth[node] = 0
for node in bfs:
for nei in graph[node]:
next_node = match2[nei]
if next_node == -1:
break
if depth[next_node] == -1:
depth[next_node] = depth[node] + 1
bfs.append(next_node)
else:
continue
break
else:
break
pointer = [len(c) for c in graph]
dfs = [node for node in range(n) if depth[node] == 0]
while dfs:
node = dfs[-1]
while pointer[node]:
pointer[node] -= 1
nei = graph[node][pointer[node]]
next_node = match2[nei]
if next_node == -1:
# Augmenting path found
while nei != -1:
node = dfs.pop()
match2[nei], match1[node], nei = node, nei, match1[node]
break
elif depth[node] + 1 == depth[next_node]:
dfs.append(next_node)
break
else:
dfs.pop()
return match1, match2
def getMatchCounts(roads,days,n):
adj=[[] for _ in range(n)]
for u,v,d in roads:
if d<=days:
adj[u].append(v)
matchCounts=n-hopcroft_karp(adj,n,n)[0].count(-1)
return matchCounts
def main():
n,m=readIntArr()
roads=[]
for _ in range(m):
u,v,d=readIntArr()
u-=1
v-=1
roads.append([u,v,d])
if getMatchCounts(roads,1e9+1,n)<n:
print(-1)
else:
days=0
b=1000000000
while b>0:
while getMatchCounts(roads,days+b,n)<n:
days+=b
b//=2
days+=1
print(days)
return
import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
# input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
# def readFloatArr():
# return [float(x) for x in input().split()]
def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m])
dv=defaultValFactory;da=dimensionArr
if len(da)==1:return [dv() for _ in range(da[0])]
else:return [makeArr(dv,da[1:]) for _ in range(da[0])]
def queryInteractive(i,j):
print('? {} {}'.format(i,j))
sys.stdout.flush()
return int(input())
def answerInteractive(ans):
print('! {}'.format(' '.join([str(x) for x in ans])))
sys.stdout.flush()
inf=float('inf')
MOD=10**9+7
# MOD=998244353
for _abc in range(1):
main()
``` | output | 1 | 49,019 | 1 | 98,039 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The pandemic is upon us, and the world is in shortage of the most important resource: toilet paper. As one of the best prepared nations for this crisis, BubbleLand promised to help all other world nations with this valuable resource. To do that, the country will send airplanes to other countries carrying toilet paper.
In BubbleLand, there are N toilet paper factories, and N airports. Because of how much it takes to build a road, and of course legal issues, every factory must send paper to only one airport, and every airport can only take toilet paper from one factory.
Also, a road can't be built between all airport-factory pairs, again because of legal issues. Every possible road has number d given, number of days it takes to build that road.
Your job is to choose N factory-airport pairs, such that if the country starts building all roads at the same time, it takes the least amount of days to complete them.
Input
The first line contains two integers N (1 ≤ N ≤ 10^4) - number of airports/factories, and M (1 ≤ M ≤ 10^5) - number of available pairs to build a road between.
On next M lines, there are three integers u, v (1 ≤ u,v ≤ N), d (1 ≤ d ≤ 10^9) - meaning that you can build a road between airport u and factory v for d days.
Output
If there are no solutions, output -1. If there exists a solution, output the minimal number of days to complete all roads, equal to maximal d among all chosen roads.
Example
Input
3 5
1 2 1
2 3 2
3 3 3
2 1 4
2 2 5
Output
4 | instruction | 0 | 49,020 | 1 | 98,040 |
Tags: binary search, flows, graph matchings, graphs
Correct Solution:
```
from sys import stdin, stdout
from collections import deque
import sys
graph = []
n = 0
current_graph = []
pair_f = []
pair_a = []
dist = []
def dfs(s):
global pair_f
global pair_a
global dist
if s != 0:
for a in current_graph[s]:
if dist[pair_a[a]] == (dist[s] + 1):
if dfs(pair_a[a]):
pair_a[a] = s
pair_f[s] = a
return True
dist[s] = 10 ** 4 + 1
return False
return True
def bfs():
global dist
q = deque()
inf = 10 ** 4 + 1
for f in range(1, n + 1):
# visit all factories that aren't still included in any path
if pair_f[f] == 0:
dist[f] = 0
q.append(f)
else:
dist[f] = inf
dist[0] = inf # inf, 0 is goin to be our nill vertex
while q:
f = q.popleft()
if (
dist[f] < dist[0]
): # solo se analizan caminos de tamanno k donde k es el nivel donde primero se da con nill
for a in current_graph[f]:
# looking for path that alternate between not taken and taken roads
if (
dist[pair_a[a]] == inf
): # the aerports already visited were marked as inf
dist[pair_a[a]] = dist[f] + 1
q.append(pair_a[a])
return dist[0] != inf
def HopcroftKarp():
global pair_f
global pair_a
global dist
match = 0
pair_f = [0] * (n + 1)
pair_a = [0] * (n + 1)
dist = [-1] * (n + 1)
while bfs():
for f in range(1, n + 1):
if pair_f[f] == 0:
if dfs(f):
match += 1
return match
def valuable_paper(min_d, max_d):
global current_graph
last_md = 10 ** 9 + 1
l = min_d
r = max_d
m = 0
while l <= r:
m = (l + r) // 2
current_graph = [[] for i in range(n + 1)]
for edge in graph:
if edge[2] <= m:
current_graph[edge[0]].append(edge[1])
current_graph[0] = [0]
matchings = HopcroftKarp()
if matchings == n:
last_md = m
r = m - 1
else:
l = m + 1
if last_md == (10 ** 9 + 1):
return -1
else:
return last_md
# input:
# line1: n, m number of airports/factories and roads available(2<=n<=10^4; n-1<=m<=10^5)
# m lines:
# line i: <v,v,d> is possible to build a road between vertices airpot u and factory v in d days
def main_method():
global graph
global n
n, m = map(int, stdin.readline().split())
graph = []
for _ in range(m):
u, v, d = map(int, stdin.readline().split())
graph.append((u, v, d))
min_d = min(graph, key=lambda e: e[2])[2]
max_d = max(graph, key=lambda e: e[2])[2]
sol = valuable_paper(min_d, max_d)
stdout.write("{}\n".format(sol))
main_method()
``` | output | 1 | 49,020 | 1 | 98,041 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The pandemic is upon us, and the world is in shortage of the most important resource: toilet paper. As one of the best prepared nations for this crisis, BubbleLand promised to help all other world nations with this valuable resource. To do that, the country will send airplanes to other countries carrying toilet paper.
In BubbleLand, there are N toilet paper factories, and N airports. Because of how much it takes to build a road, and of course legal issues, every factory must send paper to only one airport, and every airport can only take toilet paper from one factory.
Also, a road can't be built between all airport-factory pairs, again because of legal issues. Every possible road has number d given, number of days it takes to build that road.
Your job is to choose N factory-airport pairs, such that if the country starts building all roads at the same time, it takes the least amount of days to complete them.
Input
The first line contains two integers N (1 ≤ N ≤ 10^4) - number of airports/factories, and M (1 ≤ M ≤ 10^5) - number of available pairs to build a road between.
On next M lines, there are three integers u, v (1 ≤ u,v ≤ N), d (1 ≤ d ≤ 10^9) - meaning that you can build a road between airport u and factory v for d days.
Output
If there are no solutions, output -1. If there exists a solution, output the minimal number of days to complete all roads, equal to maximal d among all chosen roads.
Example
Input
3 5
1 2 1
2 3 2
3 3 3
2 1 4
2 2 5
Output
4 | instruction | 0 | 49,021 | 1 | 98,042 |
Tags: binary search, flows, graph matchings, graphs
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def print_list(l):
print(' '.join(map(str,l)))
# import sys
# sys.setrecursionlimit(5010)
# from heapq import *
# from collections import deque as dq
# from math import ceil,floor,sqrt,pow
# import bisect as bs
# from collections import Counter
from collections import defaultdict as dc
def judge(last,key,d1,d2):
if key>last:
for (a,b,c) in data:
if last<c<=key:
d1[a].add(b)
d2[b].add(a)
else:
for (a,b,c) in data:
if key<c<=last:
d1[a].remove(b)
if not d1[a]:
del d1[a]
d2[b].remove(a)
if not d2[b]:
del d2[b]
if len(d1.keys())<n or len(d2.keys())<n:
return False
for a in d1:
lone = 0
for b in d1[a]:
if len(d2[b])==1:
lone+=1
if lone>1:
return False
for b in d2:
lone = 0
for a in d2[b]:
if len(d1[a])==1:
lone+=1
if lone>1:
return False
used = set()
for a in d1:
if a not in used:
s1,s2,now = {a},d1[a].copy(),d1[a].copy()
while now:
b = now.pop()
da = d2[b]-s1
s1|=da
for aa in da:
db = d1[aa]-s2
now|=db
s2|=db
if len(s1)!=len(s2):
return False
used|=s1
return True
n,m = RL()
data = []
for _ in range(m):
data.append(tuple(map(int, sys.stdin.readline().split())))
l,r = min(a[2] for a in data),max(a[2] for a in data)+1
md = r
last = 0
du = dc(set)
dv = dc(set)
while l<r:
key = (l+r)>>1
if judge(last,key,du,dv):
r = key
else:
l = key+1
last = key
if l>=md:
print(-1)
else:
print(l)
``` | output | 1 | 49,021 | 1 | 98,043 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The pandemic is upon us, and the world is in shortage of the most important resource: toilet paper. As one of the best prepared nations for this crisis, BubbleLand promised to help all other world nations with this valuable resource. To do that, the country will send airplanes to other countries carrying toilet paper.
In BubbleLand, there are N toilet paper factories, and N airports. Because of how much it takes to build a road, and of course legal issues, every factory must send paper to only one airport, and every airport can only take toilet paper from one factory.
Also, a road can't be built between all airport-factory pairs, again because of legal issues. Every possible road has number d given, number of days it takes to build that road.
Your job is to choose N factory-airport pairs, such that if the country starts building all roads at the same time, it takes the least amount of days to complete them.
Input
The first line contains two integers N (1 ≤ N ≤ 10^4) - number of airports/factories, and M (1 ≤ M ≤ 10^5) - number of available pairs to build a road between.
On next M lines, there are three integers u, v (1 ≤ u,v ≤ N), d (1 ≤ d ≤ 10^9) - meaning that you can build a road between airport u and factory v for d days.
Output
If there are no solutions, output -1. If there exists a solution, output the minimal number of days to complete all roads, equal to maximal d among all chosen roads.
Example
Input
3 5
1 2 1
2 3 2
3 3 3
2 1 4
2 2 5
Output
4
Submitted Solution:
```
def checkPossible(factoryAdj,airportAdj): #returns if it's possible to form 1-1 mapping with available edges
factoryLeaves=[]
for i in range(1,n+1):
if len(factoryAdj[i])==0: #impossible as this factory is not connected
return False
elif len(factoryAdj[i])==1:
factoryLeaves.append(i)
while factoryLeaves: #start from leaves because leaves have no choice of airports
f=factoryLeaves.pop()
a=next(iter(factoryAdj[f]))
airportAdj[a].remove(f)
for f2 in airportAdj[a]:
factoryAdj[f2].remove(a)
if len(factoryAdj[f2])==0:
return False
elif len(factoryAdj[f2])==1:
factoryLeaves.append(f2)
return True
def createAdjSets(maxD):
factoryAdj=[set() for _ in range(n+1)]
airportAdj=[set() for _ in range(n+1)]
for u,v,d in uvd:
if d<=maxD:
factoryAdj[u].add(v)
airportAdj[v].add(u)
# print('maxD:{} factory:{} airport:{}'.format(maxD,factoryAdj,airportAdj))
return (factoryAdj,airportAdj)
import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
n,m=[int(x) for x in input().split()]
uvd=[]
maxD=0
for _ in range(m):
u,v,d=[int(x) for x in input().split()]
uvd.append([u,v,d])
maxD=max(maxD,d)
if checkPossible(*createAdjSets(maxD))==False: #impossible
ans=-1
else:
ans=-1
b=maxD
while b>0:
while not checkPossible(*createAdjSets(ans+b)):
ans+=b
b//=2
ans+=1
print(ans)
``` | instruction | 0 | 49,022 | 1 | 98,044 |
No | output | 1 | 49,022 | 1 | 98,045 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The pandemic is upon us, and the world is in shortage of the most important resource: toilet paper. As one of the best prepared nations for this crisis, BubbleLand promised to help all other world nations with this valuable resource. To do that, the country will send airplanes to other countries carrying toilet paper.
In BubbleLand, there are N toilet paper factories, and N airports. Because of how much it takes to build a road, and of course legal issues, every factory must send paper to only one airport, and every airport can only take toilet paper from one factory.
Also, a road can't be built between all airport-factory pairs, again because of legal issues. Every possible road has number d given, number of days it takes to build that road.
Your job is to choose N factory-airport pairs, such that if the country starts building all roads at the same time, it takes the least amount of days to complete them.
Input
The first line contains two integers N (1 ≤ N ≤ 10^4) - number of airports/factories, and M (1 ≤ M ≤ 10^5) - number of available pairs to build a road between.
On next M lines, there are three integers u, v (1 ≤ u,v ≤ N), d (1 ≤ d ≤ 10^9) - meaning that you can build a road between airport u and factory v for d days.
Output
If there are no solutions, output -1. If there exists a solution, output the minimal number of days to complete all roads, equal to maximal d among all chosen roads.
Example
Input
3 5
1 2 1
2 3 2
3 3 3
2 1 4
2 2 5
Output
4
Submitted Solution:
```
import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
n,m=[int(x) for x in input().split()]
airportDeg=[0 for _ in range(n+1)]
factoryDeg=[0 for _ in range(n+1)]
uvd=[]
for _ in range(m):
u,v,d=[int(x) for x in input().split()]
uvd.append([u,v,d])
airportDeg[u]+=1
factoryDeg[v]+=1
uvd.sort(key=lambda x:x[2],reverse=True) #sort by dist desc
edgeIsUsed=[True for _ in range(m)]
#try to remove the max cost greedily
for i in range(m):
u,v,d=uvd[i]
if airportDeg[u]>1 and factoryDeg[v]>1: #can remove this edge
airportDeg[u]-=1
factoryDeg[v]-=1
edgeIsUsed[i]=False
#Check if all airports and factories have exactly 1 deg each
ans=0
for i in range(1,n+1):
if airportDeg[i]!=1 or factoryDeg[i]!=1:
# print('airport/fac:{}'.format(i))
ans=-1
break
if ans!=-1: #airports and factories have exactly 1 deg each
for i in range(m):
if edgeIsUsed[i]:
ans=max(ans,uvd[i][2])
print(ans)
``` | instruction | 0 | 49,023 | 1 | 98,046 |
No | output | 1 | 49,023 | 1 | 98,047 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The pandemic is upon us, and the world is in shortage of the most important resource: toilet paper. As one of the best prepared nations for this crisis, BubbleLand promised to help all other world nations with this valuable resource. To do that, the country will send airplanes to other countries carrying toilet paper.
In BubbleLand, there are N toilet paper factories, and N airports. Because of how much it takes to build a road, and of course legal issues, every factory must send paper to only one airport, and every airport can only take toilet paper from one factory.
Also, a road can't be built between all airport-factory pairs, again because of legal issues. Every possible road has number d given, number of days it takes to build that road.
Your job is to choose N factory-airport pairs, such that if the country starts building all roads at the same time, it takes the least amount of days to complete them.
Input
The first line contains two integers N (1 ≤ N ≤ 10^4) - number of airports/factories, and M (1 ≤ M ≤ 10^5) - number of available pairs to build a road between.
On next M lines, there are three integers u, v (1 ≤ u,v ≤ N), d (1 ≤ d ≤ 10^9) - meaning that you can build a road between airport u and factory v for d days.
Output
If there are no solutions, output -1. If there exists a solution, output the minimal number of days to complete all roads, equal to maximal d among all chosen roads.
Example
Input
3 5
1 2 1
2 3 2
3 3 3
2 1 4
2 2 5
Output
4
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def print_list(l):
print(' '.join(map(str,l)))
# import sys
# sys.setrecursionlimit(5010)
# from heapq import *
# from collections import deque as dq
# from math import ceil,floor,sqrt,pow
# import bisect as bs
# from collections import Counter
from collections import defaultdict as dc
def judge(last,key,d1,d2):
if key>last:
for (a,b,c) in data:
if last<c<=key:
d1[a].add(b)
d2[b].add(a)
else:
for (a,b,c) in data:
if key<c<=last:
d1[a].remove(b)
if not d1[a]:
del d1[a]
d2[b].remove(a)
if not d2[b]:
del d2[b]
if len(d1.keys())<n or len(d2.keys())<n:
return False
for a in d1:
lone = 0
for b in d1[a]:
if len(d2[b])==1:
lone+=1
if lone>1:
return False
for b in d2:
lone = 0
for a in d2[b]:
if len(d1[a])==1:
lone+=1
if lone>1:
return False
return True
n,m = RL()
data = []
for _ in range(m):
data.append(tuple(map(int, sys.stdin.readline().split())))
l,r = min(a[2] for a in data),max(a[2] for a in data)+1
md = r
last = 0
du = dc(set)
dv = dc(set)
while l<r:
key = (l+r)>>1
if judge(last,key,du,dv):
r = key
else:
l = key+1
last = key
if l>=md:
print(-1)
else:
print(l)
``` | instruction | 0 | 49,024 | 1 | 98,048 |
No | output | 1 | 49,024 | 1 | 98,049 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The pandemic is upon us, and the world is in shortage of the most important resource: toilet paper. As one of the best prepared nations for this crisis, BubbleLand promised to help all other world nations with this valuable resource. To do that, the country will send airplanes to other countries carrying toilet paper.
In BubbleLand, there are N toilet paper factories, and N airports. Because of how much it takes to build a road, and of course legal issues, every factory must send paper to only one airport, and every airport can only take toilet paper from one factory.
Also, a road can't be built between all airport-factory pairs, again because of legal issues. Every possible road has number d given, number of days it takes to build that road.
Your job is to choose N factory-airport pairs, such that if the country starts building all roads at the same time, it takes the least amount of days to complete them.
Input
The first line contains two integers N (1 ≤ N ≤ 10^4) - number of airports/factories, and M (1 ≤ M ≤ 10^5) - number of available pairs to build a road between.
On next M lines, there are three integers u, v (1 ≤ u,v ≤ N), d (1 ≤ d ≤ 10^9) - meaning that you can build a road between airport u and factory v for d days.
Output
If there are no solutions, output -1. If there exists a solution, output the minimal number of days to complete all roads, equal to maximal d among all chosen roads.
Example
Input
3 5
1 2 1
2 3 2
3 3 3
2 1 4
2 2 5
Output
4
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def print_list(l):
print(' '.join(map(str,l)))
# import sys
# sys.setrecursionlimit(5010)
# from heapq import *
# from collections import deque as dq
# from math import ceil,floor,sqrt,pow
# import bisect as bs
# from collections import Counter
from collections import defaultdict as dc
def judge(last,key,d1,d2):
if key>last:
for (a,b,c) in data:
if last<c<=key:
d1[a].add(b)
d2[b].add(a)
else:
for (a,b,c) in data:
if key<c<=last:
d1[a].remove(b)
if not d1[a]:
del d1[a]
d2[b].remove(a)
if not d2[b]:
del d2[b]
if len(d1.keys())<n or len(d2.keys())<n:
return False
used = set()
for a in d1:
if a not in used:
s1,s2,now = {a},d1[a].copy(),d1[a].copy()
while now:
b = now.pop()
da = d2[b]-s1
s1|=da
for aa in da:
db = d1[aa]-s2
now|=db
s2|=db
if len(s1)!=len(s2):
return False
used|=s1
return True
n,m = RL()
data = []
for _ in range(m):
data.append(tuple(map(int, sys.stdin.readline().split())))
l,r = min(a[2] for a in data),max(a[2] for a in data)+1
md = r
last = 0
du = dc(set)
dv = dc(set)
while l<r:
key = (l+r)>>1
if judge(last,key,du,dv):
r = key
else:
l = key+1
last = key
if l>=md:
print(-1)
else:
print(l)
``` | instruction | 0 | 49,025 | 1 | 98,050 |
No | output | 1 | 49,025 | 1 | 98,051 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Imagine that your city is an infinite 2D plane with Cartesian coordinate system. The only crime-affected road of your city is the x-axis. Currently, there are n criminals along the road. No police station has been built on this road yet, so the mayor wants to build one.
As you are going to be in charge of this new police station, the mayor has asked you to choose a suitable position (some integer point) for building it. You should choose the best position for the police station, so that you could minimize the total time of your criminal catching mission. Your mission of catching the criminals will operate only from this station.
The new station will have only one patrol car. You will go to the criminals by this car, carry them on the car, bring them back to the police station and put them in prison. The patrol car can carry at most m criminals at a time. Note that, the criminals don't know about your mission. So, they will stay where they are instead of running away.
Your task is to find the position for the police station, so that total distance you need to cover to catch all the criminals will be minimum possible. Note that, you also can built the police station on the positions where one or more criminals already exist. In such a case all these criminals are arrested instantly.
Input
The first line of the input will have two integers n (1 ≤ n ≤ 106) and m (1 ≤ m ≤ 106) separated by spaces. The next line will contain n integers separated by spaces. The ith integer is the position of the ith criminal on the x-axis. Absolute value of positions will not exceed 109. If a criminal has position x, he/she is located in the point (x, 0) of the plane.
The positions of the criminals will be given in non-decreasing order. Note, that there can be more than one criminal standing at some point of the plane.
Note: since the size of the input/output could be very large, don't use slow input/output techniques in your language. For example, do not use input/output streams (cin, cout) in C++.
Output
Print a single integer, that means the minimum possible distance you need to cover to catch all the criminals.
Examples
Input
3 6
1 2 3
Output
4
Input
5 5
-7 -6 -3 -1 1
Output
16
Input
1 369
0
Output
0
Input
11 2
-375 -108 1336 1453 1598 1892 2804 3732 4291 4588 4822
Output
18716 | instruction | 0 | 49,181 | 1 | 98,362 |
Tags: greedy, implementation, math, ternary search
Correct Solution:
```
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
from math import gcd, ceil
def prod(a, mod=10**9+7):
ans = 1
for each in a:
ans = (ans * each) % mod
return ans
def lcm(a, b): return a * b // gcd(a, b)
def binary(x, length=16):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
for _ in range(int(input()) if not True else 1):
#n = int(input())
#n, k = map(int, input().split())
n, m = map(int, input().split())
#c, d = map(int, input().split())
a = list(map(int, input().split()))
#b = list(map(int, input().split()))
#s = input()
m = min(m, n-1)
i = n // 2
j = min(i + 1,n-1)
ans = 0
cur = 0
while cur != i:
ans += (a[i] - a[cur]) * 2
cur = min(cur + m, i)
cur = n-1
while cur != i:
ans += (a[cur] - a[i]) * 2
cur = max(i, cur - m)
answers = [ans]
i = j
ans = 0
cur = 0
while cur != i:
ans += (a[i] - a[cur]) * 2
cur = min(cur + m, i)
cur = n - 1
while cur != i:
ans += (a[cur] - a[i]) * 2
cur = max(i, cur - m)
answers += [ans]
print(min(answers))
``` | output | 1 | 49,181 | 1 | 98,363 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Imagine that your city is an infinite 2D plane with Cartesian coordinate system. The only crime-affected road of your city is the x-axis. Currently, there are n criminals along the road. No police station has been built on this road yet, so the mayor wants to build one.
As you are going to be in charge of this new police station, the mayor has asked you to choose a suitable position (some integer point) for building it. You should choose the best position for the police station, so that you could minimize the total time of your criminal catching mission. Your mission of catching the criminals will operate only from this station.
The new station will have only one patrol car. You will go to the criminals by this car, carry them on the car, bring them back to the police station and put them in prison. The patrol car can carry at most m criminals at a time. Note that, the criminals don't know about your mission. So, they will stay where they are instead of running away.
Your task is to find the position for the police station, so that total distance you need to cover to catch all the criminals will be minimum possible. Note that, you also can built the police station on the positions where one or more criminals already exist. In such a case all these criminals are arrested instantly.
Input
The first line of the input will have two integers n (1 ≤ n ≤ 106) and m (1 ≤ m ≤ 106) separated by spaces. The next line will contain n integers separated by spaces. The ith integer is the position of the ith criminal on the x-axis. Absolute value of positions will not exceed 109. If a criminal has position x, he/she is located in the point (x, 0) of the plane.
The positions of the criminals will be given in non-decreasing order. Note, that there can be more than one criminal standing at some point of the plane.
Note: since the size of the input/output could be very large, don't use slow input/output techniques in your language. For example, do not use input/output streams (cin, cout) in C++.
Output
Print a single integer, that means the minimum possible distance you need to cover to catch all the criminals.
Examples
Input
3 6
1 2 3
Output
4
Input
5 5
-7 -6 -3 -1 1
Output
16
Input
1 369
0
Output
0
Input
11 2
-375 -108 1336 1453 1598 1892 2804 3732 4291 4588 4822
Output
18716 | instruction | 0 | 49,182 | 1 | 98,364 |
Tags: greedy, implementation, math, ternary search
Correct Solution:
```
from sys import stdin, stdout
import io,os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
crims, raite = list(map(int, input().split()))
posiciones = list(map(int, input().split()))
finalle = 0
llevados = 0
while llevados < crims:
finalle += posiciones[crims - 1] - posiciones[llevados]
llevados += raite
crims -= raite
print(2 * finalle)
``` | output | 1 | 49,182 | 1 | 98,365 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Imagine that your city is an infinite 2D plane with Cartesian coordinate system. The only crime-affected road of your city is the x-axis. Currently, there are n criminals along the road. No police station has been built on this road yet, so the mayor wants to build one.
As you are going to be in charge of this new police station, the mayor has asked you to choose a suitable position (some integer point) for building it. You should choose the best position for the police station, so that you could minimize the total time of your criminal catching mission. Your mission of catching the criminals will operate only from this station.
The new station will have only one patrol car. You will go to the criminals by this car, carry them on the car, bring them back to the police station and put them in prison. The patrol car can carry at most m criminals at a time. Note that, the criminals don't know about your mission. So, they will stay where they are instead of running away.
Your task is to find the position for the police station, so that total distance you need to cover to catch all the criminals will be minimum possible. Note that, you also can built the police station on the positions where one or more criminals already exist. In such a case all these criminals are arrested instantly.
Input
The first line of the input will have two integers n (1 ≤ n ≤ 106) and m (1 ≤ m ≤ 106) separated by spaces. The next line will contain n integers separated by spaces. The ith integer is the position of the ith criminal on the x-axis. Absolute value of positions will not exceed 109. If a criminal has position x, he/she is located in the point (x, 0) of the plane.
The positions of the criminals will be given in non-decreasing order. Note, that there can be more than one criminal standing at some point of the plane.
Note: since the size of the input/output could be very large, don't use slow input/output techniques in your language. For example, do not use input/output streams (cin, cout) in C++.
Output
Print a single integer, that means the minimum possible distance you need to cover to catch all the criminals.
Examples
Input
3 6
1 2 3
Output
4
Input
5 5
-7 -6 -3 -1 1
Output
16
Input
1 369
0
Output
0
Input
11 2
-375 -108 1336 1453 1598 1892 2804 3732 4291 4588 4822
Output
18716 | instruction | 0 | 49,183 | 1 | 98,366 |
Tags: greedy, implementation, math, ternary search
Correct Solution:
```
from sys import stdin, stdout
import io,os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
print = stdout.write
crims, raite = list(map(int, input().split()))
posiciones = list(map(int, input().split()))
finalle = 0
llevados = 0
while llevados < crims:
finalle += posiciones[crims - 1] - posiciones[llevados]
llevados += raite
crims -= raite
print(str(2 * finalle))
``` | output | 1 | 49,183 | 1 | 98,367 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Imagine that your city is an infinite 2D plane with Cartesian coordinate system. The only crime-affected road of your city is the x-axis. Currently, there are n criminals along the road. No police station has been built on this road yet, so the mayor wants to build one.
As you are going to be in charge of this new police station, the mayor has asked you to choose a suitable position (some integer point) for building it. You should choose the best position for the police station, so that you could minimize the total time of your criminal catching mission. Your mission of catching the criminals will operate only from this station.
The new station will have only one patrol car. You will go to the criminals by this car, carry them on the car, bring them back to the police station and put them in prison. The patrol car can carry at most m criminals at a time. Note that, the criminals don't know about your mission. So, they will stay where they are instead of running away.
Your task is to find the position for the police station, so that total distance you need to cover to catch all the criminals will be minimum possible. Note that, you also can built the police station on the positions where one or more criminals already exist. In such a case all these criminals are arrested instantly.
Input
The first line of the input will have two integers n (1 ≤ n ≤ 106) and m (1 ≤ m ≤ 106) separated by spaces. The next line will contain n integers separated by spaces. The ith integer is the position of the ith criminal on the x-axis. Absolute value of positions will not exceed 109. If a criminal has position x, he/she is located in the point (x, 0) of the plane.
The positions of the criminals will be given in non-decreasing order. Note, that there can be more than one criminal standing at some point of the plane.
Note: since the size of the input/output could be very large, don't use slow input/output techniques in your language. For example, do not use input/output streams (cin, cout) in C++.
Output
Print a single integer, that means the minimum possible distance you need to cover to catch all the criminals.
Examples
Input
3 6
1 2 3
Output
4
Input
5 5
-7 -6 -3 -1 1
Output
16
Input
1 369
0
Output
0
Input
11 2
-375 -108 1336 1453 1598 1892 2804 3732 4291 4588 4822
Output
18716 | instruction | 0 | 49,184 | 1 | 98,368 |
Tags: greedy, implementation, math, ternary search
Correct Solution:
```
import io,os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
crims, raite = list(map(int, input().split()))
posiciones = list(map(int, input().split()))
finalle = 0
llevados = 0
while llevados < crims:
finalle += posiciones[crims - 1] - posiciones[llevados]
llevados += raite
crims -= raite
print(2 * finalle)
``` | output | 1 | 49,184 | 1 | 98,369 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Imagine that your city is an infinite 2D plane with Cartesian coordinate system. The only crime-affected road of your city is the x-axis. Currently, there are n criminals along the road. No police station has been built on this road yet, so the mayor wants to build one.
As you are going to be in charge of this new police station, the mayor has asked you to choose a suitable position (some integer point) for building it. You should choose the best position for the police station, so that you could minimize the total time of your criminal catching mission. Your mission of catching the criminals will operate only from this station.
The new station will have only one patrol car. You will go to the criminals by this car, carry them on the car, bring them back to the police station and put them in prison. The patrol car can carry at most m criminals at a time. Note that, the criminals don't know about your mission. So, they will stay where they are instead of running away.
Your task is to find the position for the police station, so that total distance you need to cover to catch all the criminals will be minimum possible. Note that, you also can built the police station on the positions where one or more criminals already exist. In such a case all these criminals are arrested instantly.
Input
The first line of the input will have two integers n (1 ≤ n ≤ 106) and m (1 ≤ m ≤ 106) separated by spaces. The next line will contain n integers separated by spaces. The ith integer is the position of the ith criminal on the x-axis. Absolute value of positions will not exceed 109. If a criminal has position x, he/she is located in the point (x, 0) of the plane.
The positions of the criminals will be given in non-decreasing order. Note, that there can be more than one criminal standing at some point of the plane.
Note: since the size of the input/output could be very large, don't use slow input/output techniques in your language. For example, do not use input/output streams (cin, cout) in C++.
Output
Print a single integer, that means the minimum possible distance you need to cover to catch all the criminals.
Examples
Input
3 6
1 2 3
Output
4
Input
5 5
-7 -6 -3 -1 1
Output
16
Input
1 369
0
Output
0
Input
11 2
-375 -108 1336 1453 1598 1892 2804 3732 4291 4588 4822
Output
18716
Submitted Solution:
```
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
from math import gcd, ceil
def prod(a, mod=10**9+7):
ans = 1
for each in a:
ans = (ans * each) % mod
return ans
def lcm(a, b): return a * b // gcd(a, b)
def binary(x, length=16):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
for _ in range(int(input()) if not True else 1):
#n = int(input())
#n, k = map(int, input().split())
n, m = map(int, input().split())
#c, d = map(int, input().split())
a = list(map(int, input().split()))
#b = list(map(int, input().split()))
#s = input()
m = min(m, n-1)
i = 0
j = n-1
while i < j:
if i + m < n:
i += m
if j - m >= 0:
j -= m
ans = 0
cur = 0
while cur != i:
ans += (a[i] - a[cur]) * 2
cur = min(cur + m, i)
cur = n-1
while cur != i:
ans += (a[cur] - a[i]) * 2
cur = max(i, cur - m)
answers = [ans]
ans = 0
cur = i
while cur != 0:
cur = max(cur - m, 0)
ans += (a[i] - a[cur]) * 2
cur = i
while cur != n - 1:
cur = min(n - 1, cur + m)
ans += (a[cur] - a[i]) * 2
answers = [ans]
i = j
ans = 0
cur = 0
while cur != i:
ans += (a[i] - a[cur]) * 2
cur = min(cur + m, i)
cur = n - 1
while cur != i:
ans += (a[cur] - a[i]) * 2
cur = max(i, cur - m)
answers += [ans]
ans = 0
cur = i
while cur != 0:
cur = max(cur - m, 0)
ans += (a[i] - a[cur]) * 2
cur = i
while cur != n - 1:
cur = min(n - 1, cur + m)
ans += (a[cur] - a[i]) * 2
answers += [ans]
print(min(answers))
``` | instruction | 0 | 49,185 | 1 | 98,370 |
No | output | 1 | 49,185 | 1 | 98,371 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Imagine that your city is an infinite 2D plane with Cartesian coordinate system. The only crime-affected road of your city is the x-axis. Currently, there are n criminals along the road. No police station has been built on this road yet, so the mayor wants to build one.
As you are going to be in charge of this new police station, the mayor has asked you to choose a suitable position (some integer point) for building it. You should choose the best position for the police station, so that you could minimize the total time of your criminal catching mission. Your mission of catching the criminals will operate only from this station.
The new station will have only one patrol car. You will go to the criminals by this car, carry them on the car, bring them back to the police station and put them in prison. The patrol car can carry at most m criminals at a time. Note that, the criminals don't know about your mission. So, they will stay where they are instead of running away.
Your task is to find the position for the police station, so that total distance you need to cover to catch all the criminals will be minimum possible. Note that, you also can built the police station on the positions where one or more criminals already exist. In such a case all these criminals are arrested instantly.
Input
The first line of the input will have two integers n (1 ≤ n ≤ 106) and m (1 ≤ m ≤ 106) separated by spaces. The next line will contain n integers separated by spaces. The ith integer is the position of the ith criminal on the x-axis. Absolute value of positions will not exceed 109. If a criminal has position x, he/she is located in the point (x, 0) of the plane.
The positions of the criminals will be given in non-decreasing order. Note, that there can be more than one criminal standing at some point of the plane.
Note: since the size of the input/output could be very large, don't use slow input/output techniques in your language. For example, do not use input/output streams (cin, cout) in C++.
Output
Print a single integer, that means the minimum possible distance you need to cover to catch all the criminals.
Examples
Input
3 6
1 2 3
Output
4
Input
5 5
-7 -6 -3 -1 1
Output
16
Input
1 369
0
Output
0
Input
11 2
-375 -108 1336 1453 1598 1892 2804 3732 4291 4588 4822
Output
18716
Submitted Solution:
```
n, m = tuple(map(int, str.split(input())))
ns = sorted(map(int, str.split(input())))
def get_length(x):
i = l = 0
count = 0
while i < n and ns[i] < x:
i += 1
count += 1
if count == m:
l += (x - ns[i - count]) * 2
count = 0
if count:
l += (x - ns[i - count]) * 2
count = 0
while i < n and ns[i] == x:
i += 1
while i < n:
i += 1
count += 1
if count == m:
l += (ns[i - 1] - x) * 2
count = 0
if count:
l += (ns[-1] - x) * 2
return l
x = ns[0]
step = (ns[-1] - ns[0]) // 2
cl = get_length(x)
path = []
while True:
sl = get_length(x - step)
sr = get_length(x + step)
if sl <= cl and (x - step) not in path:
cl, x = sl, x - step
path.append(x)
elif sr <= cl and (x + step) not in path:
cl, x = sr, x + step
path.append(x)
else:
if step == 1:
break
step = max(1, step // 2)
print(cl)
``` | instruction | 0 | 49,186 | 1 | 98,372 |
No | output | 1 | 49,186 | 1 | 98,373 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Imagine that your city is an infinite 2D plane with Cartesian coordinate system. The only crime-affected road of your city is the x-axis. Currently, there are n criminals along the road. No police station has been built on this road yet, so the mayor wants to build one.
As you are going to be in charge of this new police station, the mayor has asked you to choose a suitable position (some integer point) for building it. You should choose the best position for the police station, so that you could minimize the total time of your criminal catching mission. Your mission of catching the criminals will operate only from this station.
The new station will have only one patrol car. You will go to the criminals by this car, carry them on the car, bring them back to the police station and put them in prison. The patrol car can carry at most m criminals at a time. Note that, the criminals don't know about your mission. So, they will stay where they are instead of running away.
Your task is to find the position for the police station, so that total distance you need to cover to catch all the criminals will be minimum possible. Note that, you also can built the police station on the positions where one or more criminals already exist. In such a case all these criminals are arrested instantly.
Input
The first line of the input will have two integers n (1 ≤ n ≤ 106) and m (1 ≤ m ≤ 106) separated by spaces. The next line will contain n integers separated by spaces. The ith integer is the position of the ith criminal on the x-axis. Absolute value of positions will not exceed 109. If a criminal has position x, he/she is located in the point (x, 0) of the plane.
The positions of the criminals will be given in non-decreasing order. Note, that there can be more than one criminal standing at some point of the plane.
Note: since the size of the input/output could be very large, don't use slow input/output techniques in your language. For example, do not use input/output streams (cin, cout) in C++.
Output
Print a single integer, that means the minimum possible distance you need to cover to catch all the criminals.
Examples
Input
3 6
1 2 3
Output
4
Input
5 5
-7 -6 -3 -1 1
Output
16
Input
1 369
0
Output
0
Input
11 2
-375 -108 1336 1453 1598 1892 2804 3732 4291 4588 4822
Output
18716
Submitted Solution:
```
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
from math import gcd, ceil
def prod(a, mod=10**9+7):
ans = 1
for each in a:
ans = (ans * each) % mod
return ans
def lcm(a, b): return a * b // gcd(a, b)
def binary(x, length=16):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
for _ in range(int(input()) if not True else 1):
#n = int(input())
#n, k = map(int, input().split())
n, m = map(int, input().split())
#c, d = map(int, input().split())
a = list(map(int, input().split()))
#b = list(map(int, input().split()))
#s = input()
m = min(m, n-1)
i = 0
j = n-1
while i < j:
if i + m < n:
i += m
if j - m >= 0:
j -= m
ans = 0
cur = 0
while cur != i:
ans += (a[i] - a[cur]) * 2
cur = min(cur + m, i)
cur = n-1
while cur != i:
ans += (a[cur] - a[i]) * 2
cur = max(i, cur - m)
answers = [ans]
i = j
ans = 0
cur = 0
while cur != i:
ans += (a[i] - a[cur]) * 2
cur = min(cur + m, i)
cur = n - 1
while cur != i:
ans += (a[cur] - a[i]) * 2
cur = max(i, cur - m)
answers += [ans]
print(min(answers))
``` | instruction | 0 | 49,187 | 1 | 98,374 |
No | output | 1 | 49,187 | 1 | 98,375 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Imagine that your city is an infinite 2D plane with Cartesian coordinate system. The only crime-affected road of your city is the x-axis. Currently, there are n criminals along the road. No police station has been built on this road yet, so the mayor wants to build one.
As you are going to be in charge of this new police station, the mayor has asked you to choose a suitable position (some integer point) for building it. You should choose the best position for the police station, so that you could minimize the total time of your criminal catching mission. Your mission of catching the criminals will operate only from this station.
The new station will have only one patrol car. You will go to the criminals by this car, carry them on the car, bring them back to the police station and put them in prison. The patrol car can carry at most m criminals at a time. Note that, the criminals don't know about your mission. So, they will stay where they are instead of running away.
Your task is to find the position for the police station, so that total distance you need to cover to catch all the criminals will be minimum possible. Note that, you also can built the police station on the positions where one or more criminals already exist. In such a case all these criminals are arrested instantly.
Input
The first line of the input will have two integers n (1 ≤ n ≤ 106) and m (1 ≤ m ≤ 106) separated by spaces. The next line will contain n integers separated by spaces. The ith integer is the position of the ith criminal on the x-axis. Absolute value of positions will not exceed 109. If a criminal has position x, he/she is located in the point (x, 0) of the plane.
The positions of the criminals will be given in non-decreasing order. Note, that there can be more than one criminal standing at some point of the plane.
Note: since the size of the input/output could be very large, don't use slow input/output techniques in your language. For example, do not use input/output streams (cin, cout) in C++.
Output
Print a single integer, that means the minimum possible distance you need to cover to catch all the criminals.
Examples
Input
3 6
1 2 3
Output
4
Input
5 5
-7 -6 -3 -1 1
Output
16
Input
1 369
0
Output
0
Input
11 2
-375 -108 1336 1453 1598 1892 2804 3732 4291 4588 4822
Output
18716
Submitted Solution:
```
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
from math import gcd, ceil
def prod(a, mod=10**9+7):
ans = 1
for each in a:
ans = (ans * each) % mod
return ans
def lcm(a, b): return a * b // gcd(a, b)
def binary(x, length=16):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
for _ in range(int(input()) if not True else 1):
#n = int(input())
#n, k = map(int, input().split())
n, m = map(int, input().split())
#c, d = map(int, input().split())
a = list(map(int, input().split()))
#b = list(map(int, input().split()))
#s = input()
m = min(m, n-1)
i = 0
j = n-1
while i < j:
if i + m < n:
i += m
if j - m >= 0:
j -= m
ans = 0
cur = i
while cur != 0:
cur = max(cur - m, 0)
ans += (a[i] - a[cur]) * 2
cur = i
while cur != n-1:
cur = min(n-1, cur + m)
ans += (a[cur] - a[i]) * 2
answers = [ans]
i = j
ans = 0
cur = i
while cur != 0:
cur = max(cur - m, 0)
ans += (a[i] - a[cur]) * 2
cur = i
while cur != n - 1:
cur = min(n - 1, cur + m)
ans += (a[cur] - a[i]) * 2
answers += [ans]
print(min(answers))
``` | instruction | 0 | 49,188 | 1 | 98,376 |
No | output | 1 | 49,188 | 1 | 98,377 |
Provide a correct Python 3 solution for this coding contest problem.
problem
The IOI country consists of N towns from town 1 to town N, and the towns are connected by roads. The IOI country has K roads, all of which connect two different towns. Cars can move freely in both directions on the road, but they cannot go from one town to another through anything other than the road.
JOI, who lives in Town 1 of the IOI country, decided to take a taxi to his grandmother's house in Town N. There are N taxi companies in the IOI country, from taxi company 1 to taxi company N. Taxi companies in IOI have the following slightly special rules:
* You can take a taxi from taxi company i only in town i.
* The taxi fare of taxi company i is Ci regardless of the distance used.
* The taxi of taxi company i can only pass up to Ri roads in a row after boarding.
For example, if R1 = 2, if you take a taxi from town 1 to taxi company 1, you can only take up to 2 roads, so you need to change taxis in the middle of the town to go through 3 or more roads. ..
JOI cannot take or get off a taxi outside the town. Also, transportation other than taxis cannot be used. Create a program to find the minimum total fare required for JOI to reach town N.
input
The input consists of 1 + N + K lines.
On the first line, two integers N, K (2 ≤ N ≤ 5000, N -1 ≤ K ≤ 10000) are written separated by a blank. This means that the IOI country consists of N towns and the number of roads in the IOI country is K.
On the i-th line (1 ≤ i ≤ N) of the following N lines, two integers Ci and Ri (1 ≤ Ci ≤ 10000, 1 ≤ Ri ≤ N) are written separated by a blank. This means that the taxi fare of taxi company i is Ci, and you can only pass up to Ri roads in a row after boarding.
On the jth line (1 ≤ j ≤ K) of the following K lines, two different integers Aj and Bj (1 ≤ Aj <Bj ≤ N) are written separated by a blank. This means that there is a road between town Aj and town Bj. The same (Aj, Bj) pair has never been written more than once.
Given the input data, it is guaranteed that you can take a taxi from any town to any other town.
output
JOI Output an integer on one line that represents the minimum total fare required for you to travel from town 1 to town N.
Examples
Input
6 6
400 2
200 1
600 3
1000 1
300 5
700 4
1 2
2 3
3 6
4 6
1 5
2 4
Output
700
Input
None
Output
None | instruction | 0 | 49,553 | 1 | 99,106 |
"Correct Solution:
```
from heapq import heappop as pop
from heapq import heappush as push
def main():
n, k = map(int, input().split())
clst = []
rlst = []
for i in range(n):
c, r = map(int, input().split())
clst.append(c)
rlst.append(r)
edges = [[] * n for i in range(n)]
for i in range(k):
a, b = map(int, input().split())
a -= 1
b -= 1
edges[a].append(b)
edges[b].append(a)
costs = [None] * n
used = [False] * n
def make_to_lst(s_num):
loop = rlst[s_num]
temp = set(edges[s_num])
ret = set()
while loop and temp:
new = set()
for p in temp:
pto = set(edges[p])
new = new | pto
ret = ret | temp
temp = new - ret
loop -= 1
return ret
used[0] = True
costs[0] = 0
que = [(clst[0], 0)]
while que:
next_cost, s_num = pop(que)
to_lst = make_to_lst(s_num)
for num in to_lst:
if num == n - 1:
print(next_cost)
return
costs[num] = next_cost
if not used[num]:
push(que, (next_cost + clst[num], num))
used[num] = True
main()
``` | output | 1 | 49,553 | 1 | 99,107 |
Provide a correct Python 3 solution for this coding contest problem.
problem
The IOI country consists of N towns from town 1 to town N, and the towns are connected by roads. The IOI country has K roads, all of which connect two different towns. Cars can move freely in both directions on the road, but they cannot go from one town to another through anything other than the road.
JOI, who lives in Town 1 of the IOI country, decided to take a taxi to his grandmother's house in Town N. There are N taxi companies in the IOI country, from taxi company 1 to taxi company N. Taxi companies in IOI have the following slightly special rules:
* You can take a taxi from taxi company i only in town i.
* The taxi fare of taxi company i is Ci regardless of the distance used.
* The taxi of taxi company i can only pass up to Ri roads in a row after boarding.
For example, if R1 = 2, if you take a taxi from town 1 to taxi company 1, you can only take up to 2 roads, so you need to change taxis in the middle of the town to go through 3 or more roads. ..
JOI cannot take or get off a taxi outside the town. Also, transportation other than taxis cannot be used. Create a program to find the minimum total fare required for JOI to reach town N.
input
The input consists of 1 + N + K lines.
On the first line, two integers N, K (2 ≤ N ≤ 5000, N -1 ≤ K ≤ 10000) are written separated by a blank. This means that the IOI country consists of N towns and the number of roads in the IOI country is K.
On the i-th line (1 ≤ i ≤ N) of the following N lines, two integers Ci and Ri (1 ≤ Ci ≤ 10000, 1 ≤ Ri ≤ N) are written separated by a blank. This means that the taxi fare of taxi company i is Ci, and you can only pass up to Ri roads in a row after boarding.
On the jth line (1 ≤ j ≤ K) of the following K lines, two different integers Aj and Bj (1 ≤ Aj <Bj ≤ N) are written separated by a blank. This means that there is a road between town Aj and town Bj. The same (Aj, Bj) pair has never been written more than once.
Given the input data, it is guaranteed that you can take a taxi from any town to any other town.
output
JOI Output an integer on one line that represents the minimum total fare required for you to travel from town 1 to town N.
Examples
Input
6 6
400 2
200 1
600 3
1000 1
300 5
700 4
1 2
2 3
3 6
4 6
1 5
2 4
Output
700
Input
None
Output
None | instruction | 0 | 49,554 | 1 | 99,108 |
"Correct Solution:
```
from heapq import heappop as pop
from heapq import heappush as push
INF = 10 ** 20
def main():
n, k = map(int, input().split())
clst = []
rlst = []
for i in range(n):
c, r = map(int, input().split())
clst.append(c)
rlst.append(r)
edges = [[] * n for i in range(n)]
for i in range(k):
a, b = map(int, input().split())
a -= 1
b -= 1
edges[a].append(b)
edges[b].append(a)
costs = [INF for i in range(n)]
costs[0] = 0
used = [False for i in range(n)]
def make_to_lst(s_num):
loop = rlst[s_num]
temp = {i for i in edges[s_num]}
ret = {i for i in temp}
while loop:
new = set()
for p in temp:
pto = {i for i in edges[p]}
new = new | pto
ret = ret | temp
temp = new - ret
if not temp:
break
loop -= 1
return ret
used[0] = True
costs[0] = 0
break_flag = 0
que = [(clst[0], 0)]
while que and not break_flag:
next_cost, s_num = pop(que)
to_lst = make_to_lst(s_num)
for num in to_lst:
costs[num] = next_cost
if num == n - 1:
break_flag = 1
break
if not used[num]:
push(que, (costs[num] + clst[num], num))
used[num] = True
print(costs[n - 1])
main()
``` | output | 1 | 49,554 | 1 | 99,109 |
Provide a correct Python 3 solution for this coding contest problem.
problem
The IOI country consists of N towns from town 1 to town N, and the towns are connected by roads. The IOI country has K roads, all of which connect two different towns. Cars can move freely in both directions on the road, but they cannot go from one town to another through anything other than the road.
JOI, who lives in Town 1 of the IOI country, decided to take a taxi to his grandmother's house in Town N. There are N taxi companies in the IOI country, from taxi company 1 to taxi company N. Taxi companies in IOI have the following slightly special rules:
* You can take a taxi from taxi company i only in town i.
* The taxi fare of taxi company i is Ci regardless of the distance used.
* The taxi of taxi company i can only pass up to Ri roads in a row after boarding.
For example, if R1 = 2, if you take a taxi from town 1 to taxi company 1, you can only take up to 2 roads, so you need to change taxis in the middle of the town to go through 3 or more roads. ..
JOI cannot take or get off a taxi outside the town. Also, transportation other than taxis cannot be used. Create a program to find the minimum total fare required for JOI to reach town N.
input
The input consists of 1 + N + K lines.
On the first line, two integers N, K (2 ≤ N ≤ 5000, N -1 ≤ K ≤ 10000) are written separated by a blank. This means that the IOI country consists of N towns and the number of roads in the IOI country is K.
On the i-th line (1 ≤ i ≤ N) of the following N lines, two integers Ci and Ri (1 ≤ Ci ≤ 10000, 1 ≤ Ri ≤ N) are written separated by a blank. This means that the taxi fare of taxi company i is Ci, and you can only pass up to Ri roads in a row after boarding.
On the jth line (1 ≤ j ≤ K) of the following K lines, two different integers Aj and Bj (1 ≤ Aj <Bj ≤ N) are written separated by a blank. This means that there is a road between town Aj and town Bj. The same (Aj, Bj) pair has never been written more than once.
Given the input data, it is guaranteed that you can take a taxi from any town to any other town.
output
JOI Output an integer on one line that represents the minimum total fare required for you to travel from town 1 to town N.
Examples
Input
6 6
400 2
200 1
600 3
1000 1
300 5
700 4
1 2
2 3
3 6
4 6
1 5
2 4
Output
700
Input
None
Output
None | instruction | 0 | 49,555 | 1 | 99,110 |
"Correct Solution:
```
from heapq import heappop as pop
from heapq import heappush as push
INF = 10 ** 20
n, k = map(int, input().split())
clst = []
rlst = []
for i in range(n):
c, r = map(int, input().split())
clst.append(c)
rlst.append(r)
edges = [[0] * n for i in range(n)]
for i in range(k):
a, b = map(int, input().split())
a -= 1
b -= 1
edges[a][b] = edges[b][a] = 1
costs = [INF for i in range(n)]
costs[0] = 0
used = [False for i in range(n)]
def make_to_lst(s_num):
loop = rlst[s_num]
temp = {i for i in range(n) if edges[s_num][i]}
ret = {i for i in temp}
while loop:
new = set()
for p in temp:
pto = {i for i in range(n) if edges[p][i]}
new = new | pto
ret = ret | temp
temp = new - ret
if not temp:
break
loop -= 1
return ret
used[0] = True
costs[0] = 0
break_flag = 0
que = [(clst[0], 0)]
while que and not break_flag:
next_cost, s_num = pop(que)
to_lst = make_to_lst(s_num)
for num in to_lst:
costs[num] = next_cost
if num == n - 1:
break_flag = 1
break
if not used[num]:
push(que, (costs[num] + clst[num], num))
used[num] = True
print(costs[n - 1])
``` | output | 1 | 49,555 | 1 | 99,111 |
Provide a correct Python 3 solution for this coding contest problem.
problem
The IOI country consists of N towns from town 1 to town N, and the towns are connected by roads. The IOI country has K roads, all of which connect two different towns. Cars can move freely in both directions on the road, but they cannot go from one town to another through anything other than the road.
JOI, who lives in Town 1 of the IOI country, decided to take a taxi to his grandmother's house in Town N. There are N taxi companies in the IOI country, from taxi company 1 to taxi company N. Taxi companies in IOI have the following slightly special rules:
* You can take a taxi from taxi company i only in town i.
* The taxi fare of taxi company i is Ci regardless of the distance used.
* The taxi of taxi company i can only pass up to Ri roads in a row after boarding.
For example, if R1 = 2, if you take a taxi from town 1 to taxi company 1, you can only take up to 2 roads, so you need to change taxis in the middle of the town to go through 3 or more roads. ..
JOI cannot take or get off a taxi outside the town. Also, transportation other than taxis cannot be used. Create a program to find the minimum total fare required for JOI to reach town N.
input
The input consists of 1 + N + K lines.
On the first line, two integers N, K (2 ≤ N ≤ 5000, N -1 ≤ K ≤ 10000) are written separated by a blank. This means that the IOI country consists of N towns and the number of roads in the IOI country is K.
On the i-th line (1 ≤ i ≤ N) of the following N lines, two integers Ci and Ri (1 ≤ Ci ≤ 10000, 1 ≤ Ri ≤ N) are written separated by a blank. This means that the taxi fare of taxi company i is Ci, and you can only pass up to Ri roads in a row after boarding.
On the jth line (1 ≤ j ≤ K) of the following K lines, two different integers Aj and Bj (1 ≤ Aj <Bj ≤ N) are written separated by a blank. This means that there is a road between town Aj and town Bj. The same (Aj, Bj) pair has never been written more than once.
Given the input data, it is guaranteed that you can take a taxi from any town to any other town.
output
JOI Output an integer on one line that represents the minimum total fare required for you to travel from town 1 to town N.
Examples
Input
6 6
400 2
200 1
600 3
1000 1
300 5
700 4
1 2
2 3
3 6
4 6
1 5
2 4
Output
700
Input
None
Output
None | instruction | 0 | 49,556 | 1 | 99,112 |
"Correct Solution:
```
from heapq import heappop as pop
from heapq import heappush as push
INF = 10 ** 20
def main():
n, k = map(int, input().split())
clst = []
rlst = []
for i in range(n):
c, r = map(int, input().split())
clst.append(c)
rlst.append(r)
edges = [[] * n for i in range(n)]
for i in range(k):
a, b = map(int, input().split())
a -= 1
b -= 1
edges[a].append(b)
edges[b].append(a)
costs = [INF for i in range(n)]
costs[0] = 0
used = [False for i in range(n)]
def make_to_lst(s_num):
loop = rlst[s_num]
temp = set(edges[s_num])
ret = set()
while loop:
new = set()
for p in temp:
pto = set(edges[p])
new = new | pto
ret = ret | temp
temp = new - ret
if not temp:
break
loop -= 1
return ret
used[0] = True
costs[0] = 0
break_flag = 0
que = [(clst[0], 0)]
while que and not break_flag:
next_cost, s_num = pop(que)
to_lst = make_to_lst(s_num)
for num in to_lst:
costs[num] = next_cost
if num == n - 1:
break_flag = 1
break
if not used[num]:
push(que, (costs[num] + clst[num], num))
used[num] = True
print(costs[n - 1])
main()
``` | output | 1 | 49,556 | 1 | 99,113 |
Provide a correct Python 3 solution for this coding contest problem.
problem
The IOI country consists of N towns from town 1 to town N, and the towns are connected by roads. The IOI country has K roads, all of which connect two different towns. Cars can move freely in both directions on the road, but they cannot go from one town to another through anything other than the road.
JOI, who lives in Town 1 of the IOI country, decided to take a taxi to his grandmother's house in Town N. There are N taxi companies in the IOI country, from taxi company 1 to taxi company N. Taxi companies in IOI have the following slightly special rules:
* You can take a taxi from taxi company i only in town i.
* The taxi fare of taxi company i is Ci regardless of the distance used.
* The taxi of taxi company i can only pass up to Ri roads in a row after boarding.
For example, if R1 = 2, if you take a taxi from town 1 to taxi company 1, you can only take up to 2 roads, so you need to change taxis in the middle of the town to go through 3 or more roads. ..
JOI cannot take or get off a taxi outside the town. Also, transportation other than taxis cannot be used. Create a program to find the minimum total fare required for JOI to reach town N.
input
The input consists of 1 + N + K lines.
On the first line, two integers N, K (2 ≤ N ≤ 5000, N -1 ≤ K ≤ 10000) are written separated by a blank. This means that the IOI country consists of N towns and the number of roads in the IOI country is K.
On the i-th line (1 ≤ i ≤ N) of the following N lines, two integers Ci and Ri (1 ≤ Ci ≤ 10000, 1 ≤ Ri ≤ N) are written separated by a blank. This means that the taxi fare of taxi company i is Ci, and you can only pass up to Ri roads in a row after boarding.
On the jth line (1 ≤ j ≤ K) of the following K lines, two different integers Aj and Bj (1 ≤ Aj <Bj ≤ N) are written separated by a blank. This means that there is a road between town Aj and town Bj. The same (Aj, Bj) pair has never been written more than once.
Given the input data, it is guaranteed that you can take a taxi from any town to any other town.
output
JOI Output an integer on one line that represents the minimum total fare required for you to travel from town 1 to town N.
Examples
Input
6 6
400 2
200 1
600 3
1000 1
300 5
700 4
1 2
2 3
3 6
4 6
1 5
2 4
Output
700
Input
None
Output
None | instruction | 0 | 49,557 | 1 | 99,114 |
"Correct Solution:
```
from heapq import heappop as pop
from heapq import heappush as push
INF = 10 ** 20
n, k = map(int, input().split())
clst = []
rlst = []
for i in range(n):
c, r = map(int, input().split())
clst.append(c)
rlst.append(r)
edges = [[] * n for i in range(n)]
for i in range(k):
a, b = map(int, input().split())
a -= 1
b -= 1
edges[a].append(b)
edges[b].append(a)
costs = [INF for i in range(n)]
costs[0] = 0
used = [False for i in range(n)]
def make_to_lst(s_num):
loop = rlst[s_num]
temp = {i for i in edges[s_num]}
ret = {i for i in temp}
while loop:
new = set()
for p in temp:
pto = {i for i in edges[p]}
new = new | pto
ret = ret | temp
temp = new - ret
if not temp:
break
loop -= 1
return ret
used[0] = True
costs[0] = 0
break_flag = 0
que = [(clst[0], 0)]
while que and not break_flag:
next_cost, s_num = pop(que)
to_lst = make_to_lst(s_num)
for num in to_lst:
costs[num] = next_cost
if num == n - 1:
break_flag = 1
break
if not used[num]:
push(que, (costs[num] + clst[num], num))
used[num] = True
print(costs[n - 1])
``` | output | 1 | 49,557 | 1 | 99,115 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
problem
The IOI country consists of N towns from town 1 to town N, and the towns are connected by roads. The IOI country has K roads, all of which connect two different towns. Cars can move freely in both directions on the road, but they cannot go from one town to another through anything other than the road.
JOI, who lives in Town 1 of the IOI country, decided to take a taxi to his grandmother's house in Town N. There are N taxi companies in the IOI country, from taxi company 1 to taxi company N. Taxi companies in IOI have the following slightly special rules:
* You can take a taxi from taxi company i only in town i.
* The taxi fare of taxi company i is Ci regardless of the distance used.
* The taxi of taxi company i can only pass up to Ri roads in a row after boarding.
For example, if R1 = 2, if you take a taxi from town 1 to taxi company 1, you can only take up to 2 roads, so you need to change taxis in the middle of the town to go through 3 or more roads. ..
JOI cannot take or get off a taxi outside the town. Also, transportation other than taxis cannot be used. Create a program to find the minimum total fare required for JOI to reach town N.
input
The input consists of 1 + N + K lines.
On the first line, two integers N, K (2 ≤ N ≤ 5000, N -1 ≤ K ≤ 10000) are written separated by a blank. This means that the IOI country consists of N towns and the number of roads in the IOI country is K.
On the i-th line (1 ≤ i ≤ N) of the following N lines, two integers Ci and Ri (1 ≤ Ci ≤ 10000, 1 ≤ Ri ≤ N) are written separated by a blank. This means that the taxi fare of taxi company i is Ci, and you can only pass up to Ri roads in a row after boarding.
On the jth line (1 ≤ j ≤ K) of the following K lines, two different integers Aj and Bj (1 ≤ Aj <Bj ≤ N) are written separated by a blank. This means that there is a road between town Aj and town Bj. The same (Aj, Bj) pair has never been written more than once.
Given the input data, it is guaranteed that you can take a taxi from any town to any other town.
output
JOI Output an integer on one line that represents the minimum total fare required for you to travel from town 1 to town N.
Examples
Input
6 6
400 2
200 1
600 3
1000 1
300 5
700 4
1 2
2 3
3 6
4 6
1 5
2 4
Output
700
Input
None
Output
None
Submitted Solution:
```
def calcm(x):
gone = [set([x])]
for _ in range(a[x][1]):
gone.append(set())
for i in gone[-2]:
for j in link[i]:
for k in gone:
if j in k:
break
else:
gone[-1].add(j)
minq = []
for i in gone[1:]:
for j in i:
if cost[x] + a[x][0] < cost[j]:
cost[j] = cost[x] + a[x][0]
minq.append(j)
for i in minq:
calcm(i)
n, m = map(int, input().split())
a = [0] + [list(map(int, input().split())) for _ in range(n)]
link = [[] for _ in range(n + 1)]
cost = [1e10 for _ in range(n + 1)]
cost[1] = 0
for _ in range(m):
v1, v2 = map(int, input().split())
link[v1].append(v2)
link[v2].append(v1)
calcm(1)
print(cost[n])
``` | instruction | 0 | 49,558 | 1 | 99,116 |
No | output | 1 | 49,558 | 1 | 99,117 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
problem
The IOI country consists of N towns from town 1 to town N, and the towns are connected by roads. The IOI country has K roads, all of which connect two different towns. Cars can move freely in both directions on the road, but they cannot go from one town to another through anything other than the road.
JOI, who lives in Town 1 of the IOI country, decided to take a taxi to his grandmother's house in Town N. There are N taxi companies in the IOI country, from taxi company 1 to taxi company N. Taxi companies in IOI have the following slightly special rules:
* You can take a taxi from taxi company i only in town i.
* The taxi fare of taxi company i is Ci regardless of the distance used.
* The taxi of taxi company i can only pass up to Ri roads in a row after boarding.
For example, if R1 = 2, if you take a taxi from town 1 to taxi company 1, you can only take up to 2 roads, so you need to change taxis in the middle of the town to go through 3 or more roads. ..
JOI cannot take or get off a taxi outside the town. Also, transportation other than taxis cannot be used. Create a program to find the minimum total fare required for JOI to reach town N.
input
The input consists of 1 + N + K lines.
On the first line, two integers N, K (2 ≤ N ≤ 5000, N -1 ≤ K ≤ 10000) are written separated by a blank. This means that the IOI country consists of N towns and the number of roads in the IOI country is K.
On the i-th line (1 ≤ i ≤ N) of the following N lines, two integers Ci and Ri (1 ≤ Ci ≤ 10000, 1 ≤ Ri ≤ N) are written separated by a blank. This means that the taxi fare of taxi company i is Ci, and you can only pass up to Ri roads in a row after boarding.
On the jth line (1 ≤ j ≤ K) of the following K lines, two different integers Aj and Bj (1 ≤ Aj <Bj ≤ N) are written separated by a blank. This means that there is a road between town Aj and town Bj. The same (Aj, Bj) pair has never been written more than once.
Given the input data, it is guaranteed that you can take a taxi from any town to any other town.
output
JOI Output an integer on one line that represents the minimum total fare required for you to travel from town 1 to town N.
Examples
Input
6 6
400 2
200 1
600 3
1000 1
300 5
700 4
1 2
2 3
3 6
4 6
1 5
2 4
Output
700
Input
None
Output
None
Submitted Solution:
```
from heapq import heappop as pop
from heapq import heappush as push
INF = 10 ** 20
def main():
n, k = map(int, input().split())
clst = []
rlst = []
for i in range(n):
c, r = map(int, input().split())
clst.append(c)
rlst.append(r)
edges = [[] * n for i in range(n)]
for i in range(k):
a, b = map(int, input().split())
a -= 1
b -= 1
edges[a].append(b)
edges[b].append(a)
costs = [INF for i in range(n)]
costs[0] = 0
used = [False for i in range(n)]
def make_to_lst(s_num):
loop = rlst[s_num]
temp = {i for i in edges[s_num]}
ret = {i for i in temp}
while loop:
new = set()
for p in temp:
pto = {i for i in edges[p]}
new = new | pto
ret = ret | temp
temp = new - ret
if not temp:
break
loop -= 1
return ret
used[0] = True
costs[0] = 0
break_flag = 0
que = [(clst[0], 0)]
while que and not break_flag:
next_cost, s_num = pop(que)
to_lst = make_to_lst(s_num)
for num in to_lst:
costs[num] = next_cost
if num == n - 1:
break_flag = 1
break
if not used[num]:
push(que, (costs[num] + clst[num], num))
used[num] = True
print(costs[num - 1])
main()
``` | instruction | 0 | 49,559 | 1 | 99,118 |
No | output | 1 | 49,559 | 1 | 99,119 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
problem
The IOI country consists of N towns from town 1 to town N, and the towns are connected by roads. The IOI country has K roads, all of which connect two different towns. Cars can move freely in both directions on the road, but they cannot go from one town to another through anything other than the road.
JOI, who lives in Town 1 of the IOI country, decided to take a taxi to his grandmother's house in Town N. There are N taxi companies in the IOI country, from taxi company 1 to taxi company N. Taxi companies in IOI have the following slightly special rules:
* You can take a taxi from taxi company i only in town i.
* The taxi fare of taxi company i is Ci regardless of the distance used.
* The taxi of taxi company i can only pass up to Ri roads in a row after boarding.
For example, if R1 = 2, if you take a taxi from town 1 to taxi company 1, you can only take up to 2 roads, so you need to change taxis in the middle of the town to go through 3 or more roads. ..
JOI cannot take or get off a taxi outside the town. Also, transportation other than taxis cannot be used. Create a program to find the minimum total fare required for JOI to reach town N.
input
The input consists of 1 + N + K lines.
On the first line, two integers N, K (2 ≤ N ≤ 5000, N -1 ≤ K ≤ 10000) are written separated by a blank. This means that the IOI country consists of N towns and the number of roads in the IOI country is K.
On the i-th line (1 ≤ i ≤ N) of the following N lines, two integers Ci and Ri (1 ≤ Ci ≤ 10000, 1 ≤ Ri ≤ N) are written separated by a blank. This means that the taxi fare of taxi company i is Ci, and you can only pass up to Ri roads in a row after boarding.
On the jth line (1 ≤ j ≤ K) of the following K lines, two different integers Aj and Bj (1 ≤ Aj <Bj ≤ N) are written separated by a blank. This means that there is a road between town Aj and town Bj. The same (Aj, Bj) pair has never been written more than once.
Given the input data, it is guaranteed that you can take a taxi from any town to any other town.
output
JOI Output an integer on one line that represents the minimum total fare required for you to travel from town 1 to town N.
Examples
Input
6 6
400 2
200 1
600 3
1000 1
300 5
700 4
1 2
2 3
3 6
4 6
1 5
2 4
Output
700
Input
None
Output
None
Submitted Solution:
```
from heapq import heappop as pop
from heapq import heappush as push
INF = 10 ** 20
n, k = map(int, input().split())
clst = []
rlst = []
for i in range(n):
c, r = map(int, input().split())
clst.append(c)
rlst.append(r)
edges = [[0] * n for i in range(n)]
for i in range(k):
a, b = map(int, input().split())
a -= 1
b -= 1
edges[a][b] = edges[b][a] = 1
costs = [INF for i in range(n)]
costs[0] = 0
def make_to_lst(s_num):
loop = rlst[s_num]
temp = {i for i in range(n) if edges[s_num][i]}
ret = set()
while loop - 1:
new = set()
for p in temp:
pto = {i for i in range(n) if edges[p][i]}
new = new | pto
ret = ret | temp
temp = new - ret
loop -= 1
return ret
costs[0] = 0
break_flag = 0
que = [(clst[0], 0)]
while que and not break_flag:
next_cost, s_num = pop(que)
to_lst = make_to_lst(s_num)
for num in to_lst:
if costs[num] > next_cost:
costs[num] = next_cost
if num == n - 1:
break_flag = 1
break
push(que, (next_cost + clst[num], num))
print(costs[n - 1])
``` | instruction | 0 | 49,560 | 1 | 99,120 |
No | output | 1 | 49,560 | 1 | 99,121 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
problem
The IOI country consists of N towns from town 1 to town N, and the towns are connected by roads. The IOI country has K roads, all of which connect two different towns. Cars can move freely in both directions on the road, but they cannot go from one town to another through anything other than the road.
JOI, who lives in Town 1 of the IOI country, decided to take a taxi to his grandmother's house in Town N. There are N taxi companies in the IOI country, from taxi company 1 to taxi company N. Taxi companies in IOI have the following slightly special rules:
* You can take a taxi from taxi company i only in town i.
* The taxi fare of taxi company i is Ci regardless of the distance used.
* The taxi of taxi company i can only pass up to Ri roads in a row after boarding.
For example, if R1 = 2, if you take a taxi from town 1 to taxi company 1, you can only take up to 2 roads, so you need to change taxis in the middle of the town to go through 3 or more roads. ..
JOI cannot take or get off a taxi outside the town. Also, transportation other than taxis cannot be used. Create a program to find the minimum total fare required for JOI to reach town N.
input
The input consists of 1 + N + K lines.
On the first line, two integers N, K (2 ≤ N ≤ 5000, N -1 ≤ K ≤ 10000) are written separated by a blank. This means that the IOI country consists of N towns and the number of roads in the IOI country is K.
On the i-th line (1 ≤ i ≤ N) of the following N lines, two integers Ci and Ri (1 ≤ Ci ≤ 10000, 1 ≤ Ri ≤ N) are written separated by a blank. This means that the taxi fare of taxi company i is Ci, and you can only pass up to Ri roads in a row after boarding.
On the jth line (1 ≤ j ≤ K) of the following K lines, two different integers Aj and Bj (1 ≤ Aj <Bj ≤ N) are written separated by a blank. This means that there is a road between town Aj and town Bj. The same (Aj, Bj) pair has never been written more than once.
Given the input data, it is guaranteed that you can take a taxi from any town to any other town.
output
JOI Output an integer on one line that represents the minimum total fare required for you to travel from town 1 to town N.
Examples
Input
6 6
400 2
200 1
600 3
1000 1
300 5
700 4
1 2
2 3
3 6
4 6
1 5
2 4
Output
700
Input
None
Output
None
Submitted Solution:
```
from heapq import heappop as pop
from heapq import heappush as push
INF = 10 ** 20
n, k = map(int, input().split())
clst = []
rlst = []
for i in range(n):
c, r = map(int, input().split())
clst.append(c)
rlst.append(r)
edges = [[0] * n for i in range(n)]
for i in range(k):
a, b = map(int, input().split())
a -= 1
b -= 1
edges[a][b] = edges[b][a] = 1
costs = [INF for i in range(n)]
costs[0] = 0
used = [False for i in range(n)]
def make_to_lst(s_num):
loop = rlst[s_num]
temp = {i for i in range(n) if edges[s_num][i]}
ret = {i for i in temp}
while loop:
new = set()
for p in temp:
pto = {i for i in range(n) if edges[p][i]}
new = new | pto
ret = ret | temp
temp = new - ret
if not temp:
break
loop -= 1
return ret
used[0] = True
costs[0] = 0
break_flag = 0
que = [(clst[0], 0)]
while que and not break_flag:
next_cost, s_num = pop(que)
to_lst = make_to_lst(s_num)
for num in to_lst:
costs[num] = next_cost
if num == n - 1:
break_flag = 1
break
if not used[num]:
push(que, (costs[num] + clst[num], num))
used[num] = True
print(costs[n - 1])
print(costs)
``` | instruction | 0 | 49,561 | 1 | 99,122 |
No | output | 1 | 49,561 | 1 | 99,123 |
Provide a correct Python 3 solution for this coding contest problem.
Problem I Starting a Scenic Railroad Service
Jim, working for a railroad company, is responsible for planning a new tourist train service. He is sure that the train route along a scenic valley will arise a big boom, but not quite sure how big the boom will be.
A market survey was ordered and Jim has just received an estimated list of passengers' travel sections. Based on the list, he'd like to estimate the minimum number of train seats that meets the demand.
Providing as many seats as all of the passengers may cost unreasonably high. Assigning the same seat to more than one passenger without overlapping travel sections may lead to a great cost cutback.
Two different policies are considered on seat assignments. As the views from the train windows depend on the seat positions, it would be better if passengers can choose a seat. One possible policy (named `policy-1') is to allow the passengers to choose an arbitrary seat among all the remaining seats when they make their reservations. As the order of reservations is unknown, all the possible orders must be considered on counting the required number of seats.
The other policy (named `policy-2') does not allow the passengers to choose their seats; the seat assignments are decided by the railroad operator, not by the passengers, after all the reservations are completed. This policy may reduce the number of the required seats considerably.
Your task is to let Jim know how di erent these two policies are by providing him a program that computes the numbers of seats required under the two seat reservation policies. Let us consider a case where there are four stations, S1, S2, S3, and S4, and four expected passengers $p_1$, $p_2$, $p_3$, and $p_4$ with the travel list below.
passenger | from | to
---|---|---
$p_1$ | S1 | S2
$p_2$ | S2 | S3
$p_3$ | S1 | S3
$p_4$ | S3 | S4
The travel sections of $p_1$ and $p_2$ do not overlap, that of $p_3$ overlaps those of $p_1$ and $p_2$, and that of $p_4$ does not overlap those of any others.
Let's check if two seats would suffice under the policy-1. If $p_1$ books a seat first, either of the two seats can be chosen. If $p_2$ books second, as the travel section does not overlap that of $p_1$, the same seat can be booked, but the other seat may look more attractive to $p_2$. If $p_2$ reserves a seat different from that of $p_1$, there will remain no available seats for $p_3$ between S1 and S3 (Figure I.1).
<image>
Figure I.1. With two seats
With three seats, $p_3$ can find a seat with any seat reservation combinations by $p_1$ and $p_2$. $p_4$ can also book a seat for there are no other passengers between S3 and S4 (Figure I.2).
<image>
Figure I.2. With three seats
For this travel list, only three seats suffice considering all the possible reservation orders and seat preferences under the policy-1.
On the other hand, deciding the seat assignments after all the reservations are completed enables a tight assignment with only two seats under the policy-2 (Figure I.3).
<image>
Figure I.3. Tight assignment to two seats
Input
The input consists of a single test case of the following format.
$n$
$a_1$ $b_1$
...
$a_n$ $b_n$
Here, the first line has an integer $n$, the number of the passengers in the estimated list of passengers' travel sections ($1 \leq n \leq 200 000$). The stations are numbered starting from 1 in their order along the route. Each of the following $n$ lines describes the travel for each passenger by two integers, the boarding and the alighting station numbers, $a_i$ and $b_i$, respectively ($1 \leq a_i < b_i \leq 100 000$). Note that more than one passenger in the list may have the same boarding and alighting stations.
Output
Two integers $s_1$ and $s_2$ should be output in a line in this order, separated by a space. $s_1$ and $s_2$ are the numbers of seats required under the policy-1 and -2, respectively.
Sample Input 1
4
1 3
1 3
3 6
3 6
Sample Output 1
2 2
Sample Input 2
4
1 2
2 3
1 3
3 4
Sample Output 2
3 2
Sample Input 3
10
84 302
275 327
364 538
26 364
29 386
545 955
715 965
404 415
903 942
150 402
Sample Output 3
6 5
Example
Input
4
1 3
1 3
3 6
3 6
Output
2 2 | instruction | 0 | 49,564 | 1 | 99,128 |
"Correct Solution:
```
n = int(input())
ab = [list(map(int, input().split())) for _ in range(n)]
pol1 = 0
pol2 = 0
ft = [[0] * 2 for _ in range(100000)]
for i in ab:
ft[i[0] - 1][0] += 1
ft[i[1] - 1][1] += 1
ftsum = [[0] * 2 for _ in range(100000)]
ftsum[0][0] = ft[0][0]
for i in range(1, len(ft)):
ftsum[i][0] = ftsum[i-1][0] + ft[i][0]
ftsum[i][1] = ftsum[i-1][1] + ft[i][1]
for i in range(len(ft)-1):
pol2 = max(pol2, ftsum[i][0] - ftsum[i][1])
for f, t in ab:
f = f-1
t = t-1
temp = ftsum[t-1][0]
if f != 0:
temp -= ftsum[f][1]
pol1 = max(pol1, temp)
print(pol1, pol2)
``` | output | 1 | 49,564 | 1 | 99,129 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.