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.
Palo Alto is an unusual city because it is an endless coordinate line. It is also known for the office of Lyft Level 5.
Lyft has become so popular so that it is now used by all m taxi drivers in the city, who every day transport the rest of the city residents — n riders.
Each resident (including taxi drivers) of Palo-Alto lives in its unique location (there is no such pair of residents that their coordinates are the same).
The Lyft system is very clever: when a rider calls a taxi, his call does not go to all taxi drivers, but only to the one that is the closest to that person. If there are multiple ones with the same distance, then to taxi driver with a smaller coordinate is selected.
But one morning the taxi drivers wondered: how many riders are there that would call the given taxi driver if they were the first to order a taxi on that day? In other words, you need to find for each taxi driver i the number a_{i} — the number of riders that would call the i-th taxi driver when all drivers and riders are at their home?
The taxi driver can neither transport himself nor other taxi drivers.
Input
The first line contains two integers n and m (1 ≤ n,m ≤ 10^5) — number of riders and taxi drivers.
The second line contains n + m integers x_1, x_2, …, x_{n+m} (1 ≤ x_1 < x_2 < … < x_{n+m} ≤ 10^9), where x_i is the coordinate where the i-th resident lives.
The third line contains n + m integers t_1, t_2, …, t_{n+m} (0 ≤ t_i ≤ 1). If t_i = 1, then the i-th resident is a taxi driver, otherwise t_i = 0.
It is guaranteed that the number of i such that t_i = 1 is equal to m.
Output
Print m integers a_1, a_2, …, a_{m}, where a_i is the answer for the i-th taxi driver. The taxi driver has the number i if among all the taxi drivers he lives in the i-th smallest coordinate (see examples for better understanding).
Examples
Input
3 1
1 2 3 10
0 0 1 0
Output
3
Input
3 2
2 3 4 5 6
1 0 0 0 1
Output
2 1
Input
1 4
2 4 6 10 15
1 1 1 1 0
Output
0 0 0 1
Note
In the first example, we have only one taxi driver, which means an order from any of n riders will go to him.
In the second example, the first taxi driver lives at the point with the coordinate 2, and the second one lives at the point with the coordinate 6. Obviously, the nearest taxi driver to the rider who lives on the 3 coordinate is the first one, and to the rider who lives on the coordinate 5 is the second one. The rider who lives on the 4 coordinate has the same distance to the first and the second taxi drivers, but since the first taxi driver has a smaller coordinate, the call from this rider will go to the first taxi driver.
In the third example, we have one rider and the taxi driver nearest to him is the fourth one.
Submitted Solution:
```
def find_drivers_answers(n, m, coordinates, is_driver):
if m == 1:
return [n]
results = [0] * m
# print (is_driver)
drivers_coordinates = [coordinates[x] for x in range (n+m) if is_driver[x]]
riders_coordinates = [coordinates[x] for x in range (n+m) if not is_driver[x]]
# print (drivers_coordinates)
# print (riders_coordinates)
left_driver, right_driver = get_bounds(drivers_coordinates, riders_coordinates[0])
left_driver_idx = drivers_coordinates.index(left_driver)
for rider in riders_coordinates:
left_dist = abs(left_driver - rider)
right_dist = abs(right_driver - rider)
if left_dist > right_dist:
left_driver = right_driver
left_driver_idx, right_driver = get_next_driver(left_driver_idx, drivers_coordinates, m)
results[left_driver_idx] += 1
return results
def get_bounds(drivers_coordinates, first_rider):
if drivers_coordinates[0] > first_rider:
return drivers_coordinates[0], drivers_coordinates[1]
if drivers_coordinates[-1] <= first_rider:
return drivers_coordinates[-2], drivers_coordinates[-1]
smaller_equal = list(filter(lambda x: x <= first_rider, drivers_coordinates))
greater = list(filter(lambda x: x > first_rider, drivers_coordinates))
return smaller_equal[-1], greater[0]
def get_next_driver(left_driver_idx, drivers_coordinates, m):
next_idx = left_driver_idx +1
if left_driver_idx + 2 == m:
return next_idx, -1
# print(next_idx)
return next_idx, drivers_coordinates[next_idx+1]
n, m = [int(a) for a in input().split()]
coordinates = [int(a) for a in input().split()] # len = n+m
is_driver = [a == "1" for a in input().split()] # len = n+m
results = find_drivers_answers(n, m, coordinates, is_driver)
print(" ".join([str(x) for x in results]))
``` | instruction | 0 | 33,368 | 1 | 66,736 |
No | output | 1 | 33,368 | 1 | 66,737 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day Bob got a letter in an envelope. Bob knows that when Berland's post officers send a letter directly from city «A» to city «B», they stamp it with «A B», or «B A». Unfortunately, often it is impossible to send a letter directly from the city of the sender to the city of the receiver, that's why the letter is sent via some intermediate cities. Post officers never send a letter in such a way that the route of this letter contains some city more than once. Bob is sure that the post officers stamp the letters accurately.
There are n stamps on the envelope of Bob's letter. He understands that the possible routes of this letter are only two. But the stamps are numerous, and Bob can't determine himself none of these routes. That's why he asks you to help him. Find one of the possible routes of the letter.
Input
The first line contains integer n (1 ≤ n ≤ 105) — amount of mail stamps on the envelope. Then there follow n lines with two integers each — description of the stamps. Each stamp is described with indexes of the cities between which a letter is sent. The indexes of cities are integers from 1 to 109. Indexes of all the cities are different. Every time the letter is sent from one city to another, exactly one stamp is put on the envelope. It is guaranteed that the given stamps correspond to some valid route from some city to some other city.
Output
Output n + 1 numbers — indexes of cities in one of the two possible routes of the letter.
Examples
Input
2
1 100
100 2
Output
2 100 1
Input
3
3 1
100 2
3 2
Output
100 2 3 1 | instruction | 0 | 33,678 | 1 | 67,356 |
Tags: data structures, dfs and similar, graphs, implementation
Correct Solution:
```
dic = {}
for notused in range(int(input())):
i1, i2 = list(map(int, input().split(" ")))
if i1 in dic: dic[i1].append(i2)
else: dic[i1] = [i2]
if i2 in dic: dic[i2].append(i1)
else: dic[i2] = [i1]
start,end = -1,-1
for key in dic.keys():
if len(dic[key]) == 1:
if start == -1: start = key
else: end = key
seq = start
prev = -1
print(seq, end=' ')
while seq != end:
arr = dic[seq]
if arr[0] != prev: temp = arr[0]
else: temp = arr[1]
prev,seq = seq,temp
print(seq, end =' ')
print()
``` | output | 1 | 33,678 | 1 | 67,357 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day Bob got a letter in an envelope. Bob knows that when Berland's post officers send a letter directly from city «A» to city «B», they stamp it with «A B», or «B A». Unfortunately, often it is impossible to send a letter directly from the city of the sender to the city of the receiver, that's why the letter is sent via some intermediate cities. Post officers never send a letter in such a way that the route of this letter contains some city more than once. Bob is sure that the post officers stamp the letters accurately.
There are n stamps on the envelope of Bob's letter. He understands that the possible routes of this letter are only two. But the stamps are numerous, and Bob can't determine himself none of these routes. That's why he asks you to help him. Find one of the possible routes of the letter.
Input
The first line contains integer n (1 ≤ n ≤ 105) — amount of mail stamps on the envelope. Then there follow n lines with two integers each — description of the stamps. Each stamp is described with indexes of the cities between which a letter is sent. The indexes of cities are integers from 1 to 109. Indexes of all the cities are different. Every time the letter is sent from one city to another, exactly one stamp is put on the envelope. It is guaranteed that the given stamps correspond to some valid route from some city to some other city.
Output
Output n + 1 numbers — indexes of cities in one of the two possible routes of the letter.
Examples
Input
2
1 100
100 2
Output
2 100 1
Input
3
3 1
100 2
3 2
Output
100 2 3 1 | instruction | 0 | 33,679 | 1 | 67,358 |
Tags: data structures, dfs and similar, graphs, implementation
Correct Solution:
```
n = int(input())
edges = {}
for _ in range(n):
a, b = map(int, input().split())
if a in edges:
edges[a] += [b]
else:
edges[a] = [b]
if b in edges:
edges[b] += [a]
else:
edges[b] = [a]
route = []
for key, val in edges.items():
route = [key, val[0]]
break
while len(route) < n + 1:
if len(edges[route[-1]]) == 1:
route.reverse()
else:
if edges[route[-1]][0] == route[-2]:
route += [edges[route[-1]][1]]
else:
route += [edges[route[-1]][0]]
print(' '.join(map(str, route)))
``` | output | 1 | 33,679 | 1 | 67,359 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day Bob got a letter in an envelope. Bob knows that when Berland's post officers send a letter directly from city «A» to city «B», they stamp it with «A B», or «B A». Unfortunately, often it is impossible to send a letter directly from the city of the sender to the city of the receiver, that's why the letter is sent via some intermediate cities. Post officers never send a letter in such a way that the route of this letter contains some city more than once. Bob is sure that the post officers stamp the letters accurately.
There are n stamps on the envelope of Bob's letter. He understands that the possible routes of this letter are only two. But the stamps are numerous, and Bob can't determine himself none of these routes. That's why he asks you to help him. Find one of the possible routes of the letter.
Input
The first line contains integer n (1 ≤ n ≤ 105) — amount of mail stamps on the envelope. Then there follow n lines with two integers each — description of the stamps. Each stamp is described with indexes of the cities between which a letter is sent. The indexes of cities are integers from 1 to 109. Indexes of all the cities are different. Every time the letter is sent from one city to another, exactly one stamp is put on the envelope. It is guaranteed that the given stamps correspond to some valid route from some city to some other city.
Output
Output n + 1 numbers — indexes of cities in one of the two possible routes of the letter.
Examples
Input
2
1 100
100 2
Output
2 100 1
Input
3
3 1
100 2
3 2
Output
100 2 3 1 | instruction | 0 | 33,680 | 1 | 67,360 |
Tags: data structures, dfs and similar, graphs, implementation
Correct Solution:
```
n=int(input())
d={}
for i in range(n):
a,b=map(int,input().split())
if a in d:
d[a].append(b)
else:
d[a]=[b]
if b in d:
d[b].append(a)
else:
d[b]=[a]
ans=[]
for el in d:
if len(d[el])==1:
ans.append(el)
root=el
break
cur=root
while True:
for el in d[cur]:
if el==ans[-1]:continue
if cur!=root:ans.append(cur)
cur=el
break
if len(d[cur])==1:
ans.append(cur)
break
print(*ans)
``` | output | 1 | 33,680 | 1 | 67,361 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day Bob got a letter in an envelope. Bob knows that when Berland's post officers send a letter directly from city «A» to city «B», they stamp it with «A B», or «B A». Unfortunately, often it is impossible to send a letter directly from the city of the sender to the city of the receiver, that's why the letter is sent via some intermediate cities. Post officers never send a letter in such a way that the route of this letter contains some city more than once. Bob is sure that the post officers stamp the letters accurately.
There are n stamps on the envelope of Bob's letter. He understands that the possible routes of this letter are only two. But the stamps are numerous, and Bob can't determine himself none of these routes. That's why he asks you to help him. Find one of the possible routes of the letter.
Input
The first line contains integer n (1 ≤ n ≤ 105) — amount of mail stamps on the envelope. Then there follow n lines with two integers each — description of the stamps. Each stamp is described with indexes of the cities between which a letter is sent. The indexes of cities are integers from 1 to 109. Indexes of all the cities are different. Every time the letter is sent from one city to another, exactly one stamp is put on the envelope. It is guaranteed that the given stamps correspond to some valid route from some city to some other city.
Output
Output n + 1 numbers — indexes of cities in one of the two possible routes of the letter.
Examples
Input
2
1 100
100 2
Output
2 100 1
Input
3
3 1
100 2
3 2
Output
100 2 3 1 | instruction | 0 | 33,681 | 1 | 67,362 |
Tags: data structures, dfs and similar, graphs, implementation
Correct Solution:
```
# ------------------------------warmup----------------------------
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")
n=int(input())
d=dict()
a=[]
for j in range(n):
x,y=map(int,input().split())
if x in d.keys():
d[x].append(y)
else:
a.append(x)
d[x]=[y]
if y in d.keys():
d[y].append(x)
else:
a.append(y)
d[y] = [x]
r=len(a)
for j in range(r):
if len(d[a[j]])==1:
k=a[j]
break
c=[]
s=[k]
v=dict()
while(s):
p=s.pop()
v[p]=1
c.append(p)
if p!=k and len(d[p])==1:
break
if d[p][0] in v.keys():
s.append(d[p][1])
else:
s.append(d[p][0])
print(*c)
``` | output | 1 | 33,681 | 1 | 67,363 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day Bob got a letter in an envelope. Bob knows that when Berland's post officers send a letter directly from city «A» to city «B», they stamp it with «A B», or «B A». Unfortunately, often it is impossible to send a letter directly from the city of the sender to the city of the receiver, that's why the letter is sent via some intermediate cities. Post officers never send a letter in such a way that the route of this letter contains some city more than once. Bob is sure that the post officers stamp the letters accurately.
There are n stamps on the envelope of Bob's letter. He understands that the possible routes of this letter are only two. But the stamps are numerous, and Bob can't determine himself none of these routes. That's why he asks you to help him. Find one of the possible routes of the letter.
Input
The first line contains integer n (1 ≤ n ≤ 105) — amount of mail stamps on the envelope. Then there follow n lines with two integers each — description of the stamps. Each stamp is described with indexes of the cities between which a letter is sent. The indexes of cities are integers from 1 to 109. Indexes of all the cities are different. Every time the letter is sent from one city to another, exactly one stamp is put on the envelope. It is guaranteed that the given stamps correspond to some valid route from some city to some other city.
Output
Output n + 1 numbers — indexes of cities in one of the two possible routes of the letter.
Examples
Input
2
1 100
100 2
Output
2 100 1
Input
3
3 1
100 2
3 2
Output
100 2 3 1 | instruction | 0 | 33,682 | 1 | 67,364 |
Tags: data structures, dfs and similar, graphs, implementation
Correct Solution:
```
n = int(input())
p = [0] * n
d, t = {}, {}
for i in range(n):
for x in map(int, input().split()):
t[x], d[x] = (0, d[x] + i) if x in d else (1, i)
p[i] += x
x, q = (y for y in t if t[y])
s = [x]
while x != q:
y = p[d[x]] - x
s += [y]
d[y] -= d[x]
x = y
for q in s: print(q)
``` | output | 1 | 33,682 | 1 | 67,365 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day Bob got a letter in an envelope. Bob knows that when Berland's post officers send a letter directly from city «A» to city «B», they stamp it with «A B», or «B A». Unfortunately, often it is impossible to send a letter directly from the city of the sender to the city of the receiver, that's why the letter is sent via some intermediate cities. Post officers never send a letter in such a way that the route of this letter contains some city more than once. Bob is sure that the post officers stamp the letters accurately.
There are n stamps on the envelope of Bob's letter. He understands that the possible routes of this letter are only two. But the stamps are numerous, and Bob can't determine himself none of these routes. That's why he asks you to help him. Find one of the possible routes of the letter.
Input
The first line contains integer n (1 ≤ n ≤ 105) — amount of mail stamps on the envelope. Then there follow n lines with two integers each — description of the stamps. Each stamp is described with indexes of the cities between which a letter is sent. The indexes of cities are integers from 1 to 109. Indexes of all the cities are different. Every time the letter is sent from one city to another, exactly one stamp is put on the envelope. It is guaranteed that the given stamps correspond to some valid route from some city to some other city.
Output
Output n + 1 numbers — indexes of cities in one of the two possible routes of the letter.
Examples
Input
2
1 100
100 2
Output
2 100 1
Input
3
3 1
100 2
3 2
Output
100 2 3 1 | instruction | 0 | 33,683 | 1 | 67,366 |
Tags: data structures, dfs and similar, graphs, implementation
Correct Solution:
```
import sys
from array import array # noqa: F401
from collections import defaultdict
def input():
return sys.stdin.buffer.readline().decode('utf-8')
n = int(input())
adj = defaultdict(list)
deg = defaultdict(int)
for _ in range(n):
u, v = map(int, input().split())
adj[u].append(v)
adj[v].append(u)
deg[u] += 1
deg[v] += 1
v = -1
for key, val in deg.items():
if val == 1:
v = key
break
ans = []
while True:
ans.append(v)
deg[v] = 0
for dest in adj[v]:
if deg[dest]:
deg[dest] = 0
v = dest
break
else:
break
print(*ans)
``` | output | 1 | 33,683 | 1 | 67,367 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day Bob got a letter in an envelope. Bob knows that when Berland's post officers send a letter directly from city «A» to city «B», they stamp it with «A B», or «B A». Unfortunately, often it is impossible to send a letter directly from the city of the sender to the city of the receiver, that's why the letter is sent via some intermediate cities. Post officers never send a letter in such a way that the route of this letter contains some city more than once. Bob is sure that the post officers stamp the letters accurately.
There are n stamps on the envelope of Bob's letter. He understands that the possible routes of this letter are only two. But the stamps are numerous, and Bob can't determine himself none of these routes. That's why he asks you to help him. Find one of the possible routes of the letter.
Input
The first line contains integer n (1 ≤ n ≤ 105) — amount of mail stamps on the envelope. Then there follow n lines with two integers each — description of the stamps. Each stamp is described with indexes of the cities between which a letter is sent. The indexes of cities are integers from 1 to 109. Indexes of all the cities are different. Every time the letter is sent from one city to another, exactly one stamp is put on the envelope. It is guaranteed that the given stamps correspond to some valid route from some city to some other city.
Output
Output n + 1 numbers — indexes of cities in one of the two possible routes of the letter.
Examples
Input
2
1 100
100 2
Output
2 100 1
Input
3
3 1
100 2
3 2
Output
100 2 3 1 | instruction | 0 | 33,684 | 1 | 67,368 |
Tags: data structures, dfs and similar, graphs, implementation
Correct Solution:
```
import sys
from collections import deque
input = sys.stdin.readline
g={}
v=set()
for _ in range(int(input())):
a,b=[int(x) for x in input().split()]
if a in v:
v.remove(a)
else:
v.add(a)
if b in v:
v.remove(b)
else:
v.add(b)
if a in g:
g[a].append(b)
else:
g[a]=[b]
if b in g:
g[b].append(a)
else:
g[b]=[a]
#g[b]=a
ans=[]
for i in v:
q=deque([[i,-1]])
while q:
curr,par=q.popleft()
ans.append(curr)
for i in g[curr]:
if i!=par:
q.append([i,curr])
break
print(*ans)
``` | output | 1 | 33,684 | 1 | 67,369 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day Bob got a letter in an envelope. Bob knows that when Berland's post officers send a letter directly from city «A» to city «B», they stamp it with «A B», or «B A». Unfortunately, often it is impossible to send a letter directly from the city of the sender to the city of the receiver, that's why the letter is sent via some intermediate cities. Post officers never send a letter in such a way that the route of this letter contains some city more than once. Bob is sure that the post officers stamp the letters accurately.
There are n stamps on the envelope of Bob's letter. He understands that the possible routes of this letter are only two. But the stamps are numerous, and Bob can't determine himself none of these routes. That's why he asks you to help him. Find one of the possible routes of the letter.
Input
The first line contains integer n (1 ≤ n ≤ 105) — amount of mail stamps on the envelope. Then there follow n lines with two integers each — description of the stamps. Each stamp is described with indexes of the cities between which a letter is sent. The indexes of cities are integers from 1 to 109. Indexes of all the cities are different. Every time the letter is sent from one city to another, exactly one stamp is put on the envelope. It is guaranteed that the given stamps correspond to some valid route from some city to some other city.
Output
Output n + 1 numbers — indexes of cities in one of the two possible routes of the letter.
Examples
Input
2
1 100
100 2
Output
2 100 1
Input
3
3 1
100 2
3 2
Output
100 2 3 1 | instruction | 0 | 33,685 | 1 | 67,370 |
Tags: data structures, dfs and similar, graphs, implementation
Correct Solution:
```
from collections import defaultdict, Counter
class Solution:
def __init__(self):
pass
def solve_and_print(self):
d, c = defaultdict(int), []
for _ in range(int(input())):
x, y = [int(x) for x in input().split()]
c += [x, y]
d[x] += y
d[y] += x
a, b = [q for q, k in Counter(c).items() if k == 1]
q = 0
while a != b:
print(a, end=' ')
q, a = a, d[a] - q
print(a, end=' ')
if __name__ == "__main__":
Solution().solve_and_print()
``` | output | 1 | 33,685 | 1 | 67,371 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day Bob got a letter in an envelope. Bob knows that when Berland's post officers send a letter directly from city «A» to city «B», they stamp it with «A B», or «B A». Unfortunately, often it is impossible to send a letter directly from the city of the sender to the city of the receiver, that's why the letter is sent via some intermediate cities. Post officers never send a letter in such a way that the route of this letter contains some city more than once. Bob is sure that the post officers stamp the letters accurately.
There are n stamps on the envelope of Bob's letter. He understands that the possible routes of this letter are only two. But the stamps are numerous, and Bob can't determine himself none of these routes. That's why he asks you to help him. Find one of the possible routes of the letter.
Input
The first line contains integer n (1 ≤ n ≤ 105) — amount of mail stamps on the envelope. Then there follow n lines with two integers each — description of the stamps. Each stamp is described with indexes of the cities between which a letter is sent. The indexes of cities are integers from 1 to 109. Indexes of all the cities are different. Every time the letter is sent from one city to another, exactly one stamp is put on the envelope. It is guaranteed that the given stamps correspond to some valid route from some city to some other city.
Output
Output n + 1 numbers — indexes of cities in one of the two possible routes of the letter.
Examples
Input
2
1 100
100 2
Output
2 100 1
Input
3
3 1
100 2
3 2
Output
100 2 3 1
Submitted Solution:
```
from collections import defaultdict
from typing import List, Tuple
def solve(n: int, stamps: List[Tuple[int, int]]) -> str:
visited = set() # type: Set
graph = defaultdict(list) # type: Dict[int, List[int]]
path = [] # type: List[int]
for u, v in stamps:
graph[u].append(v)
graph[v].append(u)
start = [node for node in graph if len(graph[node]) == 1][0]
stack = [start]
while stack:
curr = stack.pop()
visited.add(curr)
path.append(curr)
for adj_node in graph[curr]:
if adj_node not in visited:
stack.append(adj_node)
return ' '.join(map(str, path))
n = int(input())
stamps = [tuple(map(int, input().split())) for _ in range(n)]
print(solve(n, stamps))
``` | instruction | 0 | 33,686 | 1 | 67,372 |
Yes | output | 1 | 33,686 | 1 | 67,373 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day Bob got a letter in an envelope. Bob knows that when Berland's post officers send a letter directly from city «A» to city «B», they stamp it with «A B», or «B A». Unfortunately, often it is impossible to send a letter directly from the city of the sender to the city of the receiver, that's why the letter is sent via some intermediate cities. Post officers never send a letter in such a way that the route of this letter contains some city more than once. Bob is sure that the post officers stamp the letters accurately.
There are n stamps on the envelope of Bob's letter. He understands that the possible routes of this letter are only two. But the stamps are numerous, and Bob can't determine himself none of these routes. That's why he asks you to help him. Find one of the possible routes of the letter.
Input
The first line contains integer n (1 ≤ n ≤ 105) — amount of mail stamps on the envelope. Then there follow n lines with two integers each — description of the stamps. Each stamp is described with indexes of the cities between which a letter is sent. The indexes of cities are integers from 1 to 109. Indexes of all the cities are different. Every time the letter is sent from one city to another, exactly one stamp is put on the envelope. It is guaranteed that the given stamps correspond to some valid route from some city to some other city.
Output
Output n + 1 numbers — indexes of cities in one of the two possible routes of the letter.
Examples
Input
2
1 100
100 2
Output
2 100 1
Input
3
3 1
100 2
3 2
Output
100 2 3 1
Submitted Solution:
```
#------------------------------warmup----------------------------
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")
#-------------------game starts now-----------------------------------------------------
n=int(input())
d=dict()
a=[[0 for i in range(2)]for j in range(n)]
for i in range(n):
a[i][0],a[i][1]=map(int,input().split())
if a[i][0] not in d:
d.update({a[i][0]:[i]})
else:
d[a[i][0]].append(i)
if a[i][1] not in d:
d.update({a[i][1]:[i]})
else:
d[a[i][1]].append(i)
ans=[0]*(n+1)
end=0
start=0
for i in d:
if len(d[i])==1 and ans[0]==0:
ans[0]=i
start=d[i][0]
elif len(d[i])==1:
ans[n]=i
end=d[i][0]
break
for j in range(1,n):
for i in range(2):
if a[start][i]!=ans[j-1]:
ans[j]=a[start][i]
for k in range(2):
if start!=d[a[start][i]][k]:
start=d[a[start][i]][k]
break
break
print(*ans,sep=" ")
``` | instruction | 0 | 33,687 | 1 | 67,374 |
Yes | output | 1 | 33,687 | 1 | 67,375 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day Bob got a letter in an envelope. Bob knows that when Berland's post officers send a letter directly from city «A» to city «B», they stamp it with «A B», or «B A». Unfortunately, often it is impossible to send a letter directly from the city of the sender to the city of the receiver, that's why the letter is sent via some intermediate cities. Post officers never send a letter in such a way that the route of this letter contains some city more than once. Bob is sure that the post officers stamp the letters accurately.
There are n stamps on the envelope of Bob's letter. He understands that the possible routes of this letter are only two. But the stamps are numerous, and Bob can't determine himself none of these routes. That's why he asks you to help him. Find one of the possible routes of the letter.
Input
The first line contains integer n (1 ≤ n ≤ 105) — amount of mail stamps on the envelope. Then there follow n lines with two integers each — description of the stamps. Each stamp is described with indexes of the cities between which a letter is sent. The indexes of cities are integers from 1 to 109. Indexes of all the cities are different. Every time the letter is sent from one city to another, exactly one stamp is put on the envelope. It is guaranteed that the given stamps correspond to some valid route from some city to some other city.
Output
Output n + 1 numbers — indexes of cities in one of the two possible routes of the letter.
Examples
Input
2
1 100
100 2
Output
2 100 1
Input
3
3 1
100 2
3 2
Output
100 2 3 1
Submitted Solution:
```
n = int(input())
d = {}
from sys import stdin
for i in range(n):
a,b = map(int,input().split())
if d.get(a)==None:d[a]=[]
if d.get(b)==None:d[b]=[]
d[a].append(b)
d[b].append(a)
for i,item in enumerate(d):
if len(d[item])==1:
break
res = [item]
prev=item
item=d[item][0]
for i in range(n-1):
res.append(item)
x,y = d[item][0],d[item][1]
if x==prev:prev=item;item=y
else:prev=item;item=x
res.append(item)
print(*res)
``` | instruction | 0 | 33,688 | 1 | 67,376 |
Yes | output | 1 | 33,688 | 1 | 67,377 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day Bob got a letter in an envelope. Bob knows that when Berland's post officers send a letter directly from city «A» to city «B», they stamp it with «A B», or «B A». Unfortunately, often it is impossible to send a letter directly from the city of the sender to the city of the receiver, that's why the letter is sent via some intermediate cities. Post officers never send a letter in such a way that the route of this letter contains some city more than once. Bob is sure that the post officers stamp the letters accurately.
There are n stamps on the envelope of Bob's letter. He understands that the possible routes of this letter are only two. But the stamps are numerous, and Bob can't determine himself none of these routes. That's why he asks you to help him. Find one of the possible routes of the letter.
Input
The first line contains integer n (1 ≤ n ≤ 105) — amount of mail stamps on the envelope. Then there follow n lines with two integers each — description of the stamps. Each stamp is described with indexes of the cities between which a letter is sent. The indexes of cities are integers from 1 to 109. Indexes of all the cities are different. Every time the letter is sent from one city to another, exactly one stamp is put on the envelope. It is guaranteed that the given stamps correspond to some valid route from some city to some other city.
Output
Output n + 1 numbers — indexes of cities in one of the two possible routes of the letter.
Examples
Input
2
1 100
100 2
Output
2 100 1
Input
3
3 1
100 2
3 2
Output
100 2 3 1
Submitted Solution:
```
from collections import *
d, c = defaultdict(int), []
for i in range(int(input())):
x, y = map(int, input().split())
c += [x, y]
d[x] += y
d[y] += x
a, b = [q for q, k in Counter(c).items() if k == 1]
q = 0
while a != b:
print(a)
q, a = a, d[a] - q
print(a)
``` | instruction | 0 | 33,689 | 1 | 67,378 |
Yes | output | 1 | 33,689 | 1 | 67,379 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day Bob got a letter in an envelope. Bob knows that when Berland's post officers send a letter directly from city «A» to city «B», they stamp it with «A B», or «B A». Unfortunately, often it is impossible to send a letter directly from the city of the sender to the city of the receiver, that's why the letter is sent via some intermediate cities. Post officers never send a letter in such a way that the route of this letter contains some city more than once. Bob is sure that the post officers stamp the letters accurately.
There are n stamps on the envelope of Bob's letter. He understands that the possible routes of this letter are only two. But the stamps are numerous, and Bob can't determine himself none of these routes. That's why he asks you to help him. Find one of the possible routes of the letter.
Input
The first line contains integer n (1 ≤ n ≤ 105) — amount of mail stamps on the envelope. Then there follow n lines with two integers each — description of the stamps. Each stamp is described with indexes of the cities between which a letter is sent. The indexes of cities are integers from 1 to 109. Indexes of all the cities are different. Every time the letter is sent from one city to another, exactly one stamp is put on the envelope. It is guaranteed that the given stamps correspond to some valid route from some city to some other city.
Output
Output n + 1 numbers — indexes of cities in one of the two possible routes of the letter.
Examples
Input
2
1 100
100 2
Output
2 100 1
Input
3
3 1
100 2
3 2
Output
100 2 3 1
Submitted Solution:
```
def occurredOnce(arr):
n = len(arr)
mp = dict()
l1 = []
for i in range(n):
if arr[i] in mp.keys():
mp[arr[i]] += 1
else:
mp[arr[i]] = 1
for it in mp:
if mp[it] == 1:
l1.append(it)
return l1
n = input()
n = int(n)
d = {}
l = []
ans = []
for i in range(n):
line = input()
a, b = line.split()
a = int(a)
b = int(b)
if a in d:
d[a].append(b)
else:
d[a] = [b]
if b in d:
d[b].append(a)
else:
d[b] = [a]
l.append(a)
l.append(b)
ul = occurredOnce(l)
ans.append(ul[1])
x = ul[1]
while True:
for i in d[x]:
if i != x:
ans.append(ul[1])
d[i].remove(x)
x = i
break
if i in ul:
break
for i in ans:
print(i)
``` | instruction | 0 | 33,690 | 1 | 67,380 |
No | output | 1 | 33,690 | 1 | 67,381 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day Bob got a letter in an envelope. Bob knows that when Berland's post officers send a letter directly from city «A» to city «B», they stamp it with «A B», or «B A». Unfortunately, often it is impossible to send a letter directly from the city of the sender to the city of the receiver, that's why the letter is sent via some intermediate cities. Post officers never send a letter in such a way that the route of this letter contains some city more than once. Bob is sure that the post officers stamp the letters accurately.
There are n stamps on the envelope of Bob's letter. He understands that the possible routes of this letter are only two. But the stamps are numerous, and Bob can't determine himself none of these routes. That's why he asks you to help him. Find one of the possible routes of the letter.
Input
The first line contains integer n (1 ≤ n ≤ 105) — amount of mail stamps on the envelope. Then there follow n lines with two integers each — description of the stamps. Each stamp is described with indexes of the cities between which a letter is sent. The indexes of cities are integers from 1 to 109. Indexes of all the cities are different. Every time the letter is sent from one city to another, exactly one stamp is put on the envelope. It is guaranteed that the given stamps correspond to some valid route from some city to some other city.
Output
Output n + 1 numbers — indexes of cities in one of the two possible routes of the letter.
Examples
Input
2
1 100
100 2
Output
2 100 1
Input
3
3 1
100 2
3 2
Output
100 2 3 1
Submitted Solution:
```
n=int(input())
Graph={}
for i in range(n):
input_=[int(i) for i in input().split(' ')]
if input_[0] in Graph:
Graph[input_[0]].append(input_[1])
else:
Graph[input_[0]]=[input_[1]]
if input_[1] in Graph:
Graph[input_[1]].append(input_[0])
else:
Graph[input_[1]]=[input_[0]]
vertice_begin=input_[1]
answer=[]
answer.append(vertice_begin)
curr=Graph[vertice_begin][0]
answer.append(curr)
while(len(Graph[curr])>1):
for i in range(len(Graph[curr])):
if Graph[curr][i] not in answer:
curr_=Graph[curr][i]
answer.append(curr_)
curr=curr_
print(' '.join([str(i) for i in answer]))
``` | instruction | 0 | 33,691 | 1 | 67,382 |
No | output | 1 | 33,691 | 1 | 67,383 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day Bob got a letter in an envelope. Bob knows that when Berland's post officers send a letter directly from city «A» to city «B», they stamp it with «A B», or «B A». Unfortunately, often it is impossible to send a letter directly from the city of the sender to the city of the receiver, that's why the letter is sent via some intermediate cities. Post officers never send a letter in such a way that the route of this letter contains some city more than once. Bob is sure that the post officers stamp the letters accurately.
There are n stamps on the envelope of Bob's letter. He understands that the possible routes of this letter are only two. But the stamps are numerous, and Bob can't determine himself none of these routes. That's why he asks you to help him. Find one of the possible routes of the letter.
Input
The first line contains integer n (1 ≤ n ≤ 105) — amount of mail stamps on the envelope. Then there follow n lines with two integers each — description of the stamps. Each stamp is described with indexes of the cities between which a letter is sent. The indexes of cities are integers from 1 to 109. Indexes of all the cities are different. Every time the letter is sent from one city to another, exactly one stamp is put on the envelope. It is guaranteed that the given stamps correspond to some valid route from some city to some other city.
Output
Output n + 1 numbers — indexes of cities in one of the two possible routes of the letter.
Examples
Input
2
1 100
100 2
Output
2 100 1
Input
3
3 1
100 2
3 2
Output
100 2 3 1
Submitted Solution:
```
from collections import defaultdict
class Solution:
def __init__(self):
self.n = int(input())
self.stamp_description = [[] for _ in range(self.n)]
for i in range(self.n):
self.stamp_description[i] = [int(x) for x in input().split()]
def solve_and_print(self):
tree = Tree(self.n, self.stamp_description)
path = []
for cities in self.stamp_description:
for root in cities:
path = tree.create_path([], defaultdict(bool), root)
if len(path) == tree.n:
print(*path)
return
class Tree:
def __init__(self, n, tree):
self.n = n + 1
self.tree = defaultdict(list)
for vertices in tree:
u, v = vertices
self.tree[u].append(v)
self.tree[v].append(u)
def create_path(self, output, visited, curr):
if visited[curr]:
return output
visited[curr] = True
output.append(curr)
for child in self.tree[curr]:
self.create_path(output, visited, child)
return output
if __name__ == "__main__":
Solution().solve_and_print()
``` | instruction | 0 | 33,692 | 1 | 67,384 |
No | output | 1 | 33,692 | 1 | 67,385 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day Bob got a letter in an envelope. Bob knows that when Berland's post officers send a letter directly from city «A» to city «B», they stamp it with «A B», or «B A». Unfortunately, often it is impossible to send a letter directly from the city of the sender to the city of the receiver, that's why the letter is sent via some intermediate cities. Post officers never send a letter in such a way that the route of this letter contains some city more than once. Bob is sure that the post officers stamp the letters accurately.
There are n stamps on the envelope of Bob's letter. He understands that the possible routes of this letter are only two. But the stamps are numerous, and Bob can't determine himself none of these routes. That's why he asks you to help him. Find one of the possible routes of the letter.
Input
The first line contains integer n (1 ≤ n ≤ 105) — amount of mail stamps on the envelope. Then there follow n lines with two integers each — description of the stamps. Each stamp is described with indexes of the cities between which a letter is sent. The indexes of cities are integers from 1 to 109. Indexes of all the cities are different. Every time the letter is sent from one city to another, exactly one stamp is put on the envelope. It is guaranteed that the given stamps correspond to some valid route from some city to some other city.
Output
Output n + 1 numbers — indexes of cities in one of the two possible routes of the letter.
Examples
Input
2
1 100
100 2
Output
2 100 1
Input
3
3 1
100 2
3 2
Output
100 2 3 1
Submitted Solution:
```
def solve(pairs):
mp = dict()
values = set()
for pair in pairs:
if pair[0] in mp or pair[1] in values:
mp[pair[1]] = pair[0]
values.add(pair[0])
else:
mp[pair[0]] = pair[1]
values.add(pair[1])
beg = None
values = set(mp.values())
for key in mp:
if key not in values:
beg = key
path = [beg]
while path[-1] in mp:
path.append(mp[path[-1]])
return path
if __name__ == '__main__':
tests = int(input())
pairs = []
for i in range(tests):
pair = [int(x) for x in input().split()]
pairs.append(pair)
print(' '.join([str(x) for x in solve(pairs)]))
``` | instruction | 0 | 33,693 | 1 | 67,386 |
No | output | 1 | 33,693 | 1 | 67,387 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.
Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.
If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers.
The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order.
The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
Output
Print minimal r so that each city will be covered by cellular network.
Examples
Input
3 2
-2 2 4
-3 0
Output
4
Input
5 3
1 5 10 14 17
4 11 15
Output
3 | instruction | 0 | 33,861 | 1 | 67,722 |
Tags: binary search, implementation, two pointers
Correct Solution:
```
import sys
import bisect
input = sys.stdin.readline
n, m = map(int, input().split())
city = list(map(int, input().split()))
tower = list(map(int, input().split()))
ans = []#
for i in range(n):
a = bisect.bisect_right(tower, city[i])
x = abs(city[i] - tower[max(0, a-1)])
y = abs(city[i] - tower[min(m-1, a)])
ans.append(min(x, y))
print(max(ans))
``` | output | 1 | 33,861 | 1 | 67,723 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.
Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.
If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers.
The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order.
The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
Output
Print minimal r so that each city will be covered by cellular network.
Examples
Input
3 2
-2 2 4
-3 0
Output
4
Input
5 3
1 5 10 14 17
4 11 15
Output
3 | instruction | 0 | 33,862 | 1 | 67,724 |
Tags: binary search, implementation, two pointers
Correct Solution:
```
n, m = map(int, input().split())
l1 = list(map(int, input().split()))
l2 = list(map(int, input().split()))
l1.sort()
l2.sort()
ans = 0
for i in range(n):
lo = 0
hi = m - 1
while lo < hi:
mid = (lo + hi) // 2
if l2[mid] < l1[i]:
lo = mid + 1
else: hi = mid
ind1 = lo
# print(ind1)
lo = 0
hi = m - 1
while lo < hi:
mid = (lo + hi) // 2
if l2[mid] > l1[i]: hi = mid - 1
else:
lo = mid
if hi - lo == 1:
if l2[hi] <= l1[i]: lo = hi
else: hi = lo
ind2 = lo
ans = max(ans, min(abs(l2[ind1] - l1[i]), abs(l1[i] - l2[ind2])))
print(ans)
``` | output | 1 | 33,862 | 1 | 67,725 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.
Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.
If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers.
The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order.
The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
Output
Print minimal r so that each city will be covered by cellular network.
Examples
Input
3 2
-2 2 4
-3 0
Output
4
Input
5 3
1 5 10 14 17
4 11 15
Output
3 | instruction | 0 | 33,863 | 1 | 67,726 |
Tags: binary search, implementation, two pointers
Correct Solution:
```
n=int(input().split()[0])
a=list(map(int, input().split()))
b=list(map(int, input().split()))
b=[-2**40]+b+[2**40]
ans=0
j=0
for i in range(n):
while a[i]>=b[j+1]:
j+=1
ans=max(ans, min(b[j+1]-a[i], a[i]-b[j]))
print(ans)
``` | output | 1 | 33,863 | 1 | 67,727 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.
Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.
If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers.
The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order.
The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
Output
Print minimal r so that each city will be covered by cellular network.
Examples
Input
3 2
-2 2 4
-3 0
Output
4
Input
5 3
1 5 10 14 17
4 11 15
Output
3 | instruction | 0 | 33,864 | 1 | 67,728 |
Tags: binary search, implementation, two pointers
Correct Solution:
```
def lower_bownd(key):
left = -1
right = m
while left < right - 1:
middle = (left + right) // 2
if b[middle] <= key:
left = middle
else:
right = middle
if right < m:
r = b[right] - key
else:
r = INF
if left > -1:
l = key - b[left]
else:
l = INF
return min(l, r)
n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
ans = [0] * n
INF = 10 ** 10
for i in range(n):
ans[i] = lower_bownd(a[i])
print(max(ans))
``` | output | 1 | 33,864 | 1 | 67,729 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.
Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.
If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers.
The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order.
The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
Output
Print minimal r so that each city will be covered by cellular network.
Examples
Input
3 2
-2 2 4
-3 0
Output
4
Input
5 3
1 5 10 14 17
4 11 15
Output
3 | instruction | 0 | 33,865 | 1 | 67,730 |
Tags: binary search, implementation, two pointers
Correct Solution:
```
def problem(nm, cities, towers):
n_c = nm[0]
n_t = nm[1]
city_index = 0
tower_index = 0
r = 0;
while cities[city_index] < towers[0]:
r = max([r, towers[0] - cities[city_index]])
city_index += 1
if city_index == n_c:
city_index -= 1
break
while tower_index <= n_t - 2:
while cities[city_index] < towers[tower_index + 1]:
r = max([r, min([cities[city_index] - towers[tower_index], towers[tower_index + 1] - cities[city_index]])])
city_index += 1
if city_index == n_c:
city_index -= 1
break
tower_index += 1
while city_index <= n_c - 1:
r = max([r, cities[city_index] - towers[tower_index]])
city_index += 1
return r
nm = [int(x) for x in input().split(' ')]
cities = [int(x) for x in input().split(' ')]
towers = [int(x) for x in input().split(' ')]
print(problem(nm, cities, towers))
``` | output | 1 | 33,865 | 1 | 67,731 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.
Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.
If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers.
The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order.
The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
Output
Print minimal r so that each city will be covered by cellular network.
Examples
Input
3 2
-2 2 4
-3 0
Output
4
Input
5 3
1 5 10 14 17
4 11 15
Output
3 | instruction | 0 | 33,866 | 1 | 67,732 |
Tags: binary search, implementation, two pointers
Correct Solution:
```
def min_dist_to_tower(a, x):
l, r = -1, len(a)
while r - l > 1:
m = (l + r) // 2
if a[m] > x:
r = m
else:
l = m
w = abs(x - a[l]) if l >= 0 else 'SORRY'
z = abs(x - a[r]) if r < len(a) else 'SORRY'
if w != 'SORRY' and z != 'SORRY':
return min(w, z)
elif w == 'SORRY':
return z
else:
return w
n, m = map(int, input().split())
houses = list(map(int, input().split()))
towers = list(map(int, input().split()))
dist = 0
for i in range(len(houses)):
if min_dist_to_tower(towers, houses[i]) > dist:
dist = min_dist_to_tower(towers, houses[i])
print(dist)
``` | output | 1 | 33,866 | 1 | 67,733 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.
Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.
If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers.
The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order.
The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
Output
Print minimal r so that each city will be covered by cellular network.
Examples
Input
3 2
-2 2 4
-3 0
Output
4
Input
5 3
1 5 10 14 17
4 11 15
Output
3 | instruction | 0 | 33,867 | 1 | 67,734 |
Tags: binary search, implementation, two pointers
Correct Solution:
```
import sys
import bisect
input=sys.stdin.readline
m,n=input().strip().split()
m,n=int(m),int(n)
cities=list(map(int,input().strip().split()))
cells=list(map(int,input().strip().split()))
cells.sort()
R=[]
for i in range(m):
x=cities[i]
l=bisect.bisect_left(cells,x)
if l==0:
left=cells[0]
else:
left=cells[l-1]
if l>=n:
right=cells[-1]
else:
right=cells[l]
R.append(min(abs(x-right),abs(x-left)))
print(max(R))
``` | output | 1 | 33,867 | 1 | 67,735 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.
Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.
If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers.
The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order.
The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
Output
Print minimal r so that each city will be covered by cellular network.
Examples
Input
3 2
-2 2 4
-3 0
Output
4
Input
5 3
1 5 10 14 17
4 11 15
Output
3 | instruction | 0 | 33,868 | 1 | 67,736 |
Tags: binary search, implementation, two pointers
Correct Solution:
```
import bisect
a, b = list(map(int, input().split()))
cities = list(map(int, input().split()))
towers = list(map(int, input().split()))
towers.sort()
dists = []
y = towers[-1]
z = towers[0]
for i in range(len(cities)):
n = bisect.bisect_left(towers, cities[i])
if n == b:
dists.append(cities[i]-y)
elif n == 0:
dists.append(z-cities[i])
else:
dists.append(min(towers[n]-cities[i], cities[i]-towers[n-1]))
print(max(dists))
``` | output | 1 | 33,868 | 1 | 67,737 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.
Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.
If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers.
The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order.
The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
Output
Print minimal r so that each city will be covered by cellular network.
Examples
Input
3 2
-2 2 4
-3 0
Output
4
Input
5 3
1 5 10 14 17
4 11 15
Output
3
Submitted Solution:
```
from bisect import bisect_left, bisect_right
def index(a, x):
'Locate the leftmost value exactly equal to x'
i = bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
return None
def find_lt(a, x):
'Find rightmost value less than x'
i = bisect_left(a, x)
if i:
return a[i - 1]
return None
def find_le(a, x):
'Find rightmost value less than or equal to x'
i = bisect_right(a, x)
if i:
return a[i - 1]
return None
def find_gt(a, x):
'Find leftmost value greater than x'
i = bisect_right(a, x)
if i != len(a):
return a[i]
return None
def find_ge(a, x):
'Find leftmost item greater than or equal to x'
i = bisect_left(a, x)
if i != len(a):
return a[i]
return None
def main():
m, n = [int(v) for v in input().split()]
vals = [int(v) for v in input().split()]
towers = [int(v) for v in input().split()]
alls = []
for c in vals:
le = find_le(towers, c)
if le is None:
le = 10**10
else:
le = abs(le-c)
ge = find_ge(towers, c)
if ge is None:
ge = 10 ** 10
else:
ge = abs(ge-c)
alls.append(min(le, ge))
print(max(alls))
if __name__ == "__main__":
main()
``` | instruction | 0 | 33,869 | 1 | 67,738 |
Yes | output | 1 | 33,869 | 1 | 67,739 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.
Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.
If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers.
The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order.
The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
Output
Print minimal r so that each city will be covered by cellular network.
Examples
Input
3 2
-2 2 4
-3 0
Output
4
Input
5 3
1 5 10 14 17
4 11 15
Output
3
Submitted Solution:
```
import bisect
import sys
EPS = sys.float_info.epsilon
LENGTH = 10
matrix = [[] for i in range(LENGTH)]
array = [0] * LENGTH
if __name__ == "__main__":
n, m = map(int, sys.stdin.readline().split())
a = list(map(int, sys.stdin.readline().split()))
b = [-10 ** 12]
b.extend(list(map(int, sys.stdin.readline().split())))
b.append(10 ** 12)
answer = 0
for val in a:
index = bisect.bisect_left(b, val)
answer = max(answer, min(abs(val - b[index - 1]), abs(b[index] - val)))
print(answer)
``` | instruction | 0 | 33,870 | 1 | 67,740 |
Yes | output | 1 | 33,870 | 1 | 67,741 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.
Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.
If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers.
The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order.
The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
Output
Print minimal r so that each city will be covered by cellular network.
Examples
Input
3 2
-2 2 4
-3 0
Output
4
Input
5 3
1 5 10 14 17
4 11 15
Output
3
Submitted Solution:
```
import sys
import bisect
input = sys.stdin.readline
ncity, ntower = list(map(int, input().split()))
city = list(map(int, input().split()))
tower = list(map(int, input().split()))
for k in range(ncity):
ops = bisect.bisect_right(tower, city[k])
if ops == ntower:
city[k] = abs(tower[ops-1]-city[k])
else:
city[k] = min(abs(tower[ops-1]-city[k]), abs(tower[ops]-city[k]))
print(max(city))
``` | instruction | 0 | 33,871 | 1 | 67,742 |
Yes | output | 1 | 33,871 | 1 | 67,743 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.
Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.
If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers.
The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order.
The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
Output
Print minimal r so that each city will be covered by cellular network.
Examples
Input
3 2
-2 2 4
-3 0
Output
4
Input
5 3
1 5 10 14 17
4 11 15
Output
3
Submitted Solution:
```
from sys import stdin
input=lambda : stdin.readline().strip()
from math import ceil,sqrt,factorial,gcd
from collections import deque
from bisect import bisect_left,bisect_right
n,m=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
t=pow(10,10)
b.append(t)
b.insert(0,-t)
z=[0]
for i in range(len(a)):
x=bisect_left(b,a[i])
if x:
# print(x)
z.append(min(a[i]-b[x-1],b[x]-a[i]))
else:
z.append(b[x]-a[i])
print(max(z))
``` | instruction | 0 | 33,872 | 1 | 67,744 |
Yes | output | 1 | 33,872 | 1 | 67,745 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.
Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.
If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers.
The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order.
The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
Output
Print minimal r so that each city will be covered by cellular network.
Examples
Input
3 2
-2 2 4
-3 0
Output
4
Input
5 3
1 5 10 14 17
4 11 15
Output
3
Submitted Solution:
```
#ROUNIAAUDI
n, m = map(int, input().split())
c = list(map(int, input().split()))
t = list(map(int, input().split()))
r = 0
j = 0
for ct in c:
print(ct)
while j + 1 < m and abs(ct - t[j]) >= abs(ct - t[j + 1]):
# print(j,end=" ")
j += 1
r = max(r, abs(ct - t[j]))
print(r)
``` | instruction | 0 | 33,874 | 1 | 67,748 |
No | output | 1 | 33,874 | 1 | 67,749 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.
Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.
If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers.
The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order.
The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
Output
Print minimal r so that each city will be covered by cellular network.
Examples
Input
3 2
-2 2 4
-3 0
Output
4
Input
5 3
1 5 10 14 17
4 11 15
Output
3
Submitted Solution:
```
n,m = map(int,input().split())
nums = [int(x) for x in input().split()]
mums = [int(x) for x in input().split()]
check = [0]*n
first = 0
second = 0
if m == 1:
a = abs(mums[0]-nums[0])
b = abs(mums[0]-nums[-1])
print(max(a,b))
else:
while first < n and second < m-1:
if abs(nums[first]-mums[second])<abs(nums[first]-mums[second+1]):
check[first] = abs(nums[first]-mums[second])
first+=1
else:
check[first] = abs(nums[first]-mums[second+1])
second+=1
for i in range(m,n):
check[i]=abs(nums[i]-mums[-1])
print(max(check))
``` | instruction | 0 | 33,875 | 1 | 67,750 |
No | output | 1 | 33,875 | 1 | 67,751 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.
Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.
If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers.
The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order.
The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.
Output
Print minimal r so that each city will be covered by cellular network.
Examples
Input
3 2
-2 2 4
-3 0
Output
4
Input
5 3
1 5 10 14 17
4 11 15
Output
3
Submitted Solution:
```
from bisect import bisect_left
t = input
p = print
r = range
n, m = map(int, t().split())
a = list(map(int, t().split()))
b = list(map(int, t().split()))
i, j = 0, 0
mi = max(abs(b[0] - a[0]), abs(b[m - 1] - a[n - 1]))
if n == 1 and m != 1:
po = bisect_left(b, a[0])
mi = max(abs(b[po] - a[0]), abs(b[po + po == 0] - a[0]), abs(b[po + po == m - 1] - a[0]))
exit()
while True:
if i < n - 1 and j < m - 1:
fd = abs(b[j] - a[i])
sd = abs(b[j + 1] - a[i])
if fd < sd:
i += 1
mi = max(fd, mi)
else:
i += 1
j += 1
else:
break
p(mi)
``` | instruction | 0 | 33,876 | 1 | 67,752 |
No | output | 1 | 33,876 | 1 | 67,753 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bankopolis is an incredible city in which all the n crossroads are located on a straight line and numbered from 1 to n along it. On each crossroad there is a bank office.
The crossroads are connected with m oriented bicycle lanes (the i-th lane goes from crossroad ui to crossroad vi), the difficulty of each of the lanes is known.
Oleg the bank client wants to gift happiness and joy to the bank employees. He wants to visit exactly k offices, in each of them he wants to gift presents to the employees.
The problem is that Oleg don't want to see the reaction on his gifts, so he can't use a bicycle lane which passes near the office in which he has already presented his gifts (formally, the i-th lane passes near the office on the x-th crossroad if and only if min(ui, vi) < x < max(ui, vi))). Of course, in each of the offices Oleg can present gifts exactly once. Oleg is going to use exactly k - 1 bicycle lane to move between offices. Oleg can start his path from any office and finish it in any office.
Oleg wants to choose such a path among possible ones that the total difficulty of the lanes he will use is minimum possible. Find this minimum possible total difficulty.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 80) — the number of crossroads (and offices) and the number of offices Oleg wants to visit.
The second line contains single integer m (0 ≤ m ≤ 2000) — the number of bicycle lanes in Bankopolis.
The next m lines contain information about the lanes.
The i-th of these lines contains three integers ui, vi and ci (1 ≤ ui, vi ≤ n, 1 ≤ ci ≤ 1000), denoting the crossroads connected by the i-th road and its difficulty.
Output
In the only line print the minimum possible total difficulty of the lanes in a valid path, or -1 if there are no valid paths.
Examples
Input
7 4
4
1 6 2
6 2 2
2 4 2
2 7 1
Output
6
Input
4 3
4
2 1 2
1 3 2
3 4 2
4 1 1
Output
3
Note
In the first example Oleg visiting banks by path 1 → 6 → 2 → 4.
Path 1 → 6 → 2 → 7 with smaller difficulity is incorrect because crossroad 2 → 7 passes near already visited office on the crossroad 6.
In the second example Oleg can visit banks by path 4 → 1 → 3. | instruction | 0 | 33,913 | 1 | 67,826 |
Tags: dp, graphs, shortest paths
Correct Solution:
```
import sys
from functools import lru_cache
input = sys.stdin.readline
# sys.setrecursionlimit(2 * 10**6)
def inpl():
return list(map(int, input().split()))
@lru_cache(maxsize=None)
def recur(v, s, e, k):
"""
vから初めて[s, e]の都市をk個まわる最小値は?
"""
if k == 0:
return 0
elif k > e - s + 1:
return INF
ret = INF
# print(v, k)
for nv in edge[v]:
if not(s <= nv <= e):
continue
tmp = [0] * 2
if v < nv:
tmp[0] = recur(nv, max(s, v + 1), nv - 1, k - 1)
tmp[1] = recur(nv, nv + 1, e, k - 1)
else:
tmp[0] = recur(nv, s, nv - 1, k - 1)
tmp[1] = recur(nv, nv + 1, min(v - 1, e), k - 1)
# print(v, nv, tmp)
if min(tmp) + cost[(v, nv)] < ret:
ret = min(tmp) + cost[(v, nv)]
return ret
def main():
M = int(input())
U, V, C = [], [], []
for _ in range(M):
u, v, c = inpl()
U.append(u)
V.append(v)
C.append(c)
for u, v, c in zip(U, V, C):
if (u, v) in cost:
cost[(u, v)] = min(cost[(u, v)], c)
else:
edge[u].append(v)
cost[(u, v)] = c
# print(cost)
ans = INF
for v in range(N + 1):
for nv in edge[v]:
tmp = [float('inf')] * 2
if v < nv:
tmp[0] = recur(nv, nv + 1, N, K - 2)
tmp[1] = recur(nv, v + 1, nv - 1, K - 2)
else:
tmp[0] = recur(nv, 1, nv - 1, K - 2)
tmp[1] = recur(nv, nv + 1, v - 1, K - 2)
if min(tmp) + cost[(v, nv)] < ans:
ans = min(tmp) + cost[(v, nv)]
if ans == INF:
print(-1)
else:
print(ans)
if __name__ == '__main__':
INF = float('inf')
N, K = inpl()
if K < 2:
print(0)
exit()
edge = [[] for _ in range(N + 1)]
cost = {}
main()
``` | output | 1 | 33,913 | 1 | 67,827 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bankopolis is an incredible city in which all the n crossroads are located on a straight line and numbered from 1 to n along it. On each crossroad there is a bank office.
The crossroads are connected with m oriented bicycle lanes (the i-th lane goes from crossroad ui to crossroad vi), the difficulty of each of the lanes is known.
Oleg the bank client wants to gift happiness and joy to the bank employees. He wants to visit exactly k offices, in each of them he wants to gift presents to the employees.
The problem is that Oleg don't want to see the reaction on his gifts, so he can't use a bicycle lane which passes near the office in which he has already presented his gifts (formally, the i-th lane passes near the office on the x-th crossroad if and only if min(ui, vi) < x < max(ui, vi))). Of course, in each of the offices Oleg can present gifts exactly once. Oleg is going to use exactly k - 1 bicycle lane to move between offices. Oleg can start his path from any office and finish it in any office.
Oleg wants to choose such a path among possible ones that the total difficulty of the lanes he will use is minimum possible. Find this minimum possible total difficulty.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 80) — the number of crossroads (and offices) and the number of offices Oleg wants to visit.
The second line contains single integer m (0 ≤ m ≤ 2000) — the number of bicycle lanes in Bankopolis.
The next m lines contain information about the lanes.
The i-th of these lines contains three integers ui, vi and ci (1 ≤ ui, vi ≤ n, 1 ≤ ci ≤ 1000), denoting the crossroads connected by the i-th road and its difficulty.
Output
In the only line print the minimum possible total difficulty of the lanes in a valid path, or -1 if there are no valid paths.
Examples
Input
7 4
4
1 6 2
6 2 2
2 4 2
2 7 1
Output
6
Input
4 3
4
2 1 2
1 3 2
3 4 2
4 1 1
Output
3
Note
In the first example Oleg visiting banks by path 1 → 6 → 2 → 4.
Path 1 → 6 → 2 → 7 with smaller difficulity is incorrect because crossroad 2 → 7 passes near already visited office on the crossroad 6.
In the second example Oleg can visit banks by path 4 → 1 → 3.
Submitted Solution:
```
import sys
sys.setrecursionlimit(100000000)
string_lines = sys.stdin.read().split('\n')[:-1]
lines = [list(x) for x in map(lambda line: map(int, line.split(' ')), string_lines)]
n, k = lines.pop(0)
[m] = lines.pop(0)
n += 1 # artificial
edges = [[] for _ in range(n)]
for u_i, v_i, c_i in lines:
edges[u_i - 1].append((v_i - 1, c_i))
edges[v_i - 1].append((u_i - 1, c_i))
edges[n - 1] = [(v_i, 0) for v_i in range(n - 1)]
memo = {}
# input: lower_bound, upper_bound, remaining_moves, current_position
def solve(lb, ub, k, pos):
if k == 0:
return 0
memo_res = memo.get((lb, ub, k, pos))
if memo.get((lb, ub, k, pos)):
return memo_res
min_ans = float('inf')
for (next, cost) in edges[pos]:
if lb < next < pos:
this_ans = solve(lb, pos, k - 1, next)
elif pos < next < ub:
this_ans = solve(pos, ub, k - 1, next)
else:
this_ans = float('inf')
if this_ans != float('inf'):
min_ans = min(min_ans, this_ans + cost)
memo[(lb, ub, k, pos)] = min_ans
return min_ans
ans = solve(-1, n, k, n - 1)
if ans == float('inf'):
print('-1', end='')
else:
print(ans, end='')
``` | instruction | 0 | 33,914 | 1 | 67,828 |
No | output | 1 | 33,914 | 1 | 67,829 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bankopolis is an incredible city in which all the n crossroads are located on a straight line and numbered from 1 to n along it. On each crossroad there is a bank office.
The crossroads are connected with m oriented bicycle lanes (the i-th lane goes from crossroad ui to crossroad vi), the difficulty of each of the lanes is known.
Oleg the bank client wants to gift happiness and joy to the bank employees. He wants to visit exactly k offices, in each of them he wants to gift presents to the employees.
The problem is that Oleg don't want to see the reaction on his gifts, so he can't use a bicycle lane which passes near the office in which he has already presented his gifts (formally, the i-th lane passes near the office on the x-th crossroad if and only if min(ui, vi) < x < max(ui, vi))). Of course, in each of the offices Oleg can present gifts exactly once. Oleg is going to use exactly k - 1 bicycle lane to move between offices. Oleg can start his path from any office and finish it in any office.
Oleg wants to choose such a path among possible ones that the total difficulty of the lanes he will use is minimum possible. Find this minimum possible total difficulty.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 80) — the number of crossroads (and offices) and the number of offices Oleg wants to visit.
The second line contains single integer m (0 ≤ m ≤ 2000) — the number of bicycle lanes in Bankopolis.
The next m lines contain information about the lanes.
The i-th of these lines contains three integers ui, vi and ci (1 ≤ ui, vi ≤ n, 1 ≤ ci ≤ 1000), denoting the crossroads connected by the i-th road and its difficulty.
Output
In the only line print the minimum possible total difficulty of the lanes in a valid path, or -1 if there are no valid paths.
Examples
Input
7 4
4
1 6 2
6 2 2
2 4 2
2 7 1
Output
6
Input
4 3
4
2 1 2
1 3 2
3 4 2
4 1 1
Output
3
Note
In the first example Oleg visiting banks by path 1 → 6 → 2 → 4.
Path 1 → 6 → 2 → 7 with smaller difficulity is incorrect because crossroad 2 → 7 passes near already visited office on the crossroad 6.
In the second example Oleg can visit banks by path 4 → 1 → 3.
Submitted Solution:
```
import sys
from copy import deepcopy
sys.setrecursionlimit(100000000)
string_lines = sys.stdin.read().split('\n')[:-1]
lines = [list(x) for x in map(lambda line: map(int, line.split(' ')), string_lines)]
n, k = lines.pop(0)
[m] = lines.pop(0)
n_aug = n + 1
#n += 1 # artificial
edges = [[] for _ in range(n_aug)]
for u_i, v_i, c_i in lines:
exists = False
for i in range(len(edges[u_i - 1])):
v, c = edges[u_i - 1][i]
if v == v_i - 1:
exists = True
edges[u_i - 1][i] = (v_i - 1, min(c, c_i))
if not exists:
edges[u_i - 1].append((v_i - 1, c_i))
edges[n] = [(v_i, 0) for v_i in range(n)]
# bound[pos] counts from 0 until n_aug
# its number of elements is n + 1
lower_bound = [[] for _ in range(n)]
upper_bound = deepcopy(lower_bound)
# input: [2, 4, 5], 0, 13
# output: [1, 1, 3, 3, 4, None...]
# input: [-11, -9, -7], -13, 0
# output: [-12, -12, -10, -10, -8, -8, None...]
# input: [5], 4, 6
# output: [4, None]
def scan_bound(ls, start, end):
if start > end:
return []
elif len(ls) == 0:
return [None] + scan_bound(ls, start + 1, end)
elif start > ls[0]:
return scan_bound(ls[1:], start, end)
else:
return [ls[0]] + scan_bound(ls, start + 1, end)
def neg_sorted_list(ls):
return list(map(lambda x: -x if x is not None else None, reversed(ls)))
for pos in range(n):
sorted_edges = sorted(map(lambda x: x[0], edges[pos]))
smaller = []
larger = []
for x in sorted_edges:
(smaller if x < pos else larger).append(x)
lb_scan = scan_bound(smaller, 0, n_aug)
lower_bound[pos] = lb_scan
if len(smaller) == 0 and len(larger) != 0:
for i in range(0, pos):
lower_bound[pos][i] = pos
ub_scan = neg_sorted_list(scan_bound(neg_sorted_list(larger), -n_aug, 0))
upper_bound[pos] = ub_scan
if len(larger) == 0 and len(smaller) != 0:
for i in range(pos + 1, n_aug + 1):
upper_bound[pos][i] = pos
#for pos in range(n):
# print(pos)
# print(list(map(lambda x: x[0], edges[pos])))
# print(lower_bound[pos])
# print(upper_bound[pos])
# print()
memo = {}
def tight_solve(lb, ub, pos, k):
if k == 0:
return 0
tight_lb = lower_bound[pos][lb]
tight_ub = upper_bound[pos][ub]
if tight_lb is None:
tight_lb = pos
if tight_ub is None:
tight_ub = pos
# print((lb, ub, pos, tight_lb, tight_ub))
return solve(tight_lb, tight_ub, pos, k)
# input: lower_bound, upper_bound, remaining_moves, current_position
def solve(lb, ub, pos, k):
memo_res = memo.get((lb, ub, pos, k))
if memo.get((lb, ub, pos, k)):
return memo_res
min_ans = float('inf')
for (next, cost) in edges[pos]:
if lb <= next <= pos:
this_ans = tight_solve(lb, pos - 1, next, k - 1)
elif pos <= next <= ub:
this_ans = tight_solve(pos + 1, ub, next, k - 1)
else:
this_ans = float('inf')
if this_ans != float('inf'):
min_ans = min(min_ans, this_ans + cost)
memo[(lb, ub, pos, k)] = min_ans
return min_ans
ans = solve(0, n - 1, n, k)
if ans == float('inf'):
print('-1', end='')
else:
print(ans, end='')
``` | instruction | 0 | 33,915 | 1 | 67,830 |
No | output | 1 | 33,915 | 1 | 67,831 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bankopolis is an incredible city in which all the n crossroads are located on a straight line and numbered from 1 to n along it. On each crossroad there is a bank office.
The crossroads are connected with m oriented bicycle lanes (the i-th lane goes from crossroad ui to crossroad vi), the difficulty of each of the lanes is known.
Oleg the bank client wants to gift happiness and joy to the bank employees. He wants to visit exactly k offices, in each of them he wants to gift presents to the employees.
The problem is that Oleg don't want to see the reaction on his gifts, so he can't use a bicycle lane which passes near the office in which he has already presented his gifts (formally, the i-th lane passes near the office on the x-th crossroad if and only if min(ui, vi) < x < max(ui, vi))). Of course, in each of the offices Oleg can present gifts exactly once. Oleg is going to use exactly k - 1 bicycle lane to move between offices. Oleg can start his path from any office and finish it in any office.
Oleg wants to choose such a path among possible ones that the total difficulty of the lanes he will use is minimum possible. Find this minimum possible total difficulty.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 80) — the number of crossroads (and offices) and the number of offices Oleg wants to visit.
The second line contains single integer m (0 ≤ m ≤ 2000) — the number of bicycle lanes in Bankopolis.
The next m lines contain information about the lanes.
The i-th of these lines contains three integers ui, vi and ci (1 ≤ ui, vi ≤ n, 1 ≤ ci ≤ 1000), denoting the crossroads connected by the i-th road and its difficulty.
Output
In the only line print the minimum possible total difficulty of the lanes in a valid path, or -1 if there are no valid paths.
Examples
Input
7 4
4
1 6 2
6 2 2
2 4 2
2 7 1
Output
6
Input
4 3
4
2 1 2
1 3 2
3 4 2
4 1 1
Output
3
Note
In the first example Oleg visiting banks by path 1 → 6 → 2 → 4.
Path 1 → 6 → 2 → 7 with smaller difficulity is incorrect because crossroad 2 → 7 passes near already visited office on the crossroad 6.
In the second example Oleg can visit banks by path 4 → 1 → 3.
Submitted Solution:
```
import sys
from copy import deepcopy
sys.setrecursionlimit(100000000)
string_lines = sys.stdin.read().split('\n')[:-1]
lines = [list(x) for x in map(lambda line: map(int, line.split(' ')), string_lines)]
n, k = lines.pop(0)
[m] = lines.pop(0)
n_aug = n + 1
edges = [[] for _ in range(n_aug)]
for u_i, v_i, c_i in lines:
if u_i == v_i:
continue
exists = False
for i in range(len(edges[u_i - 1])):
v, c = edges[u_i - 1][i]
if v == v_i - 1:
exists = True
edges[u_i - 1][i] = (v_i - 1, min(c, c_i))
if not exists:
edges[u_i - 1].append((v_i - 1, c_i))
edges[n] = [(v_i, 0) for v_i in range(n)]
# bound[pos] counts from 0 until n_aug
# each element's number of elements is n
lower_bound = [[] for _ in range(n)]
upper_bound = deepcopy(lower_bound)
# input: [2, 4, 5], 0, 13
# output: [2, 2, 2, 4, 4, 5, None...]
# input: [-11, -9, -7], -13, 0
# output: [-11, -11, -11, -9, -9, -7, -7, None...]
# input: [5], 4, 6
# output: [5, 5, None]
def scan_bound(ls, start, end):
if start > end:
return []
elif ls == []:
return [None] + scan_bound([], start + 1, end)
elif start > ls[0]:
return scan_bound(ls[1:], start, end)
else:
return [ls[0]] + scan_bound(ls, start + 1, end)
def neg_sorted_list(ls):
return list(map(lambda x: -x if x is not None else None, reversed(ls)))
for pos in range(n):
sorted_edges = sorted(map(lambda x: x[0], edges[pos]))
smaller = []
larger = []
for x in sorted_edges:
(smaller if x < pos else larger).append(x)
lb_scan = scan_bound(smaller, 0, n - 1)
lower_bound[pos] = lb_scan
ub_scan = neg_sorted_list(scan_bound(neg_sorted_list(larger), -(n - 1), 0))
upper_bound[pos] = ub_scan
smaller_edges = [[[(next, cost) for (next, cost) in edges[pos] if lb <= next < pos] for lb in range(n_aug)] for pos in range(n_aug)]
larger_edges = [[[(next, cost) for (next, cost) in edges[pos] if pos < next <= ub] for ub in range(n_aug)] for pos in range(n_aug)]
#for pos in range(n):
# print(pos)
# print(list(map(lambda x: x[0], edges[pos])))
# print(lower_bound[pos])
# print(upper_bound[pos])
# print()
memo = {}
def tight_solve(lb, ub, pos, k):
if k == 0:
return 0
tight_lb = lower_bound[pos][lb]
tight_ub = upper_bound[pos][ub]
if tight_lb is None:
tight_lb = pos
if tight_ub is None:
tight_ub = pos
tight_lb = max(tight_lb, lb)
tight_ub = min(tight_ub + 1, ub)
# print((lb, ub, pos, tight_lb, tight_ub))
return solve(tight_lb, tight_ub, pos, k)
# input: lower_bound, upper_bound, remaining_moves, current_position
def solve(lb, ub, pos, k):
memo_res = memo.get((lb, ub, pos, k))
if memo_res:
return memo_res
min_ans = float('inf')
for (next, cost) in smaller_edges[pos][lb]:
this_ans = tight_solve(lb, pos - 1, next, k - 1)
min_ans = min(min_ans, this_ans + cost)
for (next, cost) in larger_edges[pos][ub]:
this_ans = tight_solve(pos + 1, ub, next, k - 1)
min_ans = min(min_ans, this_ans + cost)
memo[(lb, ub, pos, k)] = min_ans
return min_ans
ans = solve(0, n - 1, n, k)
if ans == float('inf'):
print('-1', end='')
else:
print(ans, end='')
``` | instruction | 0 | 33,916 | 1 | 67,832 |
No | output | 1 | 33,916 | 1 | 67,833 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bankopolis is an incredible city in which all the n crossroads are located on a straight line and numbered from 1 to n along it. On each crossroad there is a bank office.
The crossroads are connected with m oriented bicycle lanes (the i-th lane goes from crossroad ui to crossroad vi), the difficulty of each of the lanes is known.
Oleg the bank client wants to gift happiness and joy to the bank employees. He wants to visit exactly k offices, in each of them he wants to gift presents to the employees.
The problem is that Oleg don't want to see the reaction on his gifts, so he can't use a bicycle lane which passes near the office in which he has already presented his gifts (formally, the i-th lane passes near the office on the x-th crossroad if and only if min(ui, vi) < x < max(ui, vi))). Of course, in each of the offices Oleg can present gifts exactly once. Oleg is going to use exactly k - 1 bicycle lane to move between offices. Oleg can start his path from any office and finish it in any office.
Oleg wants to choose such a path among possible ones that the total difficulty of the lanes he will use is minimum possible. Find this minimum possible total difficulty.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 80) — the number of crossroads (and offices) and the number of offices Oleg wants to visit.
The second line contains single integer m (0 ≤ m ≤ 2000) — the number of bicycle lanes in Bankopolis.
The next m lines contain information about the lanes.
The i-th of these lines contains three integers ui, vi and ci (1 ≤ ui, vi ≤ n, 1 ≤ ci ≤ 1000), denoting the crossroads connected by the i-th road and its difficulty.
Output
In the only line print the minimum possible total difficulty of the lanes in a valid path, or -1 if there are no valid paths.
Examples
Input
7 4
4
1 6 2
6 2 2
2 4 2
2 7 1
Output
6
Input
4 3
4
2 1 2
1 3 2
3 4 2
4 1 1
Output
3
Note
In the first example Oleg visiting banks by path 1 → 6 → 2 → 4.
Path 1 → 6 → 2 → 7 with smaller difficulity is incorrect because crossroad 2 → 7 passes near already visited office on the crossroad 6.
In the second example Oleg can visit banks by path 4 → 1 → 3.
Submitted Solution:
```
import sys
from copy import deepcopy
sys.setrecursionlimit(100000000)
string_lines = sys.stdin.read().split('\n')[:-1]
lines = [list(x) for x in map(lambda line: map(int, line.split(' ')), string_lines)]
n, k = lines.pop(0)
[m] = lines.pop(0)
n_aug = n + 1
edges = [[] for _ in range(n_aug)]
for u_i, v_i, c_i in lines:
if u_i == v_i:
continue
exists = False
for i in range(len(edges[u_i - 1])):
v, c = edges[u_i - 1][i]
if v == v_i - 1:
exists = True
edges[u_i - 1][i] = (v_i - 1, min(c, c_i))
if not exists:
edges[u_i - 1].append((v_i - 1, c_i))
edges[n] = [(v_i, 0) for v_i in range(n)]
# bound[pos] counts from 0 until n_aug
# each element's number of elements is n
lower_bound = [[] for _ in range(n)]
upper_bound = deepcopy(lower_bound)
# input: [2, 4, 5], 0, 13
# output: [2, 2, 2, 4, 4, 5, None...]
# input: [-11, -9, -7], -13, 0
# output: [-11, -11, -11, -9, -9, -7, -7, None...]
# input: [5], 4, 6
# output: [5, 5, None]
def scan_bound(ls, start, end):
if start > end:
return []
elif ls == []:
return [None] + scan_bound([], start + 1, end)
elif start > ls[0]:
return scan_bound(ls[1:], start, end)
else:
return [ls[0]] + scan_bound(ls, start + 1, end)
def neg_sorted_list(ls):
return list(map(lambda x: -x if x is not None else None, reversed(ls)))
for pos in range(n):
sorted_edges = sorted(map(lambda x: x[0], edges[pos]))
smaller = []
larger = []
for x in sorted_edges:
(smaller if x < pos else larger).append(x)
lb_scan = scan_bound(smaller, 0, n - 1)
lower_bound[pos] = lb_scan
ub_scan = neg_sorted_list(scan_bound(neg_sorted_list(larger), -(n - 1), 0))
upper_bound[pos] = ub_scan
#for pos in range(n):
# print(pos)
# print(list(map(lambda x: x[0], edges[pos])))
# print(lower_bound[pos])
# print(upper_bound[pos])
# print()
memo = {}
def tight_solve(lb, ub, pos, k):
if k == 0:
return 0
tight_lb = lower_bound[pos][lb]
tight_ub = upper_bound[pos][ub]
if tight_lb is None:
tight_lb = pos
if tight_ub is None:
tight_ub = pos
# print((lb, ub, pos, tight_lb, tight_ub))
return solve(tight_lb, tight_ub, pos, k)
# input: lower_bound, upper_bound, remaining_moves, current_position
def solve(lb, ub, pos, k):
memo_res = memo.get((lb, ub, pos, k))
if memo_res:
return memo_res
min_ans = float('inf')
for (next, cost) in edges[pos]:
if lb <= next < pos:
this_ans = tight_solve(lb, pos - 1, next, k - 1)
elif pos < next <= ub:
this_ans = tight_solve(pos + 1, ub, next, k - 1)
else:
this_ans = float('inf')
min_ans = min(min_ans, this_ans + cost)
memo[(lb, ub, pos, k)] = min_ans
return min_ans
ans = solve(0, n - 1, n, k)
if ans == float('inf'):
print('-1', end='')
else:
print(ans, end='')
``` | instruction | 0 | 33,917 | 1 | 67,834 |
No | output | 1 | 33,917 | 1 | 67,835 |
Provide a correct Python 3 solution for this coding contest problem.
There are N cities numbered 1 to N, connected by M railroads.
You are now at City 1, with 10^{100} gold coins and S silver coins in your pocket.
The i-th railroad connects City U_i and City V_i bidirectionally, and a one-way trip costs A_i silver coins and takes B_i minutes. You cannot use gold coins to pay the fare.
There is an exchange counter in each city. At the exchange counter in City i, you can get C_i silver coins for 1 gold coin. The transaction takes D_i minutes for each gold coin you give. You can exchange any number of gold coins at each exchange counter.
For each t=2, ..., N, find the minimum time needed to travel from City 1 to City t. You can ignore the time spent waiting for trains.
Constraints
* 2 \leq N \leq 50
* N-1 \leq M \leq 100
* 0 \leq S \leq 10^9
* 1 \leq A_i \leq 50
* 1 \leq B_i,C_i,D_i \leq 10^9
* 1 \leq U_i < V_i \leq N
* There is no pair i, j(i \neq j) such that (U_i,V_i)=(U_j,V_j).
* Each city t=2,...,N can be reached from City 1 with some number of railroads.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M S
U_1 V_1 A_1 B_1
:
U_M V_M A_M B_M
C_1 D_1
:
C_N D_N
Output
For each t=2, ..., N in this order, print a line containing the minimum time needed to travel from City 1 to City t.
Examples
Input
3 2 1
1 2 1 2
1 3 2 4
1 11
1 2
2 5
Output
2
14
Input
4 4 1
1 2 1 5
1 3 4 4
2 4 2 2
3 4 1 1
3 1
3 1
5 2
6 4
Output
5
5
7
Input
6 5 1
1 2 1 1
1 3 2 1
2 4 5 1
3 5 11 1
1 6 50 1
1 10000
1 3000
1 700
1 100
1 1
100 1
Output
1
9003
14606
16510
16576
Input
4 6 1000000000
1 2 50 1
1 3 50 5
1 4 50 7
2 3 50 2
2 4 50 4
3 4 50 3
10 2
4 4
5 5
7 7
Output
1
3
5
Input
2 1 0
1 2 1 1
1 1000000000
1 1
Output
1000000001 | instruction | 0 | 34,018 | 1 | 68,036 |
"Correct Solution:
```
from heapq import heappush, heappop
N, M, S = map(int, input().split())
mxCost = 0
edges = [[] for _ in range(N)]
for _ in range(M):
fr, to, cost, dist = map(int, input().split())
mxCost = max(mxCost, cost)
fr -= 1
to -= 1
edges[fr].append((to, dist, cost))
edges[to].append((fr, dist, cost))
for i in range(N):
C, D = map(int, input().split())
edges[i].append((i, D, -C))
que = [(0, S, 0)]
mxCost *= (N - 1)
minDsit = [[10**18] * (mxCost + 1) for _ in range(N)]
minDsit[0][0] = 0
while que:
dist, s, now = heappop(que)
for to, d, c in edges[now]:
cost = min(mxCost, s - c)
if cost < 0 or minDsit[to][cost] <= dist + d:
continue
minDsit[to][cost] = dist + d
que.append((dist + d, cost, to))
for dist in minDsit[1:]:
print(min(dist))
``` | output | 1 | 34,018 | 1 | 68,037 |
Provide a correct Python 3 solution for this coding contest problem.
There are N cities numbered 1 to N, connected by M railroads.
You are now at City 1, with 10^{100} gold coins and S silver coins in your pocket.
The i-th railroad connects City U_i and City V_i bidirectionally, and a one-way trip costs A_i silver coins and takes B_i minutes. You cannot use gold coins to pay the fare.
There is an exchange counter in each city. At the exchange counter in City i, you can get C_i silver coins for 1 gold coin. The transaction takes D_i minutes for each gold coin you give. You can exchange any number of gold coins at each exchange counter.
For each t=2, ..., N, find the minimum time needed to travel from City 1 to City t. You can ignore the time spent waiting for trains.
Constraints
* 2 \leq N \leq 50
* N-1 \leq M \leq 100
* 0 \leq S \leq 10^9
* 1 \leq A_i \leq 50
* 1 \leq B_i,C_i,D_i \leq 10^9
* 1 \leq U_i < V_i \leq N
* There is no pair i, j(i \neq j) such that (U_i,V_i)=(U_j,V_j).
* Each city t=2,...,N can be reached from City 1 with some number of railroads.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M S
U_1 V_1 A_1 B_1
:
U_M V_M A_M B_M
C_1 D_1
:
C_N D_N
Output
For each t=2, ..., N in this order, print a line containing the minimum time needed to travel from City 1 to City t.
Examples
Input
3 2 1
1 2 1 2
1 3 2 4
1 11
1 2
2 5
Output
2
14
Input
4 4 1
1 2 1 5
1 3 4 4
2 4 2 2
3 4 1 1
3 1
3 1
5 2
6 4
Output
5
5
7
Input
6 5 1
1 2 1 1
1 3 2 1
2 4 5 1
3 5 11 1
1 6 50 1
1 10000
1 3000
1 700
1 100
1 1
100 1
Output
1
9003
14606
16510
16576
Input
4 6 1000000000
1 2 50 1
1 3 50 5
1 4 50 7
2 3 50 2
2 4 50 4
3 4 50 3
10 2
4 4
5 5
7 7
Output
1
3
5
Input
2 1 0
1 2 1 1
1 1000000000
1 1
Output
1000000001 | instruction | 0 | 34,019 | 1 | 68,038 |
"Correct Solution:
```
import heapq
def main():
N, M, S = map(int, input().split())
money_max = 50*N
S = min(S, money_max)
dp = [[float("inf")]*(money_max+1) for _ in range(N)]
dp[0][S] = 0
G = [[] for _ in range(N)]
exchange = [None]*N
for _ in range(M):
u, v, a, b = map(int, input().split())
u, v = u-1, v-1
G[u].append([v, a, b])
G[v].append([u, a, b])
for i in range(N):
c, d = map(int, input().split())
exchange[i] = [c, d]
q = []
heapq.heapify(q)
heapq.heappush(q, [0, 0, S])
while 0 < len(q):
pre_time, idx, s = heapq.heappop(q)
if dp[idx][s] < pre_time:
continue
ex = min(s + exchange[idx][0], money_max)
if dp[idx][s] + exchange[idx][1] < dp[idx][ex]:
dp[idx][ex] = dp[idx][s] + exchange[idx][1]
heapq.heappush(q, [dp[idx][ex], idx, ex])
for to, money, time in G[idx]:
if money <= s:
if dp[idx][s] + time < dp[to][s-money]:
dp[to][s-money] = dp[idx][s] + time
heapq.heappush(q, [dp[to][s-money], to, s-money])
for i in range(1, N):
print(min(dp[i]))
if __name__ == "__main__":
main()
``` | output | 1 | 34,019 | 1 | 68,039 |
Provide a correct Python 3 solution for this coding contest problem.
There are N cities numbered 1 to N, connected by M railroads.
You are now at City 1, with 10^{100} gold coins and S silver coins in your pocket.
The i-th railroad connects City U_i and City V_i bidirectionally, and a one-way trip costs A_i silver coins and takes B_i minutes. You cannot use gold coins to pay the fare.
There is an exchange counter in each city. At the exchange counter in City i, you can get C_i silver coins for 1 gold coin. The transaction takes D_i minutes for each gold coin you give. You can exchange any number of gold coins at each exchange counter.
For each t=2, ..., N, find the minimum time needed to travel from City 1 to City t. You can ignore the time spent waiting for trains.
Constraints
* 2 \leq N \leq 50
* N-1 \leq M \leq 100
* 0 \leq S \leq 10^9
* 1 \leq A_i \leq 50
* 1 \leq B_i,C_i,D_i \leq 10^9
* 1 \leq U_i < V_i \leq N
* There is no pair i, j(i \neq j) such that (U_i,V_i)=(U_j,V_j).
* Each city t=2,...,N can be reached from City 1 with some number of railroads.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M S
U_1 V_1 A_1 B_1
:
U_M V_M A_M B_M
C_1 D_1
:
C_N D_N
Output
For each t=2, ..., N in this order, print a line containing the minimum time needed to travel from City 1 to City t.
Examples
Input
3 2 1
1 2 1 2
1 3 2 4
1 11
1 2
2 5
Output
2
14
Input
4 4 1
1 2 1 5
1 3 4 4
2 4 2 2
3 4 1 1
3 1
3 1
5 2
6 4
Output
5
5
7
Input
6 5 1
1 2 1 1
1 3 2 1
2 4 5 1
3 5 11 1
1 6 50 1
1 10000
1 3000
1 700
1 100
1 1
100 1
Output
1
9003
14606
16510
16576
Input
4 6 1000000000
1 2 50 1
1 3 50 5
1 4 50 7
2 3 50 2
2 4 50 4
3 4 50 3
10 2
4 4
5 5
7 7
Output
1
3
5
Input
2 1 0
1 2 1 1
1 1000000000
1 1
Output
1000000001 | instruction | 0 | 34,020 | 1 | 68,040 |
"Correct Solution:
```
import sys
import heapq
input = sys.stdin.readline
NCOSTS = 2501
TIME_MAX = 10 ** 15
N, M, S = map(int, input().split())
adj = [[] for _ in range(N * NCOSTS)]
fare_adj = [[NCOSTS] * N for _ in range(N)]
time_adj = [[TIME_MAX] * N for _ in range(N)]
fare_max = 0
def node(city, silvers):
return silvers * N + city
for i in range(M):
u, v, a, b = map(int, input().split())
u -= 1
v -= 1
for j in range(a, NCOSTS):
adj[node(u, j)].append((node(v, j - a), b))
adj[node(v, j)].append((node(u, j - a), b))
for i in range(N):
# g-s rate, waiting duration
c, d = map(int, input().split())
for j in range(NCOSTS - c):
adj[node(i, j)].append((node(i, j + c), d))
mintime = [TIME_MAX for _ in range(N * NCOSTS)]
def search():
q = [(0, node(0, min(S, NCOSTS - 1)))]
while q:
t, node1 = heapq.heappop(q)
if t > mintime[node1]:
continue
for node2, cost in adj[node1]:
ntime = t + cost
if mintime[node2] > ntime:
mintime[node2] = ntime
heapq.heappush(q, (ntime, node2))
search()
for i in range(1, N):
print(min(mintime[node(i, j)] for j in range(NCOSTS)))
``` | output | 1 | 34,020 | 1 | 68,041 |
Provide a correct Python 3 solution for this coding contest problem.
There are N cities numbered 1 to N, connected by M railroads.
You are now at City 1, with 10^{100} gold coins and S silver coins in your pocket.
The i-th railroad connects City U_i and City V_i bidirectionally, and a one-way trip costs A_i silver coins and takes B_i minutes. You cannot use gold coins to pay the fare.
There is an exchange counter in each city. At the exchange counter in City i, you can get C_i silver coins for 1 gold coin. The transaction takes D_i minutes for each gold coin you give. You can exchange any number of gold coins at each exchange counter.
For each t=2, ..., N, find the minimum time needed to travel from City 1 to City t. You can ignore the time spent waiting for trains.
Constraints
* 2 \leq N \leq 50
* N-1 \leq M \leq 100
* 0 \leq S \leq 10^9
* 1 \leq A_i \leq 50
* 1 \leq B_i,C_i,D_i \leq 10^9
* 1 \leq U_i < V_i \leq N
* There is no pair i, j(i \neq j) such that (U_i,V_i)=(U_j,V_j).
* Each city t=2,...,N can be reached from City 1 with some number of railroads.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M S
U_1 V_1 A_1 B_1
:
U_M V_M A_M B_M
C_1 D_1
:
C_N D_N
Output
For each t=2, ..., N in this order, print a line containing the minimum time needed to travel from City 1 to City t.
Examples
Input
3 2 1
1 2 1 2
1 3 2 4
1 11
1 2
2 5
Output
2
14
Input
4 4 1
1 2 1 5
1 3 4 4
2 4 2 2
3 4 1 1
3 1
3 1
5 2
6 4
Output
5
5
7
Input
6 5 1
1 2 1 1
1 3 2 1
2 4 5 1
3 5 11 1
1 6 50 1
1 10000
1 3000
1 700
1 100
1 1
100 1
Output
1
9003
14606
16510
16576
Input
4 6 1000000000
1 2 50 1
1 3 50 5
1 4 50 7
2 3 50 2
2 4 50 4
3 4 50 3
10 2
4 4
5 5
7 7
Output
1
3
5
Input
2 1 0
1 2 1 1
1 1000000000
1 1
Output
1000000001 | instruction | 0 | 34,021 | 1 | 68,042 |
"Correct Solution:
```
from heapq import heappop, heappush
import sys
input = sys.stdin.readline
INF = 10**100
MAX = 2500
N, M, S = map(int, input().split())
S = min(S, MAX)
G = [[] for _ in [0]*N]
C = []
for _ in [0]*M:
u, v, a, b = map(int, input().split())
u -= 1
v -= 1
G[v].append((u, a, b))
G[u].append((v, a, b))
for i in range(N):
a, b = map(int, input().split())
C.append((a, b))
# dijkstra
dp = [[INF]*MAX for _ in [0]*N]
q = []
def push(t, s, v):
if s < 0:
return
if s >= MAX:
s = MAX-1
if dp[v][s] <= t:
return
dp[v][s] = t
heappush(q, (t, s, v))
push(0, S, 0)
while q:
t, s, v = heappop(q)
if dp[v][s] != t:
continue
c, d = C[v]
push(t+d, s+c, v)
for u, a, b in G[v]:
push(t+b, s-a, u)
# output
for d in dp[1:]:
ans = INF
for s in range(MAX):
if ans > d[s]:
ans = d[s]
print(ans)
``` | output | 1 | 34,021 | 1 | 68,043 |
Provide a correct Python 3 solution for this coding contest problem.
There are N cities numbered 1 to N, connected by M railroads.
You are now at City 1, with 10^{100} gold coins and S silver coins in your pocket.
The i-th railroad connects City U_i and City V_i bidirectionally, and a one-way trip costs A_i silver coins and takes B_i minutes. You cannot use gold coins to pay the fare.
There is an exchange counter in each city. At the exchange counter in City i, you can get C_i silver coins for 1 gold coin. The transaction takes D_i minutes for each gold coin you give. You can exchange any number of gold coins at each exchange counter.
For each t=2, ..., N, find the minimum time needed to travel from City 1 to City t. You can ignore the time spent waiting for trains.
Constraints
* 2 \leq N \leq 50
* N-1 \leq M \leq 100
* 0 \leq S \leq 10^9
* 1 \leq A_i \leq 50
* 1 \leq B_i,C_i,D_i \leq 10^9
* 1 \leq U_i < V_i \leq N
* There is no pair i, j(i \neq j) such that (U_i,V_i)=(U_j,V_j).
* Each city t=2,...,N can be reached from City 1 with some number of railroads.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M S
U_1 V_1 A_1 B_1
:
U_M V_M A_M B_M
C_1 D_1
:
C_N D_N
Output
For each t=2, ..., N in this order, print a line containing the minimum time needed to travel from City 1 to City t.
Examples
Input
3 2 1
1 2 1 2
1 3 2 4
1 11
1 2
2 5
Output
2
14
Input
4 4 1
1 2 1 5
1 3 4 4
2 4 2 2
3 4 1 1
3 1
3 1
5 2
6 4
Output
5
5
7
Input
6 5 1
1 2 1 1
1 3 2 1
2 4 5 1
3 5 11 1
1 6 50 1
1 10000
1 3000
1 700
1 100
1 1
100 1
Output
1
9003
14606
16510
16576
Input
4 6 1000000000
1 2 50 1
1 3 50 5
1 4 50 7
2 3 50 2
2 4 50 4
3 4 50 3
10 2
4 4
5 5
7 7
Output
1
3
5
Input
2 1 0
1 2 1 1
1 1000000000
1 1
Output
1000000001 | instruction | 0 | 34,022 | 1 | 68,044 |
"Correct Solution:
```
import sys
import heapq
def dijkstra(s,es):
INF=sys.maxsize
cs=[INF]*len(es)
cs[s],hq=0,[]
heapq.heapify(hq)
heapq.heappush(hq,(cs[s],s))
while hq:
d,v=heapq.heappop(hq)
if cs[v]<d:continue
for t,b in es[v]:
if cs[t]>cs[v]+b:
cs[t]=cs[v]+b
heapq.heappush(hq,(cs[t],t))
return cs
def nwc(n,c):
MAX_COINS=2500
return (MAX_COINS+1)*n+c
def main():
MAX_COINS=2500
N,M,S=tuple(map(int,sys.stdin.readline().split()))
S=S if S<MAX_COINS else MAX_COINS
es=[[] for _ in range(N*(MAX_COINS+1))]
for _ in range(M):
u,v,a,b=tuple(map(int,sys.stdin.readline().split()))
u,v=u-1,v-1
for c in range(a,MAX_COINS+1):
es[nwc(u,c)].append((nwc(v,c-a),b))
es[nwc(v,c)].append((nwc(u,c-a),b))
for n in range(N):
c,d=tuple(map(int,sys.stdin.readline().split()))
c=c if c<MAX_COINS else MAX_COINS
for i in range(0,MAX_COINS-c+1):es[nwc(n,i)].append((nwc(n,i+c),d))
cs=dijkstra(nwc(0,S),es)
for n in range(1,N):print(min(cs[n*(MAX_COINS+1):(n+1)*(MAX_COINS+1)]))
if __name__=='__main__':main()
``` | output | 1 | 34,022 | 1 | 68,045 |
Provide a correct Python 3 solution for this coding contest problem.
There are N cities numbered 1 to N, connected by M railroads.
You are now at City 1, with 10^{100} gold coins and S silver coins in your pocket.
The i-th railroad connects City U_i and City V_i bidirectionally, and a one-way trip costs A_i silver coins and takes B_i minutes. You cannot use gold coins to pay the fare.
There is an exchange counter in each city. At the exchange counter in City i, you can get C_i silver coins for 1 gold coin. The transaction takes D_i minutes for each gold coin you give. You can exchange any number of gold coins at each exchange counter.
For each t=2, ..., N, find the minimum time needed to travel from City 1 to City t. You can ignore the time spent waiting for trains.
Constraints
* 2 \leq N \leq 50
* N-1 \leq M \leq 100
* 0 \leq S \leq 10^9
* 1 \leq A_i \leq 50
* 1 \leq B_i,C_i,D_i \leq 10^9
* 1 \leq U_i < V_i \leq N
* There is no pair i, j(i \neq j) such that (U_i,V_i)=(U_j,V_j).
* Each city t=2,...,N can be reached from City 1 with some number of railroads.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M S
U_1 V_1 A_1 B_1
:
U_M V_M A_M B_M
C_1 D_1
:
C_N D_N
Output
For each t=2, ..., N in this order, print a line containing the minimum time needed to travel from City 1 to City t.
Examples
Input
3 2 1
1 2 1 2
1 3 2 4
1 11
1 2
2 5
Output
2
14
Input
4 4 1
1 2 1 5
1 3 4 4
2 4 2 2
3 4 1 1
3 1
3 1
5 2
6 4
Output
5
5
7
Input
6 5 1
1 2 1 1
1 3 2 1
2 4 5 1
3 5 11 1
1 6 50 1
1 10000
1 3000
1 700
1 100
1 1
100 1
Output
1
9003
14606
16510
16576
Input
4 6 1000000000
1 2 50 1
1 3 50 5
1 4 50 7
2 3 50 2
2 4 50 4
3 4 50 3
10 2
4 4
5 5
7 7
Output
1
3
5
Input
2 1 0
1 2 1 1
1 1000000000
1 1
Output
1000000001 | instruction | 0 | 34,023 | 1 | 68,046 |
"Correct Solution:
```
import sys
input = lambda : sys.stdin.readline().rstrip()
import heapq
from collections import defaultdict
h = []
heapq.heapify(h)
n, m, s = list(map(int, input().split()))
a, b = [[None] * m for _ in range(2)]
c, d = [[None] * n for _ in range(2)]
ns = defaultdict(list)
uv2e = {}
for i in range(m):
u,v,a[i],b[i] = list(map(int, input().split()))
ns[u-1].append(v-1)
ns[v-1].append(u-1)
uv2e[u-1,v-1] = i
uv2e[v-1,u-1] = i
for i in range(n):
c[i], d[i] = list(map(int, input().split()))
maxs = max(a)*(n-1)
s = min(s, maxs)
state = (0, 0, s) # (距離, ノード, 銀貨枚数)
ans = [[None] * (maxs+1) for _ in range(n)]
heapq.heappush(h, state)
count = 0
while h:
count += 1
dd, u, ss = heapq.heappop(h)
# print(dd, u, ss)
if ans[u][ss] is not None and ans[u][ss] <= dd:
continue
ans[u][ss] = dd
# グラフの隣接点
for v in ns[u]:
e= uv2e[u,v]
if ss<a[e] or ans[v][ss-a[e]] is not None:
continue
heapq.heappush(h, (dd + b[e], v, ss-a[e]))
# 両替
if ss+c[u] <= maxs:
heapq.heappush(h, (dd + d[u], u, ss+c[u]))
elif ss < maxs:
heapq.heappush(h, (dd + d[u], u, maxs))
for item in ans[1:]:
print(min(item))
``` | output | 1 | 34,023 | 1 | 68,047 |
Provide a correct Python 3 solution for this coding contest problem.
There are N cities numbered 1 to N, connected by M railroads.
You are now at City 1, with 10^{100} gold coins and S silver coins in your pocket.
The i-th railroad connects City U_i and City V_i bidirectionally, and a one-way trip costs A_i silver coins and takes B_i minutes. You cannot use gold coins to pay the fare.
There is an exchange counter in each city. At the exchange counter in City i, you can get C_i silver coins for 1 gold coin. The transaction takes D_i minutes for each gold coin you give. You can exchange any number of gold coins at each exchange counter.
For each t=2, ..., N, find the minimum time needed to travel from City 1 to City t. You can ignore the time spent waiting for trains.
Constraints
* 2 \leq N \leq 50
* N-1 \leq M \leq 100
* 0 \leq S \leq 10^9
* 1 \leq A_i \leq 50
* 1 \leq B_i,C_i,D_i \leq 10^9
* 1 \leq U_i < V_i \leq N
* There is no pair i, j(i \neq j) such that (U_i,V_i)=(U_j,V_j).
* Each city t=2,...,N can be reached from City 1 with some number of railroads.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M S
U_1 V_1 A_1 B_1
:
U_M V_M A_M B_M
C_1 D_1
:
C_N D_N
Output
For each t=2, ..., N in this order, print a line containing the minimum time needed to travel from City 1 to City t.
Examples
Input
3 2 1
1 2 1 2
1 3 2 4
1 11
1 2
2 5
Output
2
14
Input
4 4 1
1 2 1 5
1 3 4 4
2 4 2 2
3 4 1 1
3 1
3 1
5 2
6 4
Output
5
5
7
Input
6 5 1
1 2 1 1
1 3 2 1
2 4 5 1
3 5 11 1
1 6 50 1
1 10000
1 3000
1 700
1 100
1 1
100 1
Output
1
9003
14606
16510
16576
Input
4 6 1000000000
1 2 50 1
1 3 50 5
1 4 50 7
2 3 50 2
2 4 50 4
3 4 50 3
10 2
4 4
5 5
7 7
Output
1
3
5
Input
2 1 0
1 2 1 1
1 1000000000
1 1
Output
1000000001 | instruction | 0 | 34,024 | 1 | 68,048 |
"Correct Solution:
```
import sys
input = lambda : sys.stdin.readline().rstrip()
import heapq
h = []
heapq.heapify(h)
n, m, s = list(map(int, input().split()))
a, b = [[None] * m for _ in range(2)]
c, d = [[None] * n for _ in range(2)]
ns = {}
uv2e = {}
for i in range(m):
u,v,a[i],b[i] = list(map(int, input().split()))
ns.setdefault(u-1, set())
ns.setdefault(v-1, set())
ns[u-1].add(v-1)
ns[v-1].add(u-1)
uv2e[u-1,v-1] = i
uv2e[v-1,u-1] = i
for i in range(n):
c[i], d[i] = list(map(int, input().split()))
maxs = max(a)*(n-1)
s = min(s, maxs)
state = (0, 0, s) # (距離, ノード, 銀貨枚数)
ans = [[None] * (maxs+1) for _ in range(n)]
heapq.heappush(h, state)
count = 0
while h:
count += 1
dd, u, ss = heapq.heappop(h)
# print(dd, u, ss)
if ans[u][ss] is not None and ans[u][ss] <= dd:
continue
ans[u][ss] = dd
# グラフの隣接点
for v in ns[u]:
e= uv2e[u,v]
if ss<a[e] or ans[v][ss-a[e]] is not None:
continue
heapq.heappush(h, (dd + b[e], v, ss-a[e]))
# 両替
if ss+c[u] <= maxs:
heapq.heappush(h, (dd + d[u], u, ss+c[u]))
elif ss < maxs:
heapq.heappush(h, (dd + d[u], u, maxs))
for item in ans[1:]:
print(min(item))
``` | output | 1 | 34,024 | 1 | 68,049 |
Provide a correct Python 3 solution for this coding contest problem.
There are N cities numbered 1 to N, connected by M railroads.
You are now at City 1, with 10^{100} gold coins and S silver coins in your pocket.
The i-th railroad connects City U_i and City V_i bidirectionally, and a one-way trip costs A_i silver coins and takes B_i minutes. You cannot use gold coins to pay the fare.
There is an exchange counter in each city. At the exchange counter in City i, you can get C_i silver coins for 1 gold coin. The transaction takes D_i minutes for each gold coin you give. You can exchange any number of gold coins at each exchange counter.
For each t=2, ..., N, find the minimum time needed to travel from City 1 to City t. You can ignore the time spent waiting for trains.
Constraints
* 2 \leq N \leq 50
* N-1 \leq M \leq 100
* 0 \leq S \leq 10^9
* 1 \leq A_i \leq 50
* 1 \leq B_i,C_i,D_i \leq 10^9
* 1 \leq U_i < V_i \leq N
* There is no pair i, j(i \neq j) such that (U_i,V_i)=(U_j,V_j).
* Each city t=2,...,N can be reached from City 1 with some number of railroads.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M S
U_1 V_1 A_1 B_1
:
U_M V_M A_M B_M
C_1 D_1
:
C_N D_N
Output
For each t=2, ..., N in this order, print a line containing the minimum time needed to travel from City 1 to City t.
Examples
Input
3 2 1
1 2 1 2
1 3 2 4
1 11
1 2
2 5
Output
2
14
Input
4 4 1
1 2 1 5
1 3 4 4
2 4 2 2
3 4 1 1
3 1
3 1
5 2
6 4
Output
5
5
7
Input
6 5 1
1 2 1 1
1 3 2 1
2 4 5 1
3 5 11 1
1 6 50 1
1 10000
1 3000
1 700
1 100
1 1
100 1
Output
1
9003
14606
16510
16576
Input
4 6 1000000000
1 2 50 1
1 3 50 5
1 4 50 7
2 3 50 2
2 4 50 4
3 4 50 3
10 2
4 4
5 5
7 7
Output
1
3
5
Input
2 1 0
1 2 1 1
1 1000000000
1 1
Output
1000000001 | instruction | 0 | 34,025 | 1 | 68,050 |
"Correct Solution:
```
N,M,S=map(int,input().split())
from heapq import heappop,heappush
inf = 10**18
cost=[[] for _ in range(N)]
exc=[]
for _ in range(M):
u,v,a,b=map(int,input().split())
u,v=u-1,v-1
cost[u].append((v,a,b))
cost[v].append((u,a,b))
for _ in range(N):
c,d=map(int,input().split())
exc.append((c,d))
di=[inf]*2451*N
if S>2450:
S=2450
di[S]=0
hq=[(0,S)] #時間,都市名*2451+銀貨
while hq:
t,v=heappop(hq)
u=v//2451 #都市名
s=v%2451 #所持金
for x,a,b in cost[u]:
if s>=a:
v_new=x*2451+s-a
t_new=t+b
if t_new<di[v_new]:
di[v_new]=t_new
heappush(hq,(t_new,v_new))
c,d=exc[u]
if s+c>2450:
c=2450-s
v_new=v+c
t_new=t+d
if t_new<di[v_new]:
di[v_new]=t_new
heappush(hq,(t_new,v_new))
for i in range(1,N):
m=di[i*2451]
for j in range(1,2451):
m=min(m,di[i*2451+j])
print(m)
``` | output | 1 | 34,025 | 1 | 68,051 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N cities numbered 1 to N, connected by M railroads.
You are now at City 1, with 10^{100} gold coins and S silver coins in your pocket.
The i-th railroad connects City U_i and City V_i bidirectionally, and a one-way trip costs A_i silver coins and takes B_i minutes. You cannot use gold coins to pay the fare.
There is an exchange counter in each city. At the exchange counter in City i, you can get C_i silver coins for 1 gold coin. The transaction takes D_i minutes for each gold coin you give. You can exchange any number of gold coins at each exchange counter.
For each t=2, ..., N, find the minimum time needed to travel from City 1 to City t. You can ignore the time spent waiting for trains.
Constraints
* 2 \leq N \leq 50
* N-1 \leq M \leq 100
* 0 \leq S \leq 10^9
* 1 \leq A_i \leq 50
* 1 \leq B_i,C_i,D_i \leq 10^9
* 1 \leq U_i < V_i \leq N
* There is no pair i, j(i \neq j) such that (U_i,V_i)=(U_j,V_j).
* Each city t=2,...,N can be reached from City 1 with some number of railroads.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M S
U_1 V_1 A_1 B_1
:
U_M V_M A_M B_M
C_1 D_1
:
C_N D_N
Output
For each t=2, ..., N in this order, print a line containing the minimum time needed to travel from City 1 to City t.
Examples
Input
3 2 1
1 2 1 2
1 3 2 4
1 11
1 2
2 5
Output
2
14
Input
4 4 1
1 2 1 5
1 3 4 4
2 4 2 2
3 4 1 1
3 1
3 1
5 2
6 4
Output
5
5
7
Input
6 5 1
1 2 1 1
1 3 2 1
2 4 5 1
3 5 11 1
1 6 50 1
1 10000
1 3000
1 700
1 100
1 1
100 1
Output
1
9003
14606
16510
16576
Input
4 6 1000000000
1 2 50 1
1 3 50 5
1 4 50 7
2 3 50 2
2 4 50 4
3 4 50 3
10 2
4 4
5 5
7 7
Output
1
3
5
Input
2 1 0
1 2 1 1
1 1000000000
1 1
Output
1000000001
Submitted Solution:
```
from heapq import heappop, heappush
def main():
N, M, S = map(int, input().split())
adj = [{} for _ in range(N)]
amax = 0
for _ in range(M):
u, v, a, b = map(int, input().split())
adj[u-1][v-1] = (a, b)
adj[v-1][u-1] = (a, b)
amax = max(amax, a)
C = [0] * N
D = [0] * N
for i in range(N):
C[i], D[i] = map(int, input().split())
MAX = amax * N
dp = [[float("inf")] * (MAX+1) for _ in range(N)]
q = [[0, min(S, MAX), 0, -1]]
ans = [None] * N
remain = N
while len(q) and remain:
time, coin, cur, prev = heappop(q)
if dp[cur][coin] <= time:
continue
if ans[cur] is None:
ans[cur] = time
remain -= 1
dp[cur][coin] = time
if coin < MAX:
heappush(q, [time + D[cur], min(coin + C[cur], MAX), cur, cur])
for nxt in adj[cur]:
dcost, dtime = adj[cur][nxt]
if nxt != prev and dcost <= coin:
heappush(q, [time + dtime, coin - dcost, nxt, cur])
for i in range(1, N):
print(ans[i])
if __name__ == "__main__":
main()
``` | instruction | 0 | 34,026 | 1 | 68,052 |
Yes | output | 1 | 34,026 | 1 | 68,053 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N cities numbered 1 to N, connected by M railroads.
You are now at City 1, with 10^{100} gold coins and S silver coins in your pocket.
The i-th railroad connects City U_i and City V_i bidirectionally, and a one-way trip costs A_i silver coins and takes B_i minutes. You cannot use gold coins to pay the fare.
There is an exchange counter in each city. At the exchange counter in City i, you can get C_i silver coins for 1 gold coin. The transaction takes D_i minutes for each gold coin you give. You can exchange any number of gold coins at each exchange counter.
For each t=2, ..., N, find the minimum time needed to travel from City 1 to City t. You can ignore the time spent waiting for trains.
Constraints
* 2 \leq N \leq 50
* N-1 \leq M \leq 100
* 0 \leq S \leq 10^9
* 1 \leq A_i \leq 50
* 1 \leq B_i,C_i,D_i \leq 10^9
* 1 \leq U_i < V_i \leq N
* There is no pair i, j(i \neq j) such that (U_i,V_i)=(U_j,V_j).
* Each city t=2,...,N can be reached from City 1 with some number of railroads.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M S
U_1 V_1 A_1 B_1
:
U_M V_M A_M B_M
C_1 D_1
:
C_N D_N
Output
For each t=2, ..., N in this order, print a line containing the minimum time needed to travel from City 1 to City t.
Examples
Input
3 2 1
1 2 1 2
1 3 2 4
1 11
1 2
2 5
Output
2
14
Input
4 4 1
1 2 1 5
1 3 4 4
2 4 2 2
3 4 1 1
3 1
3 1
5 2
6 4
Output
5
5
7
Input
6 5 1
1 2 1 1
1 3 2 1
2 4 5 1
3 5 11 1
1 6 50 1
1 10000
1 3000
1 700
1 100
1 1
100 1
Output
1
9003
14606
16510
16576
Input
4 6 1000000000
1 2 50 1
1 3 50 5
1 4 50 7
2 3 50 2
2 4 50 4
3 4 50 3
10 2
4 4
5 5
7 7
Output
1
3
5
Input
2 1 0
1 2 1 1
1 1000000000
1 1
Output
1000000001
Submitted Solution:
```
# coding: utf-8
import sys
from heapq import heapify, heappop, heappush
sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))
# 銀貨を何枚持っているかの状態数、N*2501の都市, dijkstra
N, M, S = lr()
limit = 2500
S = min(S, limit)
graph = [[] for _ in range((N+1) * (limit+1))] # 1-indexed
for _ in range(M):
u, v, a, b = lr()
for x in range(a, limit+1):
graph[u*(limit+1) + x].append(((v*(limit+1)+x-a), b))
graph[v*(limit+1) + x].append(((u*(limit+1)+x-a), b))
for i in range(N):
i += 1
c, d = lr()
for x in range(limit-c+1):
graph[i*(limit+1) + x].append((i*(limit+1) + x + c, d))
def dijkstra(start):
INF = 10 ** 15
dist = [INF] * ((N+1) * (limit+1))
dist[start] = 0
que = [(0, start)]
while que:
d, prev = heappop(que)
if dist[prev] < d:
continue
for next, time in graph[prev]:
d1 = d + time
if dist[next] > d1:
dist[next] = d1
heappush(que, (d1, next))
return dist
dist = dijkstra(1*(limit+1)+S)
for i in range(2, N+1):
answer = min(dist[i*(limit+1):(i+1)*(limit+1)])
print(answer)
``` | instruction | 0 | 34,027 | 1 | 68,054 |
Yes | output | 1 | 34,027 | 1 | 68,055 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N cities numbered 1 to N, connected by M railroads.
You are now at City 1, with 10^{100} gold coins and S silver coins in your pocket.
The i-th railroad connects City U_i and City V_i bidirectionally, and a one-way trip costs A_i silver coins and takes B_i minutes. You cannot use gold coins to pay the fare.
There is an exchange counter in each city. At the exchange counter in City i, you can get C_i silver coins for 1 gold coin. The transaction takes D_i minutes for each gold coin you give. You can exchange any number of gold coins at each exchange counter.
For each t=2, ..., N, find the minimum time needed to travel from City 1 to City t. You can ignore the time spent waiting for trains.
Constraints
* 2 \leq N \leq 50
* N-1 \leq M \leq 100
* 0 \leq S \leq 10^9
* 1 \leq A_i \leq 50
* 1 \leq B_i,C_i,D_i \leq 10^9
* 1 \leq U_i < V_i \leq N
* There is no pair i, j(i \neq j) such that (U_i,V_i)=(U_j,V_j).
* Each city t=2,...,N can be reached from City 1 with some number of railroads.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M S
U_1 V_1 A_1 B_1
:
U_M V_M A_M B_M
C_1 D_1
:
C_N D_N
Output
For each t=2, ..., N in this order, print a line containing the minimum time needed to travel from City 1 to City t.
Examples
Input
3 2 1
1 2 1 2
1 3 2 4
1 11
1 2
2 5
Output
2
14
Input
4 4 1
1 2 1 5
1 3 4 4
2 4 2 2
3 4 1 1
3 1
3 1
5 2
6 4
Output
5
5
7
Input
6 5 1
1 2 1 1
1 3 2 1
2 4 5 1
3 5 11 1
1 6 50 1
1 10000
1 3000
1 700
1 100
1 1
100 1
Output
1
9003
14606
16510
16576
Input
4 6 1000000000
1 2 50 1
1 3 50 5
1 4 50 7
2 3 50 2
2 4 50 4
3 4 50 3
10 2
4 4
5 5
7 7
Output
1
3
5
Input
2 1 0
1 2 1 1
1 1000000000
1 1
Output
1000000001
Submitted Solution:
```
import heapq
import sys
input = sys.stdin.readline
INF = 10 ** 18
class Edge():
def __init__(self, end, cost, time):
self.end = end
self.cost = cost
self.time = time
dp = []
h = []
def push(t, v, x):
if x < 0:
return
if dp[v][x] <= t:
return
dp[v][x] = t
heapq.heappush(h, (t, v, x))
def dijkstra(n, G, cd, start, s, max_s):
global dp
dp = [[INF for j in range(max_s+1)] for i in range(n)]
push(0, start, s)
while h:
# 使っていない頂点のうち、現時点で最も到達短時間が短いものを選びvとする
t, v, x = heapq.heappop(h)
if dp[v][x] < t:
continue
# 両替
if x < max_s:
push(t+cd[v][1], v, min(x+cd[v][0], max_s))
# vから到達可能な頂点について、到達時間が短くなれば更新
for e in G[v]:
push(t+e.time, e.end, x-e.cost)
n, m, s = map(int, input().split())
uvab = [list(map(int, input().split())) for _ in range(m)]
cd = [list(map(int, input().split())) for _ in range(n)]
es = [[] for i in range(n)]
max_s = 50 * (n-1)
for u, v, a, b in uvab:
es[u-1].append(Edge(v-1,a,b))
es[v-1].append(Edge(u-1,a,b))
dijkstra(n, es, cd, 0, min(max_s,s), max_s)
for i in range(1, n):
print(min(dp[i]))
``` | instruction | 0 | 34,028 | 1 | 68,056 |
Yes | output | 1 | 34,028 | 1 | 68,057 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N cities numbered 1 to N, connected by M railroads.
You are now at City 1, with 10^{100} gold coins and S silver coins in your pocket.
The i-th railroad connects City U_i and City V_i bidirectionally, and a one-way trip costs A_i silver coins and takes B_i minutes. You cannot use gold coins to pay the fare.
There is an exchange counter in each city. At the exchange counter in City i, you can get C_i silver coins for 1 gold coin. The transaction takes D_i minutes for each gold coin you give. You can exchange any number of gold coins at each exchange counter.
For each t=2, ..., N, find the minimum time needed to travel from City 1 to City t. You can ignore the time spent waiting for trains.
Constraints
* 2 \leq N \leq 50
* N-1 \leq M \leq 100
* 0 \leq S \leq 10^9
* 1 \leq A_i \leq 50
* 1 \leq B_i,C_i,D_i \leq 10^9
* 1 \leq U_i < V_i \leq N
* There is no pair i, j(i \neq j) such that (U_i,V_i)=(U_j,V_j).
* Each city t=2,...,N can be reached from City 1 with some number of railroads.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M S
U_1 V_1 A_1 B_1
:
U_M V_M A_M B_M
C_1 D_1
:
C_N D_N
Output
For each t=2, ..., N in this order, print a line containing the minimum time needed to travel from City 1 to City t.
Examples
Input
3 2 1
1 2 1 2
1 3 2 4
1 11
1 2
2 5
Output
2
14
Input
4 4 1
1 2 1 5
1 3 4 4
2 4 2 2
3 4 1 1
3 1
3 1
5 2
6 4
Output
5
5
7
Input
6 5 1
1 2 1 1
1 3 2 1
2 4 5 1
3 5 11 1
1 6 50 1
1 10000
1 3000
1 700
1 100
1 1
100 1
Output
1
9003
14606
16510
16576
Input
4 6 1000000000
1 2 50 1
1 3 50 5
1 4 50 7
2 3 50 2
2 4 50 4
3 4 50 3
10 2
4 4
5 5
7 7
Output
1
3
5
Input
2 1 0
1 2 1 1
1 1000000000
1 1
Output
1000000001
Submitted Solution:
```
import heapq
def dijkstra_heap():
used = [-1] * (2451*n)
edgelist=[]
heapq.heappush(edgelist,[0,ss])
while len(edgelist):
#print(len(edgelist))
minedge = heapq.heappop(edgelist)
if used[minedge[1]]!=-1:
continue
v = minedge[1]
kai=minedge[0]
mai=v%2451
used[v] = kai
for e in edge[v//2451]:
if mai-e[1]>=0:
sss=mai-e[1]
if used[e[2]*2451+sss]==-1:
heapq.heappush(edgelist,[e[0]+kai,e[2]*2451+sss])
if mai+cd[v//2451][0]<=2450:
if used[v+cd[v//2451][0]]==-1:
heapq.heappush(edgelist,[kai+cd[v//2451][1],v+cd[v//2451][0]])
return used
################################
n,m,ss = map(int,input().split())
ss=min(2450,ss)
edge = [[] for i in range(n)]
for i in range(m):
x,y,a,b = map(int,input().split())
edge[x-1].append([b,a,y-1])
edge[y-1].append([b,a,x-1])
cd=[]
for i in range(n):
cd.append(list(map(int,input().split())))
pp=dijkstra_heap()
for i in range(1,n):
ans=10**20
for j in range(2451):
if pp[i*2451+j]!=-1:
ans=min(ans,pp[i*2451+j])
print(ans)
``` | instruction | 0 | 34,029 | 1 | 68,058 |
Yes | output | 1 | 34,029 | 1 | 68,059 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N cities numbered 1 to N, connected by M railroads.
You are now at City 1, with 10^{100} gold coins and S silver coins in your pocket.
The i-th railroad connects City U_i and City V_i bidirectionally, and a one-way trip costs A_i silver coins and takes B_i minutes. You cannot use gold coins to pay the fare.
There is an exchange counter in each city. At the exchange counter in City i, you can get C_i silver coins for 1 gold coin. The transaction takes D_i minutes for each gold coin you give. You can exchange any number of gold coins at each exchange counter.
For each t=2, ..., N, find the minimum time needed to travel from City 1 to City t. You can ignore the time spent waiting for trains.
Constraints
* 2 \leq N \leq 50
* N-1 \leq M \leq 100
* 0 \leq S \leq 10^9
* 1 \leq A_i \leq 50
* 1 \leq B_i,C_i,D_i \leq 10^9
* 1 \leq U_i < V_i \leq N
* There is no pair i, j(i \neq j) such that (U_i,V_i)=(U_j,V_j).
* Each city t=2,...,N can be reached from City 1 with some number of railroads.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M S
U_1 V_1 A_1 B_1
:
U_M V_M A_M B_M
C_1 D_1
:
C_N D_N
Output
For each t=2, ..., N in this order, print a line containing the minimum time needed to travel from City 1 to City t.
Examples
Input
3 2 1
1 2 1 2
1 3 2 4
1 11
1 2
2 5
Output
2
14
Input
4 4 1
1 2 1 5
1 3 4 4
2 4 2 2
3 4 1 1
3 1
3 1
5 2
6 4
Output
5
5
7
Input
6 5 1
1 2 1 1
1 3 2 1
2 4 5 1
3 5 11 1
1 6 50 1
1 10000
1 3000
1 700
1 100
1 1
100 1
Output
1
9003
14606
16510
16576
Input
4 6 1000000000
1 2 50 1
1 3 50 5
1 4 50 7
2 3 50 2
2 4 50 4
3 4 50 3
10 2
4 4
5 5
7 7
Output
1
3
5
Input
2 1 0
1 2 1 1
1 1000000000
1 1
Output
1000000001
Submitted Solution:
```
from heapq import heappush, heappop
import sys
sys.setrecursionlimit(10**7)
from time import sleep
# スペース区切りの入力を読み込んで数値リストにして返します。
def get_nums_l():
return [ int(ss) for ss in input().split(" ")]
def rangeI(it, l, r):
for i, e in enumerate(it):
if l <= i < r:
yield e
elif l >= r:
break
def log(*args):
print("DEBUG:", *args, file=sys.stderr)
# cdef int n,m,s,co,coin,city,max_coin,u,v,a,b
# cdef long long time
n,m,s = get_nums_l()
# 銀貨所持枚数の上限。確実に最短経路を通過できる枚数
max_coin = 50*(n-1)
s = min(s, max_coin)
lines = list(map(lambda line: line.strip(), sys.stdin.readlines()))
# rails[i] = 都市iを始点とする路線情報(行き先, 運賃, 時間)
rails = [ [] for _ in range(n + 1) ]
for line in rangeI(lines, 0, m):
u,v,a,b = map(int, line.split())
rails[u].append([v, a, b])
rails[v].append([u, a, b])
cities = [None] + [ list(map(int, line.split())) for line in rangeI(lines, m, m+n) ]
# log("rails:", rails)
# log("cities:", cities)
# t = 目的地
for t in range(2, n+1):
# log("t:", t)
# table[i][j] = 現在頂点i, 銀貨j枚持っている場合の最小時間
table = [ [999999999999999999] * (max_coin + 1) for _ in range(n+1)]
hq = []
# 初期状態 時間0, 都市1, 銀貨s枚
heappush(hq, (0, 1, s))
while hq:
# sleep(0.1)
time, city, coin, = heappop(hq)
if city == t:
print(time)
break
if table[city][coin] <= time:
continue
# for co in range(coin+1):
# if table[city][co] > time:
# table[city][co] = time
table[city][coin] = time
# log(city, coin, time)
# ここで両替した場合 銀貨と時間を増やす
# log("-", city, min(max_coin, coin+cities[city][0]), time + cities[city][1])
heappush(hq, (time + cities[city][1], city, min(max_coin, coin+cities[city][0])))
# 進める都市に進む
for v, a, b in rails[city]:
if coin < a:
# 銀貨が足りないと移動できない
continue
# log("-", v, coin-a, time + b)
heappush(hq, (time+b, v, coin-a))
``` | instruction | 0 | 34,030 | 1 | 68,060 |
No | output | 1 | 34,030 | 1 | 68,061 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.