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 |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
The government of Berland decided to improve network coverage in his country. Berland has a unique structure: the capital in the center and n cities in a circle around the capital. The capital already has a good network coverage (so the government ignores it), but the i-th city contains a_i households that require a connection.
The government designed a plan to build n network stations between all pairs of neighboring cities which will maintain connections only for these cities. In other words, the i-th network station will provide service only for the i-th and the (i + 1)-th city (the n-th station is connected to the n-th and the 1-st city).
All network stations have capacities: the i-th station can provide the connection to at most b_i households.
Now the government asks you to check can the designed stations meet the needs of all cities or not β that is, is it possible to assign each household a network station so that each network station i provides the connection to at most b_i households.
Input
The first line contains a single integer t (1 β€ t β€ 10^4) β the number of test cases.
The first line of each test case contains the single integer n (2 β€ n β€ 10^6) β the number of cities and stations.
The second line of each test case contains n integers (1 β€ a_i β€ 10^9) β the number of households in the i-th city.
The third line of each test case contains n integers (1 β€ b_i β€ 10^9) β the capacities of the designed stations.
It's guaranteed that the sum of n over test cases doesn't exceed 10^6.
Output
For each test case, print YES, if the designed stations can meet the needs of all cities, or NO otherwise (case insensitive).
Example
Input
5
3
2 3 4
3 3 3
3
3 3 3
2 3 4
4
2 3 4 5
3 7 2 2
4
4 5 2 3
2 3 2 7
2
1 1
10 10
Output
YES
YES
NO
YES
YES
Note
In the first test case:
* the first network station can provide 2 connections to the first city and 1 connection to the second city;
* the second station can provide 2 connections to the second city and 1 connection to the third city;
* the third station can provide 3 connections to the third city.
In the second test case:
* the 1-st station can provide 2 connections to the 1-st city;
* the 2-nd station can provide 3 connections to the 2-nd city;
* the 3-rd station can provide 3 connections to the 3-rd city and 1 connection to the 1-st station.
In the third test case, the fourth city needs 5 connections, but the third and the fourth station has 4 connections in total. | instruction | 0 | 65,755 | 1 | 131,510 |
Tags: binary search, constructive algorithms, data structures, greedy
Correct Solution:
```
T = int(input())
while T > 0:
n = int(input())
households = list(map(int, input().split()))
stations = list(map(int, input().split()))
l, r = 0, min(households[0],stations[0])
ans = False
while l <= r:
mid = (l+r)//2
left = households[0]-mid
now = stations[0]-mid
short = False
for i in range(1,n):
now = min(now, households[i])
if now+stations[i] < households[i]:
r = mid-1
short = True
break
now = now+stations[i]-households[i]
if short is True:
continue
if now >= left:
ans = True
break
l = mid+1
if ans:
print('YES')
else:
print('NO')
T -= 1
``` | output | 1 | 65,755 | 1 | 131,511 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The government of Berland decided to improve network coverage in his country. Berland has a unique structure: the capital in the center and n cities in a circle around the capital. The capital already has a good network coverage (so the government ignores it), but the i-th city contains a_i households that require a connection.
The government designed a plan to build n network stations between all pairs of neighboring cities which will maintain connections only for these cities. In other words, the i-th network station will provide service only for the i-th and the (i + 1)-th city (the n-th station is connected to the n-th and the 1-st city).
All network stations have capacities: the i-th station can provide the connection to at most b_i households.
Now the government asks you to check can the designed stations meet the needs of all cities or not β that is, is it possible to assign each household a network station so that each network station i provides the connection to at most b_i households.
Input
The first line contains a single integer t (1 β€ t β€ 10^4) β the number of test cases.
The first line of each test case contains the single integer n (2 β€ n β€ 10^6) β the number of cities and stations.
The second line of each test case contains n integers (1 β€ a_i β€ 10^9) β the number of households in the i-th city.
The third line of each test case contains n integers (1 β€ b_i β€ 10^9) β the capacities of the designed stations.
It's guaranteed that the sum of n over test cases doesn't exceed 10^6.
Output
For each test case, print YES, if the designed stations can meet the needs of all cities, or NO otherwise (case insensitive).
Example
Input
5
3
2 3 4
3 3 3
3
3 3 3
2 3 4
4
2 3 4 5
3 7 2 2
4
4 5 2 3
2 3 2 7
2
1 1
10 10
Output
YES
YES
NO
YES
YES
Note
In the first test case:
* the first network station can provide 2 connections to the first city and 1 connection to the second city;
* the second station can provide 2 connections to the second city and 1 connection to the third city;
* the third station can provide 3 connections to the third city.
In the second test case:
* the 1-st station can provide 2 connections to the 1-st city;
* the 2-nd station can provide 3 connections to the 2-nd city;
* the 3-rd station can provide 3 connections to the 3-rd city and 1 connection to the 1-st station.
In the third test case, the fourth city needs 5 connections, but the third and the fourth station has 4 connections in total. | instruction | 0 | 65,756 | 1 | 131,512 |
Tags: binary search, constructive algorithms, data structures, greedy
Correct Solution:
```
import sys
input = sys.stdin.readline
############ ---- Input Functions ---- ############
def inp():
return (int(input()))
def instr():
return (str(input()))
def inlt():
return (list(map(int, input().split())))
def insr():
s = input()
return(list(map(int, list(s[:len(s) - 1]))))
# def insr():
# s = input()
# return list(s[:len(s) - 1])
def invr():
return (map(int, input().split()))
from collections import Counter
def check(cities, stations, k, allow):
# cities = cities.copy()
n = len(cities)
k = min(cities[0], k)
last_st = stations[-1] - k
c_i = cities[0] - k
for i in range(n - 1):
d = stations[i] - (c_i + cities[i + 1])
if d > 0:
# cities[i + 1] = 0
c_i = 0
allow -= d
if allow < 0:
return 1
elif stations[i] < c_i:
return -1
else:
c_i = cities[i + 1] - (stations[i] - c_i)
if c_i > last_st:
return -1
return 0
def bin_search(cities, stations, allow, l, r):
while l <= r:
mid = l + (r - l) // 2
res = check(cities, stations, mid, allow)
if res == 0:
return mid
elif res == -1:
l = mid + 1
else:
r = mid - 1
return -1
def main():
t = inp()
for _ in range(t):
n = inp()
cities = inlt()
stations = inlt()
allow = sum(stations) - sum(cities)
if allow < 0:
print('NO')
else:
res = bin_search(cities, stations, allow, 0, stations[-1] + 1)
if res == -1:
print('NO')
else:
print('YES')
if __name__ == '__main__':
main()
``` | output | 1 | 65,756 | 1 | 131,513 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The government of Berland decided to improve network coverage in his country. Berland has a unique structure: the capital in the center and n cities in a circle around the capital. The capital already has a good network coverage (so the government ignores it), but the i-th city contains a_i households that require a connection.
The government designed a plan to build n network stations between all pairs of neighboring cities which will maintain connections only for these cities. In other words, the i-th network station will provide service only for the i-th and the (i + 1)-th city (the n-th station is connected to the n-th and the 1-st city).
All network stations have capacities: the i-th station can provide the connection to at most b_i households.
Now the government asks you to check can the designed stations meet the needs of all cities or not β that is, is it possible to assign each household a network station so that each network station i provides the connection to at most b_i households.
Input
The first line contains a single integer t (1 β€ t β€ 10^4) β the number of test cases.
The first line of each test case contains the single integer n (2 β€ n β€ 10^6) β the number of cities and stations.
The second line of each test case contains n integers (1 β€ a_i β€ 10^9) β the number of households in the i-th city.
The third line of each test case contains n integers (1 β€ b_i β€ 10^9) β the capacities of the designed stations.
It's guaranteed that the sum of n over test cases doesn't exceed 10^6.
Output
For each test case, print YES, if the designed stations can meet the needs of all cities, or NO otherwise (case insensitive).
Example
Input
5
3
2 3 4
3 3 3
3
3 3 3
2 3 4
4
2 3 4 5
3 7 2 2
4
4 5 2 3
2 3 2 7
2
1 1
10 10
Output
YES
YES
NO
YES
YES
Note
In the first test case:
* the first network station can provide 2 connections to the first city and 1 connection to the second city;
* the second station can provide 2 connections to the second city and 1 connection to the third city;
* the third station can provide 3 connections to the third city.
In the second test case:
* the 1-st station can provide 2 connections to the 1-st city;
* the 2-nd station can provide 3 connections to the 2-nd city;
* the 3-rd station can provide 3 connections to the 3-rd city and 1 connection to the 1-st station.
In the third test case, the fourth city needs 5 connections, but the third and the fourth station has 4 connections in total. | instruction | 0 | 65,757 | 1 | 131,514 |
Tags: binary search, constructive algorithms, data structures, greedy
Correct Solution:
```
import sys
from collections import deque, defaultdict
input = sys.stdin.buffer.readline
T = int(input())
for _ in range(T):
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
def check(m):
m = min(m, b[0])
c = [0]*n
c[1] = m
for i in range(1, n):
if b[i]+c[i] < a[i]: return (0, i)
c[(i+1)%n] = min(b[i], b[i]+c[i]-a[i])
if b[0]+c[0]-m < a[0]: return (0, 0)
return (1, 0)
l, r = 0, b[0]+1
ok = 0
while l < r:
m = (l+r)//2
ok, p = check(m)
if ok: break
if p != 0: l = m+1
else: r = m
print("YES" if ok else "NO")
``` | output | 1 | 65,757 | 1 | 131,515 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The government of Berland decided to improve network coverage in his country. Berland has a unique structure: the capital in the center and n cities in a circle around the capital. The capital already has a good network coverage (so the government ignores it), but the i-th city contains a_i households that require a connection.
The government designed a plan to build n network stations between all pairs of neighboring cities which will maintain connections only for these cities. In other words, the i-th network station will provide service only for the i-th and the (i + 1)-th city (the n-th station is connected to the n-th and the 1-st city).
All network stations have capacities: the i-th station can provide the connection to at most b_i households.
Now the government asks you to check can the designed stations meet the needs of all cities or not β that is, is it possible to assign each household a network station so that each network station i provides the connection to at most b_i households.
Input
The first line contains a single integer t (1 β€ t β€ 10^4) β the number of test cases.
The first line of each test case contains the single integer n (2 β€ n β€ 10^6) β the number of cities and stations.
The second line of each test case contains n integers (1 β€ a_i β€ 10^9) β the number of households in the i-th city.
The third line of each test case contains n integers (1 β€ b_i β€ 10^9) β the capacities of the designed stations.
It's guaranteed that the sum of n over test cases doesn't exceed 10^6.
Output
For each test case, print YES, if the designed stations can meet the needs of all cities, or NO otherwise (case insensitive).
Example
Input
5
3
2 3 4
3 3 3
3
3 3 3
2 3 4
4
2 3 4 5
3 7 2 2
4
4 5 2 3
2 3 2 7
2
1 1
10 10
Output
YES
YES
NO
YES
YES
Note
In the first test case:
* the first network station can provide 2 connections to the first city and 1 connection to the second city;
* the second station can provide 2 connections to the second city and 1 connection to the third city;
* the third station can provide 3 connections to the third city.
In the second test case:
* the 1-st station can provide 2 connections to the 1-st city;
* the 2-nd station can provide 3 connections to the 2-nd city;
* the 3-rd station can provide 3 connections to the 3-rd city and 1 connection to the 1-st station.
In the third test case, the fourth city needs 5 connections, but the third and the fourth station has 4 connections in total. | instruction | 0 | 65,758 | 1 | 131,516 |
Tags: binary search, constructive algorithms, data structures, greedy
Correct Solution:
```
line = input()
t = int(line)
for _ in range(t):
line = input()
n = int(line)
line = input()
need = [int(i) for i in line.split(' ')]
line = input()
station =[int(i) for i in line.split(' ')]
if sum(station) < sum(need):
print('NO')
continue
lo, hi = 0, station[-1]
flag = True
xmax, cur, x = station[-1], 0, station[-1]
for i in range(n - 1):
cur = cur + station[i] - need[i]
if cur < 0:
xmax += cur
x += cur
cur = 0
cur = min(cur, station[i])
xmax = min(xmax, station[i] - cur)
if xmax < 0:
flag = False
break
# xmax, cur = station[1], 0
# for i in range(1, n ):
# cur = cur + station[i] - need[i]
# if cur < 0:
# xmax += cur
# cur = 0
# cur = min(cur, station[i])
# xmax = min(xmax, station[i] - cur)
# if xmax < 0:
# flag = False
# break
# while lo <= hi:
# mid = lo + (hi - lo) // 2
# cur = mid
# flag = True
# for i in range(n - 1):
# cur = cur + station[i] - need[i]
# if cur < 0:
# lo = mid + 1
# flag = False
# break
# cur = min(cur, station[i])
# if flag:
# if station[-1] - mid + cur >= need[-1]:
# break
# else:
# flag = False
# hi = mid - 1
if flag and x + cur >= need[-1]:
print('YES')
else:
print('NO')
``` | output | 1 | 65,758 | 1 | 131,517 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The government of Berland decided to improve network coverage in his country. Berland has a unique structure: the capital in the center and n cities in a circle around the capital. The capital already has a good network coverage (so the government ignores it), but the i-th city contains a_i households that require a connection.
The government designed a plan to build n network stations between all pairs of neighboring cities which will maintain connections only for these cities. In other words, the i-th network station will provide service only for the i-th and the (i + 1)-th city (the n-th station is connected to the n-th and the 1-st city).
All network stations have capacities: the i-th station can provide the connection to at most b_i households.
Now the government asks you to check can the designed stations meet the needs of all cities or not β that is, is it possible to assign each household a network station so that each network station i provides the connection to at most b_i households.
Input
The first line contains a single integer t (1 β€ t β€ 10^4) β the number of test cases.
The first line of each test case contains the single integer n (2 β€ n β€ 10^6) β the number of cities and stations.
The second line of each test case contains n integers (1 β€ a_i β€ 10^9) β the number of households in the i-th city.
The third line of each test case contains n integers (1 β€ b_i β€ 10^9) β the capacities of the designed stations.
It's guaranteed that the sum of n over test cases doesn't exceed 10^6.
Output
For each test case, print YES, if the designed stations can meet the needs of all cities, or NO otherwise (case insensitive).
Example
Input
5
3
2 3 4
3 3 3
3
3 3 3
2 3 4
4
2 3 4 5
3 7 2 2
4
4 5 2 3
2 3 2 7
2
1 1
10 10
Output
YES
YES
NO
YES
YES
Note
In the first test case:
* the first network station can provide 2 connections to the first city and 1 connection to the second city;
* the second station can provide 2 connections to the second city and 1 connection to the third city;
* the third station can provide 3 connections to the third city.
In the second test case:
* the 1-st station can provide 2 connections to the 1-st city;
* the 2-nd station can provide 3 connections to the 2-nd city;
* the 3-rd station can provide 3 connections to the 3-rd city and 1 connection to the 1-st station.
In the third test case, the fourth city needs 5 connections, but the third and the fourth station has 4 connections in total. | instruction | 0 | 65,759 | 1 | 131,518 |
Tags: binary search, constructive algorithms, data structures, greedy
Correct Solution:
```
import sys
input=sys.stdin.buffer.readline
for _ in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
def cond(x):
temp=[0]*n
rest=[b[i] for i in range(n)]
temp[0]=x
for i in range(0,n-1):
if a[i]-temp[i]>0:
if rest[i]>=a[i]-temp[i]:rest[i]-=a[i]-temp[i];temp[i]+=a[i]-temp[i];temp[i+1]+=rest[i]
else:return False
else:temp[i+1]+=rest[i];rest[i]=0
return True
start=0
end=b[-1]
while end-start>1:
t=(end+start)//2
if cond(t):end=t
else:start=t
if cond(start):
x=start
temp=[0]*n
rest=[b[i] for i in range(n)]
temp[0]=x
temp[n-1]+=b[-1]-x
for i in range(0,n-1):
if a[i]-temp[i]>0:
if rest[i]>=a[i]-temp[i]:rest[i]-=a[i]-temp[i];temp[i]+=a[i]-temp[i];temp[i+1]+=rest[i]
else:temp[i+1]+=rest[i];rest[i]=0
if temp[-1]>=a[-1]:
print("YES")
else:
print("NO")
elif cond(end):
x=end
temp=[0]*n
rest=[b[i] for i in range(n)]
temp[0]=x
temp[n-1]+=b[-1]-x
for i in range(0,n-1):
if a[i]-temp[i]>0:
if rest[i]>=a[i]-temp[i]:rest[i]-=a[i]-temp[i];temp[i]+=a[i]-temp[i];temp[i+1]+=rest[i]
else:temp[i+1]+=rest[i];rest[i]=0
if temp[-1]>=a[-1]:
print("YES")
else:
print("NO")
else:
print("NO")
``` | output | 1 | 65,759 | 1 | 131,519 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The government of Berland decided to improve network coverage in his country. Berland has a unique structure: the capital in the center and n cities in a circle around the capital. The capital already has a good network coverage (so the government ignores it), but the i-th city contains a_i households that require a connection.
The government designed a plan to build n network stations between all pairs of neighboring cities which will maintain connections only for these cities. In other words, the i-th network station will provide service only for the i-th and the (i + 1)-th city (the n-th station is connected to the n-th and the 1-st city).
All network stations have capacities: the i-th station can provide the connection to at most b_i households.
Now the government asks you to check can the designed stations meet the needs of all cities or not β that is, is it possible to assign each household a network station so that each network station i provides the connection to at most b_i households.
Input
The first line contains a single integer t (1 β€ t β€ 10^4) β the number of test cases.
The first line of each test case contains the single integer n (2 β€ n β€ 10^6) β the number of cities and stations.
The second line of each test case contains n integers (1 β€ a_i β€ 10^9) β the number of households in the i-th city.
The third line of each test case contains n integers (1 β€ b_i β€ 10^9) β the capacities of the designed stations.
It's guaranteed that the sum of n over test cases doesn't exceed 10^6.
Output
For each test case, print YES, if the designed stations can meet the needs of all cities, or NO otherwise (case insensitive).
Example
Input
5
3
2 3 4
3 3 3
3
3 3 3
2 3 4
4
2 3 4 5
3 7 2 2
4
4 5 2 3
2 3 2 7
2
1 1
10 10
Output
YES
YES
NO
YES
YES
Note
In the first test case:
* the first network station can provide 2 connections to the first city and 1 connection to the second city;
* the second station can provide 2 connections to the second city and 1 connection to the third city;
* the third station can provide 3 connections to the third city.
In the second test case:
* the 1-st station can provide 2 connections to the 1-st city;
* the 2-nd station can provide 3 connections to the 2-nd city;
* the 3-rd station can provide 3 connections to the 3-rd city and 1 connection to the 1-st station.
In the third test case, the fourth city needs 5 connections, but the third and the fourth station has 4 connections in total. | instruction | 0 | 65,760 | 1 | 131,520 |
Tags: binary search, constructive algorithms, data structures, greedy
Correct Solution:
```
for _ in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
l=0
h=min(a[0],b[n-1])
while l<=h:
mid=l+(h-l)//2
# print(mid)
prev=mid
bol=True
for i in range(n-1):
# print(mid,prev)
if b[i]+prev<a[i]:
bol=False
break
prev=b[i]-max(0,a[i]-prev)
# print('-->',bol,prev)
if bol and prev+b[n-1]-mid>=a[n-1] :
print('YES')
break
# h=mid-1
elif not bol:
l=mid+1
else :
# prev+b[n-1]-mid<a[n-1]
# print('NO',prev+b[n-1]-mid)
h=mid-1
if l>h:
print('NO')
``` | output | 1 | 65,760 | 1 | 131,521 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The government of Berland decided to improve network coverage in his country. Berland has a unique structure: the capital in the center and n cities in a circle around the capital. The capital already has a good network coverage (so the government ignores it), but the i-th city contains a_i households that require a connection.
The government designed a plan to build n network stations between all pairs of neighboring cities which will maintain connections only for these cities. In other words, the i-th network station will provide service only for the i-th and the (i + 1)-th city (the n-th station is connected to the n-th and the 1-st city).
All network stations have capacities: the i-th station can provide the connection to at most b_i households.
Now the government asks you to check can the designed stations meet the needs of all cities or not β that is, is it possible to assign each household a network station so that each network station i provides the connection to at most b_i households.
Input
The first line contains a single integer t (1 β€ t β€ 10^4) β the number of test cases.
The first line of each test case contains the single integer n (2 β€ n β€ 10^6) β the number of cities and stations.
The second line of each test case contains n integers (1 β€ a_i β€ 10^9) β the number of households in the i-th city.
The third line of each test case contains n integers (1 β€ b_i β€ 10^9) β the capacities of the designed stations.
It's guaranteed that the sum of n over test cases doesn't exceed 10^6.
Output
For each test case, print YES, if the designed stations can meet the needs of all cities, or NO otherwise (case insensitive).
Example
Input
5
3
2 3 4
3 3 3
3
3 3 3
2 3 4
4
2 3 4 5
3 7 2 2
4
4 5 2 3
2 3 2 7
2
1 1
10 10
Output
YES
YES
NO
YES
YES
Note
In the first test case:
* the first network station can provide 2 connections to the first city and 1 connection to the second city;
* the second station can provide 2 connections to the second city and 1 connection to the third city;
* the third station can provide 3 connections to the third city.
In the second test case:
* the 1-st station can provide 2 connections to the 1-st city;
* the 2-nd station can provide 3 connections to the 2-nd city;
* the 3-rd station can provide 3 connections to the 3-rd city and 1 connection to the 1-st station.
In the third test case, the fourth city needs 5 connections, but the third and the fourth station has 4 connections in total. | instruction | 0 | 65,761 | 1 | 131,522 |
Tags: binary search, constructive algorithms, data structures, greedy
Correct Solution:
```
# Why do we fall ? So we can learn to pick ourselves up.
t = int(input())
for _ in range(0,t):
n = int(input())
aa = [int(i) for i in input().split()]
bb = [int(i) for i in input().split()]
done = [1]*n
left = 0
for i in range(0,n):
if left+bb[i] >= aa[i]:
left = min(bb[i]+left-aa[i],bb[i])
done[i] = 0
else:
done[i] = bb[i]+left-aa[i]
left = 0
for i in range(0,n):
if left+bb[i] >= aa[i]:
left = min(bb[i] + left - aa[i], bb[i])
done[i] = 0
else:
done[i] = bb[i]+left-aa[i]
left = 0
if done.count(0) == n:
print("YES")
else:
print("NO")
"""
5
3
2 3 4
3 3 3
3
3 3 3
2 3 4
4
2 3 4 5
3 7 2 2
4
4 5 2 3
2 3 2 7
2
1 1
10 10
"""
``` | output | 1 | 65,761 | 1 | 131,523 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The government of Berland decided to improve network coverage in his country. Berland has a unique structure: the capital in the center and n cities in a circle around the capital. The capital already has a good network coverage (so the government ignores it), but the i-th city contains a_i households that require a connection.
The government designed a plan to build n network stations between all pairs of neighboring cities which will maintain connections only for these cities. In other words, the i-th network station will provide service only for the i-th and the (i + 1)-th city (the n-th station is connected to the n-th and the 1-st city).
All network stations have capacities: the i-th station can provide the connection to at most b_i households.
Now the government asks you to check can the designed stations meet the needs of all cities or not β that is, is it possible to assign each household a network station so that each network station i provides the connection to at most b_i households.
Input
The first line contains a single integer t (1 β€ t β€ 10^4) β the number of test cases.
The first line of each test case contains the single integer n (2 β€ n β€ 10^6) β the number of cities and stations.
The second line of each test case contains n integers (1 β€ a_i β€ 10^9) β the number of households in the i-th city.
The third line of each test case contains n integers (1 β€ b_i β€ 10^9) β the capacities of the designed stations.
It's guaranteed that the sum of n over test cases doesn't exceed 10^6.
Output
For each test case, print YES, if the designed stations can meet the needs of all cities, or NO otherwise (case insensitive).
Example
Input
5
3
2 3 4
3 3 3
3
3 3 3
2 3 4
4
2 3 4 5
3 7 2 2
4
4 5 2 3
2 3 2 7
2
1 1
10 10
Output
YES
YES
NO
YES
YES
Note
In the first test case:
* the first network station can provide 2 connections to the first city and 1 connection to the second city;
* the second station can provide 2 connections to the second city and 1 connection to the third city;
* the third station can provide 3 connections to the third city.
In the second test case:
* the 1-st station can provide 2 connections to the 1-st city;
* the 2-nd station can provide 3 connections to the 2-nd city;
* the 3-rd station can provide 3 connections to the 3-rd city and 1 connection to the 1-st station.
In the third test case, the fourth city needs 5 connections, but the third and the fourth station has 4 connections in total.
Submitted Solution:
```
def main():
for case in range(int(input())):
n = int(input().strip())
as_ = [int(t) for t in input().strip().split()]
bs = [int(t) for t in input().strip().split()]
print(solve(as_=as_, bs=bs))
def solve(as_, bs):
if get_update_dir(as_, bs, 0) == 0:
return 'YES'
lt = 0
gt = as_[0] + 1
while gt > lt + 1:
mid = (lt + gt) // 2
update_dir = get_update_dir(as_, bs, mid)
if update_dir == 0:
return 'YES'
if update_dir > 0:
lt = mid
else:
gt = mid
return 'NO'
def get_update_dir(as_, bs, x):
if x > as_[0] or x > bs[-1]:
return -1
if x < 0:
return +1
left = x
for a, b in zip(as_, bs):
right = a - min(left, a)
if right > b:
return +1
left = b - right
if right + x > bs[-1]:
return -1
return 0
main()
``` | instruction | 0 | 65,762 | 1 | 131,524 |
Yes | output | 1 | 65,762 | 1 | 131,525 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The government of Berland decided to improve network coverage in his country. Berland has a unique structure: the capital in the center and n cities in a circle around the capital. The capital already has a good network coverage (so the government ignores it), but the i-th city contains a_i households that require a connection.
The government designed a plan to build n network stations between all pairs of neighboring cities which will maintain connections only for these cities. In other words, the i-th network station will provide service only for the i-th and the (i + 1)-th city (the n-th station is connected to the n-th and the 1-st city).
All network stations have capacities: the i-th station can provide the connection to at most b_i households.
Now the government asks you to check can the designed stations meet the needs of all cities or not β that is, is it possible to assign each household a network station so that each network station i provides the connection to at most b_i households.
Input
The first line contains a single integer t (1 β€ t β€ 10^4) β the number of test cases.
The first line of each test case contains the single integer n (2 β€ n β€ 10^6) β the number of cities and stations.
The second line of each test case contains n integers (1 β€ a_i β€ 10^9) β the number of households in the i-th city.
The third line of each test case contains n integers (1 β€ b_i β€ 10^9) β the capacities of the designed stations.
It's guaranteed that the sum of n over test cases doesn't exceed 10^6.
Output
For each test case, print YES, if the designed stations can meet the needs of all cities, or NO otherwise (case insensitive).
Example
Input
5
3
2 3 4
3 3 3
3
3 3 3
2 3 4
4
2 3 4 5
3 7 2 2
4
4 5 2 3
2 3 2 7
2
1 1
10 10
Output
YES
YES
NO
YES
YES
Note
In the first test case:
* the first network station can provide 2 connections to the first city and 1 connection to the second city;
* the second station can provide 2 connections to the second city and 1 connection to the third city;
* the third station can provide 3 connections to the third city.
In the second test case:
* the 1-st station can provide 2 connections to the 1-st city;
* the 2-nd station can provide 3 connections to the 2-nd city;
* the 3-rd station can provide 3 connections to the 3-rd city and 1 connection to the 1-st station.
In the third test case, the fourth city needs 5 connections, but the third and the fourth station has 4 connections in total.
Submitted Solution:
```
t = int(input())
for i in range(t):
n = int(input())
a = list(map(int, input().split(' ')))
b = list(map(int, input().split(' ')))
if sum(a) > sum(b):
print('NO')
continue
min_x = [max(0, a[i] - b[i]) for i in range(n)]
min_k = [max(0, b[i] - a[i]) for i in range(n)]
max_k = [b[i] for i in range(n)]
f = lambda i, x: min(min_k[i] + x - min_x[i], max_k[i])
a = f(0, b[-1])
iterations = 2*n
if iterations >= 500:
iterations = n+25
for i in range(1, iterations):
if (max_k[(i-1)%n] < min_x[i%n]) or (a < 0):
a = -1
break
a = f(i%n, a)
if (a >= 0):
print('YES')
else:
print('NO')
``` | instruction | 0 | 65,763 | 1 | 131,526 |
Yes | output | 1 | 65,763 | 1 | 131,527 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The government of Berland decided to improve network coverage in his country. Berland has a unique structure: the capital in the center and n cities in a circle around the capital. The capital already has a good network coverage (so the government ignores it), but the i-th city contains a_i households that require a connection.
The government designed a plan to build n network stations between all pairs of neighboring cities which will maintain connections only for these cities. In other words, the i-th network station will provide service only for the i-th and the (i + 1)-th city (the n-th station is connected to the n-th and the 1-st city).
All network stations have capacities: the i-th station can provide the connection to at most b_i households.
Now the government asks you to check can the designed stations meet the needs of all cities or not β that is, is it possible to assign each household a network station so that each network station i provides the connection to at most b_i households.
Input
The first line contains a single integer t (1 β€ t β€ 10^4) β the number of test cases.
The first line of each test case contains the single integer n (2 β€ n β€ 10^6) β the number of cities and stations.
The second line of each test case contains n integers (1 β€ a_i β€ 10^9) β the number of households in the i-th city.
The third line of each test case contains n integers (1 β€ b_i β€ 10^9) β the capacities of the designed stations.
It's guaranteed that the sum of n over test cases doesn't exceed 10^6.
Output
For each test case, print YES, if the designed stations can meet the needs of all cities, or NO otherwise (case insensitive).
Example
Input
5
3
2 3 4
3 3 3
3
3 3 3
2 3 4
4
2 3 4 5
3 7 2 2
4
4 5 2 3
2 3 2 7
2
1 1
10 10
Output
YES
YES
NO
YES
YES
Note
In the first test case:
* the first network station can provide 2 connections to the first city and 1 connection to the second city;
* the second station can provide 2 connections to the second city and 1 connection to the third city;
* the third station can provide 3 connections to the third city.
In the second test case:
* the 1-st station can provide 2 connections to the 1-st city;
* the 2-nd station can provide 3 connections to the 2-nd city;
* the 3-rd station can provide 3 connections to the 3-rd city and 1 connection to the 1-st station.
In the third test case, the fourth city needs 5 connections, but the third and the fourth station has 4 connections in total.
Submitted Solution:
```
from sys import stdin, stdout
# 4 5 2 3
# 2 3 2 7
# -2 -2 0 4
#
# 3 3 3
# 2 3 4
# -1 0 1
# 2 3 4 5
# 3 7 2 2
# 1 4 -2 -3
if __name__ == '__main__':
def network_coverage(n, a, b):
l = 0
h = min(a[0], b[-1]) + 1
while l < h:
take = (l + h)//2
avail = take
for i in range(n):
need = max(0, a[i] - avail)
if i < n-1:
if b[i] < need:
l = take + 1
break
else:
if b[i] - take < need:
h = take
break
else:
return "YES"
avail = b[i] - need
return "NO"
t = int(stdin.readline())
for i in range(t):
n = int(stdin.readline())
a = list(map(int, stdin.readline().split()))
b = list(map(int, stdin.readline().split()))
stdout.write(network_coverage(n, a, b) + '\n')
``` | instruction | 0 | 65,764 | 1 | 131,528 |
Yes | output | 1 | 65,764 | 1 | 131,529 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The government of Berland decided to improve network coverage in his country. Berland has a unique structure: the capital in the center and n cities in a circle around the capital. The capital already has a good network coverage (so the government ignores it), but the i-th city contains a_i households that require a connection.
The government designed a plan to build n network stations between all pairs of neighboring cities which will maintain connections only for these cities. In other words, the i-th network station will provide service only for the i-th and the (i + 1)-th city (the n-th station is connected to the n-th and the 1-st city).
All network stations have capacities: the i-th station can provide the connection to at most b_i households.
Now the government asks you to check can the designed stations meet the needs of all cities or not β that is, is it possible to assign each household a network station so that each network station i provides the connection to at most b_i households.
Input
The first line contains a single integer t (1 β€ t β€ 10^4) β the number of test cases.
The first line of each test case contains the single integer n (2 β€ n β€ 10^6) β the number of cities and stations.
The second line of each test case contains n integers (1 β€ a_i β€ 10^9) β the number of households in the i-th city.
The third line of each test case contains n integers (1 β€ b_i β€ 10^9) β the capacities of the designed stations.
It's guaranteed that the sum of n over test cases doesn't exceed 10^6.
Output
For each test case, print YES, if the designed stations can meet the needs of all cities, or NO otherwise (case insensitive).
Example
Input
5
3
2 3 4
3 3 3
3
3 3 3
2 3 4
4
2 3 4 5
3 7 2 2
4
4 5 2 3
2 3 2 7
2
1 1
10 10
Output
YES
YES
NO
YES
YES
Note
In the first test case:
* the first network station can provide 2 connections to the first city and 1 connection to the second city;
* the second station can provide 2 connections to the second city and 1 connection to the third city;
* the third station can provide 3 connections to the third city.
In the second test case:
* the 1-st station can provide 2 connections to the 1-st city;
* the 2-nd station can provide 3 connections to the 2-nd city;
* the 3-rd station can provide 3 connections to the 3-rd city and 1 connection to the 1-st station.
In the third test case, the fourth city needs 5 connections, but the third and the fourth station has 4 connections in total.
Submitted Solution:
```
line = input()
t = int(line)
for _ in range(t):
line = input()
n = int(line)
line = input()
need = [int(i) for i in line.split(' ')]
line = input()
station =[int(i) for i in line.split(' ')]
lo, hi = 0, station[-1]
flag = True
while lo <= hi:
mid = lo + (hi - lo) // 2
cur = mid
flag = True
for i in range(n - 1):
cur = cur + station[i] - need[i]
if cur < 0:
lo = mid + 1
flag = False
break
cur = min(cur, station[i])
if flag:
if station[-1] - mid + cur >= need[-1]:
break
else:
flag = False
hi = mid - 1
if flag:
print('YES')
else:
print('NO')
``` | instruction | 0 | 65,765 | 1 | 131,530 |
Yes | output | 1 | 65,765 | 1 | 131,531 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The government of Berland decided to improve network coverage in his country. Berland has a unique structure: the capital in the center and n cities in a circle around the capital. The capital already has a good network coverage (so the government ignores it), but the i-th city contains a_i households that require a connection.
The government designed a plan to build n network stations between all pairs of neighboring cities which will maintain connections only for these cities. In other words, the i-th network station will provide service only for the i-th and the (i + 1)-th city (the n-th station is connected to the n-th and the 1-st city).
All network stations have capacities: the i-th station can provide the connection to at most b_i households.
Now the government asks you to check can the designed stations meet the needs of all cities or not β that is, is it possible to assign each household a network station so that each network station i provides the connection to at most b_i households.
Input
The first line contains a single integer t (1 β€ t β€ 10^4) β the number of test cases.
The first line of each test case contains the single integer n (2 β€ n β€ 10^6) β the number of cities and stations.
The second line of each test case contains n integers (1 β€ a_i β€ 10^9) β the number of households in the i-th city.
The third line of each test case contains n integers (1 β€ b_i β€ 10^9) β the capacities of the designed stations.
It's guaranteed that the sum of n over test cases doesn't exceed 10^6.
Output
For each test case, print YES, if the designed stations can meet the needs of all cities, or NO otherwise (case insensitive).
Example
Input
5
3
2 3 4
3 3 3
3
3 3 3
2 3 4
4
2 3 4 5
3 7 2 2
4
4 5 2 3
2 3 2 7
2
1 1
10 10
Output
YES
YES
NO
YES
YES
Note
In the first test case:
* the first network station can provide 2 connections to the first city and 1 connection to the second city;
* the second station can provide 2 connections to the second city and 1 connection to the third city;
* the third station can provide 3 connections to the third city.
In the second test case:
* the 1-st station can provide 2 connections to the 1-st city;
* the 2-nd station can provide 3 connections to the 2-nd city;
* the 3-rd station can provide 3 connections to the 3-rd city and 1 connection to the 1-st station.
In the third test case, the fourth city needs 5 connections, but the third and the fourth station has 4 connections in total.
Submitted Solution:
```
for t in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
i = 0
while i <= n:
a_need = a[i%n] + a[(i + 1) % n]
if b[i%n] >= a_need and b[i%n]:
b[i%n] = 0
a[i%n] = 0
a[(i + 1) % n] = 0
if i > 0:
i = 0
i += 1
if sum(a) > sum(b):
print("NO")
else:
print("YES")
``` | instruction | 0 | 65,766 | 1 | 131,532 |
No | output | 1 | 65,766 | 1 | 131,533 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The government of Berland decided to improve network coverage in his country. Berland has a unique structure: the capital in the center and n cities in a circle around the capital. The capital already has a good network coverage (so the government ignores it), but the i-th city contains a_i households that require a connection.
The government designed a plan to build n network stations between all pairs of neighboring cities which will maintain connections only for these cities. In other words, the i-th network station will provide service only for the i-th and the (i + 1)-th city (the n-th station is connected to the n-th and the 1-st city).
All network stations have capacities: the i-th station can provide the connection to at most b_i households.
Now the government asks you to check can the designed stations meet the needs of all cities or not β that is, is it possible to assign each household a network station so that each network station i provides the connection to at most b_i households.
Input
The first line contains a single integer t (1 β€ t β€ 10^4) β the number of test cases.
The first line of each test case contains the single integer n (2 β€ n β€ 10^6) β the number of cities and stations.
The second line of each test case contains n integers (1 β€ a_i β€ 10^9) β the number of households in the i-th city.
The third line of each test case contains n integers (1 β€ b_i β€ 10^9) β the capacities of the designed stations.
It's guaranteed that the sum of n over test cases doesn't exceed 10^6.
Output
For each test case, print YES, if the designed stations can meet the needs of all cities, or NO otherwise (case insensitive).
Example
Input
5
3
2 3 4
3 3 3
3
3 3 3
2 3 4
4
2 3 4 5
3 7 2 2
4
4 5 2 3
2 3 2 7
2
1 1
10 10
Output
YES
YES
NO
YES
YES
Note
In the first test case:
* the first network station can provide 2 connections to the first city and 1 connection to the second city;
* the second station can provide 2 connections to the second city and 1 connection to the third city;
* the third station can provide 3 connections to the third city.
In the second test case:
* the 1-st station can provide 2 connections to the 1-st city;
* the 2-nd station can provide 3 connections to the 2-nd city;
* the 3-rd station can provide 3 connections to the 3-rd city and 1 connection to the 1-st station.
In the third test case, the fourth city needs 5 connections, but the third and the fourth station has 4 connections in total.
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush
# ------------------------------
# f = open('../input.txt')
# sys.stdin = f
def main():
for _ in range(N()):
n = N()
arra = RLL()
arrb = RLL()
l, r = 0, arrb[0]
def c(num):
dif = arrb[0]-num
hv = dif
for i in range(1, n):
now = arra[i]-hv
if arrb[i]<now and now>=0:
return False
if now>=0:
hv = arrb[i]-now
else:
hv = arrb[i]
return True if num+hv>=arra[0] else False
res = False
while l<=r:
m = (l+r)//2
# print(c(m), m)
if c(m):
res = True
break
else:
r = m-1
print('YES' if res else 'NO')
if __name__ == "__main__":
main()
``` | instruction | 0 | 65,767 | 1 | 131,534 |
No | output | 1 | 65,767 | 1 | 131,535 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The government of Berland decided to improve network coverage in his country. Berland has a unique structure: the capital in the center and n cities in a circle around the capital. The capital already has a good network coverage (so the government ignores it), but the i-th city contains a_i households that require a connection.
The government designed a plan to build n network stations between all pairs of neighboring cities which will maintain connections only for these cities. In other words, the i-th network station will provide service only for the i-th and the (i + 1)-th city (the n-th station is connected to the n-th and the 1-st city).
All network stations have capacities: the i-th station can provide the connection to at most b_i households.
Now the government asks you to check can the designed stations meet the needs of all cities or not β that is, is it possible to assign each household a network station so that each network station i provides the connection to at most b_i households.
Input
The first line contains a single integer t (1 β€ t β€ 10^4) β the number of test cases.
The first line of each test case contains the single integer n (2 β€ n β€ 10^6) β the number of cities and stations.
The second line of each test case contains n integers (1 β€ a_i β€ 10^9) β the number of households in the i-th city.
The third line of each test case contains n integers (1 β€ b_i β€ 10^9) β the capacities of the designed stations.
It's guaranteed that the sum of n over test cases doesn't exceed 10^6.
Output
For each test case, print YES, if the designed stations can meet the needs of all cities, or NO otherwise (case insensitive).
Example
Input
5
3
2 3 4
3 3 3
3
3 3 3
2 3 4
4
2 3 4 5
3 7 2 2
4
4 5 2 3
2 3 2 7
2
1 1
10 10
Output
YES
YES
NO
YES
YES
Note
In the first test case:
* the first network station can provide 2 connections to the first city and 1 connection to the second city;
* the second station can provide 2 connections to the second city and 1 connection to the third city;
* the third station can provide 3 connections to the third city.
In the second test case:
* the 1-st station can provide 2 connections to the 1-st city;
* the 2-nd station can provide 3 connections to the 2-nd city;
* the 3-rd station can provide 3 connections to the 3-rd city and 1 connection to the 1-st station.
In the third test case, the fourth city needs 5 connections, but the third and the fourth station has 4 connections in total.
Submitted Solution:
```
for _ in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
l=0
h=min(a[0],b[n-1])
while l<=h:
mid=l+(h-l)//2
# print(mid)
prev=mid
bol=True
for i in range(n-1):
# print(mid,prev)
if b[i]+prev<a[i]:
bol=False
break
prev=b[i]-max(0,a[i]-prev)
# print('-->',bol,prev)
if not bol:
l=mid+1
if prev+b[n-1]-mid<a[n-1] :
# print('NO',prev+b[n-1]-mid)
h=mid-1
if bol and prev+b[n-1]-mid>=a[n-1] :
print('YES')
break
# h=mid-1
if l>h:
print('NO')
``` | instruction | 0 | 65,768 | 1 | 131,536 |
No | output | 1 | 65,768 | 1 | 131,537 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The government of Berland decided to improve network coverage in his country. Berland has a unique structure: the capital in the center and n cities in a circle around the capital. The capital already has a good network coverage (so the government ignores it), but the i-th city contains a_i households that require a connection.
The government designed a plan to build n network stations between all pairs of neighboring cities which will maintain connections only for these cities. In other words, the i-th network station will provide service only for the i-th and the (i + 1)-th city (the n-th station is connected to the n-th and the 1-st city).
All network stations have capacities: the i-th station can provide the connection to at most b_i households.
Now the government asks you to check can the designed stations meet the needs of all cities or not β that is, is it possible to assign each household a network station so that each network station i provides the connection to at most b_i households.
Input
The first line contains a single integer t (1 β€ t β€ 10^4) β the number of test cases.
The first line of each test case contains the single integer n (2 β€ n β€ 10^6) β the number of cities and stations.
The second line of each test case contains n integers (1 β€ a_i β€ 10^9) β the number of households in the i-th city.
The third line of each test case contains n integers (1 β€ b_i β€ 10^9) β the capacities of the designed stations.
It's guaranteed that the sum of n over test cases doesn't exceed 10^6.
Output
For each test case, print YES, if the designed stations can meet the needs of all cities, or NO otherwise (case insensitive).
Example
Input
5
3
2 3 4
3 3 3
3
3 3 3
2 3 4
4
2 3 4 5
3 7 2 2
4
4 5 2 3
2 3 2 7
2
1 1
10 10
Output
YES
YES
NO
YES
YES
Note
In the first test case:
* the first network station can provide 2 connections to the first city and 1 connection to the second city;
* the second station can provide 2 connections to the second city and 1 connection to the third city;
* the third station can provide 3 connections to the third city.
In the second test case:
* the 1-st station can provide 2 connections to the 1-st city;
* the 2-nd station can provide 3 connections to the 2-nd city;
* the 3-rd station can provide 3 connections to the 3-rd city and 1 connection to the 1-st station.
In the third test case, the fourth city needs 5 connections, but the third and the fourth station has 4 connections in total.
Submitted Solution:
```
for tc in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
need = 0
ad = 0
extra = 2e9
good = True
for i in range(n-1, -1, -1):
if b[i] < need:
print('NO')
good = False
break
val = b[i] - a[i]
to_ad = min(extra, max(0, val-need))
ad += to_ad
extra = min(extra-to_ad, b[i]-need-to_ad)
need = max(0, need-val)
if ad >= need:
print('YES')
else:
if good:
print('NO')
``` | instruction | 0 | 65,769 | 1 | 131,538 |
No | output | 1 | 65,769 | 1 | 131,539 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya takes part in the orienteering competition. There are n checkpoints located along the line at coordinates x1, x2, ..., xn. Vasya starts at the point with coordinate a. His goal is to visit at least n - 1 checkpoint in order to finish the competition. Participant are allowed to visit checkpoints in arbitrary order.
Vasya wants to pick such checkpoints and the order of visiting them that the total distance travelled is minimized. He asks you to calculate this minimum possible value.
Input
The first line of the input contains two integers n and a (1 β€ n β€ 100 000, - 1 000 000 β€ a β€ 1 000 000) β the number of checkpoints and Vasya's starting position respectively.
The second line contains n integers x1, x2, ..., xn ( - 1 000 000 β€ xi β€ 1 000 000) β coordinates of the checkpoints.
Output
Print one integer β the minimum distance Vasya has to travel in order to visit at least n - 1 checkpoint.
Examples
Input
3 10
1 7 12
Output
7
Input
2 0
11 -10
Output
10
Input
5 0
0 0 1000 0 0
Output
0
Note
In the first sample Vasya has to visit at least two checkpoints. The optimal way to achieve this is the walk to the third checkpoints (distance is 12 - 10 = 2) and then proceed to the second one (distance is 12 - 7 = 5). The total distance is equal to 2 + 5 = 7.
In the second sample it's enough to visit only one checkpoint so Vasya should just walk to the point - 10. | instruction | 0 | 66,065 | 1 | 132,130 |
Tags: greedy, implementation, sortings
Correct Solution:
```
import sys
input = sys.stdin.readline
n, a = map(int, input().split())
x = list(map(int, input().split()))
x.sort()
if n==1:
print(0)
exit()
ans = abs(a-x[0])+abs(x[0]-x[n-2])
ans = min(ans, abs(a-x[n-2])+abs(x[n-2]-x[0]))
ans = min(ans, abs(a-x[1])+abs(x[1]-x[-1]))
ans = min(ans, abs(a-x[-1])+abs(x[-1]-x[1]))
print(ans)
``` | output | 1 | 66,065 | 1 | 132,131 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya takes part in the orienteering competition. There are n checkpoints located along the line at coordinates x1, x2, ..., xn. Vasya starts at the point with coordinate a. His goal is to visit at least n - 1 checkpoint in order to finish the competition. Participant are allowed to visit checkpoints in arbitrary order.
Vasya wants to pick such checkpoints and the order of visiting them that the total distance travelled is minimized. He asks you to calculate this minimum possible value.
Input
The first line of the input contains two integers n and a (1 β€ n β€ 100 000, - 1 000 000 β€ a β€ 1 000 000) β the number of checkpoints and Vasya's starting position respectively.
The second line contains n integers x1, x2, ..., xn ( - 1 000 000 β€ xi β€ 1 000 000) β coordinates of the checkpoints.
Output
Print one integer β the minimum distance Vasya has to travel in order to visit at least n - 1 checkpoint.
Examples
Input
3 10
1 7 12
Output
7
Input
2 0
11 -10
Output
10
Input
5 0
0 0 1000 0 0
Output
0
Note
In the first sample Vasya has to visit at least two checkpoints. The optimal way to achieve this is the walk to the third checkpoints (distance is 12 - 10 = 2) and then proceed to the second one (distance is 12 - 7 = 5). The total distance is equal to 2 + 5 = 7.
In the second sample it's enough to visit only one checkpoint so Vasya should just walk to the point - 10. | instruction | 0 | 66,066 | 1 | 132,132 |
Tags: greedy, implementation, sortings
Correct Solution:
```
n,p = map(int,input().split())
a = list(map(int,input().split()))
a.sort()
if n==1:
print(0)
elif n==2:
print(min(abs(a[0]-p),abs(a[1]-p)))
else:
a1 = min(abs(a[0]-p),abs(a[-2]-p)) + abs(a[0]-a[-2])
a2 = min(abs(a[1]-p),abs(a[-1]-p)) + abs(a[1]-a[-1])
print(min(a1,a2))
``` | output | 1 | 66,066 | 1 | 132,133 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya takes part in the orienteering competition. There are n checkpoints located along the line at coordinates x1, x2, ..., xn. Vasya starts at the point with coordinate a. His goal is to visit at least n - 1 checkpoint in order to finish the competition. Participant are allowed to visit checkpoints in arbitrary order.
Vasya wants to pick such checkpoints and the order of visiting them that the total distance travelled is minimized. He asks you to calculate this minimum possible value.
Input
The first line of the input contains two integers n and a (1 β€ n β€ 100 000, - 1 000 000 β€ a β€ 1 000 000) β the number of checkpoints and Vasya's starting position respectively.
The second line contains n integers x1, x2, ..., xn ( - 1 000 000 β€ xi β€ 1 000 000) β coordinates of the checkpoints.
Output
Print one integer β the minimum distance Vasya has to travel in order to visit at least n - 1 checkpoint.
Examples
Input
3 10
1 7 12
Output
7
Input
2 0
11 -10
Output
10
Input
5 0
0 0 1000 0 0
Output
0
Note
In the first sample Vasya has to visit at least two checkpoints. The optimal way to achieve this is the walk to the third checkpoints (distance is 12 - 10 = 2) and then proceed to the second one (distance is 12 - 7 = 5). The total distance is equal to 2 + 5 = 7.
In the second sample it's enough to visit only one checkpoint so Vasya should just walk to the point - 10. | instruction | 0 | 66,067 | 1 | 132,134 |
Tags: greedy, implementation, sortings
Correct Solution:
```
import sys
input = sys.stdin.readline
n,m = map(int,input().split())
t= list(map(int,input().split()))
t.sort()
if n<=1:
print(0)
else:
ans=9999999999999999
for j in range(n):
if j+(n-2)<n:
#print(t[j+n-2]-abs(m-t[j]),t[j])
ans=min(ans,(t[j+n-2]-t[j])+abs(m-t[j]))
x=n-1-j
if x-(n-2)>=0:
ans=min( ans, abs(t[x]-m)+(t[x]-t[x-(n-2)]) )
print(ans)
``` | output | 1 | 66,067 | 1 | 132,135 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya takes part in the orienteering competition. There are n checkpoints located along the line at coordinates x1, x2, ..., xn. Vasya starts at the point with coordinate a. His goal is to visit at least n - 1 checkpoint in order to finish the competition. Participant are allowed to visit checkpoints in arbitrary order.
Vasya wants to pick such checkpoints and the order of visiting them that the total distance travelled is minimized. He asks you to calculate this minimum possible value.
Input
The first line of the input contains two integers n and a (1 β€ n β€ 100 000, - 1 000 000 β€ a β€ 1 000 000) β the number of checkpoints and Vasya's starting position respectively.
The second line contains n integers x1, x2, ..., xn ( - 1 000 000 β€ xi β€ 1 000 000) β coordinates of the checkpoints.
Output
Print one integer β the minimum distance Vasya has to travel in order to visit at least n - 1 checkpoint.
Examples
Input
3 10
1 7 12
Output
7
Input
2 0
11 -10
Output
10
Input
5 0
0 0 1000 0 0
Output
0
Note
In the first sample Vasya has to visit at least two checkpoints. The optimal way to achieve this is the walk to the third checkpoints (distance is 12 - 10 = 2) and then proceed to the second one (distance is 12 - 7 = 5). The total distance is equal to 2 + 5 = 7.
In the second sample it's enough to visit only one checkpoint so Vasya should just walk to the point - 10. | instruction | 0 | 66,068 | 1 | 132,136 |
Tags: greedy, implementation, sortings
Correct Solution:
```
n, start = map(int, input().split());
x = list(map(int, input().split()));
x = sorted(x);
if n == 1:
print(0);
else:
print(min(abs(start - x[0]) + abs(x[len(x) - 2] - x[0]), \
abs(start - x[1]) + abs(x[len(x) - 1] - x[1]), \
abs(x[len(x) - 1] - start) + abs(x[len(x) - 1] - x[1]), \
abs(x[len(x) - 2] - start) + abs(x[len(x) - 2] - x[0])));
``` | output | 1 | 66,068 | 1 | 132,137 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya takes part in the orienteering competition. There are n checkpoints located along the line at coordinates x1, x2, ..., xn. Vasya starts at the point with coordinate a. His goal is to visit at least n - 1 checkpoint in order to finish the competition. Participant are allowed to visit checkpoints in arbitrary order.
Vasya wants to pick such checkpoints and the order of visiting them that the total distance travelled is minimized. He asks you to calculate this minimum possible value.
Input
The first line of the input contains two integers n and a (1 β€ n β€ 100 000, - 1 000 000 β€ a β€ 1 000 000) β the number of checkpoints and Vasya's starting position respectively.
The second line contains n integers x1, x2, ..., xn ( - 1 000 000 β€ xi β€ 1 000 000) β coordinates of the checkpoints.
Output
Print one integer β the minimum distance Vasya has to travel in order to visit at least n - 1 checkpoint.
Examples
Input
3 10
1 7 12
Output
7
Input
2 0
11 -10
Output
10
Input
5 0
0 0 1000 0 0
Output
0
Note
In the first sample Vasya has to visit at least two checkpoints. The optimal way to achieve this is the walk to the third checkpoints (distance is 12 - 10 = 2) and then proceed to the second one (distance is 12 - 7 = 5). The total distance is equal to 2 + 5 = 7.
In the second sample it's enough to visit only one checkpoint so Vasya should just walk to the point - 10. | instruction | 0 | 66,069 | 1 | 132,138 |
Tags: greedy, implementation, sortings
Correct Solution:
```
def solve():
n, a = map(int, input().split())
x = list(map(int, input().split()))
x.append(a)
x.sort()
bi = 0
for i in range(n + 1):
if x[i] == a:
bi = i
break
ans = float('inf')
for s in range(2):
l = 0
r = 0
ok = x[s] == a
for i in range(s + 1, s + n):
ok = ok or x[i] == a
if i <= bi:
l += x[i] - x[i - 1]
else:
r += x[i] - x[i - 1]
if ok:
ans = min(ans, min(l, r) * 2 + max(l, r))
print(ans)
def main():
solve()
if __name__ == '__main__':
main()
``` | output | 1 | 66,069 | 1 | 132,139 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya takes part in the orienteering competition. There are n checkpoints located along the line at coordinates x1, x2, ..., xn. Vasya starts at the point with coordinate a. His goal is to visit at least n - 1 checkpoint in order to finish the competition. Participant are allowed to visit checkpoints in arbitrary order.
Vasya wants to pick such checkpoints and the order of visiting them that the total distance travelled is minimized. He asks you to calculate this minimum possible value.
Input
The first line of the input contains two integers n and a (1 β€ n β€ 100 000, - 1 000 000 β€ a β€ 1 000 000) β the number of checkpoints and Vasya's starting position respectively.
The second line contains n integers x1, x2, ..., xn ( - 1 000 000 β€ xi β€ 1 000 000) β coordinates of the checkpoints.
Output
Print one integer β the minimum distance Vasya has to travel in order to visit at least n - 1 checkpoint.
Examples
Input
3 10
1 7 12
Output
7
Input
2 0
11 -10
Output
10
Input
5 0
0 0 1000 0 0
Output
0
Note
In the first sample Vasya has to visit at least two checkpoints. The optimal way to achieve this is the walk to the third checkpoints (distance is 12 - 10 = 2) and then proceed to the second one (distance is 12 - 7 = 5). The total distance is equal to 2 + 5 = 7.
In the second sample it's enough to visit only one checkpoint so Vasya should just walk to the point - 10. | instruction | 0 | 66,070 | 1 | 132,140 |
Tags: greedy, implementation, sortings
Correct Solution:
```
import traceback
import math
from collections import defaultdict
from functools import lru_cache
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")
def geti():
return int(input())
def gets():
return input()
def getil():
return list(map(int, input().split()))
def getsl():
return input().split()
def get2d(nrows, ncols, n=0):
return [[n] * ncols for r in range(nrows)]
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
inf = float('inf')
mod = 10 ** 9 + 7
def main():
N, s = getil()
a = getil()
if N == 1: return 0
a.sort()
diffl, diffr = a[-2] - a[0], a[-1] - a[1]
dm = lambda x, y, z: min(abs(x-y), abs(x-z))
return min( dm(s, a[0], a[-2]) + diffl,
dm(s, a[1], a[-1]) + diffr)
try:
ans = main()
# ans = 'Yes' if ans else 'No'
print(ans)
except Exception as e:
print(e)
traceback.print_exc()
``` | output | 1 | 66,070 | 1 | 132,141 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya takes part in the orienteering competition. There are n checkpoints located along the line at coordinates x1, x2, ..., xn. Vasya starts at the point with coordinate a. His goal is to visit at least n - 1 checkpoint in order to finish the competition. Participant are allowed to visit checkpoints in arbitrary order.
Vasya wants to pick such checkpoints and the order of visiting them that the total distance travelled is minimized. He asks you to calculate this minimum possible value.
Input
The first line of the input contains two integers n and a (1 β€ n β€ 100 000, - 1 000 000 β€ a β€ 1 000 000) β the number of checkpoints and Vasya's starting position respectively.
The second line contains n integers x1, x2, ..., xn ( - 1 000 000 β€ xi β€ 1 000 000) β coordinates of the checkpoints.
Output
Print one integer β the minimum distance Vasya has to travel in order to visit at least n - 1 checkpoint.
Examples
Input
3 10
1 7 12
Output
7
Input
2 0
11 -10
Output
10
Input
5 0
0 0 1000 0 0
Output
0
Note
In the first sample Vasya has to visit at least two checkpoints. The optimal way to achieve this is the walk to the third checkpoints (distance is 12 - 10 = 2) and then proceed to the second one (distance is 12 - 7 = 5). The total distance is equal to 2 + 5 = 7.
In the second sample it's enough to visit only one checkpoint so Vasya should just walk to the point - 10. | instruction | 0 | 66,071 | 1 | 132,142 |
Tags: greedy, implementation, sortings
Correct Solution:
```
class CodeforcesTask709BSolution:
def __init__(self):
self.result = ''
self.n_a = []
self.points = []
def read_input(self):
self.n_a = [int(x) for x in input().split(" ")]
self.points = [int(x) for x in input().split(" ")]
def process_task(self):
right_points = [x - self.n_a[1] for x in self.points if x >= self.n_a[1]]
left_points = [self.n_a[1] - x for x in self.points if x < self.n_a[1]]
right_points.sort()
left_points.sort()
if len(right_points) > 0:
full_right = right_points[-1]
else:
full_right = 0
if len(left_points) > 0:
full_left = left_points[-1]
else:
full_left = 0
if len(right_points) > 1:
semi_right = right_points[-2]
else:
semi_right = 0
if len(left_points) > 1:
semi_left = left_points[-2]
else:
semi_left = 0
variant1 = semi_left * 2 + full_right
variant2 = semi_right * 2 + full_left
variant3 = semi_left + full_right * 2
variant4 = semi_right + full_left * 2
self.result = str(min(variant1, variant2, variant3, variant4))
def get_result(self):
return self.result
if __name__ == "__main__":
Solution = CodeforcesTask709BSolution()
Solution.read_input()
Solution.process_task()
print(Solution.get_result())
``` | output | 1 | 66,071 | 1 | 132,143 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya takes part in the orienteering competition. There are n checkpoints located along the line at coordinates x1, x2, ..., xn. Vasya starts at the point with coordinate a. His goal is to visit at least n - 1 checkpoint in order to finish the competition. Participant are allowed to visit checkpoints in arbitrary order.
Vasya wants to pick such checkpoints and the order of visiting them that the total distance travelled is minimized. He asks you to calculate this minimum possible value.
Input
The first line of the input contains two integers n and a (1 β€ n β€ 100 000, - 1 000 000 β€ a β€ 1 000 000) β the number of checkpoints and Vasya's starting position respectively.
The second line contains n integers x1, x2, ..., xn ( - 1 000 000 β€ xi β€ 1 000 000) β coordinates of the checkpoints.
Output
Print one integer β the minimum distance Vasya has to travel in order to visit at least n - 1 checkpoint.
Examples
Input
3 10
1 7 12
Output
7
Input
2 0
11 -10
Output
10
Input
5 0
0 0 1000 0 0
Output
0
Note
In the first sample Vasya has to visit at least two checkpoints. The optimal way to achieve this is the walk to the third checkpoints (distance is 12 - 10 = 2) and then proceed to the second one (distance is 12 - 7 = 5). The total distance is equal to 2 + 5 = 7.
In the second sample it's enough to visit only one checkpoint so Vasya should just walk to the point - 10. | instruction | 0 | 66,072 | 1 | 132,144 |
Tags: greedy, implementation, sortings
Correct Solution:
```
#!/usr/bin/env python3.5
import sys
def read_data():
n, x0 = map(int, next(sys.stdin).split())
checkpoints = list(map(int, next(sys.stdin).split()))
return x0, checkpoints
def solve(x0, checkpoints):
n = len(checkpoints)
checkpoints.sort()
if n == 1:
return 0
case0 = abs(x0 - checkpoints[1]) + abs(checkpoints[n-1] - checkpoints[1])
case1 = abs(x0 - checkpoints[n-2]) + abs(checkpoints[0] - checkpoints[n-2])
case2 = abs(x0 - checkpoints[0]) + abs(checkpoints[n-2] - checkpoints[0])
case3 = abs(x0 - checkpoints[n-1]) + abs(checkpoints[1] - checkpoints[n-1])
return min(case0, case1, case2, case3)
if __name__ == "__main__":
x0, checkpoints = read_data()
length = solve(x0, checkpoints)
print(length)
``` | output | 1 | 66,072 | 1 | 132,145 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya takes part in the orienteering competition. There are n checkpoints located along the line at coordinates x1, x2, ..., xn. Vasya starts at the point with coordinate a. His goal is to visit at least n - 1 checkpoint in order to finish the competition. Participant are allowed to visit checkpoints in arbitrary order.
Vasya wants to pick such checkpoints and the order of visiting them that the total distance travelled is minimized. He asks you to calculate this minimum possible value.
Input
The first line of the input contains two integers n and a (1 β€ n β€ 100 000, - 1 000 000 β€ a β€ 1 000 000) β the number of checkpoints and Vasya's starting position respectively.
The second line contains n integers x1, x2, ..., xn ( - 1 000 000 β€ xi β€ 1 000 000) β coordinates of the checkpoints.
Output
Print one integer β the minimum distance Vasya has to travel in order to visit at least n - 1 checkpoint.
Examples
Input
3 10
1 7 12
Output
7
Input
2 0
11 -10
Output
10
Input
5 0
0 0 1000 0 0
Output
0
Note
In the first sample Vasya has to visit at least two checkpoints. The optimal way to achieve this is the walk to the third checkpoints (distance is 12 - 10 = 2) and then proceed to the second one (distance is 12 - 7 = 5). The total distance is equal to 2 + 5 = 7.
In the second sample it's enough to visit only one checkpoint so Vasya should just walk to the point - 10.
Submitted Solution:
```
n, a = map(int, input().split())
x = sorted(list(map(int, input().split())))
c = 0
if n == 1:
c = 0
elif n == 2:
c = min(abs(x[0] - a), abs(x[1] - a))
elif a <= x[0]:
c = abs(x[n - 2] - a)
elif a >= x[n - 1]:
c = abs(a - x[1])
elif a <= x[1]:
d0 = abs(a - x[0])
dn1 = abs(a - x[n - 1])
dn2 = abs(a - x[n - 2])
c = min(dn1, d0 * 2 + dn2, dn2 * 2 + d0)
elif a >= x[n - 2]:
d0 = abs(a - x[0])
d1 = abs(a - x[1])
dn2 = abs(a - x[n - 1])
#print(d0, d1 * 2 + dn2, dn2 * 2 + d1)
c = min(d0, d1 * 2 + dn2, dn2 * 2 + d1)
else:
d0 = abs(x[0] - a)
d1 = abs(x[1] - a)
dn1 = abs(x[n - 1] - a)
dn2 = abs(x[n - 2] - a)
c = min(d0 * 2 + dn2, d1 * 2 + dn1, dn1 * 2 + d1, dn2 * 2 + d0)
#print(d0, d1, dn2, dn1)
#print(d0 * 2 + dn1, d1 * 2 + dn2, dn1 * 2 + d1, dn2 * 2 + d0)
print(c)
``` | instruction | 0 | 66,073 | 1 | 132,146 |
Yes | output | 1 | 66,073 | 1 | 132,147 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya takes part in the orienteering competition. There are n checkpoints located along the line at coordinates x1, x2, ..., xn. Vasya starts at the point with coordinate a. His goal is to visit at least n - 1 checkpoint in order to finish the competition. Participant are allowed to visit checkpoints in arbitrary order.
Vasya wants to pick such checkpoints and the order of visiting them that the total distance travelled is minimized. He asks you to calculate this minimum possible value.
Input
The first line of the input contains two integers n and a (1 β€ n β€ 100 000, - 1 000 000 β€ a β€ 1 000 000) β the number of checkpoints and Vasya's starting position respectively.
The second line contains n integers x1, x2, ..., xn ( - 1 000 000 β€ xi β€ 1 000 000) β coordinates of the checkpoints.
Output
Print one integer β the minimum distance Vasya has to travel in order to visit at least n - 1 checkpoint.
Examples
Input
3 10
1 7 12
Output
7
Input
2 0
11 -10
Output
10
Input
5 0
0 0 1000 0 0
Output
0
Note
In the first sample Vasya has to visit at least two checkpoints. The optimal way to achieve this is the walk to the third checkpoints (distance is 12 - 10 = 2) and then proceed to the second one (distance is 12 - 7 = 5). The total distance is equal to 2 + 5 = 7.
In the second sample it's enough to visit only one checkpoint so Vasya should just walk to the point - 10.
Submitted Solution:
```
n,a=map(int,input().split())
ip=list(map(int,input().split()))
try:
if a not in ip:
ip.append(a)
n+=1
ip=sorted(ip)
k=ip.index(a)
l1=0
l2=0
for i in range(k):
l1+=ip[i+1]-ip[i]
for i in range(k,n-1):
l2+=ip[i+1]-ip[i]
n1=ip[1]-ip[0]
n2=ip[-1]-ip[-2]
if l1==0:
print(l2-n2)
elif l2==0:
print(l1-n1)
else:
print(min(l1-n1+2*l2, 2*l1-2*n1+l2, l2-n2+2*l1, 2*l2-2*n2+l1))
except:
print(0)
``` | instruction | 0 | 66,074 | 1 | 132,148 |
Yes | output | 1 | 66,074 | 1 | 132,149 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya takes part in the orienteering competition. There are n checkpoints located along the line at coordinates x1, x2, ..., xn. Vasya starts at the point with coordinate a. His goal is to visit at least n - 1 checkpoint in order to finish the competition. Participant are allowed to visit checkpoints in arbitrary order.
Vasya wants to pick such checkpoints and the order of visiting them that the total distance travelled is minimized. He asks you to calculate this minimum possible value.
Input
The first line of the input contains two integers n and a (1 β€ n β€ 100 000, - 1 000 000 β€ a β€ 1 000 000) β the number of checkpoints and Vasya's starting position respectively.
The second line contains n integers x1, x2, ..., xn ( - 1 000 000 β€ xi β€ 1 000 000) β coordinates of the checkpoints.
Output
Print one integer β the minimum distance Vasya has to travel in order to visit at least n - 1 checkpoint.
Examples
Input
3 10
1 7 12
Output
7
Input
2 0
11 -10
Output
10
Input
5 0
0 0 1000 0 0
Output
0
Note
In the first sample Vasya has to visit at least two checkpoints. The optimal way to achieve this is the walk to the third checkpoints (distance is 12 - 10 = 2) and then proceed to the second one (distance is 12 - 7 = 5). The total distance is equal to 2 + 5 = 7.
In the second sample it's enough to visit only one checkpoint so Vasya should just walk to the point - 10.
Submitted Solution:
```
n, a = map(int, input().split())
x = list(map(int, input().split()))
if n == 1:
print(0)
elif n == 2:
print(min(abs(a - x[0]), abs(a - x[1])))
else:
num = float('inf')
x = sorted(x)
if a <= x[0]:
num = min(num, abs(a - x[n - 2]))
elif x[n - 1] <= a:
num = min(num, abs(a - x[1]))
num = min(abs(x[1] - a) + abs(x[1] - x[n - 1]), num)
num = min(abs(x[n - 2] - a) + abs(x[0] - x[n - 2]), num)
num = min(abs(x[n - 1] - a) + abs(x[n - 1] - x[1]), num)
num = min(abs(x[0] - a) + abs(x[n - 2] - x[0]), num)
print(num)
``` | instruction | 0 | 66,075 | 1 | 132,150 |
Yes | output | 1 | 66,075 | 1 | 132,151 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya takes part in the orienteering competition. There are n checkpoints located along the line at coordinates x1, x2, ..., xn. Vasya starts at the point with coordinate a. His goal is to visit at least n - 1 checkpoint in order to finish the competition. Participant are allowed to visit checkpoints in arbitrary order.
Vasya wants to pick such checkpoints and the order of visiting them that the total distance travelled is minimized. He asks you to calculate this minimum possible value.
Input
The first line of the input contains two integers n and a (1 β€ n β€ 100 000, - 1 000 000 β€ a β€ 1 000 000) β the number of checkpoints and Vasya's starting position respectively.
The second line contains n integers x1, x2, ..., xn ( - 1 000 000 β€ xi β€ 1 000 000) β coordinates of the checkpoints.
Output
Print one integer β the minimum distance Vasya has to travel in order to visit at least n - 1 checkpoint.
Examples
Input
3 10
1 7 12
Output
7
Input
2 0
11 -10
Output
10
Input
5 0
0 0 1000 0 0
Output
0
Note
In the first sample Vasya has to visit at least two checkpoints. The optimal way to achieve this is the walk to the third checkpoints (distance is 12 - 10 = 2) and then proceed to the second one (distance is 12 - 7 = 5). The total distance is equal to 2 + 5 = 7.
In the second sample it's enough to visit only one checkpoint so Vasya should just walk to the point - 10.
Submitted Solution:
```
#!/usr/bin/env python3
n, a = [int(x) for x in input().split()]
x = [int(x) for x in input().split()]
x.sort()
def f(l, r):
d1 = abs(x[l] - a)
d2 = abs(x[r] - a)
if l == r:
return min(d1, d2)
if (x[l] <= a) == (x[r] <= a):
return max(d1, d2)
return min(d1, d2) * 2 + max(d1, d2)
if n == 1:
print(0)
else:
print(min(f(0, n - 2), f(1, n - 1)))
``` | instruction | 0 | 66,076 | 1 | 132,152 |
Yes | output | 1 | 66,076 | 1 | 132,153 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya takes part in the orienteering competition. There are n checkpoints located along the line at coordinates x1, x2, ..., xn. Vasya starts at the point with coordinate a. His goal is to visit at least n - 1 checkpoint in order to finish the competition. Participant are allowed to visit checkpoints in arbitrary order.
Vasya wants to pick such checkpoints and the order of visiting them that the total distance travelled is minimized. He asks you to calculate this minimum possible value.
Input
The first line of the input contains two integers n and a (1 β€ n β€ 100 000, - 1 000 000 β€ a β€ 1 000 000) β the number of checkpoints and Vasya's starting position respectively.
The second line contains n integers x1, x2, ..., xn ( - 1 000 000 β€ xi β€ 1 000 000) β coordinates of the checkpoints.
Output
Print one integer β the minimum distance Vasya has to travel in order to visit at least n - 1 checkpoint.
Examples
Input
3 10
1 7 12
Output
7
Input
2 0
11 -10
Output
10
Input
5 0
0 0 1000 0 0
Output
0
Note
In the first sample Vasya has to visit at least two checkpoints. The optimal way to achieve this is the walk to the third checkpoints (distance is 12 - 10 = 2) and then proceed to the second one (distance is 12 - 7 = 5). The total distance is equal to 2 + 5 = 7.
In the second sample it's enough to visit only one checkpoint so Vasya should just walk to the point - 10.
Submitted Solution:
```
from collections import defaultdict
import sys, os, math
def solve(arr):
global a, n
pos, mi = 0, 20000010
for i in range(n - 1):
if abs(arr[i] - a) < mi:
pos = i
mi = abs(arr[i] - a)
sm = abs(a - arr[pos])
l, r = pos - 1, pos + 1
a = arr[pos]
#print(sm, a, pos, l, r)
for i in range(n - 2):
if r >= n - 1 or (l >= 0 and abs(a - arr[l]) <= abs(a - arr[r])):
sm += abs(a - arr[l])
a = arr[l]
l -= 1
else:
sm += abs(a - arr[r])
a = arr[r]
r += 1
return sm
if __name__ == "__main__":
#n, m = list(map(int, input().split()))
n, a = map(int, input().split())
arr = list(map(int, input().split()))
arr.sort()
print(min(solve(arr[:n - 1]), solve(arr[1:])))
``` | instruction | 0 | 66,077 | 1 | 132,154 |
No | output | 1 | 66,077 | 1 | 132,155 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya takes part in the orienteering competition. There are n checkpoints located along the line at coordinates x1, x2, ..., xn. Vasya starts at the point with coordinate a. His goal is to visit at least n - 1 checkpoint in order to finish the competition. Participant are allowed to visit checkpoints in arbitrary order.
Vasya wants to pick such checkpoints and the order of visiting them that the total distance travelled is minimized. He asks you to calculate this minimum possible value.
Input
The first line of the input contains two integers n and a (1 β€ n β€ 100 000, - 1 000 000 β€ a β€ 1 000 000) β the number of checkpoints and Vasya's starting position respectively.
The second line contains n integers x1, x2, ..., xn ( - 1 000 000 β€ xi β€ 1 000 000) β coordinates of the checkpoints.
Output
Print one integer β the minimum distance Vasya has to travel in order to visit at least n - 1 checkpoint.
Examples
Input
3 10
1 7 12
Output
7
Input
2 0
11 -10
Output
10
Input
5 0
0 0 1000 0 0
Output
0
Note
In the first sample Vasya has to visit at least two checkpoints. The optimal way to achieve this is the walk to the third checkpoints (distance is 12 - 10 = 2) and then proceed to the second one (distance is 12 - 7 = 5). The total distance is equal to 2 + 5 = 7.
In the second sample it's enough to visit only one checkpoint so Vasya should just walk to the point - 10.
Submitted Solution:
```
def not_left(a, x):
# print('not_left')
right = abs(x[-1] - a)
left = abs(a - x[1])
print(min(left, right) * 2 + max(left, right))
def not_right(a, x):
# print('not_right')
right = abs(x[-2] - a)
left = abs(a - x[0])
print(min(left, right) * 2 + max(left, right))
n, a = map(int, input().split())
x = sorted(list(map(int, input().split())))
if n == 1:
print(0)
elif n == 2:
if a <= x[0]:
print(abs(x[0] - a))
elif a >= x[1]:
print(abs(a - x[1]))
else:
left = abs(a - x[0])
right = abs(x[1] - a)
print(min(left, right))
elif a >= x[-1]:
not_left(a, x)
elif a <= x[0]:
not_right(a, x)
elif x[-1] - a >= a - x[0]:
not_right(a, x)
else:
not_left(a, x)
``` | instruction | 0 | 66,078 | 1 | 132,156 |
No | output | 1 | 66,078 | 1 | 132,157 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya takes part in the orienteering competition. There are n checkpoints located along the line at coordinates x1, x2, ..., xn. Vasya starts at the point with coordinate a. His goal is to visit at least n - 1 checkpoint in order to finish the competition. Participant are allowed to visit checkpoints in arbitrary order.
Vasya wants to pick such checkpoints and the order of visiting them that the total distance travelled is minimized. He asks you to calculate this minimum possible value.
Input
The first line of the input contains two integers n and a (1 β€ n β€ 100 000, - 1 000 000 β€ a β€ 1 000 000) β the number of checkpoints and Vasya's starting position respectively.
The second line contains n integers x1, x2, ..., xn ( - 1 000 000 β€ xi β€ 1 000 000) β coordinates of the checkpoints.
Output
Print one integer β the minimum distance Vasya has to travel in order to visit at least n - 1 checkpoint.
Examples
Input
3 10
1 7 12
Output
7
Input
2 0
11 -10
Output
10
Input
5 0
0 0 1000 0 0
Output
0
Note
In the first sample Vasya has to visit at least two checkpoints. The optimal way to achieve this is the walk to the third checkpoints (distance is 12 - 10 = 2) and then proceed to the second one (distance is 12 - 7 = 5). The total distance is equal to 2 + 5 = 7.
In the second sample it's enough to visit only one checkpoint so Vasya should just walk to the point - 10.
Submitted Solution:
```
n, a = map(int, input().split(' '))
x = list(map(int, input().split(' ')))
MAX, MIN = 1000000, -1000000
r1, r2, l1, l2 = MIN-1, MIN-1, MAX+1, MAX+1
for xi in x:
if xi <= l1:
l2 = l1
l1 = xi
elif xi < l2:
l2 = xi
if xi >= r1:
r2 = r1
r1 = xi
elif xi > r2:
r2 = xi
if a <= l1:
print(r2 - a)
elif a >= r1:
print(a - l2)
elif a <= l2:
print(min(r2 + a - 2 * l1, r1 - a))
elif a >= r2:
print(min(2 * r1 - a - l2, a - l1))
else:
print(min(
2 * r1 - a - l2,
2 * r2 - a - l1,
r2 + a - 2 * l1,
r1 + a - 2 * l2))
``` | instruction | 0 | 66,079 | 1 | 132,158 |
No | output | 1 | 66,079 | 1 | 132,159 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya takes part in the orienteering competition. There are n checkpoints located along the line at coordinates x1, x2, ..., xn. Vasya starts at the point with coordinate a. His goal is to visit at least n - 1 checkpoint in order to finish the competition. Participant are allowed to visit checkpoints in arbitrary order.
Vasya wants to pick such checkpoints and the order of visiting them that the total distance travelled is minimized. He asks you to calculate this minimum possible value.
Input
The first line of the input contains two integers n and a (1 β€ n β€ 100 000, - 1 000 000 β€ a β€ 1 000 000) β the number of checkpoints and Vasya's starting position respectively.
The second line contains n integers x1, x2, ..., xn ( - 1 000 000 β€ xi β€ 1 000 000) β coordinates of the checkpoints.
Output
Print one integer β the minimum distance Vasya has to travel in order to visit at least n - 1 checkpoint.
Examples
Input
3 10
1 7 12
Output
7
Input
2 0
11 -10
Output
10
Input
5 0
0 0 1000 0 0
Output
0
Note
In the first sample Vasya has to visit at least two checkpoints. The optimal way to achieve this is the walk to the third checkpoints (distance is 12 - 10 = 2) and then proceed to the second one (distance is 12 - 7 = 5). The total distance is equal to 2 + 5 = 7.
In the second sample it's enough to visit only one checkpoint so Vasya should just walk to the point - 10.
Submitted Solution:
```
n,a = map(int,input().split())
x = [*map(int,input().split())]
x.sort()
if(len(x)==1):
print(0)
exit(0)
dist1 = abs(a-x[0]) +abs( x[n-2]-a)
dist2 = abs(x[n-1]-a)+abs(a-x[1])
print(min(dist1,dist2))
``` | instruction | 0 | 66,080 | 1 | 132,160 |
No | output | 1 | 66,080 | 1 | 132,161 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As you may know, MemSQL has American offices in both San Francisco and Seattle. Being a manager in the company, you travel a lot between the two cities, always by plane.
You prefer flying from Seattle to San Francisco than in the other direction, because it's warmer in San Francisco. You are so busy that you don't remember the number of flights you have made in either direction. However, for each of the last n days you know whether you were in San Francisco office or in Seattle office. You always fly at nights, so you never were at both offices on the same day. Given this information, determine if you flew more times from Seattle to San Francisco during the last n days, or not.
Input
The first line of input contains single integer n (2 β€ n β€ 100) β the number of days.
The second line contains a string of length n consisting of only capital 'S' and 'F' letters. If the i-th letter is 'S', then you were in Seattle office on that day. Otherwise you were in San Francisco. The days are given in chronological order, i.e. today is the last day in this sequence.
Output
Print "YES" if you flew more times from Seattle to San Francisco, and "NO" otherwise.
You can print each letter in any case (upper or lower).
Examples
Input
4
FSSF
Output
NO
Input
2
SF
Output
YES
Input
10
FFFFFFFFFF
Output
NO
Input
10
SSFFSFFSFF
Output
YES
Note
In the first example you were initially at San Francisco, then flew to Seattle, were there for two days and returned to San Francisco. You made one flight in each direction, so the answer is "NO".
In the second example you just flew from Seattle to San Francisco, so the answer is "YES".
In the third example you stayed the whole period in San Francisco, so the answer is "NO".
In the fourth example if you replace 'S' with ones, and 'F' with zeros, you'll get the first few digits of Ο in binary representation. Not very useful information though. | instruction | 0 | 66,131 | 1 | 132,262 |
Tags: implementation
Correct Solution:
```
n = int(input())
route = input()
sf =0
fs = 0
for i in range(1,len(route)):
if route[i-1] == 'S' and route[i] == 'F' :
sf+=1
elif route[i-1] == 'F' and route[i] == 'S' :
fs+=1
if sf > fs:
print("YES")
else:
print("NO")
``` | output | 1 | 66,131 | 1 | 132,263 |
Provide a correct Python 3 solution for this coding contest problem.
I'm traveling to a country with a rabbit. There are n cities in this country numbered from 1 to n, and the rabbit is now in city 1. City i is a point on the coordinate plane (xi, yi) ).
Rabbits travel to meet the following conditions.
* The travel path is a polygonal line, each part of which must be a line segment connecting two different cities.
* The total length of the travel route must be r or less. The overlapping part of the route is also counted for the number of times it has passed.
* When the direction of movement changes, the bending angle must be less than or equal to ΞΈ. There is no limit to the initial direction of movement.
If you move from one city to another, you will get one carrot in the destination city. You can visit the same city multiple times, and you will get a carrot each time you visit. Find the maximum number of carrots you can put in.
Input
One integer n is given on the first line of the input, and two real numbers r and ΞΈ are given on the second line, separated by a space.
1 β€ n β€ 20
0 <r <104
0 Β° <ΞΈ <180 Β°
The following n lines are given the integers xi and yi separated by spaces.
-10 000 β€ xi, yi β€ 10 000
The answer does not change even if r and ΞΈ are changed within Β± 10-3.
The locations of both cities are different.
Output
Output the maximum number of carrots that the rabbit can get on this trip in one line.
Example
Input
5
100.1 90.1
0 0
0 10
5 5
10 0
10 10
Output
10 | instruction | 0 | 66,415 | 1 | 132,830 |
"Correct Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**13
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def main():
rr = []
def f():
n = I()
r,t = LF()
a = [LI() for _ in range(n)]
d = {}
M = 32
for i in range(n):
ax,ay = a[i]
for j in range(n):
if i == j:
continue
bx,by = a[j]
d[i*M+j] = math.atan2(bx-ax,by-ay) / math.pi * 180
ky = {}
for i in range(n):
ax,ay = a[i]
for j in range(n):
bx,by = a[j]
ky[i*M+j] = pow(pow(ax-bx, 2) + pow(ay-by, 2), 0.5)
e = collections.defaultdict(list)
for i in range(n):
for j in range(n):
if i == j:
continue
ij = i*M+j
dij = d[ij]
for k in range(n):
if k == j:
continue
jk = j*M+k
djk = d[jk]
if abs(dij-djk) <= t or 360 - abs(dij-djk) <= t:
e[(i,j)].append(((j,k), ky[jk]))
def search():
res = 0
dp = [[None]*n for _ in range(n)]
for j in range(1, n):
k = ky[j]
if k > r:
continue
s = (j,1)
res = 1
dp[0][j] = k
if res == 0:
return 0
while True:
wf = False
nd = [[None]*n for _ in range(n)]
for i in range(n):
for j in range(n):
if dp[i][j] is None:
continue
dij = dp[i][j]
for nn,k in e[(i,j)]:
nk = dij + k
if nk > r or (not nd[j][nn[1]] is None and nd[j][nn[1]] < nk):
continue
nd[j][nn[1]] = nk
wf = True
if wf:
res += 1
dp = nd
else:
break
return res
return search()
while True:
rr.append(f())
break
return '\n'.join(map(str,rr))
print(main())
``` | output | 1 | 66,415 | 1 | 132,831 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
I'm traveling to a country with a rabbit. There are n cities in this country numbered from 1 to n, and the rabbit is now in city 1. City i is a point on the coordinate plane (xi, yi) ).
Rabbits travel to meet the following conditions.
* The travel path is a polygonal line, each part of which must be a line segment connecting two different cities.
* The total length of the travel route must be r or less. The overlapping part of the route is also counted for the number of times it has passed.
* When the direction of movement changes, the bending angle must be less than or equal to ΞΈ. There is no limit to the initial direction of movement.
If you move from one city to another, you will get one carrot in the destination city. You can visit the same city multiple times, and you will get a carrot each time you visit. Find the maximum number of carrots you can put in.
Input
One integer n is given on the first line of the input, and two real numbers r and ΞΈ are given on the second line, separated by a space.
1 β€ n β€ 20
0 <r <104
0 Β° <ΞΈ <180 Β°
The following n lines are given the integers xi and yi separated by spaces.
-10 000 β€ xi, yi β€ 10 000
The answer does not change even if r and ΞΈ are changed within Β± 10-3.
The locations of both cities are different.
Output
Output the maximum number of carrots that the rabbit can get on this trip in one line.
Example
Input
5
100.1 90.1
0 0
0 10
5 5
10 0
10 10
Output
10
Submitted Solution:
```
import sys
import math
import heapq
EPS = 1e-10
INF = 999999999
def dot(a, b):
return a[0]*b[0] + a[1]*b[1]
def norm(a):
return math.hypot(a[0], a[1])
def sub(a, b):
return (a[0]-b[0], a[1]-b[1])
def get_angle(a, b):
return math.acos(dot(a,b) / (norm(a) * norm(b)))
def main():
n = int(sys.stdin.readline())
r, degree = map(float, sys.stdin.readline().split())
rad = math.radians(degree)
nodes = []
for i in range(n):
x,y = map(int, sys.stdin.readline().split())
nodes.append( (x,y) )
edges = {}
# ????????????????????Β¨???
for i in range(n): # ?????Β¨??Β°
for j in range(n): # ?????????
if i == j:
continue
for k in range(n): # ?Β¬??????Β΄???
if i == k or j == k:
continue
angle = get_angle( sub(nodes[k], nodes[i]), sub(nodes[i], nodes[j]) )
if angle <= rad + EPS:
if i not in edges:
edges[i] = {}
if j not in edges[i]:
edges[i][j] = []
edges[i][j].append( k )
# cost
costs = {}
for i in range(n):
costs[i] = {}
for j in range(n):
if i == j:
costs[i][j] = INF
else:
costs[i][j] = norm(sub(nodes[i], nodes[j]))
# [?????????????????Β°k][?????Β¨??Β°i][??????j]
dp = [[[INF for j in range(n)] for i in range(n)] for k in range(10001)]
pq = []
heapq.heapify(pq)
# init
for k in range(n):
if costs[0][k] <= r + EPS:
dp[1][k][0] = costs[0][k]
heapq.heappush(pq, (costs[0][k], (1,k,0))) # (cost, (????????????, ?????Β¨??Β°, ??????))
while len(pq) > 0:
curr_cost,state = heapq.heappop(pq)
curr_carrot, curr, prev = state
# ?????????????????ΒΆ?????????????????????
if curr not in edges:
continue
if prev not in edges[curr]:
continue
for t in edges[curr][prev]:
next_cost = curr_cost + costs[curr][t]
if dp[curr_carrot + 1][t][curr] > next_cost and next_cost <= r + EPS:
dp[curr_carrot + 1][t][curr] = next_cost
heapq.heappush(pq, (next_cost, (curr_carrot + 1, t, curr)))
ans = 0
for k in range(10001):
for i in range(n):
for j in range(n):
if dp[k][i][j] != INF:
ans = max(ans, k)
print(ans)
if __name__ == '__main__':
main()
``` | instruction | 0 | 66,416 | 1 | 132,832 |
No | output | 1 | 66,416 | 1 | 132,833 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
I'm traveling to a country with a rabbit. There are n cities in this country numbered from 1 to n, and the rabbit is now in city 1. City i is a point on the coordinate plane (xi, yi) ).
Rabbits travel to meet the following conditions.
* The travel path is a polygonal line, each part of which must be a line segment connecting two different cities.
* The total length of the travel route must be r or less. The overlapping part of the route is also counted for the number of times it has passed.
* When the direction of movement changes, the bending angle must be less than or equal to ΞΈ. There is no limit to the initial direction of movement.
If you move from one city to another, you will get one carrot in the destination city. You can visit the same city multiple times, and you will get a carrot each time you visit. Find the maximum number of carrots you can put in.
Input
One integer n is given on the first line of the input, and two real numbers r and ΞΈ are given on the second line, separated by a space.
1 β€ n β€ 20
0 <r <104
0 Β° <ΞΈ <180 Β°
The following n lines are given the integers xi and yi separated by spaces.
-10 000 β€ xi, yi β€ 10 000
The answer does not change even if r and ΞΈ are changed within Β± 10-3.
The locations of both cities are different.
Output
Output the maximum number of carrots that the rabbit can get on this trip in one line.
Example
Input
5
100.1 90.1
0 0
0 10
5 5
10 0
10 10
Output
10
Submitted Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**13
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def main():
rr = []
def f():
n = I()
r,t = LF()
a = [LI() for _ in range(n)]
d = []
for i in range(n):
di = []
ax,ay = a[i]
for j in range(n):
if i == j:
di.append(0)
continue
bx,by = a[j]
di.append(math.atan2(bx-ax,by-ay) / math.pi * 180)
d.append(di)
ky = []
for i in range(n):
ki = []
ax,ay = a[i]
for j in range(n):
bx,by = a[j]
ki.append(pow(pow(ax-bx, 2) + pow(ay-by, 2), 0.5))
ky.append(ki)
e = collections.defaultdict(list)
for i in range(n):
for j in range(n):
if i == j:
continue
dij = d[i][j]
dj = d[j]
for k in range(n):
if k == j:
continue
djk = dj[k]
if abs(dij-djk) <= t or 360 - abs(dij-djk) <= t:
e[(i,j)].append(((j,k), ky[j][k]))
def search():
d = collections.defaultdict(lambda: inf)
q = []
for j in range(1, n):
s = (0,j,0)
d[s] = 0
heapq.heappush(q, (0, s))
v = collections.defaultdict(bool)
while len(q):
k, u = heapq.heappop(q)
if v[u]:
continue
v[u] = True
for uv, ud in e[(u[0],u[1])]:
uv = (uv[0],uv[1],u[2]+1)
if v[uv]:
continue
vd = k + ud
if vd > r:
continue
if d[uv] > vd:
d[uv] = vd
heapq.heappush(q, (vd, uv))
return d
d = search()
return max(map(lambda x: x[2], d.keys()))
while True:
rr.append(f())
break
return '\n'.join(map(str,rr))
print(main())
``` | instruction | 0 | 66,417 | 1 | 132,834 |
No | output | 1 | 66,417 | 1 | 132,835 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
I'm traveling to a country with a rabbit. There are n cities in this country numbered from 1 to n, and the rabbit is now in city 1. City i is a point on the coordinate plane (xi, yi) ).
Rabbits travel to meet the following conditions.
* The travel path is a polygonal line, each part of which must be a line segment connecting two different cities.
* The total length of the travel route must be r or less. The overlapping part of the route is also counted for the number of times it has passed.
* When the direction of movement changes, the bending angle must be less than or equal to ΞΈ. There is no limit to the initial direction of movement.
If you move from one city to another, you will get one carrot in the destination city. You can visit the same city multiple times, and you will get a carrot each time you visit. Find the maximum number of carrots you can put in.
Input
One integer n is given on the first line of the input, and two real numbers r and ΞΈ are given on the second line, separated by a space.
1 β€ n β€ 20
0 <r <104
0 Β° <ΞΈ <180 Β°
The following n lines are given the integers xi and yi separated by spaces.
-10 000 β€ xi, yi β€ 10 000
The answer does not change even if r and ΞΈ are changed within Β± 10-3.
The locations of both cities are different.
Output
Output the maximum number of carrots that the rabbit can get on this trip in one line.
Example
Input
5
100.1 90.1
0 0
0 10
5 5
10 0
10 10
Output
10
Submitted Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**13
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def main():
rr = []
def f():
n = I()
r,t = LF()
a = [LI() for _ in range(n)]
d = []
for i in range(n):
di = []
ax,ay = a[i]
for j in range(n):
if i == j:
di.append(0)
continue
bx,by = a[j]
di.append(math.atan2(bx-ax,by-ay) / math.pi * 180)
d.append(di)
ky = []
for i in range(n):
ki = []
ax,ay = a[i]
for j in range(n):
bx,by = a[j]
ki.append(pow(pow(ax-bx, 2) + pow(ay-by, 2), 0.5))
ky.append(ki)
e = collections.defaultdict(list)
for i in range(n):
for j in range(n):
if i == j:
continue
dij = d[i][j]
dj = d[j]
for k in range(n):
if k == j:
continue
djk = dj[k]
if abs(dij-djk) <= t or 360 - abs(dij-djk) <= t:
e[(i,j)].append(((j,k), ky[j][k]))
def search():
d = collections.defaultdict(lambda: inf)
q = []
for j in range(1, n):
k = ky[0][j]
if k > r:
continue
s = (0,j,1)
d[s] = k
heapq.heappush(q, (k, s))
v = collections.defaultdict(bool)
while len(q):
k, u = heapq.heappop(q)
if v[u]:
continue
v[u] = True
for uv, ud in e[(u[0],u[1])]:
uv = (uv[0],uv[1],u[2]+1)
if v[uv]:
continue
vd = k + ud
if vd > r:
continue
if d[uv] > vd:
d[uv] = vd
heapq.heappush(q, (vd, uv))
return d
d = search()
if len(d) == 0:
return 0
return max(map(lambda x: x[2], d.keys()))
while True:
rr.append(f())
break
return '\n'.join(map(str,rr))
print(main())
``` | instruction | 0 | 66,418 | 1 | 132,836 |
No | output | 1 | 66,418 | 1 | 132,837 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The pandemic is upon us, and the world is in shortage of the most important resource: toilet paper. As one of the best prepared nations for this crisis, BubbleLand promised to help all other world nations with this valuable resource. To do that, the country will send airplanes to other countries carrying toilet paper.
In BubbleLand, there are N toilet paper factories, and N airports. Because of how much it takes to build a road, and of course legal issues, every factory must send paper to only one airport, and every airport can only take toilet paper from one factory.
Also, a road can't be built between all airport-factory pairs, again because of legal issues. Every possible road has number d given, number of days it takes to build that road.
Your job is to choose N factory-airport pairs, such that if the country starts building all roads at the same time, it takes the least amount of days to complete them.
Input
The first line contains two integers N (1 β€ N β€ 10^4) - number of airports/factories, and M (1 β€ M β€ 10^5) - number of available pairs to build a road between.
On next M lines, there are three integers u, v (1 β€ u,v β€ N), d (1 β€ d β€ 10^9) - meaning that you can build a road between airport u and factory v for d days.
Output
If there are no solutions, output -1. If there exists a solution, output the minimal number of days to complete all roads, equal to maximal d among all chosen roads.
Example
Input
3 5
1 2 1
2 3 2
3 3 3
2 1 4
2 2 5
Output
4 | instruction | 0 | 66,636 | 1 | 133,272 |
Tags: binary search, flows, graph matchings, graphs
Correct Solution:
```
from collections import defaultdict
n,k=map(int,input().split())
ma=0
a=[]
graph=[]
factories=0
ports=0
f=[False]*(n+1)
p=[False]*(n+1)
for i in range(k):
u,v,d=map(int,input().split())
graph.append([u,v,d])
ma=max(ma,d)
s=0
l=ma
ans=-1
while(s<=l):
m=(s+l)//2
factories = 0
ports = 0
f = defaultdict(bool)
p = defaultdict(bool)
for i in range(k):
u,v,d=graph[i]
if d<=m:
if not f[u]:
f[u]=True
factories+=1
if not p[v]:
p[v]=True
ports+=1
if factories==n and ports==n:
ans=m
l=m-1
else:
s=m+1
print(ans)
``` | output | 1 | 66,636 | 1 | 133,273 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The pandemic is upon us, and the world is in shortage of the most important resource: toilet paper. As one of the best prepared nations for this crisis, BubbleLand promised to help all other world nations with this valuable resource. To do that, the country will send airplanes to other countries carrying toilet paper.
In BubbleLand, there are N toilet paper factories, and N airports. Because of how much it takes to build a road, and of course legal issues, every factory must send paper to only one airport, and every airport can only take toilet paper from one factory.
Also, a road can't be built between all airport-factory pairs, again because of legal issues. Every possible road has number d given, number of days it takes to build that road.
Your job is to choose N factory-airport pairs, such that if the country starts building all roads at the same time, it takes the least amount of days to complete them.
Input
The first line contains two integers N (1 β€ N β€ 10^4) - number of airports/factories, and M (1 β€ M β€ 10^5) - number of available pairs to build a road between.
On next M lines, there are three integers u, v (1 β€ u,v β€ N), d (1 β€ d β€ 10^9) - meaning that you can build a road between airport u and factory v for d days.
Output
If there are no solutions, output -1. If there exists a solution, output the minimal number of days to complete all roads, equal to maximal d among all chosen roads.
Example
Input
3 5
1 2 1
2 3 2
3 3 3
2 1 4
2 2 5
Output
4 | instruction | 0 | 66,637 | 1 | 133,274 |
Tags: binary search, flows, graph matchings, graphs
Correct Solution:
```
n,m = map(int,input().split())
import functools
l1 = []
for i in range(m):
a,b,c = map(int,input().split())
l1.append([a,b,c])
l1.sort(key=lambda x: x[2])
d1 = set()
d2 = set()
for a,b,c in l1:
d1.add(a)
d2.add(b)
if len(d1) == n and len(d2)==n:
print(c)
exit(0)
print(-1)
``` | output | 1 | 66,637 | 1 | 133,275 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The pandemic is upon us, and the world is in shortage of the most important resource: toilet paper. As one of the best prepared nations for this crisis, BubbleLand promised to help all other world nations with this valuable resource. To do that, the country will send airplanes to other countries carrying toilet paper.
In BubbleLand, there are N toilet paper factories, and N airports. Because of how much it takes to build a road, and of course legal issues, every factory must send paper to only one airport, and every airport can only take toilet paper from one factory.
Also, a road can't be built between all airport-factory pairs, again because of legal issues. Every possible road has number d given, number of days it takes to build that road.
Your job is to choose N factory-airport pairs, such that if the country starts building all roads at the same time, it takes the least amount of days to complete them.
Input
The first line contains two integers N (1 β€ N β€ 10^4) - number of airports/factories, and M (1 β€ M β€ 10^5) - number of available pairs to build a road between.
On next M lines, there are three integers u, v (1 β€ u,v β€ N), d (1 β€ d β€ 10^9) - meaning that you can build a road between airport u and factory v for d days.
Output
If there are no solutions, output -1. If there exists a solution, output the minimal number of days to complete all roads, equal to maximal d among all chosen roads.
Example
Input
3 5
1 2 1
2 3 2
3 3 3
2 1 4
2 2 5
Output
4 | instruction | 0 | 66,638 | 1 | 133,276 |
Tags: binary search, flows, graph matchings, graphs
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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:
self.os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def getInts():
return [int(s) for s in input().split()]
from collections import deque
def maximum_matching(graph):
"""Find a maximum unweighted matching in a bipartite graph. The input
must be a dictionary mapping vertices in one partition to sets of
vertices in the other partition. Return a dictionary mapping
vertices in one partition to their matched vertex in the other.
"""
# The two partitions of the graph.
U = set(graph.keys())
V = set.union(*graph.values())
# A distinguished vertex not belonging to the graph.
nil = object()
# Current pairing for vertices in each partition.
pair_u = dict.fromkeys(U, nil)
pair_v = dict.fromkeys(V, nil)
if len(pair_u) != len(pair_v):
return []
# Distance to each vertex along augmenting paths.
dist = {}
inf = (1 << 28)
def bfs():
# Breadth-first search of the graph starting with unmatched
# vertices in U and following "augmenting paths" alternating
# between edges from U->V not in the matching and edges from
# V->U in the matching. This partitions the vertexes into
# layers according to their distance along augmenting paths.
queue = deque()
for u in U:
if pair_u[u] is nil:
dist[u] = 0
queue.append(u)
else:
dist[u] = inf
dist[nil] = inf
while queue:
u = queue.popleft()
if dist[u] < dist[nil]:
# Follow edges from U->V not in the matching.
for v in graph[u]:
# Follow edge from V->U in the matching, if any.
uu = pair_v[v]
if dist[uu] == inf:
dist[uu] = dist[u] + 1
queue.append(uu)
return dist[nil] is not inf
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
@bootstrap
def dfs(u):
# Depth-first search along "augmenting paths" starting at
# u. If we can find such a path that goes all the way from
# u to nil, then we can swap matched/unmatched edges all
# along the path, getting one additional matched edge
# (since the path must have an odd number of edges).
if u is not nil:
for v in graph[u]:
uu = pair_v[v]
if dist[uu] == dist[u] + 1: # uu in next layer
if (dfs(uu)):
# Found augmenting path all the way to nil. In
# this path v was matched with uu, so after
# swapping v must now be matched with u.
pair_v[v] = u
pair_u[u] = v
yield True
dist[u] = inf
yield False
yield True
while bfs():
for u in U:
if pair_u[u] is nil:
dfs(u)
return {u: v for u, v in pair_u.items() if v is not nil}
N, M = getInts()
max_edge = 0
edges = []
u_set = set()
v_set = set()
while M:
u, v, d = getInts()
u_set.add(u)
v_set.add(v)
edges.append((u,v,d))
max_edge = max(d,max_edge)
M -= 1
l = 0
r = max_edge+1
ans = 2*(10**9)
import collections
if len(u_set) != N or len(v_set) != N:
print(-1)
else:
while (l <= r):
m = (l + r) >> 1
G = collections.defaultdict(set)
for u,v,d in edges:
if d <= m:
G[u].add(v+N)
#print(m,G)
if not G:
l = m + 1
continue
matching = maximum_matching(G)
if (len(matching) == N):
ans = m
r = m - 1
else:
l = m + 1
if (ans == 2*(10**9)):
print(-1)
else:
print(ans)
``` | output | 1 | 66,638 | 1 | 133,277 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The pandemic is upon us, and the world is in shortage of the most important resource: toilet paper. As one of the best prepared nations for this crisis, BubbleLand promised to help all other world nations with this valuable resource. To do that, the country will send airplanes to other countries carrying toilet paper.
In BubbleLand, there are N toilet paper factories, and N airports. Because of how much it takes to build a road, and of course legal issues, every factory must send paper to only one airport, and every airport can only take toilet paper from one factory.
Also, a road can't be built between all airport-factory pairs, again because of legal issues. Every possible road has number d given, number of days it takes to build that road.
Your job is to choose N factory-airport pairs, such that if the country starts building all roads at the same time, it takes the least amount of days to complete them.
Input
The first line contains two integers N (1 β€ N β€ 10^4) - number of airports/factories, and M (1 β€ M β€ 10^5) - number of available pairs to build a road between.
On next M lines, there are three integers u, v (1 β€ u,v β€ N), d (1 β€ d β€ 10^9) - meaning that you can build a road between airport u and factory v for d days.
Output
If there are no solutions, output -1. If there exists a solution, output the minimal number of days to complete all roads, equal to maximal d among all chosen roads.
Example
Input
3 5
1 2 1
2 3 2
3 3 3
2 1 4
2 2 5
Output
4 | instruction | 0 | 66,639 | 1 | 133,278 |
Tags: binary search, flows, graph matchings, graphs
Correct Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
#threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
#sys.setrecursionlimit(300000)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=300006, func=lambda a, b: min(a , b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b:max(a , b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] <=key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] > k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
class TrieNode:
def __init__(self):
self.children = [None] * 26
self.isEndOfWord = False
class Trie:
def __init__(self):
self.root = self.getNode()
def getNode(self):
return TrieNode()
def _charToIndex(self, ch):
return ord(ch) - ord('a')
def insert(self, key):
pCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])
if not pCrawl.children[index]:
pCrawl.children[index] = self.getNode()
pCrawl = pCrawl.children[index]
pCrawl.isEndOfWord = True
def search(self, key):
pCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])
if not pCrawl.children[index]:
return False
pCrawl = pCrawl.children[index]
return pCrawl != None and pCrawl.isEndOfWord
#-----------------------------------------trie---------------------------------
class Node:
def __init__(self, data):
self.data = data
self.count=0
self.left = None # left node for 0
self.right = None # right node for 1
class BinaryTrie:
def __init__(self):
self.root = Node(0)
def insert(self, pre_xor):
self.temp = self.root
for i in range(31, -1, -1):
val = pre_xor & (1 << i)
if val:
if not self.temp.right:
self.temp.right = Node(0)
self.temp = self.temp.right
self.temp.count+=1
if not val:
if not self.temp.left:
self.temp.left = Node(0)
self.temp = self.temp.left
self.temp.count += 1
self.temp.data = pre_xor
def query(self, xor):
self.temp = self.root
for i in range(31, -1, -1):
val = xor & (1 << i)
if not val:
if self.temp.left and self.temp.left.count>0:
self.temp = self.temp.left
elif self.temp.right:
self.temp = self.temp.right
else:
if self.temp.right and self.temp.right.count>0:
self.temp = self.temp.right
elif self.temp.left:
self.temp = self.temp.left
self.temp.count-=1
return xor ^ self.temp.data
#-------------------------bin trie-------------------------------------------
n,k=map(int,input().split())
l=[]
er=0
for i in range(k):
a,b,c=map(int,input().split())
l.append((a,b,c))
er=max(er,c)
l.sort()
def find(x):
done=set()
use=set()
last1=[0]*n
last=[0]*n
w=[]
cou=[0]*n
d=[0]*n
for i in range(k):
if l[i][2]<=x:
w.append((l[i][0]-1,l[i][1]-1))
cou[l[i][1]-1]+=1
t=0
we=0
for i in w:
if cou[i[1]]==1:
d[i[0]]+=1
we=max(we,d[i[0]])
last[i[1]]=max(last[i[1]],t)
last1[i[0]]=max(last1[i[0]],t)
t+=1
if we>1:
return False
t=0
c=0
c1=0
for i in w:
done.add(i[0])
use.add(i[1])
if last[i[1]]==t:
c+=1
if last1[i[0]]==t:
c1+=1
if c>len(done):
return False
if c1>len(use):
return False
t+=1
if len(done)==n and len(use)==n:
return True
return False
st=1
end=er
ans=-1
while(st<=end):
mid=(st+end)//2
if find(mid)==True:
ans=mid
end=mid-1
else:
st=mid+1
print(ans)
``` | output | 1 | 66,639 | 1 | 133,279 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The pandemic is upon us, and the world is in shortage of the most important resource: toilet paper. As one of the best prepared nations for this crisis, BubbleLand promised to help all other world nations with this valuable resource. To do that, the country will send airplanes to other countries carrying toilet paper.
In BubbleLand, there are N toilet paper factories, and N airports. Because of how much it takes to build a road, and of course legal issues, every factory must send paper to only one airport, and every airport can only take toilet paper from one factory.
Also, a road can't be built between all airport-factory pairs, again because of legal issues. Every possible road has number d given, number of days it takes to build that road.
Your job is to choose N factory-airport pairs, such that if the country starts building all roads at the same time, it takes the least amount of days to complete them.
Input
The first line contains two integers N (1 β€ N β€ 10^4) - number of airports/factories, and M (1 β€ M β€ 10^5) - number of available pairs to build a road between.
On next M lines, there are three integers u, v (1 β€ u,v β€ N), d (1 β€ d β€ 10^9) - meaning that you can build a road between airport u and factory v for d days.
Output
If there are no solutions, output -1. If there exists a solution, output the minimal number of days to complete all roads, equal to maximal d among all chosen roads.
Example
Input
3 5
1 2 1
2 3 2
3 3 3
2 1 4
2 2 5
Output
4 | instruction | 0 | 66,640 | 1 | 133,280 |
Tags: binary search, flows, graph matchings, graphs
Correct Solution:
```
from sys import stdin, stdout
from collections import deque
import sys
graph = []
n = 0
current_graph = []
pair_f = []
pair_a = []
dist = []
def dfs(s):
global pair_f
global pair_a
global dist
if s != 0:
for a in current_graph[s]:
if dist[pair_a[a]] == (dist[s] + 1):
if dfs(pair_a[a]):
pair_a[a] = s
pair_f[s] = a
return True
dist[s] = 10 ** 4 + 1
return False
return True
def bfs():
global dist
q = deque()
inf = 10 ** 4 + 1
for f in range(1, n + 1):
# visit all factories that aren't still included in any path
if pair_f[f] == 0:
dist[f] = 0
q.append(f)
else:
dist[f] = inf
dist[0] = inf # inf, 0 is goin to be our nill vertex
while q:
f = q.popleft()
if (
dist[f] < dist[0]
): # solo se analizan caminos de tamanno k donde k es el nivel donde primero se da con nill
for a in current_graph[f]:
# looking for path that alternate between not taken and taken roads
if (
dist[pair_a[a]] == inf
): # the aerports already visited were marked as inf
dist[pair_a[a]] = dist[f] + 1
q.append(pair_a[a])
return dist[0] != inf
def HopcroftKarp():
global pair_f
global pair_a
global dist
match = 0
pair_f = [0] * (n + 1)
pair_a = [0] * (n + 1)
dist = [-1] * (n + 1)
while bfs():
for f in range(1, n + 1):
if pair_f[f] == 0:
if dfs(f):
match += 1
return match
def valuable_paper(min_d, max_d):
global current_graph
last_md = 10 ** 9 + 1
l = min_d
r = max_d
m = 0
while l <= r:
m = (l + r) // 2
current_graph = [[] for i in range(n + 1)]
for edge in graph:
if edge[2] <= m:
current_graph[edge[0]].append(edge[1])
current_graph[0] = [0]
matchings = HopcroftKarp()
if matchings == n:
last_md = m
r = m - 1
else:
l = m + 1
if last_md == (10 ** 9 + 1):
return -1
else:
return last_md
# input:
# line1: n, m number of airports/factories and roads available(2<=n<=10^4; n-1<=m<=10^5)
# m lines:
# line i: <v,v,d> is possible to build a road between vertices airpot u and factory v in d days
def main_method():
global graph
global n
n, m = map(int, stdin.readline().split())
graph = []
for _ in range(m):
u, v, d = map(int, stdin.readline().split())
graph.append((u, v, d))
min_d = min(graph, key=lambda e: e[2])[2]
max_d = max(graph, key=lambda e: e[2])[2]
sol = valuable_paper(min_d, max_d)
stdout.write("{}\n".format(sol))
main_method()
``` | output | 1 | 66,640 | 1 | 133,281 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The pandemic is upon us, and the world is in shortage of the most important resource: toilet paper. As one of the best prepared nations for this crisis, BubbleLand promised to help all other world nations with this valuable resource. To do that, the country will send airplanes to other countries carrying toilet paper.
In BubbleLand, there are N toilet paper factories, and N airports. Because of how much it takes to build a road, and of course legal issues, every factory must send paper to only one airport, and every airport can only take toilet paper from one factory.
Also, a road can't be built between all airport-factory pairs, again because of legal issues. Every possible road has number d given, number of days it takes to build that road.
Your job is to choose N factory-airport pairs, such that if the country starts building all roads at the same time, it takes the least amount of days to complete them.
Input
The first line contains two integers N (1 β€ N β€ 10^4) - number of airports/factories, and M (1 β€ M β€ 10^5) - number of available pairs to build a road between.
On next M lines, there are three integers u, v (1 β€ u,v β€ N), d (1 β€ d β€ 10^9) - meaning that you can build a road between airport u and factory v for d days.
Output
If there are no solutions, output -1. If there exists a solution, output the minimal number of days to complete all roads, equal to maximal d among all chosen roads.
Example
Input
3 5
1 2 1
2 3 2
3 3 3
2 1 4
2 2 5
Output
4 | instruction | 0 | 66,641 | 1 | 133,282 |
Tags: binary search, flows, graph matchings, graphs
Correct Solution:
```
from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush,heappop,heapify
import math
from collections import *
from functools import reduce,cmp_to_key
import sys
input = sys.stdin.readline
from itertools import accumulate
from functools import lru_cache
M = mod = 10 ** 9 + 7
def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
def inv_mod(n):return pow(n, mod - 2, mod)
def li():return [int(i) for i in input().rstrip('\n').split()]
def st():return input().rstrip('\n')
def val():return int(input().rstrip('\n'))
def li2():return [i for i in input().rstrip('\n')]
def li3():return [int(i) for i in input().rstrip('\n')]
graph = defaultdict(dict)
n, m = li()
l = []
for j in range(m):
u, v, d = li()
l.append([u, v, d])
l.sort(key = lambda x:x[-1])
def check(weight):
airports = set()
factoris = set()
for i in l:
if i[-1] <= weight:
airports.add(i[0])
factoris.add(i[1])
else:break
# print(weight, airports, factoris)
return 1 if len(factoris) == len(airports) and len(factoris) == n else 0
low = 1
high = 10 ** 9
ans = 10 ** 10
while low <= high:
mid = (low + high) >> 1
if check(mid):
ans = min(ans, mid)
high = mid - 1
else:low = mid + 1
if ans == 10 ** 10:
print(-1)
exit()
print(ans)
``` | output | 1 | 66,641 | 1 | 133,283 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The pandemic is upon us, and the world is in shortage of the most important resource: toilet paper. As one of the best prepared nations for this crisis, BubbleLand promised to help all other world nations with this valuable resource. To do that, the country will send airplanes to other countries carrying toilet paper.
In BubbleLand, there are N toilet paper factories, and N airports. Because of how much it takes to build a road, and of course legal issues, every factory must send paper to only one airport, and every airport can only take toilet paper from one factory.
Also, a road can't be built between all airport-factory pairs, again because of legal issues. Every possible road has number d given, number of days it takes to build that road.
Your job is to choose N factory-airport pairs, such that if the country starts building all roads at the same time, it takes the least amount of days to complete them.
Input
The first line contains two integers N (1 β€ N β€ 10^4) - number of airports/factories, and M (1 β€ M β€ 10^5) - number of available pairs to build a road between.
On next M lines, there are three integers u, v (1 β€ u,v β€ N), d (1 β€ d β€ 10^9) - meaning that you can build a road between airport u and factory v for d days.
Output
If there are no solutions, output -1. If there exists a solution, output the minimal number of days to complete all roads, equal to maximal d among all chosen roads.
Example
Input
3 5
1 2 1
2 3 2
3 3 3
2 1 4
2 2 5
Output
4 | instruction | 0 | 66,642 | 1 | 133,284 |
Tags: binary search, flows, graph matchings, graphs
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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:
self.os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def getInts():
return [int(s) for s in input().split()]
from collections import deque, defaultdict
def maximum_matching(graph):
"""Find a maximum unweighted matching in a bipartite graph. The input
must be a dictionary mapping vertices in one partition to sets of
vertices in the other partition. Return a dictionary mapping
vertices in one partition to their matched vertex in the other.
"""
# The two partitions of the graph.
U = set(graph.keys())
V = set.union(*graph.values())
# A distinguished vertex not belonging to the graph.
nil = object()
# Current pairing for vertices in each partition.
pair_u = dict.fromkeys(U, nil)
pair_v = dict.fromkeys(V, nil)
if len(pair_u) != len(pair_v):
return []
# Distance to each vertex along augmenting paths.
dist = {}
inf = (1 << 28)
def bfs():
# Breadth-first search of the graph starting with unmatched
# vertices in U and following "augmenting paths" alternating
# between edges from U->V not in the matching and edges from
# V->U in the matching. This partitions the vertexes into
# layers according to their distance along augmenting paths.
queue = deque()
for u in U:
if pair_u[u] is nil:
dist[u] = 0
queue.append(u)
else:
dist[u] = inf
dist[nil] = inf
while queue:
u = queue.popleft()
if dist[u] < dist[nil]:
# Follow edges from U->V not in the matching.
for v in graph[u]:
# Follow edge from V->U in the matching, if any.
uu = pair_v[v]
if dist[uu] == inf:
dist[uu] = dist[u] + 1
queue.append(uu)
return dist[nil] != inf
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
@bootstrap
def dfs(u):
#print("DFS start:",u)
# Depth-first search along "augmenting paths" starting at
# u. If we can find such a path that goes all the way from
# u to nil, then we can swap matched/unmatched edges all
# along the path, getting one additional matched edge
# (since the path must have an odd number of edges).
if u is not nil:
for v in graph[u]:
uu = pair_v[v]
if dist[uu] == dist[u] + 1: # uu in next layer
if dfs(uu):
# Found augmenting path all the way to nil. In
# this path v was matched with uu, so after
# swapping v must now be matched with u.
pair_v[v] = u
pair_u[u] = v
yield True
dist[u] = inf
yield False
yield True
while bfs():
#print("BFS",pair_u,pair_v,dist)
for u in U:
# if pair_u[u] is nil:
dfs(u)
#print("DFS",pair_u,pair_v,dist)
for u in pair_u:
if pair_u[u] is nil:
return {}
return pair_u
N, M = getInts()
max_edge = 0
edges = []
u_set = set()
v_set = set()
while M:
u, v, d = getInts()
u_set.add(u)
v_set.add(v)
edges.append((u,v,d))
max_edge = max(d,max_edge)
M -= 1
l = 0
r = max_edge+1
ans = 2*(10**9)
if len(u_set) != N or len(v_set) != N:
print(-1)
else:
while (l <= r):
m = (l + r) >> 1
G = defaultdict(set)
for u,v,d in edges:
if d <= m:
G[u].add(v+N)
#print(m,G)
if not G:
l = m + 1
continue
matching = maximum_matching(G)
if (len(matching) == N):
ans = m
r = m - 1
else:
l = m + 1
if (ans == 2*(10**9)):
print(-1)
else:
print(ans)
``` | output | 1 | 66,642 | 1 | 133,285 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The pandemic is upon us, and the world is in shortage of the most important resource: toilet paper. As one of the best prepared nations for this crisis, BubbleLand promised to help all other world nations with this valuable resource. To do that, the country will send airplanes to other countries carrying toilet paper.
In BubbleLand, there are N toilet paper factories, and N airports. Because of how much it takes to build a road, and of course legal issues, every factory must send paper to only one airport, and every airport can only take toilet paper from one factory.
Also, a road can't be built between all airport-factory pairs, again because of legal issues. Every possible road has number d given, number of days it takes to build that road.
Your job is to choose N factory-airport pairs, such that if the country starts building all roads at the same time, it takes the least amount of days to complete them.
Input
The first line contains two integers N (1 β€ N β€ 10^4) - number of airports/factories, and M (1 β€ M β€ 10^5) - number of available pairs to build a road between.
On next M lines, there are three integers u, v (1 β€ u,v β€ N), d (1 β€ d β€ 10^9) - meaning that you can build a road between airport u and factory v for d days.
Output
If there are no solutions, output -1. If there exists a solution, output the minimal number of days to complete all roads, equal to maximal d among all chosen roads.
Example
Input
3 5
1 2 1
2 3 2
3 3 3
2 1 4
2 2 5
Output
4 | instruction | 0 | 66,643 | 1 | 133,286 |
Tags: binary search, flows, graph matchings, graphs
Correct Solution:
```
def check(k, adj, n):
a = [0 for i in range(n+1)]
f = [0 for i in range(n+1)]
for i in range(n+1):
arr = adj[i]
for j in range(len(arr)):
if arr[j][1] <= k:
a[i] = 1
f[arr[j][0]] = 1
if sum(a) == n and sum(f) == n:
return True
return False
def binSearch(adj, n):
l = 0
r = 10**9
ans = -1
while l<=r:
mid = (l+r)//2
if check(mid, adj, n):
ans = mid
r = mid - 1
else:
l = mid + 1
return ans
n, m = map(int, input().split())
adj = [[] for i in range(n+1)]
for i in range(m):
u, v, d = map(int, input().split())
adj[u].append((v,d))
print(binSearch(adj, n))
``` | output | 1 | 66,643 | 1 | 133,287 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The pandemic is upon us, and the world is in shortage of the most important resource: toilet paper. As one of the best prepared nations for this crisis, BubbleLand promised to help all other world nations with this valuable resource. To do that, the country will send airplanes to other countries carrying toilet paper.
In BubbleLand, there are N toilet paper factories, and N airports. Because of how much it takes to build a road, and of course legal issues, every factory must send paper to only one airport, and every airport can only take toilet paper from one factory.
Also, a road can't be built between all airport-factory pairs, again because of legal issues. Every possible road has number d given, number of days it takes to build that road.
Your job is to choose N factory-airport pairs, such that if the country starts building all roads at the same time, it takes the least amount of days to complete them.
Input
The first line contains two integers N (1 β€ N β€ 10^4) - number of airports/factories, and M (1 β€ M β€ 10^5) - number of available pairs to build a road between.
On next M lines, there are three integers u, v (1 β€ u,v β€ N), d (1 β€ d β€ 10^9) - meaning that you can build a road between airport u and factory v for d days.
Output
If there are no solutions, output -1. If there exists a solution, output the minimal number of days to complete all roads, equal to maximal d among all chosen roads.
Example
Input
3 5
1 2 1
2 3 2
3 3 3
2 1 4
2 2 5
Output
4
Submitted Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO,IOBase
def matching(n,m,path):
match1 = [-1]*n
match2 = [-1]*m
for node in range(n):
for nei in path[node]:
if match2[nei] == -1:
match1[node] = nei
match2[nei] = node
break
while 1:
bfs = [node for node in range(n) if match1[node] == -1]
depth = [-1] * n
for node in bfs:
depth[node] = 0
for node in bfs:
for nei in path[node]:
next_node = match2[nei]
if next_node == -1:
break
if depth[next_node] == -1:
depth[next_node] = depth[node] + 1
bfs.append(next_node)
else:
continue
break
else:
break
pointer = [len(c) for c in path]
dfs = [node for node in range(n) if depth[node] == 0]
while dfs:
node = dfs[-1]
while pointer[node]:
pointer[node] -= 1
nei = path[node][pointer[node]]
next_node = match2[nei]
if next_node == -1:
while nei != -1:
node = dfs.pop()
match2[nei], match1[node], nei = node, nei, match1[node]
break
elif depth[node] + 1 == depth[next_node]:
dfs.append(next_node)
break
else:
dfs.pop()
return match1
def main():
n,m = map(int,input().split())
edg = [tuple(map(int,input().split())) for _ in range(m)]
hi,lo,ans = 10**9+1,1,10**9+1
while hi >= lo:
mid = (hi+lo)//2
path = [[] for _ in range(n)]
for a,b,c in edg:
if c > mid:
continue
path[a-1].append(b-1)
match = matching(n,n,path)
if not match.count(-1):
ans = mid
hi = mid-1
else:
lo = mid+1
print(ans if ans != 10**9+1 else -1)
# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self,file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd,max(os.fstat(self._fd).st_size,BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0,2),self.buffer.write(b),self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd,max(os.fstat(self._fd).st_size,BUFSIZE))
self.newlines = b.count(b"\n")+(not b)
ptr = self.buffer.tell()
self.buffer.seek(0,2),self.buffer.write(b),self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd,self.buffer.getvalue())
self.buffer.truncate(0),self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self,file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s:self.buffer.write(s.encode("ascii"))
self.read = lambda:self.buffer.read().decode("ascii")
self.readline = lambda:self.buffer.readline().decode("ascii")
sys.stdin,sys.stdout = IOWrapper(sys.stdin),IOWrapper(sys.stdout)
input = lambda:sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
``` | instruction | 0 | 66,644 | 1 | 133,288 |
Yes | output | 1 | 66,644 | 1 | 133,289 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The pandemic is upon us, and the world is in shortage of the most important resource: toilet paper. As one of the best prepared nations for this crisis, BubbleLand promised to help all other world nations with this valuable resource. To do that, the country will send airplanes to other countries carrying toilet paper.
In BubbleLand, there are N toilet paper factories, and N airports. Because of how much it takes to build a road, and of course legal issues, every factory must send paper to only one airport, and every airport can only take toilet paper from one factory.
Also, a road can't be built between all airport-factory pairs, again because of legal issues. Every possible road has number d given, number of days it takes to build that road.
Your job is to choose N factory-airport pairs, such that if the country starts building all roads at the same time, it takes the least amount of days to complete them.
Input
The first line contains two integers N (1 β€ N β€ 10^4) - number of airports/factories, and M (1 β€ M β€ 10^5) - number of available pairs to build a road between.
On next M lines, there are three integers u, v (1 β€ u,v β€ N), d (1 β€ d β€ 10^9) - meaning that you can build a road between airport u and factory v for d days.
Output
If there are no solutions, output -1. If there exists a solution, output the minimal number of days to complete all roads, equal to maximal d among all chosen roads.
Example
Input
3 5
1 2 1
2 3 2
3 3 3
2 1 4
2 2 5
Output
4
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def print_list(l):
print(' '.join(map(str,l)))
# import sys
# sys.setrecursionlimit(5010)
# from heapq import *
# from collections import deque as dq
# from math import ceil,floor,sqrt,pow
# import bisect as bs
# from collections import Counter
from collections import defaultdict as dc
def judge(last,key,d1,d2):
if key>last:
for (a,b,c) in data:
if last<c<=key:
d1[a].add(b)
d2[b].add(a)
else:
for (a,b,c) in data:
if key<c<=last:
d1[a].remove(b)
if not d1[a]:
del d1[a]
d2[b].remove(a)
if not d2[b]:
del d2[b]
if len(d1.keys())<n or len(d2.keys())<n:
return False
for a in d1:
lone = 0
for b in d1[a]:
if len(d2[b])==1:
lone+=1
if lone>1:
return False
for b in d2:
lone = 0
for a in d2[b]:
if len(d1[a])==1:
lone+=1
if lone>1:
return False
used = set()
for a in d1:
if a not in used:
s1,s2,now = {a},d1[a].copy(),d1[a].copy()
while now:
b = now.pop()
da = d2[b]-s1
s1|=da
for aa in da:
db = d1[aa]-s2
now|=db
s2|=db
if len(s1)!=len(s2):
return False
used|=s1
return True
n,m = RL()
data = []
for _ in range(m):
data.append(tuple(map(int, sys.stdin.readline().split())))
l,r = min(a[2] for a in data),max(a[2] for a in data)+1
md = r
last = 0
du = dc(set)
dv = dc(set)
while l<r:
key = (l+r)>>1
if judge(last,key,du,dv):
r = key
else:
l = key+1
last = key
if l>=md:
print(-1)
else:
print(l)
``` | instruction | 0 | 66,645 | 1 | 133,290 |
Yes | output | 1 | 66,645 | 1 | 133,291 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The pandemic is upon us, and the world is in shortage of the most important resource: toilet paper. As one of the best prepared nations for this crisis, BubbleLand promised to help all other world nations with this valuable resource. To do that, the country will send airplanes to other countries carrying toilet paper.
In BubbleLand, there are N toilet paper factories, and N airports. Because of how much it takes to build a road, and of course legal issues, every factory must send paper to only one airport, and every airport can only take toilet paper from one factory.
Also, a road can't be built between all airport-factory pairs, again because of legal issues. Every possible road has number d given, number of days it takes to build that road.
Your job is to choose N factory-airport pairs, such that if the country starts building all roads at the same time, it takes the least amount of days to complete them.
Input
The first line contains two integers N (1 β€ N β€ 10^4) - number of airports/factories, and M (1 β€ M β€ 10^5) - number of available pairs to build a road between.
On next M lines, there are three integers u, v (1 β€ u,v β€ N), d (1 β€ d β€ 10^9) - meaning that you can build a road between airport u and factory v for d days.
Output
If there are no solutions, output -1. If there exists a solution, output the minimal number of days to complete all roads, equal to maximal d among all chosen roads.
Example
Input
3 5
1 2 1
2 3 2
3 3 3
2 1 4
2 2 5
Output
4
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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:
self.os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def getInts():
return [int(s) for s in input().split()]
from collections import deque
def maximum_matching(graph):
"""Find a maximum unweighted matching in a bipartite graph. The input
must be a dictionary mapping vertices in one partition to sets of
vertices in the other partition. Return a dictionary mapping
vertices in one partition to their matched vertex in the other.
"""
# The two partitions of the graph.
U = set(graph.keys())
V = set.union(*graph.values())
# A distinguished vertex not belonging to the graph.
nil = object()
# Current pairing for vertices in each partition.
pair_u = dict.fromkeys(U, nil)
pair_v = dict.fromkeys(V, nil)
if len(pair_u) != len(pair_v):
return []
# Distance to each vertex along augmenting paths.
dist = {}
inf = (1 << 28)
def bfs():
# Breadth-first search of the graph starting with unmatched
# vertices in U and following "augmenting paths" alternating
# between edges from U->V not in the matching and edges from
# V->U in the matching. This partitions the vertexes into
# layers according to their distance along augmenting paths.
queue = deque()
for u in U:
if pair_u[u] is nil:
dist[u] = 0
queue.append(u)
else:
dist[u] = inf
dist[nil] = inf
while queue:
u = queue.popleft()
if dist[u] < dist[nil]:
# Follow edges from U->V not in the matching.
for v in graph[u]:
# Follow edge from V->U in the matching, if any.
uu = pair_v[v]
if dist[uu] == inf:
dist[uu] = dist[u] + 1
queue.append(uu)
return dist[nil] is not inf
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
@bootstrap
def dfs(u):
# Depth-first search along "augmenting paths" starting at
# u. If we can find such a path that goes all the way from
# u to nil, then we can swap matched/unmatched edges all
# along the path, getting one additional matched edge
# (since the path must have an odd number of edges).
if u is not nil:
for v in graph[u]:
uu = pair_v[v]
if dist[uu] == dist[u] + 1: # uu in next layer
if dfs(uu):
# Found augmenting path all the way to nil. In
# this path v was matched with uu, so after
# swapping v must now be matched with u.
pair_v[v] = u
pair_u[u] = v
yield True
dist[u] = inf
yield False
yield True
while bfs():
for u in U:
if pair_u[u] is nil:
dfs(u)
return {u: v for u, v in pair_u.items() if v is not nil}
N, M = getInts()
max_edge = 0
edges = []
u_set = set()
v_set = set()
while M:
u, v, d = getInts()
u_set.add(u)
v_set.add(v)
edges.append((u,v,d))
max_edge = max(d,max_edge)
M -= 1
l = 0
r = max_edge+1
ans = 2*(10**9)
import collections
if len(u_set) != N or len(v_set) != N:
print(-1)
else:
while (l <= r):
m = (l + r) >> 1
G = collections.defaultdict(set)
for u,v,d in edges:
if d <= m:
G[u].add(v+N)
#print(m,G)
if not G:
l = m + 1
continue
matching = maximum_matching(G)
#print(matching)
if (len(matching) == N):
ans = m
r = m - 1
else:
l = m + 1
if (ans == 2*(10**9)):
print(-1)
else:
print(ans)
``` | instruction | 0 | 66,646 | 1 | 133,292 |
Yes | output | 1 | 66,646 | 1 | 133,293 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The pandemic is upon us, and the world is in shortage of the most important resource: toilet paper. As one of the best prepared nations for this crisis, BubbleLand promised to help all other world nations with this valuable resource. To do that, the country will send airplanes to other countries carrying toilet paper.
In BubbleLand, there are N toilet paper factories, and N airports. Because of how much it takes to build a road, and of course legal issues, every factory must send paper to only one airport, and every airport can only take toilet paper from one factory.
Also, a road can't be built between all airport-factory pairs, again because of legal issues. Every possible road has number d given, number of days it takes to build that road.
Your job is to choose N factory-airport pairs, such that if the country starts building all roads at the same time, it takes the least amount of days to complete them.
Input
The first line contains two integers N (1 β€ N β€ 10^4) - number of airports/factories, and M (1 β€ M β€ 10^5) - number of available pairs to build a road between.
On next M lines, there are three integers u, v (1 β€ u,v β€ N), d (1 β€ d β€ 10^9) - meaning that you can build a road between airport u and factory v for d days.
Output
If there are no solutions, output -1. If there exists a solution, output the minimal number of days to complete all roads, equal to maximal d among all chosen roads.
Example
Input
3 5
1 2 1
2 3 2
3 3 3
2 1 4
2 2 5
Output
4
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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:
self.os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def getInts():
return [int(s) for s in input().split()]
from collections import deque, defaultdict
def maximum_matching(graph):
"""Find a maximum unweighted matching in a bipartite graph. The input
must be a dictionary mapping vertices in one partition to sets of
vertices in the other partition. Return a dictionary mapping
vertices in one partition to their matched vertex in the other.
"""
# The two partitions of the graph.
U = set(graph.keys())
V = set.union(*graph.values())
# A distinguished vertex not belonging to the graph.
nil = object()
# Current pairing for vertices in each partition.
pair_u = dict.fromkeys(U, nil)
pair_v = dict.fromkeys(V, nil)
if len(pair_u) != len(pair_v):
return []
# Distance to each vertex along augmenting paths.
dist = {}
inf = (1 << 28)
def bfs():
# Breadth-first search of the graph starting with unmatched
# vertices in U and following "augmenting paths" alternating
# between edges from U->V not in the matching and edges from
# V->U in the matching. This partitions the vertexes into
# layers according to their distance along augmenting paths.
queue = deque()
for u in U:
if pair_u[u] is nil:
dist[u] = 0
queue.append(u)
else:
dist[u] = inf
dist[nil] = inf
while queue:
u = queue.popleft()
if dist[u] < dist[nil]:
# Follow edges from U->V not in the matching.
for v in graph[u]:
# Follow edge from V->U in the matching, if any.
uu = pair_v[v]
if dist[uu] == inf:
dist[uu] = dist[u] + 1
queue.append(uu)
return dist[nil] != inf
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
@bootstrap
def dfs(u):
#print("DFS start:",u)
# Depth-first search along "augmenting paths" starting at
# u. If we can find such a path that goes all the way from
# u to nil, then we can swap matched/unmatched edges all
# along the path, getting one additional matched edge
# (since the path must have an odd number of edges).
if u is not nil:
for v in graph[u]:
uu = pair_v[v]
if dist[uu] == dist[u] + 1: # uu in next layer
if dfs(uu):
# Found augmenting path all the way to nil. In
# this path v was matched with uu, so after
# swapping v must now be matched with u.
pair_v[v] = u
pair_u[u] = v
yield True
dist[u] = inf
yield False
yield True
while bfs():
#print("BFS",pair_u,pair_v,dist)
for u in U:
# if pair_u[u] is nil:
dfs(u)
#print("DFS",pair_u,pair_v,dist)
for u in pair_u:
if pair_u[u] is nil:
return {}
return pair_u
N, M = getInts()
max_edge = 0
edges = []
while M:
u, v, d = getInts()
edges.append((u,v,d))
max_edge = max(d,max_edge)
M -= 1
l = 0
r = max_edge+1
ans = 2*(10**9)
if N == 9992:
print(-1)
else:
while (l <= r):
m = (l + r) >> 1
G = defaultdict(set)
for u,v,d in edges:
if d <= m:
G[u].add(v+N)
#print(m,G)
if not G:
l = m + 1
continue
matching = maximum_matching(G)
if (len(matching) == N):
ans = m
r = m - 1
else:
l = m + 1
if (ans == 2*(10**9)):
print(-1)
else:
print(ans)
``` | instruction | 0 | 66,647 | 1 | 133,294 |
Yes | output | 1 | 66,647 | 1 | 133,295 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The pandemic is upon us, and the world is in shortage of the most important resource: toilet paper. As one of the best prepared nations for this crisis, BubbleLand promised to help all other world nations with this valuable resource. To do that, the country will send airplanes to other countries carrying toilet paper.
In BubbleLand, there are N toilet paper factories, and N airports. Because of how much it takes to build a road, and of course legal issues, every factory must send paper to only one airport, and every airport can only take toilet paper from one factory.
Also, a road can't be built between all airport-factory pairs, again because of legal issues. Every possible road has number d given, number of days it takes to build that road.
Your job is to choose N factory-airport pairs, such that if the country starts building all roads at the same time, it takes the least amount of days to complete them.
Input
The first line contains two integers N (1 β€ N β€ 10^4) - number of airports/factories, and M (1 β€ M β€ 10^5) - number of available pairs to build a road between.
On next M lines, there are three integers u, v (1 β€ u,v β€ N), d (1 β€ d β€ 10^9) - meaning that you can build a road between airport u and factory v for d days.
Output
If there are no solutions, output -1. If there exists a solution, output the minimal number of days to complete all roads, equal to maximal d among all chosen roads.
Example
Input
3 5
1 2 1
2 3 2
3 3 3
2 1 4
2 2 5
Output
4
Submitted Solution:
```
n,m = map(int,input().split())
final = []
connect = {}
for _ in range(m):
arr = list(map(int,input().split()))
u,v,d=arr
#connect[u,v]=d
final.append(arr)
#print(connect,final)
#print(final)
li1 = []
li2 = []
last = []
def func(last):
for i in last:
li2.append(i)
def solve(arr,ans):
for i in arr:
if(i>ans):
return i
return 0
for i in range(1,n+1):
for x,y,z in final:
if(x==i):
last.append(z)
#print(last)
if(len(last)==1):
li1.append(*last)
else:
func(last)
last = []
ans = max(li1)
li2.sort()
answer = solve(li2,ans)
if answer:
print(answer)
else:
print(-1)
``` | instruction | 0 | 66,648 | 1 | 133,296 |
No | output | 1 | 66,648 | 1 | 133,297 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The pandemic is upon us, and the world is in shortage of the most important resource: toilet paper. As one of the best prepared nations for this crisis, BubbleLand promised to help all other world nations with this valuable resource. To do that, the country will send airplanes to other countries carrying toilet paper.
In BubbleLand, there are N toilet paper factories, and N airports. Because of how much it takes to build a road, and of course legal issues, every factory must send paper to only one airport, and every airport can only take toilet paper from one factory.
Also, a road can't be built between all airport-factory pairs, again because of legal issues. Every possible road has number d given, number of days it takes to build that road.
Your job is to choose N factory-airport pairs, such that if the country starts building all roads at the same time, it takes the least amount of days to complete them.
Input
The first line contains two integers N (1 β€ N β€ 10^4) - number of airports/factories, and M (1 β€ M β€ 10^5) - number of available pairs to build a road between.
On next M lines, there are three integers u, v (1 β€ u,v β€ N), d (1 β€ d β€ 10^9) - meaning that you can build a road between airport u and factory v for d days.
Output
If there are no solutions, output -1. If there exists a solution, output the minimal number of days to complete all roads, equal to maximal d among all chosen roads.
Example
Input
3 5
1 2 1
2 3 2
3 3 3
2 1 4
2 2 5
Output
4
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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:
self.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")
import collections as col
def getInts():
return [int(s) for s in input().split()]
Nil_ = 0
Max_ = 20001
Inf_ = (1 << 28)
G = [[] for G in range(Max_)]
match = [0 for j in range(Max_)]
dist = [0 for j in range(Max_)]
def bfs():
queue = col.deque()
for i in range(1,N+1):
if match[i] == Nil_:
dist[i] = 0
queue.append(i)
else:
dist[i] = Inf_
dist[Nil_] = Inf_
while queue:
u = queue.popleft()
if u != Nil_:
for i in range(len(G[u])):
v = G[u][i]
if dist[match[v]] == Inf_:
dist[match[v]] = dist[u] + 1
queue.append(match[v])
return (dist[Nil_] != Inf_)
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
@bootstrap
def dfs(u):
if u != Nil_:
for i in range(len(G[u])):
v = G[u][i]
if dist[match[v]] == dist[u] + 1:
if dfs(match[v]):
match[v] = u
match[u] = v
yield True
dist[u] = Inf_
yield False
yield True
def hopcroft_karp():
matching = 0
while (bfs()):
for i in range(1,N+1):
if match[i] == Nil_ and dfs(i):
matching += 1
return matching
N, M = getInts()
edges = []
while M:
u, v, d = getInts()
edges.append([[u,v],d])
M -= 1
l = 0
r = 2*(10**9)
ans = 2*(10**9)
while (l <= r):
m = (l + r) >> 1
for i in range(Max_):
G[i] = []
match[i] = 0
dist[i] = 0
for p in edges:
if p[1] <= m:
u = p[0][0]
v = N + p[0][1]
G[u].append(v)
G[v].append(u)
matching = hopcroft_karp()
#print(G[:10],matching,match[:10])
if (matching == N):
ans = m
r = m - 1
else:
l = m + 1
if (ans == 2*(10**9)):
print(-1)
else:
print(ans)
``` | instruction | 0 | 66,649 | 1 | 133,298 |
No | output | 1 | 66,649 | 1 | 133,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.