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.
Farmer John has a farm that consists of n pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.
Unfortunately, Farmer John lost the map of the farm. All he remembers is an array d, where d_i is the smallest amount of time it took the cows to reach the i-th pasture from pasture 1 using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t cases follow.
The first line of each test case contains a single integer n (1 β€ n β€ 10^5) β the number of pastures.
The second line of each test case contains n space separated integers d_1, d_2, β¦, d_n (0 β€ d_i β€ 10^9) β the array d. It is guaranteed that d_1 = 0.
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
Example
Input
3
3
0 2 3
2
0 1000000000
1
0
Output
-3
0
0
Note
In the first test case, you can add roads
* from pasture 1 to pasture 2 with a time of 2,
* from pasture 2 to pasture 3 with a time of 1,
* from pasture 3 to pasture 1 with a time of -3,
* from pasture 3 to pasture 2 with a time of -1,
* from pasture 2 to pasture 1 with a time of -2.
The total cost is 2 + 1 + -3 + -1 + -2 = -3.
In the second test case, you can add a road from pasture 1 to pasture 2 with cost 1000000000 and a road from pasture 2 to pasture 1 with cost -1000000000. The total cost is 1000000000 + -1000000000 = 0.
In the third test case, you can't add any roads. The total cost is 0. | instruction | 0 | 54,205 | 1 | 108,410 |
Tags: constructive algorithms, graphs, greedy, shortest paths, sortings
Correct Solution:
```
t=int(input())
for i in range(t):
n=int(input())
l=list(map(int,input().split()))
l.sort()
req=0
s=0
j=2
while j<n:
req-=l[j]*(j-1)
s+=l[j-2]
req+=s
j+=1
print(req)
``` | output | 1 | 54,205 | 1 | 108,411 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Farmer John has a farm that consists of n pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.
Unfortunately, Farmer John lost the map of the farm. All he remembers is an array d, where d_i is the smallest amount of time it took the cows to reach the i-th pasture from pasture 1 using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t cases follow.
The first line of each test case contains a single integer n (1 β€ n β€ 10^5) β the number of pastures.
The second line of each test case contains n space separated integers d_1, d_2, β¦, d_n (0 β€ d_i β€ 10^9) β the array d. It is guaranteed that d_1 = 0.
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
Example
Input
3
3
0 2 3
2
0 1000000000
1
0
Output
-3
0
0
Note
In the first test case, you can add roads
* from pasture 1 to pasture 2 with a time of 2,
* from pasture 2 to pasture 3 with a time of 1,
* from pasture 3 to pasture 1 with a time of -3,
* from pasture 3 to pasture 2 with a time of -1,
* from pasture 2 to pasture 1 with a time of -2.
The total cost is 2 + 1 + -3 + -1 + -2 = -3.
In the second test case, you can add a road from pasture 1 to pasture 2 with cost 1000000000 and a road from pasture 2 to pasture 1 with cost -1000000000. The total cost is 1000000000 + -1000000000 = 0.
In the third test case, you can't add any roads. The total cost is 0. | instruction | 0 | 54,206 | 1 | 108,412 |
Tags: constructive algorithms, graphs, greedy, shortest paths, sortings
Correct Solution:
```
from collections import defaultdict
t = int(input())
def solve():
n = int(input())
arr = list(map(int, input().split()))
arr.sort()
v0 = 0
s = 0
for i in range(2, n):
s += arr[i - 2]
v0 -= (arr[i] * (i - 1))
v0 += s
print(v0)
for i in range(t):
solve()
``` | output | 1 | 54,206 | 1 | 108,413 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Farmer John has a farm that consists of n pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.
Unfortunately, Farmer John lost the map of the farm. All he remembers is an array d, where d_i is the smallest amount of time it took the cows to reach the i-th pasture from pasture 1 using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t cases follow.
The first line of each test case contains a single integer n (1 β€ n β€ 10^5) β the number of pastures.
The second line of each test case contains n space separated integers d_1, d_2, β¦, d_n (0 β€ d_i β€ 10^9) β the array d. It is guaranteed that d_1 = 0.
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
Example
Input
3
3
0 2 3
2
0 1000000000
1
0
Output
-3
0
0
Note
In the first test case, you can add roads
* from pasture 1 to pasture 2 with a time of 2,
* from pasture 2 to pasture 3 with a time of 1,
* from pasture 3 to pasture 1 with a time of -3,
* from pasture 3 to pasture 2 with a time of -1,
* from pasture 2 to pasture 1 with a time of -2.
The total cost is 2 + 1 + -3 + -1 + -2 = -3.
In the second test case, you can add a road from pasture 1 to pasture 2 with cost 1000000000 and a road from pasture 2 to pasture 1 with cost -1000000000. The total cost is 1000000000 + -1000000000 = 0.
In the third test case, you can't add any roads. The total cost is 0. | instruction | 0 | 54,207 | 1 | 108,414 |
Tags: constructive algorithms, graphs, greedy, shortest paths, sortings
Correct Solution:
```
t = int(input())
for c in range(t):
n = int(input())
a = [int(e) for e in input().split()]
a.sort()
ans = 0
for i in range(1, n):
d = a[i] - a[i - 1]
ans += d
for i in range(1, n):
d = a[i] - a[i - 1]
cnt = i * (n - i)
ans -= d * cnt
print(ans)
# 0, 1, 2, 3
# i - 1 n
# 0 1
``` | output | 1 | 54,207 | 1 | 108,415 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Π‘ity N. has a huge problem with roads, food and IT-infrastructure. In total the city has n junctions, some pairs of them are connected by bidirectional roads. The road network consists of n - 1 roads, you can get from any junction to any other one by these roads. Yes, you're right β the road network forms an undirected tree.
Recently, the Mayor came up with a way that eliminates the problems with the food and the IT-infrastructure at the same time! He decided to put at the city junctions restaurants of two well-known cafe networks for IT professionals: "iMac D0naldz" and "Burger Bing". Since the network owners are not friends, it is strictly prohibited to place two restaurants of different networks on neighboring junctions. There are other requirements. Here's the full list:
* each junction must have at most one restaurant;
* each restaurant belongs either to "iMac D0naldz", or to "Burger Bing";
* each network should build at least one restaurant;
* there is no pair of junctions that are connected by a road and contains restaurants of different networks.
The Mayor is going to take a large tax from each restaurant, so he is interested in making the total number of the restaurants as large as possible.
Help the Mayor to analyze the situation. Find all such pairs of (a, b) that a restaurants can belong to "iMac D0naldz", b restaurants can belong to "Burger Bing", and the sum of a + b is as large as possible.
Input
The first input line contains integer n (3 β€ n β€ 5000) β the number of junctions in the city. Next n - 1 lines list all roads one per line. Each road is given as a pair of integers xi, yi (1 β€ xi, yi β€ n) β the indexes of connected junctions. Consider the junctions indexed from 1 to n.
It is guaranteed that the given road network is represented by an undirected tree with n vertexes.
Output
Print on the first line integer z β the number of sought pairs. Then print all sought pairs (a, b) in the order of increasing of the first component a.
Examples
Input
5
1 2
2 3
3 4
4 5
Output
3
1 3
2 2
3 1
Input
10
1 2
2 3
3 4
5 6
6 7
7 4
8 9
9 10
10 4
Output
6
1 8
2 7
3 6
6 3
7 2
8 1
Note
The figure below shows the answers to the first test case. The junctions with "iMac D0naldz" restaurants are marked red and "Burger Bing" restaurants are marked blue.
<image> | instruction | 0 | 54,232 | 1 | 108,464 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
from sys import stdin
n=int(stdin.readline())
g=[[] for i in range(n)]
for _ in range(n-1):
x,y=map(int,stdin.readline().split())
x-=1
y-=1
g[x].append(y)
g[y].append(x)
subtree_size=[0]*n
stack=[[-1,0,0]]
ans=[]
while stack:
par,ver,state=stack.pop()
if state==0:
stack.append([par,ver,1])
for to in g[ver]:
if to!=par:
stack.append([ver,to,0])
else:
if len(g[ver])==1:
subtree_size[ver]=1
else:
cnt=0
tmp=[]
for to in g[ver]:
if to!=par:
cnt+=subtree_size[to]
tmp.append(subtree_size[to])
tmp.append(n-cnt-1)
local=[0]*(n+1)
local[0]=1
for x in tmp:
for i in range(n-x,-1,-1):
if local[i]==1:
local[i+x]=1
if x+i!=0 and n-1-(x+i)!=0:
ans.append(x+i)
subtree_size[ver]=cnt+1
ans=sorted(list(set(ans)))
print(len(ans))
for x in ans:
print(x,n-1-x)
``` | output | 1 | 54,232 | 1 | 108,465 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Π‘ity N. has a huge problem with roads, food and IT-infrastructure. In total the city has n junctions, some pairs of them are connected by bidirectional roads. The road network consists of n - 1 roads, you can get from any junction to any other one by these roads. Yes, you're right β the road network forms an undirected tree.
Recently, the Mayor came up with a way that eliminates the problems with the food and the IT-infrastructure at the same time! He decided to put at the city junctions restaurants of two well-known cafe networks for IT professionals: "iMac D0naldz" and "Burger Bing". Since the network owners are not friends, it is strictly prohibited to place two restaurants of different networks on neighboring junctions. There are other requirements. Here's the full list:
* each junction must have at most one restaurant;
* each restaurant belongs either to "iMac D0naldz", or to "Burger Bing";
* each network should build at least one restaurant;
* there is no pair of junctions that are connected by a road and contains restaurants of different networks.
The Mayor is going to take a large tax from each restaurant, so he is interested in making the total number of the restaurants as large as possible.
Help the Mayor to analyze the situation. Find all such pairs of (a, b) that a restaurants can belong to "iMac D0naldz", b restaurants can belong to "Burger Bing", and the sum of a + b is as large as possible.
Input
The first input line contains integer n (3 β€ n β€ 5000) β the number of junctions in the city. Next n - 1 lines list all roads one per line. Each road is given as a pair of integers xi, yi (1 β€ xi, yi β€ n) β the indexes of connected junctions. Consider the junctions indexed from 1 to n.
It is guaranteed that the given road network is represented by an undirected tree with n vertexes.
Output
Print on the first line integer z β the number of sought pairs. Then print all sought pairs (a, b) in the order of increasing of the first component a.
Examples
Input
5
1 2
2 3
3 4
4 5
Output
3
1 3
2 2
3 1
Input
10
1 2
2 3
3 4
5 6
6 7
7 4
8 9
9 10
10 4
Output
6
1 8
2 7
3 6
6 3
7 2
8 1
Note
The figure below shows the answers to the first test case. The junctions with "iMac D0naldz" restaurants are marked red and "Burger Bing" restaurants are marked blue.
<image> | instruction | 0 | 54,233 | 1 | 108,466 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
###pyrival template for fast IO
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")
#####change recurssion limit
import sys,threading
sys.setrecursionlimit(6100)
threading.stack_size()
thread=threading.Thread()
thread.start()
def graph_undirected():
n=int(input())
graph={} #####adjecancy list using dict
for i in range(n-1):
vertex,neighbour=[int(x) for x in input().split()]
if vertex in graph:
graph[vertex].append(neighbour)
else:
graph[vertex]=[neighbour]
if neighbour in graph: #####for undirected part remove to get directed
graph[neighbour].append(vertex)
else:
graph[neighbour]=[vertex]
return graph,n
graph,n=graph_undirected()
dp=[[] for x in range(n+1)] ####store sizes of all sub graph for each articulation point
###### undirected
def dfs(graph,n,currnode):
visited=[False for x in range(n+1)]
stack=[currnode]
while stack:
currnode=stack[-1]
if visited[currnode]==False:
visited[currnode]=True
for neighbour in graph[currnode]:
if visited[neighbour]==False:
visited[neighbour]=True
stack.append(neighbour)
break #####if we remove break it becomes bfs
else:
if len(stack)>1:
s=sum(dp[stack[-1]])
dp[stack[-1]].append(n-s-1)
dp[stack[-2]].append(s+1);#print(stack[-2],stack[-1])
stack.pop() ####we are backtracking to previous node which is in our stack
def func(arr,n):
k=[];i=0;l=len(arr);dict={}
for i in range(n+1):
dict[i]=False
for i in range(l):
temp=[]
for item in k:
if dict[item+arr[i]]==False :temp.append(item+arr[i]);dict[item+arr[i]]=True
if dict[arr[i]]==False:k.append(arr[i]);dict[arr[i]]=True
k+=temp
return k
dfs(graph,n,1);ans=[]
ans={}
for i in range(1,n+1):
k=func(dp[i],n)
for item in k:
if item not in ans:
if item!=0 and item!=n-1:ans[item]=True
print(len(ans))
for key in sorted(ans):
sys.stdout.write(str(key)+" "+str(n-1-key)+"\n")
``` | output | 1 | 54,233 | 1 | 108,467 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Π‘ity N. has a huge problem with roads, food and IT-infrastructure. In total the city has n junctions, some pairs of them are connected by bidirectional roads. The road network consists of n - 1 roads, you can get from any junction to any other one by these roads. Yes, you're right β the road network forms an undirected tree.
Recently, the Mayor came up with a way that eliminates the problems with the food and the IT-infrastructure at the same time! He decided to put at the city junctions restaurants of two well-known cafe networks for IT professionals: "iMac D0naldz" and "Burger Bing". Since the network owners are not friends, it is strictly prohibited to place two restaurants of different networks on neighboring junctions. There are other requirements. Here's the full list:
* each junction must have at most one restaurant;
* each restaurant belongs either to "iMac D0naldz", or to "Burger Bing";
* each network should build at least one restaurant;
* there is no pair of junctions that are connected by a road and contains restaurants of different networks.
The Mayor is going to take a large tax from each restaurant, so he is interested in making the total number of the restaurants as large as possible.
Help the Mayor to analyze the situation. Find all such pairs of (a, b) that a restaurants can belong to "iMac D0naldz", b restaurants can belong to "Burger Bing", and the sum of a + b is as large as possible.
Input
The first input line contains integer n (3 β€ n β€ 5000) β the number of junctions in the city. Next n - 1 lines list all roads one per line. Each road is given as a pair of integers xi, yi (1 β€ xi, yi β€ n) β the indexes of connected junctions. Consider the junctions indexed from 1 to n.
It is guaranteed that the given road network is represented by an undirected tree with n vertexes.
Output
Print on the first line integer z β the number of sought pairs. Then print all sought pairs (a, b) in the order of increasing of the first component a.
Examples
Input
5
1 2
2 3
3 4
4 5
Output
3
1 3
2 2
3 1
Input
10
1 2
2 3
3 4
5 6
6 7
7 4
8 9
9 10
10 4
Output
6
1 8
2 7
3 6
6 3
7 2
8 1
Note
The figure below shows the answers to the first test case. The junctions with "iMac D0naldz" restaurants are marked red and "Burger Bing" restaurants are marked blue.
<image> | instruction | 0 | 54,234 | 1 | 108,468 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
from os import path
import sys,time, collections as c , math as m , pprint as p
maxx , localsys , mod = float('inf'), 0 , int(1e9 + 7)
if (path.exists('input.txt')): sys.stdin=open('input.txt','r') ; sys.stdout=open('output.txt','w')
input = sys.stdin.readline
def dfs(v , p):
ans = 1
for i in d[v]:
if i != p:
ans+=dfs(i, v)
return ans
n = int(input()) ; d = c.defaultdict(list)
for _ in range(1 ,n):
u , v = map(int , input().split())
d[u].append(v) ; d[v].append(u)
check , observe = 1 , 0
st , tree , possible = [(observe , 1 , 0)] , [0]*n + [0] , [0]*n+[0]
while st:
state , vertex , parent = st.pop()
if state == observe:
st.append((check , vertex , parent))
for c in d[vertex]:
if c != parent:
st.append((observe , c,vertex))
else:
tmp , loc , cnt=[] , [0]*(n+1) ,0
for c in d[vertex]:
if c!= parent:
cnt+=tree[c]
tmp.append(tree[c])
tmp.append(n-cnt-1)
tree[vertex] = cnt + 1
loc[0] =1
for x in tmp:
for i in range(n-x , -1 ,-1):
if loc[i] == 1:
loc[x+i] = 1
possible[x+i] = 1
possible[0] = possible[n-1] = 0
print(possible.count(1))
for i in range(1 , n- 1):
if possible[i]:
print(i , n-1-i)
``` | output | 1 | 54,234 | 1 | 108,469 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Π‘ity N. has a huge problem with roads, food and IT-infrastructure. In total the city has n junctions, some pairs of them are connected by bidirectional roads. The road network consists of n - 1 roads, you can get from any junction to any other one by these roads. Yes, you're right β the road network forms an undirected tree.
Recently, the Mayor came up with a way that eliminates the problems with the food and the IT-infrastructure at the same time! He decided to put at the city junctions restaurants of two well-known cafe networks for IT professionals: "iMac D0naldz" and "Burger Bing". Since the network owners are not friends, it is strictly prohibited to place two restaurants of different networks on neighboring junctions. There are other requirements. Here's the full list:
* each junction must have at most one restaurant;
* each restaurant belongs either to "iMac D0naldz", or to "Burger Bing";
* each network should build at least one restaurant;
* there is no pair of junctions that are connected by a road and contains restaurants of different networks.
The Mayor is going to take a large tax from each restaurant, so he is interested in making the total number of the restaurants as large as possible.
Help the Mayor to analyze the situation. Find all such pairs of (a, b) that a restaurants can belong to "iMac D0naldz", b restaurants can belong to "Burger Bing", and the sum of a + b is as large as possible.
Input
The first input line contains integer n (3 β€ n β€ 5000) β the number of junctions in the city. Next n - 1 lines list all roads one per line. Each road is given as a pair of integers xi, yi (1 β€ xi, yi β€ n) β the indexes of connected junctions. Consider the junctions indexed from 1 to n.
It is guaranteed that the given road network is represented by an undirected tree with n vertexes.
Output
Print on the first line integer z β the number of sought pairs. Then print all sought pairs (a, b) in the order of increasing of the first component a.
Examples
Input
5
1 2
2 3
3 4
4 5
Output
3
1 3
2 2
3 1
Input
10
1 2
2 3
3 4
5 6
6 7
7 4
8 9
9 10
10 4
Output
6
1 8
2 7
3 6
6 3
7 2
8 1
Note
The figure below shows the answers to the first test case. The junctions with "iMac D0naldz" restaurants are marked red and "Burger Bing" restaurants are marked blue.
<image> | instruction | 0 | 54,235 | 1 | 108,470 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
"""
Author - Satwik Tiwari .
17th NOV , 2020 - Tuesday
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from functools import cmp_to_key
# from itertools import *
from heapq import *
from math import gcd, factorial,floor,ceil,sqrt
from copy import deepcopy
from collections import deque
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
#==============================================================================================
#fast I/O 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")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
# inp = lambda: sys.stdin.readline().rstrip("\r\n")
#===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
def wrapped_func(*args, **kwargs):
if stack: return f(*args, **kwargs)
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
continue
stack.pop()
if not stack: break
to = stack[-1].send(to)
return to
return wrapped_func
#### END ITERATE RECURSION ####
#===============================================================================================
#some shortcuts
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var)) #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
# def graph(vertex): return [[] for i in range(0,vertex+1)]
def testcase(t):
for pp in range(t):
solve(pp)
def google(p):
print('Case #'+str(p)+': ',end='')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(x, y, p) :
y%=(p-1) #not so sure about this. used when y>p-1. if p is prime.
res = 1 # Initialize result
x = x % p # Update x if it is more , than or equal to p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) : # If y is odd, multiply, x with result
res = (res * x) % p
y = y >> 1 # y = y/2
x = (x * x) % p
return res
def ncr(n,r): return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))
def isPrime(n) :
if (n <= 1) : return False
if (n <= 3) : return True
if (n % 2 == 0 or n % 3 == 0) : return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
inf = pow(10,20)
mod = 10**9+7
#===============================================================================================
# code here ;))
def bucketsort(order, seq):
buckets = [0] * (max(seq) + 1)
for x in seq:
buckets[x] += 1
for i in range(len(buckets) - 1):
buckets[i + 1] += buckets[i]
new_order = [-1] * len(seq)
for i in reversed(order):
x = seq[i]
idx = buckets[x] = buckets[x] - 1
new_order[idx] = i
return new_order
def ordersort(order, seq, reverse=False):
bit = max(seq).bit_length() >> 1
mask = (1 << bit) - 1
order = bucketsort(order, [x & mask for x in seq])
order = bucketsort(order, [x >> bit for x in seq])
if reverse:
order.reverse()
return order
def long_ordersort(order, seq):
order = ordersort(order, [int(i & 0x7fffffff) for i in seq])
return ordersort(order, [int(i >> 31) for i in seq])
def multikey_ordersort(order, *seqs, sort=ordersort):
for i in reversed(range(len(seqs))):
order = sort(order, seqs[i])
return order
@iterative
def dfs1(v,visited,st,sub):
visited[st] = 1
for i in v[st]:
if(visited[i] == 0):
ok = yield dfs1(v,visited,i,sub)
sub[st] += sub[i]
yield True
@iterative
def dfs12(v,visited,frm,st,sub):
global pairs
visited[st] = 1
pre = [sub[0] - sub[st]] if st else []
for i in v[st]:
if(visited[i] == 0):
ok = yield dfs12(v,visited,st,i,sub)
pre.append(sub[i])
pos = [False]*(len(v)+1)
pos[0] = True
for j in pre:
for i in range(len(v),0,-1):
if(i-j<0):
continue
pos[i] = pos[i] or pos[i-j]
pos[sum(pre)] = False
for i in range(1,len(v)+1):
if(pos[i]):
pairs.add((i,len(v)-i-1))
pairs.add((len(v) - i - 1,i))
yield True
def solve(case):
global pairs
n = int(inp())
g = [[] for i in range(n)]
for i in range(n-1):
x,y = sep()
x-=1;y-=1
g[x].append(y)
g[y].append(x)
sub = [1]*n ; vis = [0]*n
dfs1(g,vis,0,sub)
vis = [0]*n
dfs12(g,vis,-1,0,sub)
# print(sub)
ans = []
l = [];r = []
for i,j in pairs:
if(i<1 or j<1):
continue
l.append(i)
r.append(j)
order = multikey_ordersort(range(len(l)),l,r)
for i in order:
ans.append((l[i],r[i]))
print(len(ans))
for i in ans:
print(*i)
pairs = set()
f = 1
testcase(1)
# testcase(int(inp()))
"""
4
10 0 0
20 1 0
30 0 1
40 1 1
4 1
2 3
1 3
"""
``` | output | 1 | 54,235 | 1 | 108,471 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Π‘ity N. has a huge problem with roads, food and IT-infrastructure. In total the city has n junctions, some pairs of them are connected by bidirectional roads. The road network consists of n - 1 roads, you can get from any junction to any other one by these roads. Yes, you're right β the road network forms an undirected tree.
Recently, the Mayor came up with a way that eliminates the problems with the food and the IT-infrastructure at the same time! He decided to put at the city junctions restaurants of two well-known cafe networks for IT professionals: "iMac D0naldz" and "Burger Bing". Since the network owners are not friends, it is strictly prohibited to place two restaurants of different networks on neighboring junctions. There are other requirements. Here's the full list:
* each junction must have at most one restaurant;
* each restaurant belongs either to "iMac D0naldz", or to "Burger Bing";
* each network should build at least one restaurant;
* there is no pair of junctions that are connected by a road and contains restaurants of different networks.
The Mayor is going to take a large tax from each restaurant, so he is interested in making the total number of the restaurants as large as possible.
Help the Mayor to analyze the situation. Find all such pairs of (a, b) that a restaurants can belong to "iMac D0naldz", b restaurants can belong to "Burger Bing", and the sum of a + b is as large as possible.
Input
The first input line contains integer n (3 β€ n β€ 5000) β the number of junctions in the city. Next n - 1 lines list all roads one per line. Each road is given as a pair of integers xi, yi (1 β€ xi, yi β€ n) β the indexes of connected junctions. Consider the junctions indexed from 1 to n.
It is guaranteed that the given road network is represented by an undirected tree with n vertexes.
Output
Print on the first line integer z β the number of sought pairs. Then print all sought pairs (a, b) in the order of increasing of the first component a.
Examples
Input
5
1 2
2 3
3 4
4 5
Output
3
1 3
2 2
3 1
Input
10
1 2
2 3
3 4
5 6
6 7
7 4
8 9
9 10
10 4
Output
6
1 8
2 7
3 6
6 3
7 2
8 1
Note
The figure below shows the answers to the first test case. The junctions with "iMac D0naldz" restaurants are marked red and "Burger Bing" restaurants are marked blue.
<image> | instruction | 0 | 54,236 | 1 | 108,472 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
from collections import defaultdict,deque
import sys
import bisect
input=sys.stdin.readline
mod=1000000007
graph=defaultdict(list)
n=int(input())
for i in range(n-1):
x,y=map(int,input().split())
graph[x].append(y)
graph[y].append(x)
vis=set()
CHECK,OBSERVE=1,0
stack=[(OBSERVE,1,0)]
tree=[0]*(n+1) #size of subtree for each vertex
possible=[0]*(n+1) # list to contain all the possible value for a
while stack:
state,vertex,parent=stack.pop()
if state==OBSERVE:
stack.append((CHECK,vertex,parent))
for child in graph[vertex]:
if child!=parent:
stack.append((OBSERVE,child,vertex))
else:
if len(graph[vertex])==1:
tree[vertex]=1
else:
tmp,local=[],[0]*(n+1)
count=0
for child in graph[vertex]:
if child!=parent:
count+=tree[child]
tmp.append(tree[child])
tmp.append(n-count-1)
tree[vertex]=count+1
#Knapsack
local[0]=1
for x in tmp:
for i in range(n-x,-1,-1):
if local[i]==1:
local[x+i]=1
possible[x+i]=1
ans=[]
for i in range(1,n-1):
if possible[i]:
ans.append(i)
print(len(ans))
for i in ans:
sys.stdout.write(str(i)+' '+str(n-1-i)+'\n')
``` | output | 1 | 54,236 | 1 | 108,473 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Π‘ity N. has a huge problem with roads, food and IT-infrastructure. In total the city has n junctions, some pairs of them are connected by bidirectional roads. The road network consists of n - 1 roads, you can get from any junction to any other one by these roads. Yes, you're right β the road network forms an undirected tree.
Recently, the Mayor came up with a way that eliminates the problems with the food and the IT-infrastructure at the same time! He decided to put at the city junctions restaurants of two well-known cafe networks for IT professionals: "iMac D0naldz" and "Burger Bing". Since the network owners are not friends, it is strictly prohibited to place two restaurants of different networks on neighboring junctions. There are other requirements. Here's the full list:
* each junction must have at most one restaurant;
* each restaurant belongs either to "iMac D0naldz", or to "Burger Bing";
* each network should build at least one restaurant;
* there is no pair of junctions that are connected by a road and contains restaurants of different networks.
The Mayor is going to take a large tax from each restaurant, so he is interested in making the total number of the restaurants as large as possible.
Help the Mayor to analyze the situation. Find all such pairs of (a, b) that a restaurants can belong to "iMac D0naldz", b restaurants can belong to "Burger Bing", and the sum of a + b is as large as possible.
Input
The first input line contains integer n (3 β€ n β€ 5000) β the number of junctions in the city. Next n - 1 lines list all roads one per line. Each road is given as a pair of integers xi, yi (1 β€ xi, yi β€ n) β the indexes of connected junctions. Consider the junctions indexed from 1 to n.
It is guaranteed that the given road network is represented by an undirected tree with n vertexes.
Output
Print on the first line integer z β the number of sought pairs. Then print all sought pairs (a, b) in the order of increasing of the first component a.
Examples
Input
5
1 2
2 3
3 4
4 5
Output
3
1 3
2 2
3 1
Input
10
1 2
2 3
3 4
5 6
6 7
7 4
8 9
9 10
10 4
Output
6
1 8
2 7
3 6
6 3
7 2
8 1
Note
The figure below shows the answers to the first test case. The junctions with "iMac D0naldz" restaurants are marked red and "Burger Bing" restaurants are marked blue.
<image>
Submitted Solution:
```
from sys import stdin
n=int(stdin.readline())
g=[[] for i in range(n)]
for _ in range(n-1):
x,y=map(int,stdin.readline().split())
x-=1
y-=1
g[x].append(y)
g[y].append(x)
subtree_size=[0]*n
stack=[[-1,0,1]]
while stack:
par,ver,cnt=stack.pop()
for to in g[ver]:
if to!=par:
subtree_size[to]=cnt+1
stack.append([ver,to,cnt+1])
for i in range(n):
if len(g[i])==1:
subtree_size[i]=1
ans=[]
use=set()
for i in range(n):
d=subtree_size[i]
if d==0 or n-1-d==0:
continue
if not d in use:
ans.append([d,n-1-d])
use.add(d)
if not n-1-d in use:
ans.append([n-1-d,d])
use.add(n-1-d)
ans.sort()
print(len(ans))
for z in ans:
print(*z)
``` | instruction | 0 | 54,237 | 1 | 108,474 |
No | output | 1 | 54,237 | 1 | 108,475 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Π‘ity N. has a huge problem with roads, food and IT-infrastructure. In total the city has n junctions, some pairs of them are connected by bidirectional roads. The road network consists of n - 1 roads, you can get from any junction to any other one by these roads. Yes, you're right β the road network forms an undirected tree.
Recently, the Mayor came up with a way that eliminates the problems with the food and the IT-infrastructure at the same time! He decided to put at the city junctions restaurants of two well-known cafe networks for IT professionals: "iMac D0naldz" and "Burger Bing". Since the network owners are not friends, it is strictly prohibited to place two restaurants of different networks on neighboring junctions. There are other requirements. Here's the full list:
* each junction must have at most one restaurant;
* each restaurant belongs either to "iMac D0naldz", or to "Burger Bing";
* each network should build at least one restaurant;
* there is no pair of junctions that are connected by a road and contains restaurants of different networks.
The Mayor is going to take a large tax from each restaurant, so he is interested in making the total number of the restaurants as large as possible.
Help the Mayor to analyze the situation. Find all such pairs of (a, b) that a restaurants can belong to "iMac D0naldz", b restaurants can belong to "Burger Bing", and the sum of a + b is as large as possible.
Input
The first input line contains integer n (3 β€ n β€ 5000) β the number of junctions in the city. Next n - 1 lines list all roads one per line. Each road is given as a pair of integers xi, yi (1 β€ xi, yi β€ n) β the indexes of connected junctions. Consider the junctions indexed from 1 to n.
It is guaranteed that the given road network is represented by an undirected tree with n vertexes.
Output
Print on the first line integer z β the number of sought pairs. Then print all sought pairs (a, b) in the order of increasing of the first component a.
Examples
Input
5
1 2
2 3
3 4
4 5
Output
3
1 3
2 2
3 1
Input
10
1 2
2 3
3 4
5 6
6 7
7 4
8 9
9 10
10 4
Output
6
1 8
2 7
3 6
6 3
7 2
8 1
Note
The figure below shows the answers to the first test case. The junctions with "iMac D0naldz" restaurants are marked red and "Burger Bing" restaurants are marked blue.
<image>
Submitted Solution:
```
###pyrival template for fast IO
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 graph_undirected():
n=int(input())
graph={} #####adjecancy list using dict
for i in range(n-1):
vertex,neighbour=[int(x) for x in input().split()]
if vertex in graph:
graph[vertex].append(neighbour)
else:
graph[vertex]=[neighbour]
if neighbour in graph: #####for undirected part remove to get directed
graph[neighbour].append(vertex)
else:
graph[neighbour]=[vertex]
return graph,n
graph,n=graph_undirected()
dp=[0 for x in range(n+1)]
###### undirected
def dfs(graph,n,currnode):
visited=[False for x in range(n+1)]
stack=[currnode]
while stack:
currnode=stack[-1]
if visited[currnode]==False:
visited[currnode]=True
for neighbour in graph[currnode]:
if visited[neighbour]==False:
visited[neighbour]=True
stack.append(neighbour)
break #####if we remove break it becomes bfs
else:
if len(stack)>1:dp[stack[-2]]+=dp[stack[-1]]+1;#print(stack[-2],stack[-1])
stack.pop() ####we are backtracking to previous node which is in our stack
dfs(graph,n,1);ans=[]
for i in range(2,n+1):
if dp[i]!=0:
if dp[i] not in ans:
ans.append(dp[i])
if n-1-dp[i] not in ans:
ans.append(n-1-dp[i])
ans.sort();print(len(ans))
for i in range(len(ans)):
print(ans[i],n-1-ans[i])
``` | instruction | 0 | 54,238 | 1 | 108,476 |
No | output | 1 | 54,238 | 1 | 108,477 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Π‘ity N. has a huge problem with roads, food and IT-infrastructure. In total the city has n junctions, some pairs of them are connected by bidirectional roads. The road network consists of n - 1 roads, you can get from any junction to any other one by these roads. Yes, you're right β the road network forms an undirected tree.
Recently, the Mayor came up with a way that eliminates the problems with the food and the IT-infrastructure at the same time! He decided to put at the city junctions restaurants of two well-known cafe networks for IT professionals: "iMac D0naldz" and "Burger Bing". Since the network owners are not friends, it is strictly prohibited to place two restaurants of different networks on neighboring junctions. There are other requirements. Here's the full list:
* each junction must have at most one restaurant;
* each restaurant belongs either to "iMac D0naldz", or to "Burger Bing";
* each network should build at least one restaurant;
* there is no pair of junctions that are connected by a road and contains restaurants of different networks.
The Mayor is going to take a large tax from each restaurant, so he is interested in making the total number of the restaurants as large as possible.
Help the Mayor to analyze the situation. Find all such pairs of (a, b) that a restaurants can belong to "iMac D0naldz", b restaurants can belong to "Burger Bing", and the sum of a + b is as large as possible.
Input
The first input line contains integer n (3 β€ n β€ 5000) β the number of junctions in the city. Next n - 1 lines list all roads one per line. Each road is given as a pair of integers xi, yi (1 β€ xi, yi β€ n) β the indexes of connected junctions. Consider the junctions indexed from 1 to n.
It is guaranteed that the given road network is represented by an undirected tree with n vertexes.
Output
Print on the first line integer z β the number of sought pairs. Then print all sought pairs (a, b) in the order of increasing of the first component a.
Examples
Input
5
1 2
2 3
3 4
4 5
Output
3
1 3
2 2
3 1
Input
10
1 2
2 3
3 4
5 6
6 7
7 4
8 9
9 10
10 4
Output
6
1 8
2 7
3 6
6 3
7 2
8 1
Note
The figure below shows the answers to the first test case. The junctions with "iMac D0naldz" restaurants are marked red and "Burger Bing" restaurants are marked blue.
<image>
Submitted Solution:
```
from collections import defaultdict,deque
import sys
import bisect
input=sys.stdin.readline
mod=1000000007
graph=defaultdict(list)
n=int(input())
for i in range(n-1):
x,y=map(int,input().split())
graph[x].append(y)
graph[y].append(x)
vis=set()
CHECK,OBSERVE=1,0
stack=[(OBSERVE,1,0)]
tree=[0]*(n+1)
while stack:
state,vertex,parent=stack.pop()
if state==OBSERVE:
stack.append((CHECK,vertex,parent))
for child in graph[vertex]:
if child!=parent:
stack.append((OBSERVE,child,vertex))
else:
if len(graph[vertex])==1:
tree[vertex]=1
else:
count=0
for child in graph[vertex]:
count+=tree[child]
mina=min(count,n-count-1)
maxa=max(count,n-count-1)
vis.add((mina,maxa))
tree[vertex]=count+1
l=[]
for i in vis:
l.append(i)
l.sort()
if len(l)&1:
print(len(l)*2)
else:
print(len(l)*2-1)
for i in l:
print(i[0],i[1])
if len(l)&1:
for i in reversed(l):
print(i[1],i[0])
else:
l.pop()
for i in reversed(l):
print(i[1],i[0])
``` | instruction | 0 | 54,239 | 1 | 108,478 |
No | output | 1 | 54,239 | 1 | 108,479 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Π‘ity N. has a huge problem with roads, food and IT-infrastructure. In total the city has n junctions, some pairs of them are connected by bidirectional roads. The road network consists of n - 1 roads, you can get from any junction to any other one by these roads. Yes, you're right β the road network forms an undirected tree.
Recently, the Mayor came up with a way that eliminates the problems with the food and the IT-infrastructure at the same time! He decided to put at the city junctions restaurants of two well-known cafe networks for IT professionals: "iMac D0naldz" and "Burger Bing". Since the network owners are not friends, it is strictly prohibited to place two restaurants of different networks on neighboring junctions. There are other requirements. Here's the full list:
* each junction must have at most one restaurant;
* each restaurant belongs either to "iMac D0naldz", or to "Burger Bing";
* each network should build at least one restaurant;
* there is no pair of junctions that are connected by a road and contains restaurants of different networks.
The Mayor is going to take a large tax from each restaurant, so he is interested in making the total number of the restaurants as large as possible.
Help the Mayor to analyze the situation. Find all such pairs of (a, b) that a restaurants can belong to "iMac D0naldz", b restaurants can belong to "Burger Bing", and the sum of a + b is as large as possible.
Input
The first input line contains integer n (3 β€ n β€ 5000) β the number of junctions in the city. Next n - 1 lines list all roads one per line. Each road is given as a pair of integers xi, yi (1 β€ xi, yi β€ n) β the indexes of connected junctions. Consider the junctions indexed from 1 to n.
It is guaranteed that the given road network is represented by an undirected tree with n vertexes.
Output
Print on the first line integer z β the number of sought pairs. Then print all sought pairs (a, b) in the order of increasing of the first component a.
Examples
Input
5
1 2
2 3
3 4
4 5
Output
3
1 3
2 2
3 1
Input
10
1 2
2 3
3 4
5 6
6 7
7 4
8 9
9 10
10 4
Output
6
1 8
2 7
3 6
6 3
7 2
8 1
Note
The figure below shows the answers to the first test case. The junctions with "iMac D0naldz" restaurants are marked red and "Burger Bing" restaurants are marked blue.
<image>
Submitted Solution:
```
from collections import defaultdict,deque
import sys
import bisect
input=sys.stdin.readline
mod=1000000007
graph=defaultdict(list)
n=int(input())
for i in range(n-1):
x,y=map(int,input().split())
graph[x].append(y)
graph[y].append(x)
vis=set()
CHECK,OBSERVE=1,0
stack=[(OBSERVE,1,0)]
tree=[0]*(n+1)
while stack:
state,vertex,parent=stack.pop()
if state==OBSERVE:
stack.append((CHECK,vertex,parent))
for child in graph[vertex]:
if child!=parent:
stack.append((OBSERVE,child,vertex))
else:
if len(graph[vertex])==1:
tree[vertex]=1
else:
count=0
for child in graph[vertex]:
count+=tree[child]
if min(count,n-count-1)!=0:
vis.add((count,n-count-1))
tree[vertex]=count+1
l=[]
for i in vis:
l.append(i)
l.sort()
print(len(l))
for i in l:
print(i[0],i[1])
``` | instruction | 0 | 54,240 | 1 | 108,480 |
No | output | 1 | 54,240 | 1 | 108,481 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The New Vasjuki village is stretched along the motorway and that's why every house on it is characterized by its shift relative to some fixed point β the xi coordinate. The village consists of n houses, the i-th house is located in the point with coordinates of xi.
TELE3, a cellular communication provider planned to locate three base stations so as to provide every house in the village with cellular communication. The base station having power d located in the point t provides with communication all the houses on the segment [t - d, t + d] (including boundaries).
To simplify the integration (and simply not to mix anything up) all the three stations are planned to possess the equal power of d. Which minimal value of d is enough to provide all the houses in the village with cellular communication.
Input
The first line contains an integer n (1 β€ n β€ 2Β·105) which represents the number of houses in the village. The second line contains the coordinates of houses β the sequence x1, x2, ..., xn of integer numbers (1 β€ xi β€ 109). It is possible that two or more houses are located on one point. The coordinates are given in a arbitrary order.
Output
Print the required minimal power d. In the second line print three numbers β the possible coordinates of the base stations' location. Print the coordinates with 6 digits after the decimal point. The positions of the stations can be any from 0 to 2Β·109 inclusively. It is accepted for the base stations to have matching coordinates. If there are many solutions, print any of them.
Examples
Input
4
1 2 3 4
Output
0.500000
1.500000 2.500000 3.500000
Input
3
10 20 30
Output
0
10.000000 20.000000 30.000000
Input
5
10003 10004 10001 10002 1
Output
0.500000
1.000000 10001.500000 10003.500000 | instruction | 0 | 54,356 | 1 | 108,712 |
Tags: binary search, greedy
Correct Solution:
```
from decimal import *
n=int(input())
a=sorted(map(int,input().split()))
i=1-n
j=n-2
s=0
getcontext().prec = 6
Decimal(1) / Decimal(7)
n=a[j]-a[i]
while s<n:
l,r=a[i]-a[0],a[-1]-a[j]
if l<r:
if n<=l:
s=n
break
i+=1
s=l
else:
if n<=r:
s=n
break
j-=1
s=r
n=a[j]-a[i]
s/=2
print(Decimal(s))
print(s+a[0]+0.0000001,float(a[j]-s),float(a[-1]-s))
``` | output | 1 | 54,356 | 1 | 108,713 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The New Vasjuki village is stretched along the motorway and that's why every house on it is characterized by its shift relative to some fixed point β the xi coordinate. The village consists of n houses, the i-th house is located in the point with coordinates of xi.
TELE3, a cellular communication provider planned to locate three base stations so as to provide every house in the village with cellular communication. The base station having power d located in the point t provides with communication all the houses on the segment [t - d, t + d] (including boundaries).
To simplify the integration (and simply not to mix anything up) all the three stations are planned to possess the equal power of d. Which minimal value of d is enough to provide all the houses in the village with cellular communication.
Input
The first line contains an integer n (1 β€ n β€ 2Β·105) which represents the number of houses in the village. The second line contains the coordinates of houses β the sequence x1, x2, ..., xn of integer numbers (1 β€ xi β€ 109). It is possible that two or more houses are located on one point. The coordinates are given in a arbitrary order.
Output
Print the required minimal power d. In the second line print three numbers β the possible coordinates of the base stations' location. Print the coordinates with 6 digits after the decimal point. The positions of the stations can be any from 0 to 2Β·109 inclusively. It is accepted for the base stations to have matching coordinates. If there are many solutions, print any of them.
Examples
Input
4
1 2 3 4
Output
0.500000
1.500000 2.500000 3.500000
Input
3
10 20 30
Output
0
10.000000 20.000000 30.000000
Input
5
10003 10004 10001 10002 1
Output
0.500000
1.000000 10001.500000 10003.500000 | instruction | 0 | 54,357 | 1 | 108,714 |
Tags: binary search, greedy
Correct Solution:
```
n = int(input())
houses = sorted(set(map(int, input().split())))
if len(houses) <= 3:
print(0)
result = houses[:]
while len(result) < 3:
result.append(result[-1])
print('%.6f %.6f %.6f' % tuple(result))
import sys; sys.exit()
span = 0
left = 1
right = len(houses) - 2
#print(houses)
#print('span = %d, houses[%d] = %d, houses[%d] = %d' % (span,
# left, houses[left], right, houses[right]))
while houses[right] - houses[left] > span:
left_gap = houses[left] - houses[0] - span
right_gap = houses[-1] - houses[right] - span
middle = houses[right] - houses[left]
if left_gap <= right_gap:
if span + left_gap > middle:
span = middle
break
left += 1
if left_gap == right_gap:
right -= 1
span += left_gap
else:
if span + right_gap > middle:
span = middle
break
right -= 1
span += right_gap
#print('span = %d, houses[%d] = %d, houses[%d] = %d' % (span,
# left, houses[left], right, houses[right]))
print('%.6f' % (span / 2))
print('%.6f %.6f %.6f' % ((houses[0] + houses[left - 1]) / 2,
(houses[left] + houses[right]) / 2,
(houses[right + 1] + houses[-1]) / 2))
``` | output | 1 | 54,357 | 1 | 108,715 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The New Vasjuki village is stretched along the motorway and that's why every house on it is characterized by its shift relative to some fixed point β the xi coordinate. The village consists of n houses, the i-th house is located in the point with coordinates of xi.
TELE3, a cellular communication provider planned to locate three base stations so as to provide every house in the village with cellular communication. The base station having power d located in the point t provides with communication all the houses on the segment [t - d, t + d] (including boundaries).
To simplify the integration (and simply not to mix anything up) all the three stations are planned to possess the equal power of d. Which minimal value of d is enough to provide all the houses in the village with cellular communication.
Input
The first line contains an integer n (1 β€ n β€ 2Β·105) which represents the number of houses in the village. The second line contains the coordinates of houses β the sequence x1, x2, ..., xn of integer numbers (1 β€ xi β€ 109). It is possible that two or more houses are located on one point. The coordinates are given in a arbitrary order.
Output
Print the required minimal power d. In the second line print three numbers β the possible coordinates of the base stations' location. Print the coordinates with 6 digits after the decimal point. The positions of the stations can be any from 0 to 2Β·109 inclusively. It is accepted for the base stations to have matching coordinates. If there are many solutions, print any of them.
Examples
Input
4
1 2 3 4
Output
0.500000
1.500000 2.500000 3.500000
Input
3
10 20 30
Output
0
10.000000 20.000000 30.000000
Input
5
10003 10004 10001 10002 1
Output
0.500000
1.000000 10001.500000 10003.500000 | instruction | 0 | 54,358 | 1 | 108,716 |
Tags: binary search, greedy
Correct Solution:
```
import math,sys
#from itertools import permutations, combinations;import heapq,random;
from collections import defaultdict,deque
import bisect as bi
def yes():print('YES')
def no():print('NO')
#sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w');
def I():return (int(sys.stdin.readline()))
def In():return(map(int,sys.stdin.readline().split()))
def Sn():return sys.stdin.readline().strip()
#sys.setrecursionlimit(1500)
def dict(a):
d={}
for x in a:
if d.get(x,-1)!=-1:
d[x]+=1
else:
d[x]=1
return d
def find_gt(a, x):
'Find leftmost value greater than x'
i = bi.bisect_right(a, x)
if i != len(a):
return i
else:
return len(a)
def check(mid):
pos=0
for i in range(3):
p=l[pos]+2*mid
if p>=l[n-1]:
pos=n
else:
pos=find_gt(l,p)
if pos>=n:
return True
return False
def main():
try:
global l,n
n=I()
l=list(In())
for x in range(n):
l[x]*=2
l.sort()
low,high=-1,int(1e9+1)
while low+1<high:
mid=low+(high-low)//2
if check(mid):
high=mid
else:
low=mid
rad=high/2
print(rad)
pos=0
i=0
while i<3:
if pos>=n:
print(2*(1e8),end=' ')
# i=2
else:
p=l[pos]+2*high
if p>=l[n-1]:
pos=n
else:
pos=find_gt(l,p)
print((p-high)/2,end=' ')
# i=2
i+=1
print()
except:
pass
M = 998244353
P = 1000000007
if __name__ == '__main__':
# for _ in range(I()):main()
for _ in range(1):main()
#End#
# ******************* All The Best ******************* #
``` | output | 1 | 54,358 | 1 | 108,717 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The New Vasjuki village is stretched along the motorway and that's why every house on it is characterized by its shift relative to some fixed point β the xi coordinate. The village consists of n houses, the i-th house is located in the point with coordinates of xi.
TELE3, a cellular communication provider planned to locate three base stations so as to provide every house in the village with cellular communication. The base station having power d located in the point t provides with communication all the houses on the segment [t - d, t + d] (including boundaries).
To simplify the integration (and simply not to mix anything up) all the three stations are planned to possess the equal power of d. Which minimal value of d is enough to provide all the houses in the village with cellular communication.
Input
The first line contains an integer n (1 β€ n β€ 2Β·105) which represents the number of houses in the village. The second line contains the coordinates of houses β the sequence x1, x2, ..., xn of integer numbers (1 β€ xi β€ 109). It is possible that two or more houses are located on one point. The coordinates are given in a arbitrary order.
Output
Print the required minimal power d. In the second line print three numbers β the possible coordinates of the base stations' location. Print the coordinates with 6 digits after the decimal point. The positions of the stations can be any from 0 to 2Β·109 inclusively. It is accepted for the base stations to have matching coordinates. If there are many solutions, print any of them.
Examples
Input
4
1 2 3 4
Output
0.500000
1.500000 2.500000 3.500000
Input
3
10 20 30
Output
0
10.000000 20.000000 30.000000
Input
5
10003 10004 10001 10002 1
Output
0.500000
1.000000 10001.500000 10003.500000 | instruction | 0 | 54,359 | 1 | 108,718 |
Tags: binary search, greedy
Correct Solution:
```
from decimal import *
n=int(input())
a=sorted(map(int,input().split()))
i=1-n
j=n-2
s=0
getcontext().prec = 6
Decimal(1) / Decimal(7)
n=a[j]-a[i]
while s<n:
l,r=a[i]-a[0],a[-1]-a[j]
if l<r:
if n<=l:
s=n
break
i+=1
s=l
else:
if n<=r:
s=n
break
j-=1
s=r
n=a[j]-a[i]
s/=2
print(Decimal(s))
print(Decimal(s+a[0]),float(a[j]-s),float(a[-1]-s))
``` | output | 1 | 54,359 | 1 | 108,719 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The New Vasjuki village is stretched along the motorway and that's why every house on it is characterized by its shift relative to some fixed point β the xi coordinate. The village consists of n houses, the i-th house is located in the point with coordinates of xi.
TELE3, a cellular communication provider planned to locate three base stations so as to provide every house in the village with cellular communication. The base station having power d located in the point t provides with communication all the houses on the segment [t - d, t + d] (including boundaries).
To simplify the integration (and simply not to mix anything up) all the three stations are planned to possess the equal power of d. Which minimal value of d is enough to provide all the houses in the village with cellular communication.
Input
The first line contains an integer n (1 β€ n β€ 2Β·105) which represents the number of houses in the village. The second line contains the coordinates of houses β the sequence x1, x2, ..., xn of integer numbers (1 β€ xi β€ 109). It is possible that two or more houses are located on one point. The coordinates are given in a arbitrary order.
Output
Print the required minimal power d. In the second line print three numbers β the possible coordinates of the base stations' location. Print the coordinates with 6 digits after the decimal point. The positions of the stations can be any from 0 to 2Β·109 inclusively. It is accepted for the base stations to have matching coordinates. If there are many solutions, print any of them.
Examples
Input
4
1 2 3 4
Output
0.500000
1.500000 2.500000 3.500000
Input
3
10 20 30
Output
0
10.000000 20.000000 30.000000
Input
5
10003 10004 10001 10002 1
Output
0.500000
1.000000 10001.500000 10003.500000 | instruction | 0 | 54,360 | 1 | 108,720 |
Tags: binary search, greedy
Correct Solution:
```
#!/usr/bin/env python
#-*-coding:utf-8 -*-
n=int(input())
X=sorted(map(int,input().split()))
i=1-n
j=n-2
s=0
n=X[j]-X[i]
while s<n:
l,r=X[i]-X[0],X[-1]-X[j]
if l<r:
if n<=l:
s=n
break
i+=1
s=l
else:
if n<=r:
s=n
break
j-=1
s=r
n=X[j]-X[i]
s/=2
print(s)
print(s+X[0],X[j]-s,X[-1]-s)
# Made By Mostafa_Khaled
``` | output | 1 | 54,360 | 1 | 108,721 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The New Vasjuki village is stretched along the motorway and that's why every house on it is characterized by its shift relative to some fixed point β the xi coordinate. The village consists of n houses, the i-th house is located in the point with coordinates of xi.
TELE3, a cellular communication provider planned to locate three base stations so as to provide every house in the village with cellular communication. The base station having power d located in the point t provides with communication all the houses on the segment [t - d, t + d] (including boundaries).
To simplify the integration (and simply not to mix anything up) all the three stations are planned to possess the equal power of d. Which minimal value of d is enough to provide all the houses in the village with cellular communication.
Input
The first line contains an integer n (1 β€ n β€ 2Β·105) which represents the number of houses in the village. The second line contains the coordinates of houses β the sequence x1, x2, ..., xn of integer numbers (1 β€ xi β€ 109). It is possible that two or more houses are located on one point. The coordinates are given in a arbitrary order.
Output
Print the required minimal power d. In the second line print three numbers β the possible coordinates of the base stations' location. Print the coordinates with 6 digits after the decimal point. The positions of the stations can be any from 0 to 2Β·109 inclusively. It is accepted for the base stations to have matching coordinates. If there are many solutions, print any of them.
Examples
Input
4
1 2 3 4
Output
0.500000
1.500000 2.500000 3.500000
Input
3
10 20 30
Output
0
10.000000 20.000000 30.000000
Input
5
10003 10004 10001 10002 1
Output
0.500000
1.000000 10001.500000 10003.500000 | instruction | 0 | 54,361 | 1 | 108,722 |
Tags: binary search, greedy
Correct Solution:
```
#!/usr/bin/env python
#-*-coding:utf-8 -*-
n=int(input())
X=sorted(map(int,input().split()))
i=1-n
j=n-2
s=0
n=X[j]-X[i]
while s<n:
l,r=X[i]-X[0],X[-1]-X[j]
if l<r:
if n<=l:
s=n
break
i+=1
s=l
else:
if n<=r:
s=n
break
j-=1
s=r
n=X[j]-X[i]
s/=2
print(s)
print(s+X[0],X[j]-s,X[-1]-s)
``` | output | 1 | 54,361 | 1 | 108,723 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The New Vasjuki village is stretched along the motorway and that's why every house on it is characterized by its shift relative to some fixed point β the xi coordinate. The village consists of n houses, the i-th house is located in the point with coordinates of xi.
TELE3, a cellular communication provider planned to locate three base stations so as to provide every house in the village with cellular communication. The base station having power d located in the point t provides with communication all the houses on the segment [t - d, t + d] (including boundaries).
To simplify the integration (and simply not to mix anything up) all the three stations are planned to possess the equal power of d. Which minimal value of d is enough to provide all the houses in the village with cellular communication.
Input
The first line contains an integer n (1 β€ n β€ 2Β·105) which represents the number of houses in the village. The second line contains the coordinates of houses β the sequence x1, x2, ..., xn of integer numbers (1 β€ xi β€ 109). It is possible that two or more houses are located on one point. The coordinates are given in a arbitrary order.
Output
Print the required minimal power d. In the second line print three numbers β the possible coordinates of the base stations' location. Print the coordinates with 6 digits after the decimal point. The positions of the stations can be any from 0 to 2Β·109 inclusively. It is accepted for the base stations to have matching coordinates. If there are many solutions, print any of them.
Examples
Input
4
1 2 3 4
Output
0.500000
1.500000 2.500000 3.500000
Input
3
10 20 30
Output
0
10.000000 20.000000 30.000000
Input
5
10003 10004 10001 10002 1
Output
0.500000
1.000000 10001.500000 10003.500000 | instruction | 0 | 54,362 | 1 | 108,724 |
Tags: binary search, greedy
Correct Solution:
```
import os, sys
from io import IOBase, BytesIO
py2 = round(0.5)
if py2:
from future_builtins import ascii, filter, hex, map, oct, zip
range = xrange
BUFSIZE = 8192
class FastIO(BytesIO):
newlines = 0
def __init__(self, file):
self._file = file
self._fd = file.fileno()
self.writable = "x" in file.mode or "w" in file.mode
self.write = super(FastIO, self).write if self.writable else None
def _fill(self):
s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
return s
def read(self):
while self._fill():
pass
return super(FastIO, self).read()
def readline(self):
while self.newlines == 0:
s = self._fill()
self.newlines = s.count(b"\n") + (not s)
self.newlines -= 1
return super(FastIO, self).readline()
def flush(self):
if self.writable:
os.write(self._fd, self.getvalue())
self.truncate(0), self.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
if py2:
self.write = self.buffer.write
self.read = self.buffer.read
self.readline = self.buffer.readline
else:
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")
# Cout implemented in Python
import sys
class ostream:
def __lshift__(self, a):
sys.stdout.write(str(a))
return self
cout = ostream()
endl = "\n"
def solve():
n = int(input())
homes = list(map(int, input().split()))
homes.sort()
def can_cover(d_i):
# print(d_i)
total_posts = 3
curr_cover = 0
ptr = 0
res = []
while ptr < len(homes):
if curr_cover < homes[ptr]:
if total_posts > 0:
total_posts -= 1
curr_cover = (homes[ptr] + (2 * d_i))
res.append(float("{:.6f}".format(min(homes[ptr] + d_i, homes[-1]))))
else:
break
ptr += 1
if ptr < len(homes):
return False, []
else:
return True, res
lo = 0
hi = 4 * (10 ** 8)
res = -1
mx = 100
while lo < hi and mx:
mid = lo + (hi - lo) / 2
r, pos = can_cover(mid)
if r:
res = mid
hi = mid
else:
lo = mid
mx -= 1
re = can_cover(res)[1]
while len(re) < 3:
re.append(float("{:.6f}".format(homes[-1])))
# print(re)
cout << ("%.6f" % res) << endl
cout << " ".join(map(str, re))<<endl
def main():
solve()
if __name__ == "__main__":
main()
``` | output | 1 | 54,362 | 1 | 108,725 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The New Vasjuki village is stretched along the motorway and that's why every house on it is characterized by its shift relative to some fixed point β the xi coordinate. The village consists of n houses, the i-th house is located in the point with coordinates of xi.
TELE3, a cellular communication provider planned to locate three base stations so as to provide every house in the village with cellular communication. The base station having power d located in the point t provides with communication all the houses on the segment [t - d, t + d] (including boundaries).
To simplify the integration (and simply not to mix anything up) all the three stations are planned to possess the equal power of d. Which minimal value of d is enough to provide all the houses in the village with cellular communication.
Input
The first line contains an integer n (1 β€ n β€ 2Β·105) which represents the number of houses in the village. The second line contains the coordinates of houses β the sequence x1, x2, ..., xn of integer numbers (1 β€ xi β€ 109). It is possible that two or more houses are located on one point. The coordinates are given in a arbitrary order.
Output
Print the required minimal power d. In the second line print three numbers β the possible coordinates of the base stations' location. Print the coordinates with 6 digits after the decimal point. The positions of the stations can be any from 0 to 2Β·109 inclusively. It is accepted for the base stations to have matching coordinates. If there are many solutions, print any of them.
Examples
Input
4
1 2 3 4
Output
0.500000
1.500000 2.500000 3.500000
Input
3
10 20 30
Output
0
10.000000 20.000000 30.000000
Input
5
10003 10004 10001 10002 1
Output
0.500000
1.000000 10001.500000 10003.500000 | instruction | 0 | 54,363 | 1 | 108,726 |
Tags: binary search, greedy
Correct Solution:
```
n = int(input())
a = sorted(map(int, input().split()))
i = 1 - n
j = n - 2
s = 0
n = a[j] - a[i]
while s < n:
l, r = a[i] - a[0], a[-1] - a[j]
if l < r:
if n <= l:
s = n
break
i += 1
s = l
else:
if n <= r:
s = n
break
j -= 1
s = r
n = a[j] - a[i]
s /= 2
print(s)
print(s + a[0], a[j] - s, a[-1] - s)
``` | output | 1 | 54,363 | 1 | 108,727 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The New Vasjuki village is stretched along the motorway and that's why every house on it is characterized by its shift relative to some fixed point β the xi coordinate. The village consists of n houses, the i-th house is located in the point with coordinates of xi.
TELE3, a cellular communication provider planned to locate three base stations so as to provide every house in the village with cellular communication. The base station having power d located in the point t provides with communication all the houses on the segment [t - d, t + d] (including boundaries).
To simplify the integration (and simply not to mix anything up) all the three stations are planned to possess the equal power of d. Which minimal value of d is enough to provide all the houses in the village with cellular communication.
Input
The first line contains an integer n (1 β€ n β€ 2Β·105) which represents the number of houses in the village. The second line contains the coordinates of houses β the sequence x1, x2, ..., xn of integer numbers (1 β€ xi β€ 109). It is possible that two or more houses are located on one point. The coordinates are given in a arbitrary order.
Output
Print the required minimal power d. In the second line print three numbers β the possible coordinates of the base stations' location. Print the coordinates with 6 digits after the decimal point. The positions of the stations can be any from 0 to 2Β·109 inclusively. It is accepted for the base stations to have matching coordinates. If there are many solutions, print any of them.
Examples
Input
4
1 2 3 4
Output
0.500000
1.500000 2.500000 3.500000
Input
3
10 20 30
Output
0
10.000000 20.000000 30.000000
Input
5
10003 10004 10001 10002 1
Output
0.500000
1.000000 10001.500000 10003.500000
Submitted Solution:
```
n = int(input())
houses = sorted(set(map(int, input().split())))
if len(houses) <= 3:
print(0)
result = houses[:]
while len(result) < 3:
result.append(result[-1])
print('%.6f %.6f %.6f' % tuple(result))
import sys; sys.exit()
span = 0
left = 1
right = len(houses) - 2
while houses[right] - houses[left] > span:
left_gap = houses[left] - houses[left - 1]
right_gap = houses[right + 1] - houses[right]
if left_gap <= right_gap:
left += 1
if left_gap == right_gap:
right -= 1
span += left_gap
else:
right -= 1
span += right_gap
print('%.6f' % (span / 2))
print('%.6f %.6f %.6f' % ((houses[0] + houses[left - 1]) / 2,
(houses[left] + houses[right]) / 2,
(houses[right + 1] + houses[-1]) / 2))
``` | instruction | 0 | 54,364 | 1 | 108,728 |
No | output | 1 | 54,364 | 1 | 108,729 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The New Vasjuki village is stretched along the motorway and that's why every house on it is characterized by its shift relative to some fixed point β the xi coordinate. The village consists of n houses, the i-th house is located in the point with coordinates of xi.
TELE3, a cellular communication provider planned to locate three base stations so as to provide every house in the village with cellular communication. The base station having power d located in the point t provides with communication all the houses on the segment [t - d, t + d] (including boundaries).
To simplify the integration (and simply not to mix anything up) all the three stations are planned to possess the equal power of d. Which minimal value of d is enough to provide all the houses in the village with cellular communication.
Input
The first line contains an integer n (1 β€ n β€ 2Β·105) which represents the number of houses in the village. The second line contains the coordinates of houses β the sequence x1, x2, ..., xn of integer numbers (1 β€ xi β€ 109). It is possible that two or more houses are located on one point. The coordinates are given in a arbitrary order.
Output
Print the required minimal power d. In the second line print three numbers β the possible coordinates of the base stations' location. Print the coordinates with 6 digits after the decimal point. The positions of the stations can be any from 0 to 2Β·109 inclusively. It is accepted for the base stations to have matching coordinates. If there are many solutions, print any of them.
Examples
Input
4
1 2 3 4
Output
0.500000
1.500000 2.500000 3.500000
Input
3
10 20 30
Output
0
10.000000 20.000000 30.000000
Input
5
10003 10004 10001 10002 1
Output
0.500000
1.000000 10001.500000 10003.500000
Submitted Solution:
```
n = int(input())
x = set(map(int, input().split()))
mx, mn = max(x), min(x)
ans = mx - mn
a1, a2 = ans / 6, ans / 3
print(a1)
print(mn + a1, mn + a1 + a2, mn + a1 + 2 * a2)
``` | instruction | 0 | 54,366 | 1 | 108,732 |
No | output | 1 | 54,366 | 1 | 108,733 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The New Vasjuki village is stretched along the motorway and that's why every house on it is characterized by its shift relative to some fixed point β the xi coordinate. The village consists of n houses, the i-th house is located in the point with coordinates of xi.
TELE3, a cellular communication provider planned to locate three base stations so as to provide every house in the village with cellular communication. The base station having power d located in the point t provides with communication all the houses on the segment [t - d, t + d] (including boundaries).
To simplify the integration (and simply not to mix anything up) all the three stations are planned to possess the equal power of d. Which minimal value of d is enough to provide all the houses in the village with cellular communication.
Input
The first line contains an integer n (1 β€ n β€ 2Β·105) which represents the number of houses in the village. The second line contains the coordinates of houses β the sequence x1, x2, ..., xn of integer numbers (1 β€ xi β€ 109). It is possible that two or more houses are located on one point. The coordinates are given in a arbitrary order.
Output
Print the required minimal power d. In the second line print three numbers β the possible coordinates of the base stations' location. Print the coordinates with 6 digits after the decimal point. The positions of the stations can be any from 0 to 2Β·109 inclusively. It is accepted for the base stations to have matching coordinates. If there are many solutions, print any of them.
Examples
Input
4
1 2 3 4
Output
0.500000
1.500000 2.500000 3.500000
Input
3
10 20 30
Output
0
10.000000 20.000000 30.000000
Input
5
10003 10004 10001 10002 1
Output
0.500000
1.000000 10001.500000 10003.500000
Submitted Solution:
```
def main():
read = lambda: tuple(map(int, input().split()))
n = read()[0]
arr = sorted(read())
l, r = 0, 1e9
p = [0,0,0]
while l + 1e-7 < r:
m = round((l + r) / 2, 7)
s, e = 0, 0
for i in range(3):
while e < n and arr[e] <= arr[s] + 2 * m: e += 1
if s >= n:
ch = True
break
p[i] = (arr[min(e - 1,n - 1)] + arr[min(s,n - 1)]) / 2
s, e = e, e
ch = e >= n
if ch:
r = m
else:
l = m
l = round(l, 6)
print("%0.6f" % l)
print(*["%0.6f" % v for v in p])
main()
``` | instruction | 0 | 54,367 | 1 | 108,734 |
No | output | 1 | 54,367 | 1 | 108,735 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Okabe likes to take walks but knows that spies from the Organization could be anywhere; that's why he wants to know how many different walks he can take in his city safely. Okabe's city can be represented as all points (x, y) such that x and y are non-negative. Okabe starts at the origin (point (0, 0)), and needs to reach the point (k, 0). If Okabe is currently at the point (x, y), in one step he can go to (x + 1, y + 1), (x + 1, y), or (x + 1, y - 1).
Additionally, there are n horizontal line segments, the i-th of which goes from x = ai to x = bi inclusive, and is at y = ci. It is guaranteed that a1 = 0, an β€ k β€ bn, and ai = bi - 1 for 2 β€ i β€ n. The i-th line segment forces Okabe to walk with y-value in the range 0 β€ y β€ ci when his x value satisfies ai β€ x β€ bi, or else he might be spied on. This also means he is required to be under two line segments when one segment ends and another begins.
Okabe now wants to know how many walks there are from the origin to the point (k, 0) satisfying these conditions, modulo 109 + 7.
Input
The first line of input contains the integers n and k (1 β€ n β€ 100, 1 β€ k β€ 1018) β the number of segments and the destination x coordinate.
The next n lines contain three space-separated integers ai, bi, and ci (0 β€ ai < bi β€ 1018, 0 β€ ci β€ 15) β the left and right ends of a segment, and its y coordinate.
It is guaranteed that a1 = 0, an β€ k β€ bn, and ai = bi - 1 for 2 β€ i β€ n.
Output
Print the number of walks satisfying the conditions, modulo 1000000007 (109 + 7).
Examples
Input
1 3
0 3 3
Output
4
Input
2 6
0 3 0
3 10 2
Output
4
Note
<image>
The graph above corresponds to sample 1. The possible walks are:
* <image>
* <image>
* <image>
* <image>
<image>
The graph above corresponds to sample 2. There is only one walk for Okabe to reach (3, 0). After this, the possible walks are:
* <image>
* <image>
* <image>
* <image>
Submitted Solution:
```
def matrixTimesVector(A, x):
#A a matrix, x a (horizontal) vector; computes Ax
n = len(x)
prod = n*[0]
for i in range(n):
for k in range(n):
prod[i] += A[i][k]*x[k]
return prod
def matrixMultiply(A, B):
#A and B are square matrices; computes AB
n = len(A)
prod = n*[0]
for i in range(n):
prod[i] = n*[0]
for i in range(n):
for j in range(n):
for k in range(n):
prod[i][j] += A[i][k]*B[k][j]
return prod
def matrixPower(A, n):
#A a square matrix, n >= 1; computes A^n
if n == 1:
return A
if n%2 == 0:
return matrixPower(matrixMultiply(A,A), n/2)
else:
return matrixMultiply(A, matrixPower(A, n-1))
n, k = map(int, input().split())
c = n*[0]
length = n*[0]
for i in range(n):
a, b, c[i] = map(int, input().split())
if i<n-1:
length[i] = b-a
else:
length[i] = k-a
vector = [1]+14*[0]
for i in range(n):
matrix = 15*[0]
for f in range(15):
matrix[f] = 15*[0]
if c[i] == 0:
matrix[0][0] = 1
else:
row = 15*[0]
for r in range(c[i]+1):
if r == 0:
row = [1,1]+13*[0]
elif r != c[i]:
row = (r-1)*[0]+[1,1,1]+(13-r)*[0]
else:
row = (c[i]-1)*[0]+[1,1]+(14-c[i])*[0]
matrix[r] = row
print(matrix)
power = matrixPower(matrix, length[i])
vector = matrixTimesVector(power, vector)
print(vector[0])
``` | instruction | 0 | 54,483 | 1 | 108,966 |
No | output | 1 | 54,483 | 1 | 108,967 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Okabe likes to take walks but knows that spies from the Organization could be anywhere; that's why he wants to know how many different walks he can take in his city safely. Okabe's city can be represented as all points (x, y) such that x and y are non-negative. Okabe starts at the origin (point (0, 0)), and needs to reach the point (k, 0). If Okabe is currently at the point (x, y), in one step he can go to (x + 1, y + 1), (x + 1, y), or (x + 1, y - 1).
Additionally, there are n horizontal line segments, the i-th of which goes from x = ai to x = bi inclusive, and is at y = ci. It is guaranteed that a1 = 0, an β€ k β€ bn, and ai = bi - 1 for 2 β€ i β€ n. The i-th line segment forces Okabe to walk with y-value in the range 0 β€ y β€ ci when his x value satisfies ai β€ x β€ bi, or else he might be spied on. This also means he is required to be under two line segments when one segment ends and another begins.
Okabe now wants to know how many walks there are from the origin to the point (k, 0) satisfying these conditions, modulo 109 + 7.
Input
The first line of input contains the integers n and k (1 β€ n β€ 100, 1 β€ k β€ 1018) β the number of segments and the destination x coordinate.
The next n lines contain three space-separated integers ai, bi, and ci (0 β€ ai < bi β€ 1018, 0 β€ ci β€ 15) β the left and right ends of a segment, and its y coordinate.
It is guaranteed that a1 = 0, an β€ k β€ bn, and ai = bi - 1 for 2 β€ i β€ n.
Output
Print the number of walks satisfying the conditions, modulo 1000000007 (109 + 7).
Examples
Input
1 3
0 3 3
Output
4
Input
2 6
0 3 0
3 10 2
Output
4
Note
<image>
The graph above corresponds to sample 1. The possible walks are:
* <image>
* <image>
* <image>
* <image>
<image>
The graph above corresponds to sample 2. There is only one walk for Okabe to reach (3, 0). After this, the possible walks are:
* <image>
* <image>
* <image>
* <image>
Submitted Solution:
```
# import functools
# @functools.lru_cache(maxsize=None)
# def fib(num):
# if num < 2:
# return num
# else:
# return fib(num-1) + fib(num-2)
n,m=map(int,input().split())
a=list(map(int,input().split()))
``` | instruction | 0 | 54,484 | 1 | 108,968 |
No | output | 1 | 54,484 | 1 | 108,969 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Okabe likes to take walks but knows that spies from the Organization could be anywhere; that's why he wants to know how many different walks he can take in his city safely. Okabe's city can be represented as all points (x, y) such that x and y are non-negative. Okabe starts at the origin (point (0, 0)), and needs to reach the point (k, 0). If Okabe is currently at the point (x, y), in one step he can go to (x + 1, y + 1), (x + 1, y), or (x + 1, y - 1).
Additionally, there are n horizontal line segments, the i-th of which goes from x = ai to x = bi inclusive, and is at y = ci. It is guaranteed that a1 = 0, an β€ k β€ bn, and ai = bi - 1 for 2 β€ i β€ n. The i-th line segment forces Okabe to walk with y-value in the range 0 β€ y β€ ci when his x value satisfies ai β€ x β€ bi, or else he might be spied on. This also means he is required to be under two line segments when one segment ends and another begins.
Okabe now wants to know how many walks there are from the origin to the point (k, 0) satisfying these conditions, modulo 109 + 7.
Input
The first line of input contains the integers n and k (1 β€ n β€ 100, 1 β€ k β€ 1018) β the number of segments and the destination x coordinate.
The next n lines contain three space-separated integers ai, bi, and ci (0 β€ ai < bi β€ 1018, 0 β€ ci β€ 15) β the left and right ends of a segment, and its y coordinate.
It is guaranteed that a1 = 0, an β€ k β€ bn, and ai = bi - 1 for 2 β€ i β€ n.
Output
Print the number of walks satisfying the conditions, modulo 1000000007 (109 + 7).
Examples
Input
1 3
0 3 3
Output
4
Input
2 6
0 3 0
3 10 2
Output
4
Note
<image>
The graph above corresponds to sample 1. The possible walks are:
* <image>
* <image>
* <image>
* <image>
<image>
The graph above corresponds to sample 2. There is only one walk for Okabe to reach (3, 0). After this, the possible walks are:
* <image>
* <image>
* <image>
* <image>
Submitted Solution:
```
import functools
@functools.lru_cache(maxsize=None)
def fib(num):
if num < 2:
return num
else:
return fib(num-1) + fib(num-2)
n,m=map(int,input().split())
a=list(map(int,input().split()))
print(4)
``` | instruction | 0 | 54,485 | 1 | 108,970 |
No | output | 1 | 54,485 | 1 | 108,971 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Okabe likes to take walks but knows that spies from the Organization could be anywhere; that's why he wants to know how many different walks he can take in his city safely. Okabe's city can be represented as all points (x, y) such that x and y are non-negative. Okabe starts at the origin (point (0, 0)), and needs to reach the point (k, 0). If Okabe is currently at the point (x, y), in one step he can go to (x + 1, y + 1), (x + 1, y), or (x + 1, y - 1).
Additionally, there are n horizontal line segments, the i-th of which goes from x = ai to x = bi inclusive, and is at y = ci. It is guaranteed that a1 = 0, an β€ k β€ bn, and ai = bi - 1 for 2 β€ i β€ n. The i-th line segment forces Okabe to walk with y-value in the range 0 β€ y β€ ci when his x value satisfies ai β€ x β€ bi, or else he might be spied on. This also means he is required to be under two line segments when one segment ends and another begins.
Okabe now wants to know how many walks there are from the origin to the point (k, 0) satisfying these conditions, modulo 109 + 7.
Input
The first line of input contains the integers n and k (1 β€ n β€ 100, 1 β€ k β€ 1018) β the number of segments and the destination x coordinate.
The next n lines contain three space-separated integers ai, bi, and ci (0 β€ ai < bi β€ 1018, 0 β€ ci β€ 15) β the left and right ends of a segment, and its y coordinate.
It is guaranteed that a1 = 0, an β€ k β€ bn, and ai = bi - 1 for 2 β€ i β€ n.
Output
Print the number of walks satisfying the conditions, modulo 1000000007 (109 + 7).
Examples
Input
1 3
0 3 3
Output
4
Input
2 6
0 3 0
3 10 2
Output
4
Note
<image>
The graph above corresponds to sample 1. The possible walks are:
* <image>
* <image>
* <image>
* <image>
<image>
The graph above corresponds to sample 2. There is only one walk for Okabe to reach (3, 0). After this, the possible walks are:
* <image>
* <image>
* <image>
* <image>
Submitted Solution:
```
import functools
@functools.lru_cache(maxsize=None)
def fib(num):
if num < 2:
return num
else:
return fib(num-1) + fib(num-2)
n,m=map(int,input().split())
a=list(map(int,input().split()))
print(fib(10))
``` | instruction | 0 | 54,486 | 1 | 108,972 |
No | output | 1 | 54,486 | 1 | 108,973 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ralph is in the Binary Country. The Binary Country consists of n cities and (n - 1) bidirectional roads connecting the cities. The roads are numbered from 1 to (n - 1), the i-th road connects the city labeled <image> (here β xβ denotes the x rounded down to the nearest integer) and the city labeled (i + 1), and the length of the i-th road is Li.
Now Ralph gives you m queries. In each query he tells you some city Ai and an integer Hi. He wants to make some tours starting from this city. He can choose any city in the Binary Country (including Ai) as the terminal city for a tour. He gains happiness (Hi - L) during a tour, where L is the distance between the city Ai and the terminal city.
Ralph is interested in tours from Ai in which he can gain positive happiness. For each query, compute the sum of happiness gains for all such tours.
Ralph will never take the same tour twice or more (in one query), he will never pass the same city twice or more in one tour.
Input
The first line contains two integers n and m (1 β€ n β€ 106, 1 β€ m β€ 105).
(n - 1) lines follow, each line contains one integer Li (1 β€ Li β€ 105), which denotes the length of the i-th road.
m lines follow, each line contains two integers Ai and Hi (1 β€ Ai β€ n, 0 β€ Hi β€ 107).
Output
Print m lines, on the i-th line print one integer β the answer for the i-th query.
Examples
Input
2 2
5
1 8
2 4
Output
11
4
Input
6 4
2
1
1
3
2
2 4
1 3
3 2
1 7
Output
11
6
3
28
Note
Here is the explanation for the second sample.
Ralph's first query is to start tours from city 2 and Hi equals to 4. Here are the options:
* He can choose city 5 as his terminal city. Since the distance between city 5 and city 2 is 3, he can gain happiness 4 - 3 = 1.
* He can choose city 4 as his terminal city and gain happiness 3.
* He can choose city 1 as his terminal city and gain happiness 2.
* He can choose city 3 as his terminal city and gain happiness 1.
* Note that Ralph can choose city 2 as his terminal city and gain happiness 4.
* Ralph won't choose city 6 as his terminal city because the distance between city 6 and city 2 is 5, which leads to negative happiness for Ralph.
So the answer for the first query is 1 + 3 + 2 + 1 + 4 = 11.
Submitted Solution:
```
n,m = map(int,input().split(' '))
L = list()
L.append(0)
for i in range(n-1):
L.append(int(input()))
mn = [[0] for i in range(n+1)]
for i in range(n,0,-1):
if i*2 <= n:
## for j in range(len(mn[i*2])):
## mn[i].append(mn[i*2][j]+L[i*2-1])
mn[i].extend(list(map(lambda x: x+L[i*2-1],mn[i*2])))
if i*2+1 <= n:
mn[i].extend(list(map(lambda x: x+L[i*2],mn[i*2+1])))
mn[i].sort
## k = 0
## j = 0
## if i*2+1 <= n:
## while j<len(mn[i]):
## while k<len(mn[i*2+1]) and mn[i*2+1][k]+L[i*2] < mn[i][j]:
## mn[i].insert(j,mn[i*2+1][k]+L[i*2])
## j += 1
## k += 1
## j += 1
## for j in range(k,len(mn[i*2+1])):
## mn[i].append(mn[i*2+1][k]+L[i*2])
## print(mn,' ',i)
##print(mn[1])
for i in range(m):
a,h = map(int,input().split(' '))
s = 0
fl = True
j = 0
while fl and j < len(mn[a]):
if mn[a][j] < h:
s += h-mn[a][j]
j += 1
else:
fl = False
while a != 1 and h > L[a-1]:
h -= L[a-1]
if h >= 0:
s += h
if a%2 == 1:
a = (a-1)//2
fl = True
j = 0
while fl and j < len(mn[a*2]):
if mn[a*2][j] < h-L[a*2-1]:
s += h-L[a*2-1]-mn[a*2][j]
j += 1
else:
fl = False
else:
if a+1 <= n and h >= L[a]:
fl = True
j = 0
while fl and j < len(mn[a+1]):
if mn[a+1][j] < h-L[a]:
s += h-L[a]-mn[a+1][j]
j += 1
else:
fl = False
a = a//2
print(s)
``` | instruction | 0 | 54,498 | 1 | 108,996 |
No | output | 1 | 54,498 | 1 | 108,997 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ralph is in the Binary Country. The Binary Country consists of n cities and (n - 1) bidirectional roads connecting the cities. The roads are numbered from 1 to (n - 1), the i-th road connects the city labeled <image> (here β xβ denotes the x rounded down to the nearest integer) and the city labeled (i + 1), and the length of the i-th road is Li.
Now Ralph gives you m queries. In each query he tells you some city Ai and an integer Hi. He wants to make some tours starting from this city. He can choose any city in the Binary Country (including Ai) as the terminal city for a tour. He gains happiness (Hi - L) during a tour, where L is the distance between the city Ai and the terminal city.
Ralph is interested in tours from Ai in which he can gain positive happiness. For each query, compute the sum of happiness gains for all such tours.
Ralph will never take the same tour twice or more (in one query), he will never pass the same city twice or more in one tour.
Input
The first line contains two integers n and m (1 β€ n β€ 106, 1 β€ m β€ 105).
(n - 1) lines follow, each line contains one integer Li (1 β€ Li β€ 105), which denotes the length of the i-th road.
m lines follow, each line contains two integers Ai and Hi (1 β€ Ai β€ n, 0 β€ Hi β€ 107).
Output
Print m lines, on the i-th line print one integer β the answer for the i-th query.
Examples
Input
2 2
5
1 8
2 4
Output
11
4
Input
6 4
2
1
1
3
2
2 4
1 3
3 2
1 7
Output
11
6
3
28
Note
Here is the explanation for the second sample.
Ralph's first query is to start tours from city 2 and Hi equals to 4. Here are the options:
* He can choose city 5 as his terminal city. Since the distance between city 5 and city 2 is 3, he can gain happiness 4 - 3 = 1.
* He can choose city 4 as his terminal city and gain happiness 3.
* He can choose city 1 as his terminal city and gain happiness 2.
* He can choose city 3 as his terminal city and gain happiness 1.
* Note that Ralph can choose city 2 as his terminal city and gain happiness 4.
* Ralph won't choose city 6 as his terminal city because the distance between city 6 and city 2 is 5, which leads to negative happiness for Ralph.
So the answer for the first query is 1 + 3 + 2 + 1 + 4 = 11.
Submitted Solution:
```
A = input().split()
n = int(A[0])
m = int(A[1])
L = []
def path(a,b):
if a==b:
return[a]
elif a == 2 and b == 1:
return([2,1])
else:
return(path(min(a,b),int(max(a,b)/2))+[b])
for i in range (0,n-1):
L = L + [input()]
L = [int(i) for i in L]
for i in range (0,m):
B = input().split()
start = int(B[0])
happy = int(B[1])
total = 0
if n==1:
print(happy)
else:
for j in range (1, n+1):
if j == start:
total = total + happy
else:
temp3 = max(start,j)
temp4 = min(start,j)
C = path(temp4, temp3)
length = 0
for k in range (0, len(C)-1):
temp5 = max(C[k+1],C[k])
temp6 = min(C[k+1],C[k])
if temp5 == 2*temp6:
pathnum = 2*temp6-1
else:
pathnum = 2*temp6
length = length + L[pathnum-1]
temp = happy-length
if temp >0: total = total + temp
print(total)
``` | instruction | 0 | 54,499 | 1 | 108,998 |
No | output | 1 | 54,499 | 1 | 108,999 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ralph is in the Binary Country. The Binary Country consists of n cities and (n - 1) bidirectional roads connecting the cities. The roads are numbered from 1 to (n - 1), the i-th road connects the city labeled <image> (here β xβ denotes the x rounded down to the nearest integer) and the city labeled (i + 1), and the length of the i-th road is Li.
Now Ralph gives you m queries. In each query he tells you some city Ai and an integer Hi. He wants to make some tours starting from this city. He can choose any city in the Binary Country (including Ai) as the terminal city for a tour. He gains happiness (Hi - L) during a tour, where L is the distance between the city Ai and the terminal city.
Ralph is interested in tours from Ai in which he can gain positive happiness. For each query, compute the sum of happiness gains for all such tours.
Ralph will never take the same tour twice or more (in one query), he will never pass the same city twice or more in one tour.
Input
The first line contains two integers n and m (1 β€ n β€ 106, 1 β€ m β€ 105).
(n - 1) lines follow, each line contains one integer Li (1 β€ Li β€ 105), which denotes the length of the i-th road.
m lines follow, each line contains two integers Ai and Hi (1 β€ Ai β€ n, 0 β€ Hi β€ 107).
Output
Print m lines, on the i-th line print one integer β the answer for the i-th query.
Examples
Input
2 2
5
1 8
2 4
Output
11
4
Input
6 4
2
1
1
3
2
2 4
1 3
3 2
1 7
Output
11
6
3
28
Note
Here is the explanation for the second sample.
Ralph's first query is to start tours from city 2 and Hi equals to 4. Here are the options:
* He can choose city 5 as his terminal city. Since the distance between city 5 and city 2 is 3, he can gain happiness 4 - 3 = 1.
* He can choose city 4 as his terminal city and gain happiness 3.
* He can choose city 1 as his terminal city and gain happiness 2.
* He can choose city 3 as his terminal city and gain happiness 1.
* Note that Ralph can choose city 2 as his terminal city and gain happiness 4.
* Ralph won't choose city 6 as his terminal city because the distance between city 6 and city 2 is 5, which leads to negative happiness for Ralph.
So the answer for the first query is 1 + 3 + 2 + 1 + 4 = 11.
Submitted Solution:
```
def poisk(a,h,mn,L):
s = 0
fl = True
j = 0
while fl and j < len(mn[a]):
if mn[a][j] < h:
s += h-mn[a][j]
j += 1
## print(s,'x',a)
else:
fl = False
return s
n,m = map(int,input().split(' '))
L = list()
L.append(0)
for i in range(n-1):
L.append(int(input()))
mn = [[0] for i in range(n+1)]
for i in range(n,0,-1):
if i*2 <= n:
for j in range(len(mn[i*2])):
mn[i].append(mn[i*2][j]+L[i*2-1])
k = 0
j = 0
if i*2+1 <= n:
while j<len(mn[i]):
while k<len(mn[i*2+1]) and mn[i*2+1][k]+L[i*2] < mn[i][j]:
mn[i].insert(j,mn[i*2+1][k]+L[i*2])
j += 1
k += 1
j += 1
for j in range(k,len(mn[i*2+1])):
mn[i].append(mn[i*2+1][k]+L[i*2])
## print(mn,' ',i)
##print(mn[1])
for i in range(m):
a,h = map(int,input().split(' '))
s = 0
s += poisk(a,h,mn,L)
while a != 1 and h > L[a-1]:
h -= L[a-1]
if h >= 0:
s += h
## print(h,'h')
if a%2 == 1:
a = (a-1)//2
s += poisk(a*2,h-L[a*2-1],mn,L)
## print(a*2,h-L[a*2-1],'ch',a)
else:
if a+1 < n and h >= L[a]:
s += poisk(a+1,h-L[a],mn,L)
## print(a+1,h-L[a],'nech',a)
a = a//2
print(s)
``` | instruction | 0 | 54,500 | 1 | 109,000 |
No | output | 1 | 54,500 | 1 | 109,001 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ralph is in the Binary Country. The Binary Country consists of n cities and (n - 1) bidirectional roads connecting the cities. The roads are numbered from 1 to (n - 1), the i-th road connects the city labeled <image> (here β xβ denotes the x rounded down to the nearest integer) and the city labeled (i + 1), and the length of the i-th road is Li.
Now Ralph gives you m queries. In each query he tells you some city Ai and an integer Hi. He wants to make some tours starting from this city. He can choose any city in the Binary Country (including Ai) as the terminal city for a tour. He gains happiness (Hi - L) during a tour, where L is the distance between the city Ai and the terminal city.
Ralph is interested in tours from Ai in which he can gain positive happiness. For each query, compute the sum of happiness gains for all such tours.
Ralph will never take the same tour twice or more (in one query), he will never pass the same city twice or more in one tour.
Input
The first line contains two integers n and m (1 β€ n β€ 106, 1 β€ m β€ 105).
(n - 1) lines follow, each line contains one integer Li (1 β€ Li β€ 105), which denotes the length of the i-th road.
m lines follow, each line contains two integers Ai and Hi (1 β€ Ai β€ n, 0 β€ Hi β€ 107).
Output
Print m lines, on the i-th line print one integer β the answer for the i-th query.
Examples
Input
2 2
5
1 8
2 4
Output
11
4
Input
6 4
2
1
1
3
2
2 4
1 3
3 2
1 7
Output
11
6
3
28
Note
Here is the explanation for the second sample.
Ralph's first query is to start tours from city 2 and Hi equals to 4. Here are the options:
* He can choose city 5 as his terminal city. Since the distance between city 5 and city 2 is 3, he can gain happiness 4 - 3 = 1.
* He can choose city 4 as his terminal city and gain happiness 3.
* He can choose city 1 as his terminal city and gain happiness 2.
* He can choose city 3 as his terminal city and gain happiness 1.
* Note that Ralph can choose city 2 as his terminal city and gain happiness 4.
* Ralph won't choose city 6 as his terminal city because the distance between city 6 and city 2 is 5, which leads to negative happiness for Ralph.
So the answer for the first query is 1 + 3 + 2 + 1 + 4 = 11.
Submitted Solution:
```
def poisk(a,h,mn,L):
s = 0
fl = True
j = 0
while fl and j < len(mn[a]):
if mn[a][j] < h:
s += h-mn[a][j]
j += 1
else:
fl = False
return s
n,m = map(int,input().split(' '))
L = list()
L.append(0)
for i in range(n-1):
L.append(int(input()))
mn = [[0] for i in range(n+1)]
##print(mn)
for i in range(n,0,-1):
if i*2 <= n:
for j in range(len(mn[i*2])):
mn[i].append(mn[i*2][j]+L[i*2-1])
k = 0
j = 0
if i*2+1 <= n:
while j<len(mn[i]):
while k<len(mn[i*2+1]) and mn[i*2+1][k]+L[i*2] < mn[i][j]:
mn[i].insert(j,mn[i*2+1][k]+L[i*2])
j += 1
k += 1
j += 1
for j in range(k,len(mn[i*2+1])):
mn[i].append(mn[i*2+1][k]+L[i*2])
## print(mn,' ',i)
##print(mn[1])
##
for i in range(m):
a,h = map(int,input().split(' '))
s = 0
s += poisk(a,h,mn,L)
while a != 1 and h > 0:
h -= L[a-1]
if h > 0:
s += h
if a%2 == 1:
a = (a+1)//2
s += poisk(a*2-2,h-L[a*2-1],mn,L)
else:
if a*2 < n:
a = a//2
s += poisk(a*2-1,h-L[a*2],mn,L)
print(s)
``` | instruction | 0 | 54,501 | 1 | 109,002 |
No | output | 1 | 54,501 | 1 | 109,003 |
Provide tags and a correct Python 3 solution for this coding contest problem.
So, the Berland is at war with its eternal enemy Flatland again, and Vasya, an accountant, was assigned to fulfil his duty to the nation.
Right now the situation in Berland is dismal β their both cities are surrounded! The armies of flatlanders stand on the borders of circles, the circles' centers are in the surrounded cities. At any moment all points of the flatland ring can begin to move quickly in the direction of the city β that's the strategy the flatlanders usually follow when they besiege cities.
The berlanders are sure that they can repel the enemy's attack if they learn the exact time the attack starts. For that they need to construct a radar that would register any movement at the distance of at most r from it. Thus, we can install a radar at such point, that at least one point of the enemy ring will be in its detecting range (that is, at a distance of at most r). Then the radar can immediately inform about the enemy's attack.
Due to the newest technologies, we can place a radar at any point without any problems. But the problem is that the berlanders have the time to make only one radar. Besides, the larger the detection radius (r) is, the more the radar costs.
That's why Vasya's task (that is, your task) is to find the minimum possible detection radius for the radar. In other words, your task is to find the minimum radius r (r β₯ 0) such, that a radar with radius r can be installed at some point and it can register the start of the movements of both flatland rings from that point.
In this problem you can consider the cities as material points, the attacking enemy rings - as circles with centers in the cities, the radar's detection range β as a disk (including the border) with the center at the point where the radar is placed.
Input
The input files consist of two lines. Each line represents the city and the flatland ring that surrounds it as three space-separated integers xi, yi, ri (|xi|, |yi| β€ 104; 1 β€ ri β€ 104) β the city's coordinates and the distance from the city to the flatlanders, correspondingly.
It is guaranteed that the cities are located at different points.
Output
Print a single real number β the minimum detection radius of the described radar. The answer is considered correct if the absolute or relative error does not exceed 10 - 6.
Examples
Input
0 0 1
6 0 3
Output
1.000000000000000
Input
-10 10 3
10 -10 3
Output
11.142135623730951
Note
The figure below shows the answer to the first sample. In this sample the best decision is to put the radar at point with coordinates (2, 0).
<image>
The figure below shows the answer for the second sample. In this sample the best decision is to put the radar at point with coordinates (0, 0).
<image> | instruction | 0 | 55,061 | 1 | 110,122 |
Tags: geometry
Correct Solution:
```
import os, sys
from io import IOBase, BytesIO
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf, log, pi, sin
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
# sys.setrecursionlimit(pow(10, 6))
# sys.stdin = open("input.txt", "r")
# sys.stdout = open("output.txt", "w")
mod = pow(10, 9) + 7
mod2 = 998244353
def data(): return sys.stdin.readline().strip()
def out(var, end="\n"): sys.stdout.write(str(var)+end)
def outarr(*var, end="\n"): sys.stdout.write(' '.join(map(str, var))+end)
def l(): return list(sp())
def sl(): return list(ssp())
def sp(): return map(int, data().split())
def ssp(): return map(str, data().split())
def l1d(n, val=0): return [val for i in range(n)]
def l2d(n, m, val=0): return [l1d(m, val) for j in range(n)]
def distance():
return sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
x1, y1, r1 = sp()
x2, y2, r2 = sp()
dist = distance()
radius: float = dist - r1 - r2
if radius < 0:
radius = -radius
radius /= 2
radius -= min(r1,r2)
else:
radius /= 2
out(max(0.0, radius))
``` | output | 1 | 55,061 | 1 | 110,123 |
Provide tags and a correct Python 3 solution for this coding contest problem.
So, the Berland is at war with its eternal enemy Flatland again, and Vasya, an accountant, was assigned to fulfil his duty to the nation.
Right now the situation in Berland is dismal β their both cities are surrounded! The armies of flatlanders stand on the borders of circles, the circles' centers are in the surrounded cities. At any moment all points of the flatland ring can begin to move quickly in the direction of the city β that's the strategy the flatlanders usually follow when they besiege cities.
The berlanders are sure that they can repel the enemy's attack if they learn the exact time the attack starts. For that they need to construct a radar that would register any movement at the distance of at most r from it. Thus, we can install a radar at such point, that at least one point of the enemy ring will be in its detecting range (that is, at a distance of at most r). Then the radar can immediately inform about the enemy's attack.
Due to the newest technologies, we can place a radar at any point without any problems. But the problem is that the berlanders have the time to make only one radar. Besides, the larger the detection radius (r) is, the more the radar costs.
That's why Vasya's task (that is, your task) is to find the minimum possible detection radius for the radar. In other words, your task is to find the minimum radius r (r β₯ 0) such, that a radar with radius r can be installed at some point and it can register the start of the movements of both flatland rings from that point.
In this problem you can consider the cities as material points, the attacking enemy rings - as circles with centers in the cities, the radar's detection range β as a disk (including the border) with the center at the point where the radar is placed.
Input
The input files consist of two lines. Each line represents the city and the flatland ring that surrounds it as three space-separated integers xi, yi, ri (|xi|, |yi| β€ 104; 1 β€ ri β€ 104) β the city's coordinates and the distance from the city to the flatlanders, correspondingly.
It is guaranteed that the cities are located at different points.
Output
Print a single real number β the minimum detection radius of the described radar. The answer is considered correct if the absolute or relative error does not exceed 10 - 6.
Examples
Input
0 0 1
6 0 3
Output
1.000000000000000
Input
-10 10 3
10 -10 3
Output
11.142135623730951
Note
The figure below shows the answer to the first sample. In this sample the best decision is to put the radar at point with coordinates (2, 0).
<image>
The figure below shows the answer for the second sample. In this sample the best decision is to put the radar at point with coordinates (0, 0).
<image> | instruction | 0 | 55,062 | 1 | 110,124 |
Tags: geometry
Correct Solution:
```
import math
city1 = list(map(int, input().split()))
city2 = list(map(int, input().split()))
x = max(city1[0], city2[0]) - min(city1[0], city2[0])
y = max(city1[1], city2[1]) - min(city1[1], city2[1])
R = max(city1[2], city2[2])
r = min(city1[2], city2[2])
c = math.sqrt(x ** 2 + y ** 2)
if R > r + c:
print(max((c - r) / 2, (R - c - r) / 2))
else:
ans = (c - (city1[2] + city2[2])) / 2
if ans < 0:
print(0)
else:
print(ans)
``` | output | 1 | 55,062 | 1 | 110,125 |
Provide tags and a correct Python 3 solution for this coding contest problem.
So, the Berland is at war with its eternal enemy Flatland again, and Vasya, an accountant, was assigned to fulfil his duty to the nation.
Right now the situation in Berland is dismal β their both cities are surrounded! The armies of flatlanders stand on the borders of circles, the circles' centers are in the surrounded cities. At any moment all points of the flatland ring can begin to move quickly in the direction of the city β that's the strategy the flatlanders usually follow when they besiege cities.
The berlanders are sure that they can repel the enemy's attack if they learn the exact time the attack starts. For that they need to construct a radar that would register any movement at the distance of at most r from it. Thus, we can install a radar at such point, that at least one point of the enemy ring will be in its detecting range (that is, at a distance of at most r). Then the radar can immediately inform about the enemy's attack.
Due to the newest technologies, we can place a radar at any point without any problems. But the problem is that the berlanders have the time to make only one radar. Besides, the larger the detection radius (r) is, the more the radar costs.
That's why Vasya's task (that is, your task) is to find the minimum possible detection radius for the radar. In other words, your task is to find the minimum radius r (r β₯ 0) such, that a radar with radius r can be installed at some point and it can register the start of the movements of both flatland rings from that point.
In this problem you can consider the cities as material points, the attacking enemy rings - as circles with centers in the cities, the radar's detection range β as a disk (including the border) with the center at the point where the radar is placed.
Input
The input files consist of two lines. Each line represents the city and the flatland ring that surrounds it as three space-separated integers xi, yi, ri (|xi|, |yi| β€ 104; 1 β€ ri β€ 104) β the city's coordinates and the distance from the city to the flatlanders, correspondingly.
It is guaranteed that the cities are located at different points.
Output
Print a single real number β the minimum detection radius of the described radar. The answer is considered correct if the absolute or relative error does not exceed 10 - 6.
Examples
Input
0 0 1
6 0 3
Output
1.000000000000000
Input
-10 10 3
10 -10 3
Output
11.142135623730951
Note
The figure below shows the answer to the first sample. In this sample the best decision is to put the radar at point with coordinates (2, 0).
<image>
The figure below shows the answer for the second sample. In this sample the best decision is to put the radar at point with coordinates (0, 0).
<image> | instruction | 0 | 55,063 | 1 | 110,126 |
Tags: geometry
Correct Solution:
```
a, b, c = map(int, input().split())
d, e, f = map(int, input().split())
r = ((a - d)**2 + (b - e)**2) ** .5
if r >= c + f:
print((r - c - f) / 2)
elif r <= abs(c - f):
print((abs(c - f) - r) / 2)
else:
print(0)
``` | output | 1 | 55,063 | 1 | 110,127 |
Provide tags and a correct Python 3 solution for this coding contest problem.
So, the Berland is at war with its eternal enemy Flatland again, and Vasya, an accountant, was assigned to fulfil his duty to the nation.
Right now the situation in Berland is dismal β their both cities are surrounded! The armies of flatlanders stand on the borders of circles, the circles' centers are in the surrounded cities. At any moment all points of the flatland ring can begin to move quickly in the direction of the city β that's the strategy the flatlanders usually follow when they besiege cities.
The berlanders are sure that they can repel the enemy's attack if they learn the exact time the attack starts. For that they need to construct a radar that would register any movement at the distance of at most r from it. Thus, we can install a radar at such point, that at least one point of the enemy ring will be in its detecting range (that is, at a distance of at most r). Then the radar can immediately inform about the enemy's attack.
Due to the newest technologies, we can place a radar at any point without any problems. But the problem is that the berlanders have the time to make only one radar. Besides, the larger the detection radius (r) is, the more the radar costs.
That's why Vasya's task (that is, your task) is to find the minimum possible detection radius for the radar. In other words, your task is to find the minimum radius r (r β₯ 0) such, that a radar with radius r can be installed at some point and it can register the start of the movements of both flatland rings from that point.
In this problem you can consider the cities as material points, the attacking enemy rings - as circles with centers in the cities, the radar's detection range β as a disk (including the border) with the center at the point where the radar is placed.
Input
The input files consist of two lines. Each line represents the city and the flatland ring that surrounds it as three space-separated integers xi, yi, ri (|xi|, |yi| β€ 104; 1 β€ ri β€ 104) β the city's coordinates and the distance from the city to the flatlanders, correspondingly.
It is guaranteed that the cities are located at different points.
Output
Print a single real number β the minimum detection radius of the described radar. The answer is considered correct if the absolute or relative error does not exceed 10 - 6.
Examples
Input
0 0 1
6 0 3
Output
1.000000000000000
Input
-10 10 3
10 -10 3
Output
11.142135623730951
Note
The figure below shows the answer to the first sample. In this sample the best decision is to put the radar at point with coordinates (2, 0).
<image>
The figure below shows the answer for the second sample. In this sample the best decision is to put the radar at point with coordinates (0, 0).
<image> | instruction | 0 | 55,064 | 1 | 110,128 |
Tags: geometry
Correct Solution:
```
a = list(map(int,input().split()))
b = list(map(int,input().split()))
import math
d = abs(a[0]-b[0])**2+abs(a[1]-b[1])**2
if d >= (a[2] + b[2])**2:
print((math.sqrt(d)-a[2]-b[2])/2)
quit()
d = math.sqrt(d)
print(max(max(a[2],b[2])-d-min(a[2],b[2]),0)/2)
``` | output | 1 | 55,064 | 1 | 110,129 |
Provide tags and a correct Python 3 solution for this coding contest problem.
So, the Berland is at war with its eternal enemy Flatland again, and Vasya, an accountant, was assigned to fulfil his duty to the nation.
Right now the situation in Berland is dismal β their both cities are surrounded! The armies of flatlanders stand on the borders of circles, the circles' centers are in the surrounded cities. At any moment all points of the flatland ring can begin to move quickly in the direction of the city β that's the strategy the flatlanders usually follow when they besiege cities.
The berlanders are sure that they can repel the enemy's attack if they learn the exact time the attack starts. For that they need to construct a radar that would register any movement at the distance of at most r from it. Thus, we can install a radar at such point, that at least one point of the enemy ring will be in its detecting range (that is, at a distance of at most r). Then the radar can immediately inform about the enemy's attack.
Due to the newest technologies, we can place a radar at any point without any problems. But the problem is that the berlanders have the time to make only one radar. Besides, the larger the detection radius (r) is, the more the radar costs.
That's why Vasya's task (that is, your task) is to find the minimum possible detection radius for the radar. In other words, your task is to find the minimum radius r (r β₯ 0) such, that a radar with radius r can be installed at some point and it can register the start of the movements of both flatland rings from that point.
In this problem you can consider the cities as material points, the attacking enemy rings - as circles with centers in the cities, the radar's detection range β as a disk (including the border) with the center at the point where the radar is placed.
Input
The input files consist of two lines. Each line represents the city and the flatland ring that surrounds it as three space-separated integers xi, yi, ri (|xi|, |yi| β€ 104; 1 β€ ri β€ 104) β the city's coordinates and the distance from the city to the flatlanders, correspondingly.
It is guaranteed that the cities are located at different points.
Output
Print a single real number β the minimum detection radius of the described radar. The answer is considered correct if the absolute or relative error does not exceed 10 - 6.
Examples
Input
0 0 1
6 0 3
Output
1.000000000000000
Input
-10 10 3
10 -10 3
Output
11.142135623730951
Note
The figure below shows the answer to the first sample. In this sample the best decision is to put the radar at point with coordinates (2, 0).
<image>
The figure below shows the answer for the second sample. In this sample the best decision is to put the radar at point with coordinates (0, 0).
<image> | instruction | 0 | 55,065 | 1 | 110,130 |
Tags: geometry
Correct Solution:
```
from math import pow
n, m, r = map(int, input().split())
n1, m1, r1 = map(int, input().split())
dis = pow(pow(n1-n,2)+pow(m-m1,2), 1/2)
if abs(r1-r)<=dis<=abs(r1+r):
rad = 0
elif dis<r1+r:
if r1>r:
rad = r1-dis-r
else:
rad = r -dis-r1
else:
rad = dis-(r+r1)
print(rad/2)
``` | output | 1 | 55,065 | 1 | 110,131 |
Provide tags and a correct Python 3 solution for this coding contest problem.
So, the Berland is at war with its eternal enemy Flatland again, and Vasya, an accountant, was assigned to fulfil his duty to the nation.
Right now the situation in Berland is dismal β their both cities are surrounded! The armies of flatlanders stand on the borders of circles, the circles' centers are in the surrounded cities. At any moment all points of the flatland ring can begin to move quickly in the direction of the city β that's the strategy the flatlanders usually follow when they besiege cities.
The berlanders are sure that they can repel the enemy's attack if they learn the exact time the attack starts. For that they need to construct a radar that would register any movement at the distance of at most r from it. Thus, we can install a radar at such point, that at least one point of the enemy ring will be in its detecting range (that is, at a distance of at most r). Then the radar can immediately inform about the enemy's attack.
Due to the newest technologies, we can place a radar at any point without any problems. But the problem is that the berlanders have the time to make only one radar. Besides, the larger the detection radius (r) is, the more the radar costs.
That's why Vasya's task (that is, your task) is to find the minimum possible detection radius for the radar. In other words, your task is to find the minimum radius r (r β₯ 0) such, that a radar with radius r can be installed at some point and it can register the start of the movements of both flatland rings from that point.
In this problem you can consider the cities as material points, the attacking enemy rings - as circles with centers in the cities, the radar's detection range β as a disk (including the border) with the center at the point where the radar is placed.
Input
The input files consist of two lines. Each line represents the city and the flatland ring that surrounds it as three space-separated integers xi, yi, ri (|xi|, |yi| β€ 104; 1 β€ ri β€ 104) β the city's coordinates and the distance from the city to the flatlanders, correspondingly.
It is guaranteed that the cities are located at different points.
Output
Print a single real number β the minimum detection radius of the described radar. The answer is considered correct if the absolute or relative error does not exceed 10 - 6.
Examples
Input
0 0 1
6 0 3
Output
1.000000000000000
Input
-10 10 3
10 -10 3
Output
11.142135623730951
Note
The figure below shows the answer to the first sample. In this sample the best decision is to put the radar at point with coordinates (2, 0).
<image>
The figure below shows the answer for the second sample. In this sample the best decision is to put the radar at point with coordinates (0, 0).
<image> | instruction | 0 | 55,066 | 1 | 110,132 |
Tags: geometry
Correct Solution:
```
x1,y1,r1=list(map(float,input().split()))
x2,y2,r2=list(map(float,input().split()))
if r1>r2:
r2,r1=r1,r2
d=((x2-x1)**2 + (y2-y1)**2)**(0.5)
if d>r1+r2:
print((d-(r1+r2))/2)
elif r2>d+r1:
print((r2-(r1+d))/2)
else:
print(0)
``` | output | 1 | 55,066 | 1 | 110,133 |
Provide tags and a correct Python 3 solution for this coding contest problem.
So, the Berland is at war with its eternal enemy Flatland again, and Vasya, an accountant, was assigned to fulfil his duty to the nation.
Right now the situation in Berland is dismal β their both cities are surrounded! The armies of flatlanders stand on the borders of circles, the circles' centers are in the surrounded cities. At any moment all points of the flatland ring can begin to move quickly in the direction of the city β that's the strategy the flatlanders usually follow when they besiege cities.
The berlanders are sure that they can repel the enemy's attack if they learn the exact time the attack starts. For that they need to construct a radar that would register any movement at the distance of at most r from it. Thus, we can install a radar at such point, that at least one point of the enemy ring will be in its detecting range (that is, at a distance of at most r). Then the radar can immediately inform about the enemy's attack.
Due to the newest technologies, we can place a radar at any point without any problems. But the problem is that the berlanders have the time to make only one radar. Besides, the larger the detection radius (r) is, the more the radar costs.
That's why Vasya's task (that is, your task) is to find the minimum possible detection radius for the radar. In other words, your task is to find the minimum radius r (r β₯ 0) such, that a radar with radius r can be installed at some point and it can register the start of the movements of both flatland rings from that point.
In this problem you can consider the cities as material points, the attacking enemy rings - as circles with centers in the cities, the radar's detection range β as a disk (including the border) with the center at the point where the radar is placed.
Input
The input files consist of two lines. Each line represents the city and the flatland ring that surrounds it as three space-separated integers xi, yi, ri (|xi|, |yi| β€ 104; 1 β€ ri β€ 104) β the city's coordinates and the distance from the city to the flatlanders, correspondingly.
It is guaranteed that the cities are located at different points.
Output
Print a single real number β the minimum detection radius of the described radar. The answer is considered correct if the absolute or relative error does not exceed 10 - 6.
Examples
Input
0 0 1
6 0 3
Output
1.000000000000000
Input
-10 10 3
10 -10 3
Output
11.142135623730951
Note
The figure below shows the answer to the first sample. In this sample the best decision is to put the radar at point with coordinates (2, 0).
<image>
The figure below shows the answer for the second sample. In this sample the best decision is to put the radar at point with coordinates (0, 0).
<image> | instruction | 0 | 55,067 | 1 | 110,134 |
Tags: geometry
Correct Solution:
```
import math
x1,y1,r1=map(int,input().split())
x2,y2,r2=map(int,input().split())
d=math.sqrt((x1-x2)**2+(y1-y2)**2)
R=max(r1,r2)
r=min(r1,r2)
# print(R+r,R-r,d)
if(R-r==d or R+r==d or (R+r>d and R-r<d)):
print("{0:.15f}".format(0))
else:
a=[]
m=(y2-y1)/(x2-x1)
c=x1+(r1/math.sqrt(m**2+1))
d=y1+((r1*m)/math.sqrt(m**2+1))
a.append([c,d])
c=x1-(r1/math.sqrt(m**2+1))
d=y1-((r1*m)/math.sqrt(m**2+1))
a.append([c,d])
b=[]
c=x2+(r2/math.sqrt(m**2+1))
d=y2+((r2*m)/math.sqrt(m**2+1))
b.append([c,d])
c=x2-(r2/math.sqrt(m**2+1))
d=y2-((r2*m)/math.sqrt(m**2+1))
b.append([c,d])
dis=10**10
for i in a:
for j in b:
dis=min(dis,math.sqrt((i[0]-j[0])**2+(i[1]-j[1])**2))
print("{0:.15f}".format(dis/2))
``` | output | 1 | 55,067 | 1 | 110,135 |
Provide tags and a correct Python 3 solution for this coding contest problem.
So, the Berland is at war with its eternal enemy Flatland again, and Vasya, an accountant, was assigned to fulfil his duty to the nation.
Right now the situation in Berland is dismal β their both cities are surrounded! The armies of flatlanders stand on the borders of circles, the circles' centers are in the surrounded cities. At any moment all points of the flatland ring can begin to move quickly in the direction of the city β that's the strategy the flatlanders usually follow when they besiege cities.
The berlanders are sure that they can repel the enemy's attack if they learn the exact time the attack starts. For that they need to construct a radar that would register any movement at the distance of at most r from it. Thus, we can install a radar at such point, that at least one point of the enemy ring will be in its detecting range (that is, at a distance of at most r). Then the radar can immediately inform about the enemy's attack.
Due to the newest technologies, we can place a radar at any point without any problems. But the problem is that the berlanders have the time to make only one radar. Besides, the larger the detection radius (r) is, the more the radar costs.
That's why Vasya's task (that is, your task) is to find the minimum possible detection radius for the radar. In other words, your task is to find the minimum radius r (r β₯ 0) such, that a radar with radius r can be installed at some point and it can register the start of the movements of both flatland rings from that point.
In this problem you can consider the cities as material points, the attacking enemy rings - as circles with centers in the cities, the radar's detection range β as a disk (including the border) with the center at the point where the radar is placed.
Input
The input files consist of two lines. Each line represents the city and the flatland ring that surrounds it as three space-separated integers xi, yi, ri (|xi|, |yi| β€ 104; 1 β€ ri β€ 104) β the city's coordinates and the distance from the city to the flatlanders, correspondingly.
It is guaranteed that the cities are located at different points.
Output
Print a single real number β the minimum detection radius of the described radar. The answer is considered correct if the absolute or relative error does not exceed 10 - 6.
Examples
Input
0 0 1
6 0 3
Output
1.000000000000000
Input
-10 10 3
10 -10 3
Output
11.142135623730951
Note
The figure below shows the answer to the first sample. In this sample the best decision is to put the radar at point with coordinates (2, 0).
<image>
The figure below shows the answer for the second sample. In this sample the best decision is to put the radar at point with coordinates (0, 0).
<image> | instruction | 0 | 55,068 | 1 | 110,136 |
Tags: geometry
Correct Solution:
```
from math import sqrt
x1, y1, r1 = map(int, input().split())
x2, y2, r2 = map(int, input().split())
if r1 < r2:
x1, x2 = x2, x1
y1, y2 = y2, y1
r1, r2 = r2, r1
dist = sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
ans = 0.0
if dist > r1 + r2:
ans = (dist - r1 - r2) / 2
elif r1 - r2 > dist:
ans = (r1 - r2 - dist) / 2
else:
ans = 0.0
print("%.15f" % ans) #/*2018-08-25 20:57:05.97*/
``` | output | 1 | 55,068 | 1 | 110,137 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
So, the Berland is at war with its eternal enemy Flatland again, and Vasya, an accountant, was assigned to fulfil his duty to the nation.
Right now the situation in Berland is dismal β their both cities are surrounded! The armies of flatlanders stand on the borders of circles, the circles' centers are in the surrounded cities. At any moment all points of the flatland ring can begin to move quickly in the direction of the city β that's the strategy the flatlanders usually follow when they besiege cities.
The berlanders are sure that they can repel the enemy's attack if they learn the exact time the attack starts. For that they need to construct a radar that would register any movement at the distance of at most r from it. Thus, we can install a radar at such point, that at least one point of the enemy ring will be in its detecting range (that is, at a distance of at most r). Then the radar can immediately inform about the enemy's attack.
Due to the newest technologies, we can place a radar at any point without any problems. But the problem is that the berlanders have the time to make only one radar. Besides, the larger the detection radius (r) is, the more the radar costs.
That's why Vasya's task (that is, your task) is to find the minimum possible detection radius for the radar. In other words, your task is to find the minimum radius r (r β₯ 0) such, that a radar with radius r can be installed at some point and it can register the start of the movements of both flatland rings from that point.
In this problem you can consider the cities as material points, the attacking enemy rings - as circles with centers in the cities, the radar's detection range β as a disk (including the border) with the center at the point where the radar is placed.
Input
The input files consist of two lines. Each line represents the city and the flatland ring that surrounds it as three space-separated integers xi, yi, ri (|xi|, |yi| β€ 104; 1 β€ ri β€ 104) β the city's coordinates and the distance from the city to the flatlanders, correspondingly.
It is guaranteed that the cities are located at different points.
Output
Print a single real number β the minimum detection radius of the described radar. The answer is considered correct if the absolute or relative error does not exceed 10 - 6.
Examples
Input
0 0 1
6 0 3
Output
1.000000000000000
Input
-10 10 3
10 -10 3
Output
11.142135623730951
Note
The figure below shows the answer to the first sample. In this sample the best decision is to put the radar at point with coordinates (2, 0).
<image>
The figure below shows the answer for the second sample. In this sample the best decision is to put the radar at point with coordinates (0, 0).
<image>
Submitted Solution:
```
import sys
import math
a,b,c=map(int,sys.stdin.readline().split())
d,e,f=map(int,sys.stdin.readline().split())
ds=math.sqrt((a-d)**2+(b-e)**2)
if ds>=c+f:
print((ds-c-f)/2)
elif ds<=abs(c-f):
print((abs(c-f)-ds)/2)
else:
print(0)
``` | instruction | 0 | 55,069 | 1 | 110,138 |
Yes | output | 1 | 55,069 | 1 | 110,139 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
So, the Berland is at war with its eternal enemy Flatland again, and Vasya, an accountant, was assigned to fulfil his duty to the nation.
Right now the situation in Berland is dismal β their both cities are surrounded! The armies of flatlanders stand on the borders of circles, the circles' centers are in the surrounded cities. At any moment all points of the flatland ring can begin to move quickly in the direction of the city β that's the strategy the flatlanders usually follow when they besiege cities.
The berlanders are sure that they can repel the enemy's attack if they learn the exact time the attack starts. For that they need to construct a radar that would register any movement at the distance of at most r from it. Thus, we can install a radar at such point, that at least one point of the enemy ring will be in its detecting range (that is, at a distance of at most r). Then the radar can immediately inform about the enemy's attack.
Due to the newest technologies, we can place a radar at any point without any problems. But the problem is that the berlanders have the time to make only one radar. Besides, the larger the detection radius (r) is, the more the radar costs.
That's why Vasya's task (that is, your task) is to find the minimum possible detection radius for the radar. In other words, your task is to find the minimum radius r (r β₯ 0) such, that a radar with radius r can be installed at some point and it can register the start of the movements of both flatland rings from that point.
In this problem you can consider the cities as material points, the attacking enemy rings - as circles with centers in the cities, the radar's detection range β as a disk (including the border) with the center at the point where the radar is placed.
Input
The input files consist of two lines. Each line represents the city and the flatland ring that surrounds it as three space-separated integers xi, yi, ri (|xi|, |yi| β€ 104; 1 β€ ri β€ 104) β the city's coordinates and the distance from the city to the flatlanders, correspondingly.
It is guaranteed that the cities are located at different points.
Output
Print a single real number β the minimum detection radius of the described radar. The answer is considered correct if the absolute or relative error does not exceed 10 - 6.
Examples
Input
0 0 1
6 0 3
Output
1.000000000000000
Input
-10 10 3
10 -10 3
Output
11.142135623730951
Note
The figure below shows the answer to the first sample. In this sample the best decision is to put the radar at point with coordinates (2, 0).
<image>
The figure below shows the answer for the second sample. In this sample the best decision is to put the radar at point with coordinates (0, 0).
<image>
Submitted Solution:
```
import sys
import math
from heapq import *;
input = sys.stdin.readline
from functools import cmp_to_key;
def pi():
return(int(input()))
def pl():
return(int(input(), 16))
def ti():
return(list(map(int,input().split())))
def ts():
s = input()
return(list(s[:len(s) - 1]))
def invr():
return(map(int,input().split()))
mod = 1000000007;
f = [];
def fact(n,m):
global f;
f = [1 for i in range(n+1)];
f[0] = 1;
for i in range(1,n+1):
f[i] = (f[i-1]*i)%m;
def fast_mod_exp(a,b,m):
res = 1;
while b > 0:
if b & 1:
res = (res*a)%m;
a = (a*a)%m;
b = b >> 1;
return res;
def inverseMod(n,m):
return fast_mod_exp(n,m-2,m);
def ncr(n,r,m):
if n < 0 or r < 0 or r > n: return 0;
if r == 0: return 1;
return ((f[n]*inverseMod(f[n-r],m))%m*inverseMod(f[r],m))%m;
def main():
B();
def B():
[x1,y1,r1] = ti();
[x2,y2,r2] = ti();
d = ((x1-x2)**2+(y1-y2)**2)**0.5;
x = (d-r1-r2)/2;
y = (max(r1,r2)-d-min(r1,r2))/2;
print(x if x >= 0 else y if y >= 0 else 0.0);
main();
``` | instruction | 0 | 55,070 | 1 | 110,140 |
Yes | output | 1 | 55,070 | 1 | 110,141 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
So, the Berland is at war with its eternal enemy Flatland again, and Vasya, an accountant, was assigned to fulfil his duty to the nation.
Right now the situation in Berland is dismal β their both cities are surrounded! The armies of flatlanders stand on the borders of circles, the circles' centers are in the surrounded cities. At any moment all points of the flatland ring can begin to move quickly in the direction of the city β that's the strategy the flatlanders usually follow when they besiege cities.
The berlanders are sure that they can repel the enemy's attack if they learn the exact time the attack starts. For that they need to construct a radar that would register any movement at the distance of at most r from it. Thus, we can install a radar at such point, that at least one point of the enemy ring will be in its detecting range (that is, at a distance of at most r). Then the radar can immediately inform about the enemy's attack.
Due to the newest technologies, we can place a radar at any point without any problems. But the problem is that the berlanders have the time to make only one radar. Besides, the larger the detection radius (r) is, the more the radar costs.
That's why Vasya's task (that is, your task) is to find the minimum possible detection radius for the radar. In other words, your task is to find the minimum radius r (r β₯ 0) such, that a radar with radius r can be installed at some point and it can register the start of the movements of both flatland rings from that point.
In this problem you can consider the cities as material points, the attacking enemy rings - as circles with centers in the cities, the radar's detection range β as a disk (including the border) with the center at the point where the radar is placed.
Input
The input files consist of two lines. Each line represents the city and the flatland ring that surrounds it as three space-separated integers xi, yi, ri (|xi|, |yi| β€ 104; 1 β€ ri β€ 104) β the city's coordinates and the distance from the city to the flatlanders, correspondingly.
It is guaranteed that the cities are located at different points.
Output
Print a single real number β the minimum detection radius of the described radar. The answer is considered correct if the absolute or relative error does not exceed 10 - 6.
Examples
Input
0 0 1
6 0 3
Output
1.000000000000000
Input
-10 10 3
10 -10 3
Output
11.142135623730951
Note
The figure below shows the answer to the first sample. In this sample the best decision is to put the radar at point with coordinates (2, 0).
<image>
The figure below shows the answer for the second sample. In this sample the best decision is to put the radar at point with coordinates (0, 0).
<image>
Submitted Solution:
```
a=[int(i) for i in input().split()]
b=[int(i) for i in input().split()]
cities=((a[0]-b[0])**2+(a[1]-b[1])**2)**0.5
if a[2]+b[2]>cities:
if a[2]>b[2]+cities:
print((a[2]-(b[2]+cities))/2)
elif b[2]>a[2]+cities:
print((b[2]-a[2]-cities)/2)
else:
print(0.0)
else:
print((cities-a[2]-b[2])/2)
``` | instruction | 0 | 55,071 | 1 | 110,142 |
Yes | output | 1 | 55,071 | 1 | 110,143 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
So, the Berland is at war with its eternal enemy Flatland again, and Vasya, an accountant, was assigned to fulfil his duty to the nation.
Right now the situation in Berland is dismal β their both cities are surrounded! The armies of flatlanders stand on the borders of circles, the circles' centers are in the surrounded cities. At any moment all points of the flatland ring can begin to move quickly in the direction of the city β that's the strategy the flatlanders usually follow when they besiege cities.
The berlanders are sure that they can repel the enemy's attack if they learn the exact time the attack starts. For that they need to construct a radar that would register any movement at the distance of at most r from it. Thus, we can install a radar at such point, that at least one point of the enemy ring will be in its detecting range (that is, at a distance of at most r). Then the radar can immediately inform about the enemy's attack.
Due to the newest technologies, we can place a radar at any point without any problems. But the problem is that the berlanders have the time to make only one radar. Besides, the larger the detection radius (r) is, the more the radar costs.
That's why Vasya's task (that is, your task) is to find the minimum possible detection radius for the radar. In other words, your task is to find the minimum radius r (r β₯ 0) such, that a radar with radius r can be installed at some point and it can register the start of the movements of both flatland rings from that point.
In this problem you can consider the cities as material points, the attacking enemy rings - as circles with centers in the cities, the radar's detection range β as a disk (including the border) with the center at the point where the radar is placed.
Input
The input files consist of two lines. Each line represents the city and the flatland ring that surrounds it as three space-separated integers xi, yi, ri (|xi|, |yi| β€ 104; 1 β€ ri β€ 104) β the city's coordinates and the distance from the city to the flatlanders, correspondingly.
It is guaranteed that the cities are located at different points.
Output
Print a single real number β the minimum detection radius of the described radar. The answer is considered correct if the absolute or relative error does not exceed 10 - 6.
Examples
Input
0 0 1
6 0 3
Output
1.000000000000000
Input
-10 10 3
10 -10 3
Output
11.142135623730951
Note
The figure below shows the answer to the first sample. In this sample the best decision is to put the radar at point with coordinates (2, 0).
<image>
The figure below shows the answer for the second sample. In this sample the best decision is to put the radar at point with coordinates (0, 0).
<image>
Submitted Solution:
```
from math import sqrt
x_1, y_1, r_1 = map(int, input().split())
x_2, y_2, r_2 = map(int, input().split())
d = sqrt((x_1 - x_2) ** 2 + (y_1 - y_2) ** 2)
if d + r_2 < r_1:
print((r_1 - d - r_2) / 2)
elif d + r_1 < r_2:
print((r_2 - d - r_1) / 2)
elif d <= r_1 + r_2:
print(0)
else:
print((d - r_1 - r_2) / 2)
``` | instruction | 0 | 55,072 | 1 | 110,144 |
Yes | output | 1 | 55,072 | 1 | 110,145 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
So, the Berland is at war with its eternal enemy Flatland again, and Vasya, an accountant, was assigned to fulfil his duty to the nation.
Right now the situation in Berland is dismal β their both cities are surrounded! The armies of flatlanders stand on the borders of circles, the circles' centers are in the surrounded cities. At any moment all points of the flatland ring can begin to move quickly in the direction of the city β that's the strategy the flatlanders usually follow when they besiege cities.
The berlanders are sure that they can repel the enemy's attack if they learn the exact time the attack starts. For that they need to construct a radar that would register any movement at the distance of at most r from it. Thus, we can install a radar at such point, that at least one point of the enemy ring will be in its detecting range (that is, at a distance of at most r). Then the radar can immediately inform about the enemy's attack.
Due to the newest technologies, we can place a radar at any point without any problems. But the problem is that the berlanders have the time to make only one radar. Besides, the larger the detection radius (r) is, the more the radar costs.
That's why Vasya's task (that is, your task) is to find the minimum possible detection radius for the radar. In other words, your task is to find the minimum radius r (r β₯ 0) such, that a radar with radius r can be installed at some point and it can register the start of the movements of both flatland rings from that point.
In this problem you can consider the cities as material points, the attacking enemy rings - as circles with centers in the cities, the radar's detection range β as a disk (including the border) with the center at the point where the radar is placed.
Input
The input files consist of two lines. Each line represents the city and the flatland ring that surrounds it as three space-separated integers xi, yi, ri (|xi|, |yi| β€ 104; 1 β€ ri β€ 104) β the city's coordinates and the distance from the city to the flatlanders, correspondingly.
It is guaranteed that the cities are located at different points.
Output
Print a single real number β the minimum detection radius of the described radar. The answer is considered correct if the absolute or relative error does not exceed 10 - 6.
Examples
Input
0 0 1
6 0 3
Output
1.000000000000000
Input
-10 10 3
10 -10 3
Output
11.142135623730951
Note
The figure below shows the answer to the first sample. In this sample the best decision is to put the radar at point with coordinates (2, 0).
<image>
The figure below shows the answer for the second sample. In this sample the best decision is to put the radar at point with coordinates (0, 0).
<image>
Submitted Solution:
```
import math
x1,y1,r1 = map(int,input().split())
x2,y2,r2 = map(int,input().split())
print("{:.10f}".format(abs(math.sqrt(abs(x1-x2)**2+abs(y1-y2)**2)-r1-r2)/2))
``` | instruction | 0 | 55,073 | 1 | 110,146 |
No | output | 1 | 55,073 | 1 | 110,147 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
So, the Berland is at war with its eternal enemy Flatland again, and Vasya, an accountant, was assigned to fulfil his duty to the nation.
Right now the situation in Berland is dismal β their both cities are surrounded! The armies of flatlanders stand on the borders of circles, the circles' centers are in the surrounded cities. At any moment all points of the flatland ring can begin to move quickly in the direction of the city β that's the strategy the flatlanders usually follow when they besiege cities.
The berlanders are sure that they can repel the enemy's attack if they learn the exact time the attack starts. For that they need to construct a radar that would register any movement at the distance of at most r from it. Thus, we can install a radar at such point, that at least one point of the enemy ring will be in its detecting range (that is, at a distance of at most r). Then the radar can immediately inform about the enemy's attack.
Due to the newest technologies, we can place a radar at any point without any problems. But the problem is that the berlanders have the time to make only one radar. Besides, the larger the detection radius (r) is, the more the radar costs.
That's why Vasya's task (that is, your task) is to find the minimum possible detection radius for the radar. In other words, your task is to find the minimum radius r (r β₯ 0) such, that a radar with radius r can be installed at some point and it can register the start of the movements of both flatland rings from that point.
In this problem you can consider the cities as material points, the attacking enemy rings - as circles with centers in the cities, the radar's detection range β as a disk (including the border) with the center at the point where the radar is placed.
Input
The input files consist of two lines. Each line represents the city and the flatland ring that surrounds it as three space-separated integers xi, yi, ri (|xi|, |yi| β€ 104; 1 β€ ri β€ 104) β the city's coordinates and the distance from the city to the flatlanders, correspondingly.
It is guaranteed that the cities are located at different points.
Output
Print a single real number β the minimum detection radius of the described radar. The answer is considered correct if the absolute or relative error does not exceed 10 - 6.
Examples
Input
0 0 1
6 0 3
Output
1.000000000000000
Input
-10 10 3
10 -10 3
Output
11.142135623730951
Note
The figure below shows the answer to the first sample. In this sample the best decision is to put the radar at point with coordinates (2, 0).
<image>
The figure below shows the answer for the second sample. In this sample the best decision is to put the radar at point with coordinates (0, 0).
<image>
Submitted Solution:
```
from math import *
x1,y1,r1 = map(int,input().split())
x2,y2,r2 = map(int,input().split())
dist = sqrt((x1-x2)**2+(y1-y2)**2)
dist -= r1+r2
print(dist/2)
``` | instruction | 0 | 55,074 | 1 | 110,148 |
No | output | 1 | 55,074 | 1 | 110,149 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
So, the Berland is at war with its eternal enemy Flatland again, and Vasya, an accountant, was assigned to fulfil his duty to the nation.
Right now the situation in Berland is dismal β their both cities are surrounded! The armies of flatlanders stand on the borders of circles, the circles' centers are in the surrounded cities. At any moment all points of the flatland ring can begin to move quickly in the direction of the city β that's the strategy the flatlanders usually follow when they besiege cities.
The berlanders are sure that they can repel the enemy's attack if they learn the exact time the attack starts. For that they need to construct a radar that would register any movement at the distance of at most r from it. Thus, we can install a radar at such point, that at least one point of the enemy ring will be in its detecting range (that is, at a distance of at most r). Then the radar can immediately inform about the enemy's attack.
Due to the newest technologies, we can place a radar at any point without any problems. But the problem is that the berlanders have the time to make only one radar. Besides, the larger the detection radius (r) is, the more the radar costs.
That's why Vasya's task (that is, your task) is to find the minimum possible detection radius for the radar. In other words, your task is to find the minimum radius r (r β₯ 0) such, that a radar with radius r can be installed at some point and it can register the start of the movements of both flatland rings from that point.
In this problem you can consider the cities as material points, the attacking enemy rings - as circles with centers in the cities, the radar's detection range β as a disk (including the border) with the center at the point where the radar is placed.
Input
The input files consist of two lines. Each line represents the city and the flatland ring that surrounds it as three space-separated integers xi, yi, ri (|xi|, |yi| β€ 104; 1 β€ ri β€ 104) β the city's coordinates and the distance from the city to the flatlanders, correspondingly.
It is guaranteed that the cities are located at different points.
Output
Print a single real number β the minimum detection radius of the described radar. The answer is considered correct if the absolute or relative error does not exceed 10 - 6.
Examples
Input
0 0 1
6 0 3
Output
1.000000000000000
Input
-10 10 3
10 -10 3
Output
11.142135623730951
Note
The figure below shows the answer to the first sample. In this sample the best decision is to put the radar at point with coordinates (2, 0).
<image>
The figure below shows the answer for the second sample. In this sample the best decision is to put the radar at point with coordinates (0, 0).
<image>
Submitted Solution:
```
import math
x1,y1,r1=map(int,input().split())
x2,y2,r2=map(int,input().split())
d=math.sqrt((x1-x2)**2+(y1-y2)**2)
R=max(r1,r2)
r=min(r1,r2)
if(R-r<=d or R+r<=d):
print("{0:.15f}".format(0))
else:
a=[]
m=(y2-y1)/(x2-x1)
c=x1+(r1/math.sqrt(m**2+1))
d=y1+((r1*m)/math.sqrt(m**2+1))
a.append([c,d])
c=x1-(r1/math.sqrt(m**2+1))
d=y1-((r1*m)/math.sqrt(m**2+1))
a.append([c,d])
b=[]
c=x2+(r2/math.sqrt(m**2+1))
d=y2+((r2*m)/math.sqrt(m**2+1))
b.append([c,d])
c=x2-(r2/math.sqrt(m**2+1))
d=y2-((r2*m)/math.sqrt(m**2+1))
b.append([c,d])
dis=10**10
for i in a:
for j in b:
dis=min(dis,math.sqrt((i[0]-j[0])**2+(i[1]-j[1])**2))
print("{0:.15f}".format(dis/2))
``` | instruction | 0 | 55,075 | 1 | 110,150 |
No | output | 1 | 55,075 | 1 | 110,151 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
So, the Berland is at war with its eternal enemy Flatland again, and Vasya, an accountant, was assigned to fulfil his duty to the nation.
Right now the situation in Berland is dismal β their both cities are surrounded! The armies of flatlanders stand on the borders of circles, the circles' centers are in the surrounded cities. At any moment all points of the flatland ring can begin to move quickly in the direction of the city β that's the strategy the flatlanders usually follow when they besiege cities.
The berlanders are sure that they can repel the enemy's attack if they learn the exact time the attack starts. For that they need to construct a radar that would register any movement at the distance of at most r from it. Thus, we can install a radar at such point, that at least one point of the enemy ring will be in its detecting range (that is, at a distance of at most r). Then the radar can immediately inform about the enemy's attack.
Due to the newest technologies, we can place a radar at any point without any problems. But the problem is that the berlanders have the time to make only one radar. Besides, the larger the detection radius (r) is, the more the radar costs.
That's why Vasya's task (that is, your task) is to find the minimum possible detection radius for the radar. In other words, your task is to find the minimum radius r (r β₯ 0) such, that a radar with radius r can be installed at some point and it can register the start of the movements of both flatland rings from that point.
In this problem you can consider the cities as material points, the attacking enemy rings - as circles with centers in the cities, the radar's detection range β as a disk (including the border) with the center at the point where the radar is placed.
Input
The input files consist of two lines. Each line represents the city and the flatland ring that surrounds it as three space-separated integers xi, yi, ri (|xi|, |yi| β€ 104; 1 β€ ri β€ 104) β the city's coordinates and the distance from the city to the flatlanders, correspondingly.
It is guaranteed that the cities are located at different points.
Output
Print a single real number β the minimum detection radius of the described radar. The answer is considered correct if the absolute or relative error does not exceed 10 - 6.
Examples
Input
0 0 1
6 0 3
Output
1.000000000000000
Input
-10 10 3
10 -10 3
Output
11.142135623730951
Note
The figure below shows the answer to the first sample. In this sample the best decision is to put the radar at point with coordinates (2, 0).
<image>
The figure below shows the answer for the second sample. In this sample the best decision is to put the radar at point with coordinates (0, 0).
<image>
Submitted Solution:
```
from math import sqrt
x1, y1, r1 = map(int, input().split())
x2, y2, r2 = map(int, input().split())
dist = sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
dist_r = r1 + r2
ans = 0.0
if dist <= dist_r:
ans = 0.0
else:
ans = (dist - dist_r) / 2
print("%.15f" % ans)
``` | instruction | 0 | 55,076 | 1 | 110,152 |
No | output | 1 | 55,076 | 1 | 110,153 |
Provide a correct Python 3 solution for this coding contest problem.
There is a railroad in Takahashi Kingdom. The railroad consists of N sections, numbered 1, 2, ..., N, and N+1 stations, numbered 0, 1, ..., N. Section i directly connects the stations i-1 and i. A train takes exactly A_i minutes to run through section i, regardless of direction. Each of the N sections is either single-tracked over the whole length, or double-tracked over the whole length. If B_i = 1, section i is single-tracked; if B_i = 2, section i is double-tracked. Two trains running in opposite directions can cross each other on a double-tracked section, but not on a single-tracked section. Trains can also cross each other at a station.
Snuke is creating the timetable for this railroad. In this timetable, the trains on the railroad run every K minutes, as shown in the following figure. Here, bold lines represent the positions of trains running on the railroad. (See Sample 1 for clarification.)
<image>
When creating such a timetable, find the minimum sum of the amount of time required for a train to depart station 0 and reach station N, and the amount of time required for a train to depart station N and reach station 0. It can be proved that, if there exists a timetable satisfying the conditions in this problem, this minimum sum is always an integer.
Formally, the times at which trains arrive and depart must satisfy the following:
* Each train either departs station 0 and is bound for station N, or departs station N and is bound for station 0.
* Each train takes exactly A_i minutes to run through section i. For example, if a train bound for station N departs station i-1 at time t, the train arrives at station i exactly at time t+A_i.
* Assume that a train bound for station N arrives at a station at time s, and departs the station at time t. Then, the next train bound for station N arrives at the station at time s+K, and departs the station at time t+K. Additionally, the previous train bound for station N arrives at the station at time s-K, and departs the station at time t-K. This must also be true for trains bound for station 0.
* Trains running in opposite directions must not be running on the same single-tracked section (except the stations at both ends) at the same time.
Constraints
* 1 \leq N \leq 100000
* 1 \leq K \leq 10^9
* 1 \leq A_i \leq 10^9
* A_i is an integer.
* B_i is either 1 or 2.
Input
The input is given from Standard Input in the following format:
N K
A_1 B_1
A_2 B_2
:
A_N B_N
Output
Print an integer representing the minimum sum of the amount of time required for a train to depart station 0 and reach station N, and the amount of time required for a train to depart station N and reach station 0. If it is impossible to create a timetable satisfying the conditions, print -1 instead.
Examples
Input
3 10
4 1
3 1
4 1
Output
26
Input
1 10
10 1
Output
-1
Input
6 4
1 1
1 1
1 1
1 1
1 1
1 1
Output
12
Input
20 987654321
129662684 2
162021979 1
458437539 1
319670097 2
202863355 1
112218745 1
348732033 1
323036578 1
382398703 1
55854389 1
283445191 1
151300613 1
693338042 2
191178308 2
386707193 1
204580036 1
335134457 1
122253639 1
824646518 2
902554792 2
Output
14829091348 | instruction | 0 | 55,502 | 1 | 111,004 |
"Correct Solution:
```
import sys
def merge_delay_pattern(k, half1, half2):
len1 = len(half1)
len2 = len(half2)
start, delay1_next = half1[0]
start2 = half2[0][0]
time1 = start - start2
mid_start = start + time1 + delay1_next
offset2_num_period = (mid_start - start2) // k
offset2_phase = mid_start - offset2_num_period * k
for head2 in range(len2):
if half2[head2][0] >= offset2_phase:
head2 -= 1
break
head2 += offset2_num_period * len2
head1 = 0
ret = []
prev = ()
half1.append((start + k, None))
pos1_next = start
pos2_next, delay2_next = half2[head2 % len2]
pos2_next += (head2 // len2) * k
mid = pos2_next
while True:
if mid <= pos2_next:
if head1 == len1: break
head1 += 1
pos1, delay1 = pos1_next, delay1_next
pos1_next, delay1_next = half1[head1]
if pos2_next <= mid:
head2 += 1
pos2, delay2 = pos2_next, delay2_next
pos2_next, delay2_next = half2[head2 % len2]
pos2_next += (head2 // len2) * k
if delay1 == 0:
mid = pos1_next + time1
if delay2 == 0:
if prev is not None:
ret.append((start, 0))
prev = None
else:
delay = pos2 + delay2 - time1 - start
if prev != start + delay:
ret.append((start, delay))
prev = start + delay
if pos2_next <= mid:
start = pos2_next - time1
else:
start = pos1_next
else:
mid = pos1 + time1 + delay1
if mid <= pos2_next:
if delay2 == 0:
delay = delay1
else:
delay = pos2 + delay2 - time1 - start
if prev != start + delay:
ret.append((start, delay))
prev = start + delay
start = pos1_next
return ret
def get_delay_pattern(k, data, first, last):
if last - first == 1: return data[first]
middle = (first + last) // 2
half1 = get_delay_pattern(k, data, first, middle)
half2 = get_delay_pattern(k, data, middle, last)
return merge_delay_pattern(k, half1, half2)
def solve():
data = []
int_list = [int(s) for s in sys.stdin.read().split()]
n = int_list[0]
k = int_list[1]
position = 0
for i in range(2, (n + 1) * 2, 2):
a = int_list[i]
b = int_list[i + 1]
if b == 1:
a2 = a * 2
if k < a2: return -1
data.append([(-position, 0), (-position + k - a2, a2)])
position += a
if not data: return position * 2
delay_pattern = get_delay_pattern(k, data, 0, len(data))
pat_adj_pairs = zip(delay_pattern, delay_pattern[1:] + [(delay_pattern[0][0] + k, None)])
delay_list = (pos + delay - next_pos for (pos, delay), (next_pos, _) in pat_adj_pairs if delay)
return position * 2 + min(delay_list, default=0)
print(solve())
``` | output | 1 | 55,502 | 1 | 111,005 |
Provide a correct Python 3 solution for this coding contest problem.
Water Country Water Deven has n cities. Each city is surrounded by water and looks like an island country. Water Deven has m bridges, and transportation between cities is carried out by these bridges, which allows you to travel to and from all cities.
Recently, it was decided to reduce the maintenance cost of the bridge by reviewing the road specific financial resources. I couldn't maintain all the bridges and had to demolish some of them. Therefore, the challenge for Water Deven was to minimize the cost of maintaining the bridge while leaving the bridge so that it could reach any city.
Create a program that inputs the number of cities, the number of bridges, and the maintenance cost of each bridge, so that you can go to any city using the bridge, and outputs the minimum value of the maintenance cost when the bridge is demolished. Please give me. There is no cost to demolish the bridge. However, each city shall be numbered sequentially from 0 to n-1.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format:
n m
a1 b1 cost1
a2 b2 cost2
::
am bm costm
The first line gives the number of cities n (2 β€ n β€ 100) and the number of bridges m (1 β€ m β€ 500). The following m lines give information about the i-th bridge. ai and bi are the numbers of the cities to which the bridge is connected, and costi (1 β€ costi β€ 1000) is the maintenance cost of the bridge.
Output
The total bridge maintenance cost is output to one line for each data set.
Example
Input
5 6
0 2 1
2 1 3
2 3 8
1 3 2
3 4 5
1 4 4
3 3
1 2 3
2 0 3
0 1 3
0 0
Output
10
6 | instruction | 0 | 55,535 | 1 | 111,070 |
"Correct Solution:
```
from heapq import heappush, heappop
def get_par(x, par_lst):
if x == par_lst[x]:
return x
p = get_par(par_lst[x], par_lst)
par_lst[x] = p
return p
while True:
n, m = map(int, input().split())
if n == 0:
break
que = []
for _ in range(m):
a, b, c = map(int, input().split())
heappush(que, (c, a, b))
par_lst = [i for i in range(n)]
ans = 0
while que:
c, a, b = heappop(que)
pa, pb = get_par(a, par_lst), get_par(b, par_lst)
if pa != pb:
par_lst[pa] = pb
ans += c
print(ans)
``` | output | 1 | 55,535 | 1 | 111,071 |
Provide a correct Python 3 solution for this coding contest problem.
Water Country Water Deven has n cities. Each city is surrounded by water and looks like an island country. Water Deven has m bridges, and transportation between cities is carried out by these bridges, which allows you to travel to and from all cities.
Recently, it was decided to reduce the maintenance cost of the bridge by reviewing the road specific financial resources. I couldn't maintain all the bridges and had to demolish some of them. Therefore, the challenge for Water Deven was to minimize the cost of maintaining the bridge while leaving the bridge so that it could reach any city.
Create a program that inputs the number of cities, the number of bridges, and the maintenance cost of each bridge, so that you can go to any city using the bridge, and outputs the minimum value of the maintenance cost when the bridge is demolished. Please give me. There is no cost to demolish the bridge. However, each city shall be numbered sequentially from 0 to n-1.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format:
n m
a1 b1 cost1
a2 b2 cost2
::
am bm costm
The first line gives the number of cities n (2 β€ n β€ 100) and the number of bridges m (1 β€ m β€ 500). The following m lines give information about the i-th bridge. ai and bi are the numbers of the cities to which the bridge is connected, and costi (1 β€ costi β€ 1000) is the maintenance cost of the bridge.
Output
The total bridge maintenance cost is output to one line for each data set.
Example
Input
5 6
0 2 1
2 1 3
2 3 8
1 3 2
3 4 5
1 4 4
3 3
1 2 3
2 0 3
0 1 3
0 0
Output
10
6 | instruction | 0 | 55,536 | 1 | 111,072 |
"Correct Solution:
```
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
N, M = map(int, readline().split())
if N == 0:
return False
*p, = range(N)
def root(x):
if x == p[x]:
return x
p[x] = y = root(p[x])
return y
def unite(x, y):
px = root(x); py = root(y)
if px == py:
return 0
if px < py:
p[py] = px
else:
p[px] = py
return 1
E = []
for i in range(M):
a, b, c = map(int, readline().split())
E.append((c, a, b))
E.sort()
ans = 0
for c, a, b in E:
if unite(a-1, b-1):
ans += c
write("%d\n" % ans)
return True
while solve():
...
``` | output | 1 | 55,536 | 1 | 111,073 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.