message stringlengths 2 22.8k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 16 109k | cluster float64 1 1 | __index_level_0__ int64 32 217k |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected unweighted graph consisting of n vertices and m edges (which represents the map of Bertown) and the array of prices p of length m. It is guaranteed that there is a path between each pair of vertices (districts).
Mike has planned a trip from the vertex (district) a to the vertex (district) b and then from the vertex (district) b to the vertex (district) c. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used p is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.
You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
The first line of the test case contains five integers n, m, a, b and c (2 β€ n β€ 2 β
10^5, n-1 β€ m β€ min((n(n-1))/(2), 2 β
10^5), 1 β€ a, b, c β€ n) β the number of vertices, the number of edges and districts in Mike's trip.
The second line of the test case contains m integers p_1, p_2, ..., p_m (1 β€ p_i β€ 10^9), where p_i is the i-th price from the array.
The following m lines of the test case denote edges: edge i is represented by a pair of integers v_i, u_i (1 β€ v_i, u_i β€ n, u_i β v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the array of edges, and for each pair (v_i, u_i) the condition v_i β u_i is satisfied. It is guaranteed that the given graph is connected.
It is guaranteed that the sum of n (as well as the sum of m) does not exceed 2 β
10^5 (β n β€ 2 β
10^5, β m β€ 2 β
10^5).
Output
For each test case, print the answer β the minimum possible price of Mike's trip if you distribute prices between edges optimally.
Example
Input
2
4 3 2 3 4
1 2 3
1 2
1 3
1 4
7 9 1 5 7
2 10 4 8 5 6 7 3 3
1 2
1 3
1 4
3 2
3 5
4 2
5 6
1 7
6 7
Output
7
12
Note
One of the possible solution to the first test case of the example:
<image>
One of the possible solution to the second test case of the example:
<image>
Submitted Solution:
```
from collections import deque
t = int(input())
for _ in range(t):
n,m,a,b,c = map(int,input().split())
g = [[] for i in range(n+5)]
cost = list(map(int,input().split(" ")))
cost.insert(0,0)
cost.sort()
for i in range(m):
cost[i+1]+=cost[i]
for _ in range(m):
u,v = map(int,input().split(" "))
g[u].append(v)
g[v].append(u)
def BFS(source):
dis=[-1]*(n+1)
dis[source]=0
q = deque([source])
while(q):
cur = q.popleft()
for i in g[cur]:
if(dis[i]==-1):
dis[i] = 1+dis[cur]
q.append(i)
return dis
dis1 = []
dis2 = []
dis3 = []
dis1.extend(BFS(a))
dis2.extend(BFS(b))
dis3.extend(BFS(c))
ans = 2e5
for i in range(1,n+1):
temp = dis1[i]+dis2[i]+dis3[i]
if(temp>m):
continue
ans = min(ans,cost[dis2[i]]+cost[temp])
print(ans)
``` | instruction | 0 | 3,512 | 1 | 7,024 |
No | output | 1 | 3,512 | 1 | 7,025 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected unweighted graph consisting of n vertices and m edges (which represents the map of Bertown) and the array of prices p of length m. It is guaranteed that there is a path between each pair of vertices (districts).
Mike has planned a trip from the vertex (district) a to the vertex (district) b and then from the vertex (district) b to the vertex (district) c. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used p is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.
You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
The first line of the test case contains five integers n, m, a, b and c (2 β€ n β€ 2 β
10^5, n-1 β€ m β€ min((n(n-1))/(2), 2 β
10^5), 1 β€ a, b, c β€ n) β the number of vertices, the number of edges and districts in Mike's trip.
The second line of the test case contains m integers p_1, p_2, ..., p_m (1 β€ p_i β€ 10^9), where p_i is the i-th price from the array.
The following m lines of the test case denote edges: edge i is represented by a pair of integers v_i, u_i (1 β€ v_i, u_i β€ n, u_i β v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the array of edges, and for each pair (v_i, u_i) the condition v_i β u_i is satisfied. It is guaranteed that the given graph is connected.
It is guaranteed that the sum of n (as well as the sum of m) does not exceed 2 β
10^5 (β n β€ 2 β
10^5, β m β€ 2 β
10^5).
Output
For each test case, print the answer β the minimum possible price of Mike's trip if you distribute prices between edges optimally.
Example
Input
2
4 3 2 3 4
1 2 3
1 2
1 3
1 4
7 9 1 5 7
2 10 4 8 5 6 7 3 3
1 2
1 3
1 4
3 2
3 5
4 2
5 6
1 7
6 7
Output
7
12
Note
One of the possible solution to the first test case of the example:
<image>
One of the possible solution to the second test case of the example:
<image>
Submitted Solution:
```
import sys
input=sys.stdin.readline
import collections
from collections import defaultdict
def bfs1(root,v):
queue = collections.deque([root])
prev=defaultdict(list)
prev[root].append(-1)
prev[root].append(-1)
while queue:
vertex = queue.popleft()
for neighbour in graph1[vertex]:
if neighbour[0] in prev:
continue
prev[neighbour[0]].append(vertex)
prev[neighbour[0]].append(neighbour[1])
queue.append(neighbour[0])
#print(prev)
if neighbour[0]==v:
return(prev)
return(prev)
def restore(a, s,src):
res = []
while s != src:
res.append(a[s][1])
s = a[s][0]
return res
t=int(input())
for i in range(t):
n,m,a,b,c=map(int,input().split())
p=[int(i) for i in input().split() if i!='\n']
p.sort()
graph1=defaultdict(list)
for j in range(m):
x,y=map(int,input().split())
graph1[x].append([y,j])
graph1[y].append([x,j])
first=bfs1(a,b)
first_path=restore(first,b,a)
second=bfs1(b,c)
second_path=restore(second,c,b)
total_path=first_path+second_path
freq=[0]*(m+1)
for k in total_path:
freq[k]+=1
freq.sort(reverse=True)
#print(freq)
ans=0
for j in range(len(freq)):
if freq[j]>0:
ans+=freq[j]*p[j]
print(ans)
``` | instruction | 0 | 3,513 | 1 | 7,026 |
No | output | 1 | 3,513 | 1 | 7,027 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected unweighted graph consisting of n vertices and m edges (which represents the map of Bertown) and the array of prices p of length m. It is guaranteed that there is a path between each pair of vertices (districts).
Mike has planned a trip from the vertex (district) a to the vertex (district) b and then from the vertex (district) b to the vertex (district) c. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used p is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.
You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
The first line of the test case contains five integers n, m, a, b and c (2 β€ n β€ 2 β
10^5, n-1 β€ m β€ min((n(n-1))/(2), 2 β
10^5), 1 β€ a, b, c β€ n) β the number of vertices, the number of edges and districts in Mike's trip.
The second line of the test case contains m integers p_1, p_2, ..., p_m (1 β€ p_i β€ 10^9), where p_i is the i-th price from the array.
The following m lines of the test case denote edges: edge i is represented by a pair of integers v_i, u_i (1 β€ v_i, u_i β€ n, u_i β v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the array of edges, and for each pair (v_i, u_i) the condition v_i β u_i is satisfied. It is guaranteed that the given graph is connected.
It is guaranteed that the sum of n (as well as the sum of m) does not exceed 2 β
10^5 (β n β€ 2 β
10^5, β m β€ 2 β
10^5).
Output
For each test case, print the answer β the minimum possible price of Mike's trip if you distribute prices between edges optimally.
Example
Input
2
4 3 2 3 4
1 2 3
1 2
1 3
1 4
7 9 1 5 7
2 10 4 8 5 6 7 3 3
1 2
1 3
1 4
3 2
3 5
4 2
5 6
1 7
6 7
Output
7
12
Note
One of the possible solution to the first test case of the example:
<image>
One of the possible solution to the second test case of the example:
<image>
Submitted Solution:
```
from sys import stdin
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Queue:
def __init__(self):
self.head = None
self.last = None
def enqueue(self, data):
if self.last is None:
self.head = Node(data)
self.last = self.head
else:
self.last.next = Node(data)
self.last = self.last.next
def dequeue(self):
if self.head is None:
return None
else:
to_return = self.head.data
self.head = self.head.next
if(self.head==None):
self.last=None
return to_return
def help():
n,m,a,b,c=map(int,stdin.readline().split(" "))
neigh=[[] for i in range(n)]
parent=[-1]*(n)
visited=[False]*(n)
visited[b-1]=True
parr=list(map(int,stdin.readline().split(" ")))
for i in range(m):
s,t=map(int,stdin.readline().split(" "))
neigh[s-1].append(t-1)
neigh[t-1].append(s-1)
queue=Queue()
queue.enqueue(b-1)
while queue:
perm=queue.dequeue()
if(perm==None):
break
for i in neigh[perm]:
if(not visited[i]):
visited[i]=True
parent[i]=perm
queue.enqueue(i)
curr=a-1
aaa=[a-1]
while parent[curr]!=-1:
aaa.append(parent[curr])
curr=parent[curr]
aaa.reverse()
ccc=[c-1]
curr=c-1
while parent[curr]!=-1:
ccc.append(parent[curr])
curr=parent[curr]
ccc.reverse()
parent=[-1]*(n)
visited=[False]*(n)
visited[a-1]=True
queue=Queue()
queue.enqueue(a-1)
while queue:
perm=queue.dequeue()
if(perm==None):
break
for i in neigh[perm]:
if(not visited[i]):
visited[i]=True
parent[i]=perm
queue.enqueue(i)
if(visited[c-1]):
break
bbb=[c-1]
curr=c-1
while parent[curr]!=-1:
bbb.append(parent[curr])
curr=parent[curr]
parr.sort()
common1=0
ans1=0
la=len(aaa)
lb=len(bbb)
lc=len(ccc)
for i in range(min(la,lc)):
if(aaa[i]==ccc[i]):
common1+=1
else:
break
common1-=1
notcommon=(la+lc-2)-2*common1
ans1=2*(sum(parr[:common1]))+sum(parr[common1:common1+notcommon])
common2=la-1
notcommon=lb-1
ans2=2*(sum(parr[:common2]))+sum(parr[common2:common2+notcommon])
print(min(ans1,ans2))
for i in range(int(stdin.readline())):
help()
# def help(ii):
# # stri=stdin.readline().strip("\n")
# # row,col,r1,c1,r2,c2=map(int,stdin.readline().split(" "))
# arr=[[0]*row for i in range(col)]
# # print("Case #"+str(ii+1)+":",east,south)
# for i in range(int(stdin.readline())):
# help(i)
# row,col=map(int,stdin.readline().split(" "))
# def func(row,col):
# arr=[[0]*(col) for i in range(row)]
# arr[0][0]=1
# for i in range(row):
# for j in range(col):
# if(i+1==row and j+1==col):
# continue
# elif(i+1==row):
# arr[i][j+1]+=arr[i][j]
# elif(j+1==col):
# arr[i+1][j]+=arr[i][j]
# else:
# arr[i+1][j]+=arr[i][j]/2
# arr[i][j+1]+=arr[i][j]/2
# for i in range(row):
# print(*arr[i],sep="\t\t")
# func(8,8)
``` | instruction | 0 | 3,514 | 1 | 7,028 |
No | output | 1 | 3,514 | 1 | 7,029 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
As Sherlock Holmes was investigating another crime, he found a certain number of clues. Also, he has already found direct links between some of those clues. The direct links between the clues are mutual. That is, the direct link between clues A and B and the direct link between clues B and A is the same thing. No more than one direct link can exist between two clues.
Of course Sherlock is able to find direct links between all clues. But it will take too much time and the criminals can use this extra time to hide. To solve the crime, Sherlock needs each clue to be linked to all other clues (maybe not directly, via some other clues). Clues A and B are considered linked either if there is a direct link between them or if there is a direct link between A and some other clue C which is linked to B.
Sherlock Holmes counted the minimum number of additional direct links that he needs to find to solve the crime. As it turns out, it equals T.
Please count the number of different ways to find exactly T direct links between the clues so that the crime is solved in the end. Two ways to find direct links are considered different if there exist two clues which have a direct link in one way and do not have a direct link in the other way.
As the number of different ways can turn out rather big, print it modulo k.
Input
The first line contains three space-separated integers n, m, k (1 β€ n β€ 105, 0 β€ m β€ 105, 1 β€ k β€ 109) β the number of clues, the number of direct clue links that Holmes has already found and the divisor for the modulo operation.
Each of next m lines contains two integers a and b (1 β€ a, b β€ n, a β b), that represent a direct link between clues. It is guaranteed that any two clues are linked by no more than one direct link. Note that the direct links between the clues are mutual.
Output
Print the single number β the answer to the problem modulo k.
Examples
Input
2 0 1000000000
Output
1
Input
3 0 100
Output
3
Input
4 1 1000000000
1 4
Output
8
Note
The first sample only has two clues and Sherlock hasn't found any direct link between them yet. The only way to solve the crime is to find the link.
The second sample has three clues and Sherlock hasn't found any direct links between them. He has to find two of three possible direct links between clues to solve the crime β there are 3 ways to do it.
The third sample has four clues and the detective has already found one direct link between the first and the fourth clue. There are 8 ways to find two remaining clues to solve the crime.
Submitted Solution:
```
n, m, k = map(int, input().split())
g = [[] for i in range(n)]
for i in range(m):
a, b = map(int, input().split())
a -= 1
b -= 1
g[a].append(b)
g[b].append(a)
visited = [False for i in range(n)]
count = 0
def dfs(x):
global count
visited[x] = True
count += 1
for y in g[x]:
if not visited[y]:
dfs(y)
total_count = 1
for i in range(n):
if not visited[i]:
dfs(i)
total_count = (total_count * count) % k
count = 0
def fast_exp(n, x, k):
if x == 1:
return n % k
if x == 0:
return 1 % k
else:
sqrt = fast_exp(n, x // 2, k)
ans = (sqrt * sqrt) % k
if x % 2 != 0:
ans = (ans * n) % k
return ans
#print("Total count is", total_count)
if m == n - 1:
print(1)
else:
result = (total_count * fast_exp(n, n - m - 2, k)) % k
print(result)
``` | instruction | 0 | 3,638 | 1 | 7,276 |
No | output | 1 | 3,638 | 1 | 7,277 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
As Sherlock Holmes was investigating another crime, he found a certain number of clues. Also, he has already found direct links between some of those clues. The direct links between the clues are mutual. That is, the direct link between clues A and B and the direct link between clues B and A is the same thing. No more than one direct link can exist between two clues.
Of course Sherlock is able to find direct links between all clues. But it will take too much time and the criminals can use this extra time to hide. To solve the crime, Sherlock needs each clue to be linked to all other clues (maybe not directly, via some other clues). Clues A and B are considered linked either if there is a direct link between them or if there is a direct link between A and some other clue C which is linked to B.
Sherlock Holmes counted the minimum number of additional direct links that he needs to find to solve the crime. As it turns out, it equals T.
Please count the number of different ways to find exactly T direct links between the clues so that the crime is solved in the end. Two ways to find direct links are considered different if there exist two clues which have a direct link in one way and do not have a direct link in the other way.
As the number of different ways can turn out rather big, print it modulo k.
Input
The first line contains three space-separated integers n, m, k (1 β€ n β€ 105, 0 β€ m β€ 105, 1 β€ k β€ 109) β the number of clues, the number of direct clue links that Holmes has already found and the divisor for the modulo operation.
Each of next m lines contains two integers a and b (1 β€ a, b β€ n, a β b), that represent a direct link between clues. It is guaranteed that any two clues are linked by no more than one direct link. Note that the direct links between the clues are mutual.
Output
Print the single number β the answer to the problem modulo k.
Examples
Input
2 0 1000000000
Output
1
Input
3 0 100
Output
3
Input
4 1 1000000000
1 4
Output
8
Note
The first sample only has two clues and Sherlock hasn't found any direct link between them yet. The only way to solve the crime is to find the link.
The second sample has three clues and Sherlock hasn't found any direct links between them. He has to find two of three possible direct links between clues to solve the crime β there are 3 ways to do it.
The third sample has four clues and the detective has already found one direct link between the first and the fourth clue. There are 8 ways to find two remaining clues to solve the crime.
Submitted Solution:
```
n, m, k = map(int, input().split())
g = [[] for i in range(n)]
for i in range(m):
a, b = map(int, input().split())
a -= 1
b -= 1
g[a].append(b)
g[b].append(a)
visited = [False for i in range(n)]
count = 0
total_visited = 0
def dfs(x):
global count
visited[x] = True
count += 1
for y in g[x]:
if not visited[y]:
dfs(y)
total_count = 1
total_effective_edges = 0
for i in range(n):
if not visited[i]:
dfs(i)
total_effective_edges += count - 1
total_count = (total_count * count) % k
count = 0
def fast_exp(n, x, k):
if x == 1:
return n % k
if x == 0:
return 1 % k
else:
sqrt = fast_exp(n, x // 2, k)
ans = (sqrt * sqrt) % k
if x % 2 != 0:
ans = (ans * n) % k
return ans
#print("Total count is", total_count)
m = total_effective_edges
if m == n - 1:
print(1)
else:
result = (total_count * fast_exp(n, n - m - 2, k)) % k
print(result)
``` | instruction | 0 | 3,639 | 1 | 7,278 |
No | output | 1 | 3,639 | 1 | 7,279 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
As Sherlock Holmes was investigating another crime, he found a certain number of clues. Also, he has already found direct links between some of those clues. The direct links between the clues are mutual. That is, the direct link between clues A and B and the direct link between clues B and A is the same thing. No more than one direct link can exist between two clues.
Of course Sherlock is able to find direct links between all clues. But it will take too much time and the criminals can use this extra time to hide. To solve the crime, Sherlock needs each clue to be linked to all other clues (maybe not directly, via some other clues). Clues A and B are considered linked either if there is a direct link between them or if there is a direct link between A and some other clue C which is linked to B.
Sherlock Holmes counted the minimum number of additional direct links that he needs to find to solve the crime. As it turns out, it equals T.
Please count the number of different ways to find exactly T direct links between the clues so that the crime is solved in the end. Two ways to find direct links are considered different if there exist two clues which have a direct link in one way and do not have a direct link in the other way.
As the number of different ways can turn out rather big, print it modulo k.
Input
The first line contains three space-separated integers n, m, k (1 β€ n β€ 105, 0 β€ m β€ 105, 1 β€ k β€ 109) β the number of clues, the number of direct clue links that Holmes has already found and the divisor for the modulo operation.
Each of next m lines contains two integers a and b (1 β€ a, b β€ n, a β b), that represent a direct link between clues. It is guaranteed that any two clues are linked by no more than one direct link. Note that the direct links between the clues are mutual.
Output
Print the single number β the answer to the problem modulo k.
Examples
Input
2 0 1000000000
Output
1
Input
3 0 100
Output
3
Input
4 1 1000000000
1 4
Output
8
Note
The first sample only has two clues and Sherlock hasn't found any direct link between them yet. The only way to solve the crime is to find the link.
The second sample has three clues and Sherlock hasn't found any direct links between them. He has to find two of three possible direct links between clues to solve the crime β there are 3 ways to do it.
The third sample has four clues and the detective has already found one direct link between the first and the fourth clue. There are 8 ways to find two remaining clues to solve the crime.
Submitted Solution:
```
def dfs(node, my_cc):
vis[node] = True
acc[my_cc]+=1
for i in adj[node]:
if not vis[i]:
dfs(i, my_cc)
def ittDfs(node):
queue = [node]
curr = 0
while(queue):
node = queue.pop()
vis[node] = True
acc[cc] += 1
for i in adj[node]:
if not vis[i]:
queue.append(i)
def bfs(node):
vis[node] = True
cola = [node]
cur = 0
while (cur < len(cola)):
x = cola[cur]
acc[cc] += 1
cur += 1;
for i in adj[x]:
if not vis[i]:
vis[i] = True
cola.append(i)
if __name__ == '__main__':
_input = input().split()
n = int(_input[0])
m = int(_input[1])
k = int(_input[2])
adj = []
vis = []
acc = []
cc = 0
for i in range(n):
vis.append(False)
adj.append([])
acc.append(0)
for i in range(m):
_in2 = input().split()
v = int(_in2[0]) - 1
w = int(_in2[1]) - 1
adj[v].append(w)
adj[w].append(v)
for i in range(n):
if not vis[i]:
# dfs(i, cc)
ittDfs(i)
cc+=1
if cc == 1:
print(1 % k)
exit()
ans = 1
for i in range(cc - 2):
ans = ans * n
ans = ans % k
for i in range(cc):
ans = ans * acc[i]
ans = ans % k
print(ans)
``` | instruction | 0 | 3,640 | 1 | 7,280 |
No | output | 1 | 3,640 | 1 | 7,281 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
As Sherlock Holmes was investigating another crime, he found a certain number of clues. Also, he has already found direct links between some of those clues. The direct links between the clues are mutual. That is, the direct link between clues A and B and the direct link between clues B and A is the same thing. No more than one direct link can exist between two clues.
Of course Sherlock is able to find direct links between all clues. But it will take too much time and the criminals can use this extra time to hide. To solve the crime, Sherlock needs each clue to be linked to all other clues (maybe not directly, via some other clues). Clues A and B are considered linked either if there is a direct link between them or if there is a direct link between A and some other clue C which is linked to B.
Sherlock Holmes counted the minimum number of additional direct links that he needs to find to solve the crime. As it turns out, it equals T.
Please count the number of different ways to find exactly T direct links between the clues so that the crime is solved in the end. Two ways to find direct links are considered different if there exist two clues which have a direct link in one way and do not have a direct link in the other way.
As the number of different ways can turn out rather big, print it modulo k.
Input
The first line contains three space-separated integers n, m, k (1 β€ n β€ 105, 0 β€ m β€ 105, 1 β€ k β€ 109) β the number of clues, the number of direct clue links that Holmes has already found and the divisor for the modulo operation.
Each of next m lines contains two integers a and b (1 β€ a, b β€ n, a β b), that represent a direct link between clues. It is guaranteed that any two clues are linked by no more than one direct link. Note that the direct links between the clues are mutual.
Output
Print the single number β the answer to the problem modulo k.
Examples
Input
2 0 1000000000
Output
1
Input
3 0 100
Output
3
Input
4 1 1000000000
1 4
Output
8
Note
The first sample only has two clues and Sherlock hasn't found any direct link between them yet. The only way to solve the crime is to find the link.
The second sample has three clues and Sherlock hasn't found any direct links between them. He has to find two of three possible direct links between clues to solve the crime β there are 3 ways to do it.
The third sample has four clues and the detective has already found one direct link between the first and the fourth clue. There are 8 ways to find two remaining clues to solve the crime.
Submitted Solution:
```
from collections import deque
n, m, k = map(int, input().split())
g = [[] for i in range(n)]
for i in range(m):
a, b = map(int, input().split())
a -= 1
b -= 1
g[a].append(b)
g[b].append(a)
visited = [False for i in range(n)]
count = 0
def bfs(x):
global count
q = deque([x])
while len(q) != 0:
y = q.pop()
if not visited[y]:
count += 1
visited[y] = True
for z in g[y]:
q.appendleft(z)
total_count = 1
total_effective_edges = 0
for i in range(n):
if not visited[i]:
bfs(i)
total_effective_edges += count - 1
total_count = (total_count * count) % k
count = 0
def fast_exp(n, x, k):
if x == 1:
return n % k
if x == 0:
return 1 % k
else:
sqrt = fast_exp(n, x // 2, k)
ans = (sqrt * sqrt) % k
if x % 2 != 0:
ans = (ans * n) % k
return ans
#print("Total count is", total_count)
m = total_effective_edges
if n == 1:
print(0 % k)
elif m == n - 1:
print(1 % k)
else:
result = (total_count * fast_exp(n, n - m - 2, k)) % k
print(result)
``` | instruction | 0 | 3,641 | 1 | 7,282 |
No | output | 1 | 3,641 | 1 | 7,283 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Of course our child likes walking in a zoo. The zoo has n areas, that are numbered from 1 to n. The i-th area contains ai animals in it. Also there are m roads in the zoo, and each road connects two distinct areas. Naturally the zoo is connected, so you can reach any area of the zoo from any other area using the roads.
Our child is very smart. Imagine the child want to go from area p to area q. Firstly he considers all the simple routes from p to q. For each route the child writes down the number, that is equal to the minimum number of animals among the route areas. Let's denote the largest of the written numbers as f(p, q). Finally, the child chooses one of the routes for which he writes down the value f(p, q).
After the child has visited the zoo, he thinks about the question: what is the average value of f(p, q) for all pairs p, q (p β q)? Can you answer his question?
Input
The first line contains two integers n and m (2 β€ n β€ 105; 0 β€ m β€ 105). The second line contains n integers: a1, a2, ..., an (0 β€ ai β€ 105). Then follow m lines, each line contains two integers xi and yi (1 β€ xi, yi β€ n; xi β yi), denoting the road between areas xi and yi.
All roads are bidirectional, each pair of areas is connected by at most one road.
Output
Output a real number β the value of <image>.
The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 4.
Examples
Input
4 3
10 20 30 40
1 3
2 3
4 3
Output
16.666667
Input
3 3
10 20 30
1 2
2 3
3 1
Output
13.333333
Input
7 8
40 20 10 30 20 50 40
1 2
2 3
3 4
4 5
5 6
6 7
1 4
5 7
Output
18.571429
Note
Consider the first sample. There are 12 possible situations:
* p = 1, q = 3, f(p, q) = 10.
* p = 2, q = 3, f(p, q) = 20.
* p = 4, q = 3, f(p, q) = 30.
* p = 1, q = 2, f(p, q) = 10.
* p = 2, q = 4, f(p, q) = 20.
* p = 4, q = 1, f(p, q) = 10.
Another 6 cases are symmetrical to the above. The average is <image>.
Consider the second sample. There are 6 possible situations:
* p = 1, q = 2, f(p, q) = 10.
* p = 2, q = 3, f(p, q) = 20.
* p = 1, q = 3, f(p, q) = 10.
Another 3 cases are symmetrical to the above. The average is <image>. | instruction | 0 | 3,734 | 1 | 7,468 |
Tags: dsu, sortings
Correct Solution:
```
n, m = map(int, input().split())
p, c = list(range(n + 1)), [1] * (n + 1)
v = [0] + list(map(int, input().split()))
s, e = 0, [()] * m
for i in range(m):
x, y = map(int, input().split())
e[i] = (x, y, min(v[x], v[y]))
e.sort(key = lambda x: x[2], reverse = True)
q = [[i] for i in range(n + 1)]
for l, r, v in e:
l, r = p[l], p[r]
if l == r: continue
if len(q[l]) > len(q[r]): l, r = r, l
q[r].extend(q[l])
for t in q[l]: p[t] = r
s += c[l] * c[r] * v
c[r] += c[l]
print(s * 2 / (n * (n - 1)))
``` | output | 1 | 3,734 | 1 | 7,469 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Of course our child likes walking in a zoo. The zoo has n areas, that are numbered from 1 to n. The i-th area contains ai animals in it. Also there are m roads in the zoo, and each road connects two distinct areas. Naturally the zoo is connected, so you can reach any area of the zoo from any other area using the roads.
Our child is very smart. Imagine the child want to go from area p to area q. Firstly he considers all the simple routes from p to q. For each route the child writes down the number, that is equal to the minimum number of animals among the route areas. Let's denote the largest of the written numbers as f(p, q). Finally, the child chooses one of the routes for which he writes down the value f(p, q).
After the child has visited the zoo, he thinks about the question: what is the average value of f(p, q) for all pairs p, q (p β q)? Can you answer his question?
Input
The first line contains two integers n and m (2 β€ n β€ 105; 0 β€ m β€ 105). The second line contains n integers: a1, a2, ..., an (0 β€ ai β€ 105). Then follow m lines, each line contains two integers xi and yi (1 β€ xi, yi β€ n; xi β yi), denoting the road between areas xi and yi.
All roads are bidirectional, each pair of areas is connected by at most one road.
Output
Output a real number β the value of <image>.
The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 4.
Examples
Input
4 3
10 20 30 40
1 3
2 3
4 3
Output
16.666667
Input
3 3
10 20 30
1 2
2 3
3 1
Output
13.333333
Input
7 8
40 20 10 30 20 50 40
1 2
2 3
3 4
4 5
5 6
6 7
1 4
5 7
Output
18.571429
Note
Consider the first sample. There are 12 possible situations:
* p = 1, q = 3, f(p, q) = 10.
* p = 2, q = 3, f(p, q) = 20.
* p = 4, q = 3, f(p, q) = 30.
* p = 1, q = 2, f(p, q) = 10.
* p = 2, q = 4, f(p, q) = 20.
* p = 4, q = 1, f(p, q) = 10.
Another 6 cases are symmetrical to the above. The average is <image>.
Consider the second sample. There are 6 possible situations:
* p = 1, q = 2, f(p, q) = 10.
* p = 2, q = 3, f(p, q) = 20.
* p = 1, q = 3, f(p, q) = 10.
Another 3 cases are symmetrical to the above. The average is <image>. | instruction | 0 | 3,735 | 1 | 7,470 |
Tags: dsu, sortings
Correct Solution:
```
def main():
n, m = map(int,input().split())
l = [int(i) for i in input().split()]
rank, ans = [], 0
for i in range(m):
a,b = map(int, input().split())
a,b = a-1,b-1
rank.append((min(l[a],l[b]),a,b))
rank = sorted(rank,key = lambda x: -x[0])
par = list(range(n))
siz = [1]*n
ans = 0.0
def find(a):
root = a
while root != par[root]: root = par[root]
while a != par[a]:
newp = par[a]
par[a] = root
a = newp
return root
def merge(a,b,i):
a = find(a)
b = find(b)
if a == b: return 0
add = siz[a]*siz[b]
siz[a] += siz[b]
par[b] = a
return (add * i[0]) / (n * (n - 1))
for i in rank:
ans += merge(i[1],i[2],i)
print("%.12f"%(2*ans))
if __name__ == "__main__":
main()
``` | output | 1 | 3,735 | 1 | 7,471 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Of course our child likes walking in a zoo. The zoo has n areas, that are numbered from 1 to n. The i-th area contains ai animals in it. Also there are m roads in the zoo, and each road connects two distinct areas. Naturally the zoo is connected, so you can reach any area of the zoo from any other area using the roads.
Our child is very smart. Imagine the child want to go from area p to area q. Firstly he considers all the simple routes from p to q. For each route the child writes down the number, that is equal to the minimum number of animals among the route areas. Let's denote the largest of the written numbers as f(p, q). Finally, the child chooses one of the routes for which he writes down the value f(p, q).
After the child has visited the zoo, he thinks about the question: what is the average value of f(p, q) for all pairs p, q (p β q)? Can you answer his question?
Input
The first line contains two integers n and m (2 β€ n β€ 105; 0 β€ m β€ 105). The second line contains n integers: a1, a2, ..., an (0 β€ ai β€ 105). Then follow m lines, each line contains two integers xi and yi (1 β€ xi, yi β€ n; xi β yi), denoting the road between areas xi and yi.
All roads are bidirectional, each pair of areas is connected by at most one road.
Output
Output a real number β the value of <image>.
The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 4.
Examples
Input
4 3
10 20 30 40
1 3
2 3
4 3
Output
16.666667
Input
3 3
10 20 30
1 2
2 3
3 1
Output
13.333333
Input
7 8
40 20 10 30 20 50 40
1 2
2 3
3 4
4 5
5 6
6 7
1 4
5 7
Output
18.571429
Note
Consider the first sample. There are 12 possible situations:
* p = 1, q = 3, f(p, q) = 10.
* p = 2, q = 3, f(p, q) = 20.
* p = 4, q = 3, f(p, q) = 30.
* p = 1, q = 2, f(p, q) = 10.
* p = 2, q = 4, f(p, q) = 20.
* p = 4, q = 1, f(p, q) = 10.
Another 6 cases are symmetrical to the above. The average is <image>.
Consider the second sample. There are 6 possible situations:
* p = 1, q = 2, f(p, q) = 10.
* p = 2, q = 3, f(p, q) = 20.
* p = 1, q = 3, f(p, q) = 10.
Another 3 cases are symmetrical to the above. The average is <image>. | instruction | 0 | 3,736 | 1 | 7,472 |
Tags: dsu, sortings
Correct Solution:
```
R = lambda:map(int, input().split())
n, m = R()
a = list(R())
p, f, sz =[], [], []
e = [[] for i in range(n)]
vis = [0] * n
ans = 0
def find(u):
if f[u] != u:
f[u] = find(f[u])
return f[u]
for i in range(n):
p.append([a[i], i])
f.append(i)
sz.append(1)
p.sort()
p.reverse()
for i in range(m):
u, v = R()
e[u - 1].append(v - 1)
e[v - 1].append(u - 1)
for i in range(n):
u = p[i][1]
for v in e[u]:
if (vis[v] and find(u) != find(v)):
pu, pv = u, v
if (sz[f[u]] > sz[f[v]]):
pu, pv = pv, pu
ans += p[i][0] * sz[f[pu]] * sz[f[pv]]
sz[f[pv]] += sz[f[pu]]
f[f[pu]] = f[pv]
vis[u] = 1
print("%.6f" %(2. * ans / n / (n - 1)))
``` | output | 1 | 3,736 | 1 | 7,473 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Of course our child likes walking in a zoo. The zoo has n areas, that are numbered from 1 to n. The i-th area contains ai animals in it. Also there are m roads in the zoo, and each road connects two distinct areas. Naturally the zoo is connected, so you can reach any area of the zoo from any other area using the roads.
Our child is very smart. Imagine the child want to go from area p to area q. Firstly he considers all the simple routes from p to q. For each route the child writes down the number, that is equal to the minimum number of animals among the route areas. Let's denote the largest of the written numbers as f(p, q). Finally, the child chooses one of the routes for which he writes down the value f(p, q).
After the child has visited the zoo, he thinks about the question: what is the average value of f(p, q) for all pairs p, q (p β q)? Can you answer his question?
Input
The first line contains two integers n and m (2 β€ n β€ 105; 0 β€ m β€ 105). The second line contains n integers: a1, a2, ..., an (0 β€ ai β€ 105). Then follow m lines, each line contains two integers xi and yi (1 β€ xi, yi β€ n; xi β yi), denoting the road between areas xi and yi.
All roads are bidirectional, each pair of areas is connected by at most one road.
Output
Output a real number β the value of <image>.
The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 4.
Examples
Input
4 3
10 20 30 40
1 3
2 3
4 3
Output
16.666667
Input
3 3
10 20 30
1 2
2 3
3 1
Output
13.333333
Input
7 8
40 20 10 30 20 50 40
1 2
2 3
3 4
4 5
5 6
6 7
1 4
5 7
Output
18.571429
Note
Consider the first sample. There are 12 possible situations:
* p = 1, q = 3, f(p, q) = 10.
* p = 2, q = 3, f(p, q) = 20.
* p = 4, q = 3, f(p, q) = 30.
* p = 1, q = 2, f(p, q) = 10.
* p = 2, q = 4, f(p, q) = 20.
* p = 4, q = 1, f(p, q) = 10.
Another 6 cases are symmetrical to the above. The average is <image>.
Consider the second sample. There are 6 possible situations:
* p = 1, q = 2, f(p, q) = 10.
* p = 2, q = 3, f(p, q) = 20.
* p = 1, q = 3, f(p, q) = 10.
Another 3 cases are symmetrical to the above. The average is <image>. | instruction | 0 | 3,737 | 1 | 7,474 |
Tags: dsu, sortings
Correct Solution:
```
read = lambda: map(int, input().split())
n, m = read()
v = list(read())
e = []
for i in range(m):
x, y = map(lambda x: int(x) - 1, input().split())
e.append((x, y, min(v[x], v[y])))
e.sort(key = lambda x: x[2], reverse = True)
belong = list(range(n))
union = [[i] for i in belong]
size = [1] * n
ans = 0
for i, j, k in e:
fi, fj = belong[i], belong[j];
if fi == fj: continue
if not (len(union[fi]) > len(union[fj])):
fi, fj = fj, fi
ans += k * size[fi] * size[fj]
size[fi] += size[fj]
union[fi] += union[fj]
for t in union[fj]: belong[t] = fi
print("%.7lf" % (ans * 2 / n / (n - 1)))
``` | output | 1 | 3,737 | 1 | 7,475 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Of course our child likes walking in a zoo. The zoo has n areas, that are numbered from 1 to n. The i-th area contains ai animals in it. Also there are m roads in the zoo, and each road connects two distinct areas. Naturally the zoo is connected, so you can reach any area of the zoo from any other area using the roads.
Our child is very smart. Imagine the child want to go from area p to area q. Firstly he considers all the simple routes from p to q. For each route the child writes down the number, that is equal to the minimum number of animals among the route areas. Let's denote the largest of the written numbers as f(p, q). Finally, the child chooses one of the routes for which he writes down the value f(p, q).
After the child has visited the zoo, he thinks about the question: what is the average value of f(p, q) for all pairs p, q (p β q)? Can you answer his question?
Input
The first line contains two integers n and m (2 β€ n β€ 105; 0 β€ m β€ 105). The second line contains n integers: a1, a2, ..., an (0 β€ ai β€ 105). Then follow m lines, each line contains two integers xi and yi (1 β€ xi, yi β€ n; xi β yi), denoting the road between areas xi and yi.
All roads are bidirectional, each pair of areas is connected by at most one road.
Output
Output a real number β the value of <image>.
The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 4.
Examples
Input
4 3
10 20 30 40
1 3
2 3
4 3
Output
16.666667
Input
3 3
10 20 30
1 2
2 3
3 1
Output
13.333333
Input
7 8
40 20 10 30 20 50 40
1 2
2 3
3 4
4 5
5 6
6 7
1 4
5 7
Output
18.571429
Note
Consider the first sample. There are 12 possible situations:
* p = 1, q = 3, f(p, q) = 10.
* p = 2, q = 3, f(p, q) = 20.
* p = 4, q = 3, f(p, q) = 30.
* p = 1, q = 2, f(p, q) = 10.
* p = 2, q = 4, f(p, q) = 20.
* p = 4, q = 1, f(p, q) = 10.
Another 6 cases are symmetrical to the above. The average is <image>.
Consider the second sample. There are 6 possible situations:
* p = 1, q = 2, f(p, q) = 10.
* p = 2, q = 3, f(p, q) = 20.
* p = 1, q = 3, f(p, q) = 10.
Another 3 cases are symmetrical to the above. The average is <image>. | instruction | 0 | 3,738 | 1 | 7,476 |
Tags: dsu, sortings
Correct Solution:
```
n, m = map(int, input().split())
p, c = list(range(n + 1)), [1] * (n + 1)
v = [0] + list(map(int, input().split()))
s, e = 0, [()] * m
for i in range(m):
x, y = map(int, input().split())
e[i] = (x, y, min(v[x], v[y]))
e.sort(key = lambda x: x[2], reverse = True)
q = [[i] for i in range(n + 1)]
for l, r, v in e:
l, r = p[l], p[r]
if l == r: continue
if len(q[l]) > len(q[r]): l, r = r, l
q[r].extend(q[l])
for t in q[l]: p[t] = r
s += c[l] * c[r] * v
c[r] += c[l]
print(s * 2 / (n * (n - 1)))
# Made By Mostafa_Khaled
``` | output | 1 | 3,738 | 1 | 7,477 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Motorist Kojiro spent 10 years saving up for his favorite car brand, Furrari. Finally Kojiro's dream came true! Kojiro now wants to get to his girlfriend Johanna to show off his car to her.
Kojiro wants to get to his girlfriend, so he will go to her along a coordinate line. For simplicity, we can assume that Kojiro is at the point f of a coordinate line, and Johanna is at point e. Some points of the coordinate line have gas stations. Every gas station fills with only one type of fuel: Regular-92, Premium-95 or Super-98. Thus, each gas station is characterized by a pair of integers ti and xi β the number of the gas type and its position.
One liter of fuel is enough to drive for exactly 1 km (this value does not depend on the type of fuel). Fuels of three types differ only in quality, according to the research, that affects the lifetime of the vehicle motor. A Furrari tank holds exactly s liters of fuel (regardless of the type of fuel). At the moment of departure from point f Kojiro's tank is completely filled with fuel Super-98. At each gas station Kojiro can fill the tank with any amount of fuel, but of course, at no point in time, the amount of fuel in the tank can be more than s liters. Note that the tank can simultaneously have different types of fuel. The car can moves both left and right.
To extend the lifetime of the engine Kojiro seeks primarily to minimize the amount of fuel of type Regular-92. If there are several strategies to go from f to e, using the minimum amount of fuel of type Regular-92, it is necessary to travel so as to minimize the amount of used fuel of type Premium-95.
Write a program that can for the m possible positions of the start fi minimize firstly, the amount of used fuel of type Regular-92 and secondly, the amount of used fuel of type Premium-95.
Input
The first line of the input contains four positive integers e, s, n, m (1 β€ e, s β€ 109, 1 β€ n, m β€ 2Β·105) β the coordinate of the point where Johanna is, the capacity of a Furrari tank, the number of gas stations and the number of starting points.
Next n lines contain two integers each ti, xi (1 β€ ti β€ 3, - 109 β€ xi β€ 109), representing the type of the i-th gas station (1 represents Regular-92, 2 β Premium-95 and 3 β Super-98) and the position on a coordinate line of the i-th gas station. Gas stations don't necessarily follow in order from left to right.
The last line contains m integers fi ( - 109 β€ fi < e). Start positions don't necessarily follow in order from left to right.
No point of the coordinate line contains more than one gas station. It is possible that some of points fi or point e coincide with a gas station.
Output
Print exactly m lines. The i-th of them should contain two integers β the minimum amount of gas of type Regular-92 and type Premium-95, if Kojiro starts at point fi. First you need to minimize the first value. If there are multiple ways to do it, you need to also minimize the second value.
If there is no way to get to Johanna from point fi, the i-th line should look like that "-1 -1" (two numbers minus one without the quotes).
Examples
Input
8 4 1 1
2 4
0
Output
0 4
Input
9 3 2 3
2 3
1 6
-1 0 1
Output
-1 -1
3 3
3 2
Input
20 9 2 4
1 5
2 10
-1 0 1 2
Output
-1 -1
-1 -1
-1 -1
-1 -1 | instruction | 0 | 3,775 | 1 | 7,550 |
Tags: dp, greedy
Correct Solution:
```
import os,io
input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
e,s,n,m=map(int,input().split())
fuel1=[]
fuel2=[]
fuel3=[]
keymoments=[]
for i in range(n):
t,x=map(int,input().split())
if t==1:
fuel1.append(x)
if t==2:
fuel2.append(x)
if t==3:
fuel3.append(x)
keymoments.append(x)
keymoments.append(x+s)
fuel1.sort()
fuel2.sort()
fuel3.sort()
keymoments.sort()
pointer1=-1
pointer2=-1
pointer3=-1
last1=-10**9-1
last2=-10**9-1
last3=-10**9-1
keymoments2=[]
lastmoment=-10**9-1
for moment in keymoments:
if moment==lastmoment:
continue
lastmoment=moment
while pointer1+1<len(fuel1) and fuel1[pointer1+1]<=moment:
last1=fuel1[pointer1+1]
pointer1+=1
while pointer2+1<len(fuel2) and fuel2[pointer2+1]<=moment:
last2=fuel2[pointer2+1]
pointer2+=1
while pointer3+1<len(fuel3) and fuel3[pointer3+1]<=moment:
last3=fuel3[pointer3+1]
pointer3+=1
if pointer3!=-1 and moment<s+last3:
keymoments2.append([moment,3])
elif pointer2!=-1 and moment<s+last2:
keymoments2.append([moment,2])
elif pointer1!=-1 and moment<s+last1:
keymoments2.append([moment,1])
else:
keymoments2.append([moment,-1])
keymoments3=[]
start=10**9
for i in range(len(keymoments2)-1,-1,-1):
if e>keymoments2[i][0]:
start=i
break
if not start==10**9:
fuel1use=0
fuel2use=0
if keymoments2[start][1]==1:
fuel1use+=e-keymoments2[start][0]
elif keymoments2[start][1]==2:
fuel2use+=e-keymoments2[start][0]
elif keymoments2[start][1]==-1:
fuel1use=-1
fuel2use=-1
moment=keymoments2[start][0]
keymoments3.append([moment,fuel1use,fuel2use])
for i in range(start-1,-1,-1):
moment=keymoments2[i][0]
if fuel1use==-1:
keymoments3.append([moment,-1,-1])
continue
time=keymoments2[i+1][0]-moment
if time>s:
fuel1use=-1
fuel2use=-1
keymoments3.append([moment,-1,-1])
continue
if keymoments2[i][1]==1:
fuel1use+=time
elif keymoments2[i][1]==2:
fuel2use+=time
elif keymoments2[i][1]==-1:
fuel1use=-1
fuel2use=-1
keymoments3.append([moment,fuel1use,fuel2use])
keymoments3.reverse()
f=list(map(int,input().split()))
for i in range(m):
if f[i]+s>=e:
print(0,0)
continue
if not keymoments3:
print(-1,-1)
continue
if f[i]+s<keymoments3[0][0]:
print(-1,-1)
continue
l=0
r=len(keymoments3)-1
while l<r:
if l+1==r:
try1=r
else:
try1=(l+r)//2
if f[i]+s>=keymoments2[try1][0]:
l=try1
else:
if l+1==r:
l=l
break
r=try1
ans1=keymoments3[l][1]
ans2=keymoments3[l][2]
if ans1!=-1 and keymoments2[l][1]==1:
ans1+=keymoments3[l][0]-(f[i]+s)
elif ans2!=-1 and keymoments2[l][1]==2:
ans2+=keymoments3[l][0]-(f[i]+s)
print(ans1,ans2)
``` | output | 1 | 3,775 | 1 | 7,551 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Motorist Kojiro spent 10 years saving up for his favorite car brand, Furrari. Finally Kojiro's dream came true! Kojiro now wants to get to his girlfriend Johanna to show off his car to her.
Kojiro wants to get to his girlfriend, so he will go to her along a coordinate line. For simplicity, we can assume that Kojiro is at the point f of a coordinate line, and Johanna is at point e. Some points of the coordinate line have gas stations. Every gas station fills with only one type of fuel: Regular-92, Premium-95 or Super-98. Thus, each gas station is characterized by a pair of integers ti and xi β the number of the gas type and its position.
One liter of fuel is enough to drive for exactly 1 km (this value does not depend on the type of fuel). Fuels of three types differ only in quality, according to the research, that affects the lifetime of the vehicle motor. A Furrari tank holds exactly s liters of fuel (regardless of the type of fuel). At the moment of departure from point f Kojiro's tank is completely filled with fuel Super-98. At each gas station Kojiro can fill the tank with any amount of fuel, but of course, at no point in time, the amount of fuel in the tank can be more than s liters. Note that the tank can simultaneously have different types of fuel. The car can moves both left and right.
To extend the lifetime of the engine Kojiro seeks primarily to minimize the amount of fuel of type Regular-92. If there are several strategies to go from f to e, using the minimum amount of fuel of type Regular-92, it is necessary to travel so as to minimize the amount of used fuel of type Premium-95.
Write a program that can for the m possible positions of the start fi minimize firstly, the amount of used fuel of type Regular-92 and secondly, the amount of used fuel of type Premium-95.
Input
The first line of the input contains four positive integers e, s, n, m (1 β€ e, s β€ 109, 1 β€ n, m β€ 2Β·105) β the coordinate of the point where Johanna is, the capacity of a Furrari tank, the number of gas stations and the number of starting points.
Next n lines contain two integers each ti, xi (1 β€ ti β€ 3, - 109 β€ xi β€ 109), representing the type of the i-th gas station (1 represents Regular-92, 2 β Premium-95 and 3 β Super-98) and the position on a coordinate line of the i-th gas station. Gas stations don't necessarily follow in order from left to right.
The last line contains m integers fi ( - 109 β€ fi < e). Start positions don't necessarily follow in order from left to right.
No point of the coordinate line contains more than one gas station. It is possible that some of points fi or point e coincide with a gas station.
Output
Print exactly m lines. The i-th of them should contain two integers β the minimum amount of gas of type Regular-92 and type Premium-95, if Kojiro starts at point fi. First you need to minimize the first value. If there are multiple ways to do it, you need to also minimize the second value.
If there is no way to get to Johanna from point fi, the i-th line should look like that "-1 -1" (two numbers minus one without the quotes).
Examples
Input
8 4 1 1
2 4
0
Output
0 4
Input
9 3 2 3
2 3
1 6
-1 0 1
Output
-1 -1
3 3
3 2
Input
20 9 2 4
1 5
2 10
-1 0 1 2
Output
-1 -1
-1 -1
-1 -1
-1 -1
Submitted Solution:
```
from bisect import bisect_left
def gas(e, s, n, m, G, F):
G.append((e, 0))
G.sort()
while G[-1][0] > e:
G.pop()
D = [None for _ in range(len(G))]
I = [None for _ in range(len(G))]
T = [None for _ in range(len(G))]
def gf(f, g, i):
if D[i] is None:
# log(f, g, i, "Too far")
return -1, -1
x, t = G[i]
g -= (x - f)
if g < 0:
# log(f, g, i, "Too far")
return -1, -1
if t == 0:
# log(f, g, i, "End")
return T[i]
elif t == 3:
# log(f, g, i, "S98")
return T[i]
elif t == 2:
if D[i][2] <= g:
# log(f, g, i, "P95 skip")
return gf(x, g, I[i][2])
elif D[i][2] <= s:
# log(f, g, i, "P95 -> S98")
t1, t2 = gf(x, D[i][2], I[i][2])
return t1, t2 + D[i][2] - g
else:
# log(f, g, i, "P95 fill", s - g)
t1, t2 = T[i]
return t1, t2 + s - g
elif t == 1:
if D[i][1] <= g:
# log(f, g, i, "R92 skip")
return gf(x, g, I[i][1])
elif D[i][1] <= s:
if D[i][2] == D[i][1]:
# log(f, g, i, "R92 -> S98", D[i][2] - g)
t1, t2 = gf(x, D[i][2], I[i][2])
return t1 + D[i][2] - g, t2
else:
# log(f, g, i, "R92 -> P95", D[i][1] - g)
t1, t2 = gf(x, D[i][1], I[i][1])
return t1 + D[i][1] - g, t2
else:
# log(f, g, i, "R92 fill", s - g)
t1, t2 = T[i]
return t1 + s - g, t2
x1 = x2 = x3 = e
i1 = i2 = i3 = len(G)-1
for i in reversed(range(len(G))):
x, t = G[i]
if t == 0:
D[i] = 0, 0, 0
T[i] = 0, 0
continue
d3 = x3 - x
d2 = min(d3, x2 - x)
d1 = min(d2, x1 - x)
if d1 > s: # Too far
break
D[i] = d1, d2, d3
I[i] = i1, i2, i3
if d3 <= s:
T[i] = gf(x, s, i3)
elif d2 <= s:
T[i] = gf(x, s, i2)
else:
T[i] = gf(x, s, i1)
if t == 1:
x1 = x
i1 = i
elif t == 2:
x2 = x
i2 = i
elif t == 3:
x3 = x
i3 = i
for f in F:
# log(">", f)
result = gf(f, s, bisect_left(G, (f, 0)))
# log("<", result)
yield result
def gs():
t, x = map(int, input().split())
return x, t
def main():
e, s, n, m = map(int, input().split())
G = [gs() for _ in range(n)]
F = list(map(int, input().split()))
assert len(F) == m
print('\n'.join(f'{i} {j}' for i, j in gas(e, s, n, m, G, F)))
##########
import sys
import time
import traceback
from contextlib import contextmanager
from io import StringIO
def log(*args, **kwargs):
print(*args, **kwargs, file=sys.stderr)
@contextmanager
def patchio(i):
try:
sys.stdin = StringIO(i)
sys.stdout = StringIO()
yield sys.stdout
finally:
sys.stdin = sys.__stdin__
sys.stdout = sys.__stdout__
def do_test(k, test):
try:
log(f"TEST {k}")
i, o = test
with patchio(i) as r:
t0 = time.time()
main()
t1 = time.time()
if r.getvalue() == o:
log(f"OK ({int((t1-t0)*1000000)/1000:0.3f} ms)\n")
else:
log(f"Expected:\n{o}"
f"Got ({int((t1-t0)*1000000)/1000:0.3f} ms):\n{r.getvalue()}")
except Exception:
traceback.print_exc()
log()
def test(ts):
for k in ts or range(len(tests)):
do_test(k, tests[k])
tests = [("""\
8 4 1 1
2 4
0
""", """\
0 4
"""), ("""\
9 3 2 3
2 3
1 6
-1 0 1
""", """\
-1 -1
3 3
3 2
"""), ("""\
20 9 2 4
1 5
2 10
-1 0 1 2
""", """\
-1 -1
-1 -1
-1 -1
-1 -1
"""), ("""\
18 9 2 1
2 9
1 12
0
""", """\
0 9
"""), ("""\
18 9 2 1
1 9
2 12
0
""", """\
3 6
"""), ("""\
9 3 2 1
2 3
1 6
0
""", """\
3 3
"""), ("""\
67 10 9 10
3 -1
1 59
1 39
1 -11
2 29
1 9
1 19
1 49
3 77
27 14 21 36 0 13 57 41 20 28
""", """\
28 2
33 10
28 8
21 0
47 10
34 10
0 0
16 0
28 9
28 1
"""), ("""\
216 15 19 10
2 -31
2 100
3 230
1 57
3 42
1 157
2 186
1 113
2 -16
3 245
2 142
1 86
2 -3
3 201
3 128
3 12
3 171
2 27
2 72
98 197 114 0 155 35 36 11 146 27
""", """\
27 31
0 0
14 29
55 74
1 15
55 59
55 59
55 74
10 15
55 59
""")]
if __name__ == '__main__':
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('--test', '-t', type=int, nargs='*')
args = parser.parse_args()
main() if args.test is None else test(args.test)
``` | instruction | 0 | 3,776 | 1 | 7,552 |
No | output | 1 | 3,776 | 1 | 7,553 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Motorist Kojiro spent 10 years saving up for his favorite car brand, Furrari. Finally Kojiro's dream came true! Kojiro now wants to get to his girlfriend Johanna to show off his car to her.
Kojiro wants to get to his girlfriend, so he will go to her along a coordinate line. For simplicity, we can assume that Kojiro is at the point f of a coordinate line, and Johanna is at point e. Some points of the coordinate line have gas stations. Every gas station fills with only one type of fuel: Regular-92, Premium-95 or Super-98. Thus, each gas station is characterized by a pair of integers ti and xi β the number of the gas type and its position.
One liter of fuel is enough to drive for exactly 1 km (this value does not depend on the type of fuel). Fuels of three types differ only in quality, according to the research, that affects the lifetime of the vehicle motor. A Furrari tank holds exactly s liters of fuel (regardless of the type of fuel). At the moment of departure from point f Kojiro's tank is completely filled with fuel Super-98. At each gas station Kojiro can fill the tank with any amount of fuel, but of course, at no point in time, the amount of fuel in the tank can be more than s liters. Note that the tank can simultaneously have different types of fuel. The car can moves both left and right.
To extend the lifetime of the engine Kojiro seeks primarily to minimize the amount of fuel of type Regular-92. If there are several strategies to go from f to e, using the minimum amount of fuel of type Regular-92, it is necessary to travel so as to minimize the amount of used fuel of type Premium-95.
Write a program that can for the m possible positions of the start fi minimize firstly, the amount of used fuel of type Regular-92 and secondly, the amount of used fuel of type Premium-95.
Input
The first line of the input contains four positive integers e, s, n, m (1 β€ e, s β€ 109, 1 β€ n, m β€ 2Β·105) β the coordinate of the point where Johanna is, the capacity of a Furrari tank, the number of gas stations and the number of starting points.
Next n lines contain two integers each ti, xi (1 β€ ti β€ 3, - 109 β€ xi β€ 109), representing the type of the i-th gas station (1 represents Regular-92, 2 β Premium-95 and 3 β Super-98) and the position on a coordinate line of the i-th gas station. Gas stations don't necessarily follow in order from left to right.
The last line contains m integers fi ( - 109 β€ fi < e). Start positions don't necessarily follow in order from left to right.
No point of the coordinate line contains more than one gas station. It is possible that some of points fi or point e coincide with a gas station.
Output
Print exactly m lines. The i-th of them should contain two integers β the minimum amount of gas of type Regular-92 and type Premium-95, if Kojiro starts at point fi. First you need to minimize the first value. If there are multiple ways to do it, you need to also minimize the second value.
If there is no way to get to Johanna from point fi, the i-th line should look like that "-1 -1" (two numbers minus one without the quotes).
Examples
Input
8 4 1 1
2 4
0
Output
0 4
Input
9 3 2 3
2 3
1 6
-1 0 1
Output
-1 -1
3 3
3 2
Input
20 9 2 4
1 5
2 10
-1 0 1 2
Output
-1 -1
-1 -1
-1 -1
-1 -1
Submitted Solution:
```
import os,io
input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
e,s,n,m=map(int,input().split())
fuel1=[]
fuel2=[]
fuel3=[]
keymoments=[]
for i in range(n):
t,x=map(int,input().split())
if t==1:
fuel1.append(x)
if t==2:
fuel2.append(x)
if t==3:
fuel3.append(x)
keymoments.append(x)
keymoments.append(x+s)
fuel1.sort()
fuel2.sort()
fuel3.sort()
keymoments.sort()
pointer1=-1
pointer2=-1
pointer3=-1
last1=-10**9-1
last2=-10**9-1
last3=-10**9-1
keymoments2=[]
lastmoment=-10**9-1
for moment in keymoments:
if moment==lastmoment:
continue
lastmoment=moment
while pointer1+1<len(fuel1) and fuel1[pointer1+1]<=moment:
last1=fuel1[pointer1+1]
pointer1+=1
while pointer2+1<len(fuel2) and fuel2[pointer2+1]<=moment:
last2=fuel2[pointer2+1]
pointer2+=1
while pointer3+1<len(fuel3) and fuel3[pointer3+1]<=moment:
last3=fuel3[pointer3+1]
pointer3+=1
if pointer3!=-1 and moment<s+last3:
keymoments2.append([moment,3])
elif pointer2!=-1 and moment<s+last2:
keymoments2.append([moment,2])
elif pointer1!=-1 and moment<s+last1:
keymoments2.append([moment,1])
else:
keymoments2.append([moment,-1])
keymoments3=[]
start=10**9
for i in range(len(keymoments2)-1,-1,-1):
if e>keymoments2[i][0]:
start=i
break
if not start==10**9:
fuel1use=0
fuel2use=0
if keymoments2[start][1]==1:
fuel1use+=e-keymoments2[start][0]
elif keymoments2[start][1]==2:
fuel2use+=e-keymoments2[start][0]
elif keymoments2[start][1]==-1:
fuel1use=-1
fuel2use=-1
moment=keymoments2[start][0]
keymoments3.append([moment,fuel1use,fuel2use])
for i in range(start-1,-1,-1):
moment=keymoments2[i][0]
if fuel1use==-1:
keymoments3.append([moment,-1,-1])
continue
time=keymoments2[i+1][0]-moment
if time>s:
fuel1use==-1
fuel2use==-1
keymoments3.append([moment,-1,-1])
continue
if keymoments2[i][1]==1:
fuel1use+=time
elif keymoments2[i][1]==2:
fuel2use+=time
keymoments3.append([moment,fuel1use,fuel2use])
keymoments3.reverse()
f=list(map(int,input().split()))
for i in range(m):
if f[i]+s>=e:
print(0,0)
continue
if not keymoments3:
print(-1,-1)
continue
if f[i]+s<keymoments3[0][0]:
print(-1,-1)
continue
l=0
r=len(keymoments3)-1
while l<r:
if l+1==r:
try1=r
else:
try1=(l+r)//2
if f[i]+s>=keymoments2[try1][0]:
l=try1
else:
if l+1==r:
l=l
break
r=try1
ans1=keymoments3[l][1]
ans2=keymoments3[l][2]
if ans1!=-1 and keymoments2[l][1]==1:
ans1+=keymoments3[l][0]-(f[i]+s)
elif ans2!=-1 and keymoments2[l][1]==2:
ans2+=keymoments3[l][0]-(f[i]+s)
print(ans1,ans2)
``` | instruction | 0 | 3,777 | 1 | 7,554 |
No | output | 1 | 3,777 | 1 | 7,555 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Motorist Kojiro spent 10 years saving up for his favorite car brand, Furrari. Finally Kojiro's dream came true! Kojiro now wants to get to his girlfriend Johanna to show off his car to her.
Kojiro wants to get to his girlfriend, so he will go to her along a coordinate line. For simplicity, we can assume that Kojiro is at the point f of a coordinate line, and Johanna is at point e. Some points of the coordinate line have gas stations. Every gas station fills with only one type of fuel: Regular-92, Premium-95 or Super-98. Thus, each gas station is characterized by a pair of integers ti and xi β the number of the gas type and its position.
One liter of fuel is enough to drive for exactly 1 km (this value does not depend on the type of fuel). Fuels of three types differ only in quality, according to the research, that affects the lifetime of the vehicle motor. A Furrari tank holds exactly s liters of fuel (regardless of the type of fuel). At the moment of departure from point f Kojiro's tank is completely filled with fuel Super-98. At each gas station Kojiro can fill the tank with any amount of fuel, but of course, at no point in time, the amount of fuel in the tank can be more than s liters. Note that the tank can simultaneously have different types of fuel. The car can moves both left and right.
To extend the lifetime of the engine Kojiro seeks primarily to minimize the amount of fuel of type Regular-92. If there are several strategies to go from f to e, using the minimum amount of fuel of type Regular-92, it is necessary to travel so as to minimize the amount of used fuel of type Premium-95.
Write a program that can for the m possible positions of the start fi minimize firstly, the amount of used fuel of type Regular-92 and secondly, the amount of used fuel of type Premium-95.
Input
The first line of the input contains four positive integers e, s, n, m (1 β€ e, s β€ 109, 1 β€ n, m β€ 2Β·105) β the coordinate of the point where Johanna is, the capacity of a Furrari tank, the number of gas stations and the number of starting points.
Next n lines contain two integers each ti, xi (1 β€ ti β€ 3, - 109 β€ xi β€ 109), representing the type of the i-th gas station (1 represents Regular-92, 2 β Premium-95 and 3 β Super-98) and the position on a coordinate line of the i-th gas station. Gas stations don't necessarily follow in order from left to right.
The last line contains m integers fi ( - 109 β€ fi < e). Start positions don't necessarily follow in order from left to right.
No point of the coordinate line contains more than one gas station. It is possible that some of points fi or point e coincide with a gas station.
Output
Print exactly m lines. The i-th of them should contain two integers β the minimum amount of gas of type Regular-92 and type Premium-95, if Kojiro starts at point fi. First you need to minimize the first value. If there are multiple ways to do it, you need to also minimize the second value.
If there is no way to get to Johanna from point fi, the i-th line should look like that "-1 -1" (two numbers minus one without the quotes).
Examples
Input
8 4 1 1
2 4
0
Output
0 4
Input
9 3 2 3
2 3
1 6
-1 0 1
Output
-1 -1
3 3
3 2
Input
20 9 2 4
1 5
2 10
-1 0 1 2
Output
-1 -1
-1 -1
-1 -1
-1 -1
Submitted Solution:
```
from bisect import bisect_right
def gas(e, s, n, m, G, F):
G.append((e, 0))
G.sort()
while G[-1][0] > e:
G.pop()
D = [None for _ in range(len(G))]
I = [None for _ in range(len(G))]
T = [None for _ in range(len(G))]
x1 = x2 = x3 = e
i1 = i2 = i3 = len(G)-1
for i in reversed(range(len(G))):
x, t = G[i]
if t == 0:
D[i] = 0, 0, 0
T[i] = 0, 0
continue
d3 = x3 - x
d2 = min(d3, x2 - x)
d1 = min(d2, x1 - x)
if d1 > s: # Too far
break
D[i] = d1, d2, d3
I[i] = i1, i2, i3
if d3 <= s:
T[i] = T[i3]
elif d2 <= s:
if D[i2][2] <= s:
s2 = s - d2
T[i] = T[i3][0], T[i3][1] + D[i2][2] - s2
else:
T[i] = T[i2][0], T[i2][1] + d2
else:
if D[i1][1] <= s:
s1 = s - d1
if D[i1][2] == D[i1][1]:
T[i] = T[i3][0] + D[i1][2] - s1, T[i3][1]
else:
if D[i2][2] <= s:
T[i] = (T[i3][0] + D[i1][1] - s1,
T[i3][1] + D[i2][2])
else:
T[i] = T[i2][0] + d1, T[i2][1] + s
else:
T[i] = T[i1][0] + d1, T[i1][1]
if t == 1:
x1 = x
i1 = i
elif t == 2:
x2 = x
i2 = i
elif t == 3:
x3 = x
i3 = i
def gf(f, g, i):
if D[i] is None:
# log(f, g, i, "Too far")
return -1, -1
x, t = G[i]
g -= (x - f)
if g < 0:
# log(f, g, i, "Too far")
return -1, -1
if t == 0:
# log(f, g, i, "End")
return T[i]
elif t == 3:
# log(f, g, i, "S98")
return T[i]
elif t == 2:
if D[i][2] <= g:
# log(f, g, i, "P95 skip")
return gf(x, g, I[i][2])
elif D[i][2] <= s:
# log(f, g, i, "P95 -> S98")
t1, t2 = gf(x, D[i][2], I[i][2])
return t1, t2 + D[i][2] - g
else:
# log(f, g, i, "P95 fill", s - g)
t1, t2 = T[i]
return t1, t2 + s - g
elif t == 1:
if D[i][1] <= g:
# log(f, g, i, "R92 skip")
return gf(x, g, I[i][1])
elif D[i][1] <= s:
if D[i][2] == D[i][1]:
# log(f, g, i, "R92 -> S98", D[i][2] - g)
t1, t2 = gf(x, D[i][2], I[i][2])
return t1 + D[i][2] - g, t2
else:
# log(f, g, i, "R92 -> P95", D[i][1] - g)
t1, t2 = gf(x, D[i][1], I[i][1])
return t1 + D[i][1] - g, t2
else:
# log(f, g, i, "R92 fill", s - g)
t1, t2 = T[i]
return t1 + s - g, t2
for f in F:
# log(">", f)
result = gf(f, s, bisect_right(G, (f, 4)))
# log("<", result)
yield result
def gs():
t, x = map(int, input().split())
return x, t
def main():
e, s, n, m = map(int, input().split())
G = [gs() for _ in range(n)]
F = list(map(int, input().split()))
assert len(F) == m
print('\n'.join(f'{i} {j}' for i, j in gas(e, s, n, m, G, F)))
##########
import sys
import time
import traceback
from contextlib import contextmanager
from io import StringIO
def log(*args, **kwargs):
print(*args, **kwargs, file=sys.stderr)
@contextmanager
def patchio(i):
try:
sys.stdin = StringIO(i)
sys.stdout = StringIO()
yield sys.stdout
finally:
sys.stdin = sys.__stdin__
sys.stdout = sys.__stdout__
def do_test(k, test):
try:
log(f"TEST {k}")
i, o = test
with patchio(i) as r:
t0 = time.time()
main()
t1 = time.time()
if r.getvalue() == o:
log(f"OK ({int((t1-t0)*1000000)/1000:0.3f} ms)\n")
else:
log(f"Expected:\n{o}"
f"Got ({int((t1-t0)*1000000)/1000:0.3f} ms):\n{r.getvalue()}")
except Exception:
traceback.print_exc()
log()
def test(ts):
for k in ts or range(len(tests)):
do_test(k, tests[k])
tests = [("""\
8 4 1 1
2 4
0
""", """\
0 4
"""), ("""\
9 3 2 3
2 3
1 6
-1 0 1
""", """\
-1 -1
3 3
3 2
"""), ("""\
20 9 2 4
1 5
2 10
-1 0 1 2
""", """\
-1 -1
-1 -1
-1 -1
-1 -1
""")]
if __name__ == '__main__':
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('--test', '-t', type=int, nargs='*')
args = parser.parse_args()
main() if args.test is None else test(args.test)
``` | instruction | 0 | 3,778 | 1 | 7,556 |
No | output | 1 | 3,778 | 1 | 7,557 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Motorist Kojiro spent 10 years saving up for his favorite car brand, Furrari. Finally Kojiro's dream came true! Kojiro now wants to get to his girlfriend Johanna to show off his car to her.
Kojiro wants to get to his girlfriend, so he will go to her along a coordinate line. For simplicity, we can assume that Kojiro is at the point f of a coordinate line, and Johanna is at point e. Some points of the coordinate line have gas stations. Every gas station fills with only one type of fuel: Regular-92, Premium-95 or Super-98. Thus, each gas station is characterized by a pair of integers ti and xi β the number of the gas type and its position.
One liter of fuel is enough to drive for exactly 1 km (this value does not depend on the type of fuel). Fuels of three types differ only in quality, according to the research, that affects the lifetime of the vehicle motor. A Furrari tank holds exactly s liters of fuel (regardless of the type of fuel). At the moment of departure from point f Kojiro's tank is completely filled with fuel Super-98. At each gas station Kojiro can fill the tank with any amount of fuel, but of course, at no point in time, the amount of fuel in the tank can be more than s liters. Note that the tank can simultaneously have different types of fuel. The car can moves both left and right.
To extend the lifetime of the engine Kojiro seeks primarily to minimize the amount of fuel of type Regular-92. If there are several strategies to go from f to e, using the minimum amount of fuel of type Regular-92, it is necessary to travel so as to minimize the amount of used fuel of type Premium-95.
Write a program that can for the m possible positions of the start fi minimize firstly, the amount of used fuel of type Regular-92 and secondly, the amount of used fuel of type Premium-95.
Input
The first line of the input contains four positive integers e, s, n, m (1 β€ e, s β€ 109, 1 β€ n, m β€ 2Β·105) β the coordinate of the point where Johanna is, the capacity of a Furrari tank, the number of gas stations and the number of starting points.
Next n lines contain two integers each ti, xi (1 β€ ti β€ 3, - 109 β€ xi β€ 109), representing the type of the i-th gas station (1 represents Regular-92, 2 β Premium-95 and 3 β Super-98) and the position on a coordinate line of the i-th gas station. Gas stations don't necessarily follow in order from left to right.
The last line contains m integers fi ( - 109 β€ fi < e). Start positions don't necessarily follow in order from left to right.
No point of the coordinate line contains more than one gas station. It is possible that some of points fi or point e coincide with a gas station.
Output
Print exactly m lines. The i-th of them should contain two integers β the minimum amount of gas of type Regular-92 and type Premium-95, if Kojiro starts at point fi. First you need to minimize the first value. If there are multiple ways to do it, you need to also minimize the second value.
If there is no way to get to Johanna from point fi, the i-th line should look like that "-1 -1" (two numbers minus one without the quotes).
Examples
Input
8 4 1 1
2 4
0
Output
0 4
Input
9 3 2 3
2 3
1 6
-1 0 1
Output
-1 -1
3 3
3 2
Input
20 9 2 4
1 5
2 10
-1 0 1 2
Output
-1 -1
-1 -1
-1 -1
-1 -1
Submitted Solution:
```
from bisect import bisect_right
def gas(e, s, n, m, G, F):
G.append((e, 0))
G.sort()
while G[-1][0] > e:
G.pop()
D = [None for _ in range(len(G))]
I = [None for _ in range(len(G))]
T = [None for _ in range(len(G))]
x1 = x2 = x3 = e
i1 = i2 = i3 = len(G)-1
for i in reversed(range(len(G))):
x, t = G[i]
if t == 0:
D[i] = 0, 0, 0
T[i] = 0, 0
continue
d3 = x3 - x
d2 = min(d3, x2 - x)
d1 = min(d2, x1 - x)
if d1 > s: # Too far
break
D[i] = d1, d2, d3
I[i] = i1, i2, i3
if d3 <= s:
T[i] = T[i3]
elif d2 <= s:
if D[i2][2] <= s:
s2 = s - d2
T[i] = T[i3][0], T[i3][1] + D[i2][2] - s2
else:
T[i] = T[i2][0], T[i2][1] + d2
else:
if D[i1][1] <= s:
s1 = s - d1
if D[i1][2] == D[i1][1]:
T[i] = T[i3][0] + D[i1][2] - s1, T[i3][1]
else:
if D[i2][2] <= s:
T[i] = (T[i3][0] + D[i1][1] - s1,
T[i3][1] + D[i2][2])
else:
T[i] = T[i2][0] + d1, T[i2][1] + s
else:
T[i] = T[i1][0] + d1, T[i1][1]
if t == 1:
x1 = x
i1 = i
elif t == 2:
x2 = x
i2 = i
elif t == 3:
x3 = x
i3 = i
def gf(f, g, i):
if D[i] is None:
return -1, -1
x, t = G[i]
g -= (x - f)
if g < 0:
return -1, -1
if t == 0 or t == 3:
return T[i]
elif t == 2:
if D[i][2] <= g:
return gf(x, g, I[i][2])
elif D[i][2] <= s:
t1, t2 = gf(x, D[i][2], I[i][2])
return t1, t2 + D[i][2] - g
else:
t1, t2 = T[i]
return t1, t2 + s - g
elif t == 1:
if D[i][2] <= g:
return gf(x, g, I[i][2])
elif D[i][1] <= g:
return gf(x, g, I[i][1])
elif D[i][1] <= s:
if D[i][2] == D[i][1]:
t1, t2 = gf(x, D[i][2], I[i][2])
return t1 + D[i][2] - g, t2
else:
t1, t2 = gf(x, D[i][1], I[i][1])
return t1 + D[i][1] - g, t2
else:
t1, t2 = T[i]
return t1 + s - g, t2
for f in F:
yield gf(f, s, i)
def gs():
t, x = map(int, input().split())
return x, t
def main():
e, s, n, m = map(int, input().split())
G = [gs() for _ in range(n)]
F = list(map(int, input().split()))
assert len(F) == m
print('\n'.join(f'{i} {j}' for i, j in gas(e, s, n, m, G, F)))
##########
import sys
import time
import traceback
from contextlib import contextmanager
from io import StringIO
def log(*args, **kwargs):
print(*args, **kwargs, file=sys.stderr)
@contextmanager
def patchio(i):
try:
sys.stdin = StringIO(i)
sys.stdout = StringIO()
yield sys.stdout
finally:
sys.stdin = sys.__stdin__
sys.stdout = sys.__stdout__
def do_test(k, test):
try:
log(f"TEST {k}")
i, o = test
with patchio(i) as r:
t0 = time.time()
main()
t1 = time.time()
if r.getvalue() == o:
log(f"OK ({int((t1-t0)*1000000)/1000:0.3f} ms)\n")
else:
log(f"Expected:\n{o}"
f"Got ({int((t1-t0)*1000000)/1000:0.3f} ms):\n{r.getvalue()}")
except Exception:
traceback.print_exc()
log()
def test(ts):
for k in ts or range(len(tests)):
do_test(k, tests[k])
tests = [("""\
8 4 1 1
2 4
0
""", """\
0 4
"""), ("""\
9 3 2 3
2 3
1 6
-1 0 1
""", """\
-1 -1
3 3
3 2
"""), ("""\
20 9 2 4
1 5
2 10
-1 0 1 2
""", """\
-1 -1
-1 -1
-1 -1
-1 -1
""")]
if __name__ == '__main__':
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('--test', '-t', type=int, nargs='*')
args = parser.parse_args()
main() if args.test is None else test(args.test)
``` | instruction | 0 | 3,779 | 1 | 7,558 |
No | output | 1 | 3,779 | 1 | 7,559 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little town Nsk consists of n junctions connected by m bidirectional roads. Each road connects two distinct junctions and no two roads connect the same pair of junctions. It is possible to get from any junction to any other junction by these roads. The distance between two junctions is equal to the minimum possible number of roads on a path between them.
In order to improve the transportation system, the city council asks mayor to build one new road. The problem is that the mayor has just bought a wonderful new car and he really enjoys a ride from his home, located near junction s to work located near junction t. Thus, he wants to build a new road in such a way that the distance between these two junctions won't decrease.
You are assigned a task to compute the number of pairs of junctions that are not connected by the road, such that if the new road between these two junctions is built the distance between s and t won't decrease.
Input
The firt line of the input contains integers n, m, s and t (2 β€ n β€ 1000, 1 β€ m β€ 1000, 1 β€ s, t β€ n, s β t) β the number of junctions and the number of roads in Nsk, as well as the indices of junctions where mayors home and work are located respectively. The i-th of the following m lines contains two integers ui and vi (1 β€ ui, vi β€ n, ui β vi), meaning that this road connects junctions ui and vi directly. It is guaranteed that there is a path between any two junctions and no two roads connect the same pair of junctions.
Output
Print one integer β the number of pairs of junctions not connected by a direct road, such that building a road between these two junctions won't decrease the distance between junctions s and t.
Examples
Input
5 4 1 5
1 2
2 3
3 4
4 5
Output
0
Input
5 4 3 5
1 2
2 3
3 4
4 5
Output
5
Input
5 6 1 5
1 2
1 3
1 4
4 5
3 5
2 5
Output
3 | instruction | 0 | 3,900 | 1 | 7,800 |
Tags: dfs and similar, graphs, shortest paths
Correct Solution:
```
#!/usr/bin/env python3
import sys
[n, m, s1, t1] = map(int, sys.stdin.readline().strip().split())
s, t = s1 - 1, t1 - 1
tos = [[] for _ in range(n)]
for _ in range(m):
[u1, v1] = map(int, sys.stdin.readline().strip().split())
v, u = v1 - 1, u1 - 1
tos[v].append(u)
tos[u].append(v)
def S_l(v0, tos):
n = len(tos)
visited = [False for _ in range(n)]
visited[v0] = True
queue = [v0]
hq = 0
l = [0 for _ in range(n)]
while len(queue) > hq:
u = queue[hq]
hq += 1
for v in tos[u]:
if not visited[v]:
l[v] = l[u] + 1
queue.append(v)
visited[v] = True
return l
lt = S_l(t, tos)
ls = S_l(s, tos)
d = lt[s]
count = 0
for u in range(n):
for v in range(u):
if (v not in tos[u]) and (min(lt[u] + ls[v], lt[v] + ls[u]) + 1 >= d):
count += 1
print (count)
``` | output | 1 | 3,900 | 1 | 7,801 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little town Nsk consists of n junctions connected by m bidirectional roads. Each road connects two distinct junctions and no two roads connect the same pair of junctions. It is possible to get from any junction to any other junction by these roads. The distance between two junctions is equal to the minimum possible number of roads on a path between them.
In order to improve the transportation system, the city council asks mayor to build one new road. The problem is that the mayor has just bought a wonderful new car and he really enjoys a ride from his home, located near junction s to work located near junction t. Thus, he wants to build a new road in such a way that the distance between these two junctions won't decrease.
You are assigned a task to compute the number of pairs of junctions that are not connected by the road, such that if the new road between these two junctions is built the distance between s and t won't decrease.
Input
The firt line of the input contains integers n, m, s and t (2 β€ n β€ 1000, 1 β€ m β€ 1000, 1 β€ s, t β€ n, s β t) β the number of junctions and the number of roads in Nsk, as well as the indices of junctions where mayors home and work are located respectively. The i-th of the following m lines contains two integers ui and vi (1 β€ ui, vi β€ n, ui β vi), meaning that this road connects junctions ui and vi directly. It is guaranteed that there is a path between any two junctions and no two roads connect the same pair of junctions.
Output
Print one integer β the number of pairs of junctions not connected by a direct road, such that building a road between these two junctions won't decrease the distance between junctions s and t.
Examples
Input
5 4 1 5
1 2
2 3
3 4
4 5
Output
0
Input
5 4 3 5
1 2
2 3
3 4
4 5
Output
5
Input
5 6 1 5
1 2
1 3
1 4
4 5
3 5
2 5
Output
3 | instruction | 0 | 3,901 | 1 | 7,802 |
Tags: dfs and similar, graphs, shortest paths
Correct Solution:
```
from collections import deque, namedtuple
from heapq import *
from sys import stdin
inf = float('inf')
Edge = namedtuple('Edge', 'start, end, cost')
def make_edge(start, end, cost=1):
return Edge(start, end, cost)
class Graph:
def __init__(self, edges, bi=True):
wrong_edges = [i for i in edges if len(i) not in [2, 3]]
if wrong_edges:
raise ValueError('Wrong edges data: {}'.format(wrong_edges))
self.edges = [make_edge(*edge) for edge in edges]
self.vertices = set(
sum(
([edge.start, edge.end] for edge in self.edges), []
))
self.neighbors = {vertex: set() for vertex in self.vertices}
for edge in self.edges:
self.neighbors[edge.start].add(edge.end)
def get_node_pairs(self, n1, n2, both_ends=True):
if both_ends:
node_pairs = [[n1, n2], [n2, n1]]
else:
node_pairs = [[n1, n2]]
return node_pairs
def remove_edge(self, n1, n2, both_ends=True):
node_pairs = self.get_node_pairs(n1, n2, both_ends)
edges = self.edges[:]
for edge in edges:
if[edge.start, edge.end] in node_pairs:
self.edges.remove(edge)
def add_edge(self, n1, n2, cost=1, both_ends=True):
node_pairs = self.get_node_pairs(n1, n2, both_ends)
for edge in self.edges:
if [edge.start, edge.end] in node_pairs:
return ValueError('Edge {} {} already exists'.format(n1, n2))
self.edges.append(Edge(start=n1, end=n2, cost=cost))
if both_ends:
self.edges.append(Edge(start=n2, end=n1, cost=cost))
def dijkstra(self, source, dest):
assert source in self.vertices, 'Such source node doesn\'t exist'
distances = {vertex: inf for vertex in self.vertices}
distances[source] = 0
q, seen = [(0, source)], set()
while q:
(curr_cost, current_vertex) = heappop(q)
if current_vertex in seen:
continue
seen.add(current_vertex)
for neighbor in self.neighbors[current_vertex]:
cost = 1
if neighbor in seen:
continue
alternative_route = distances[current_vertex] + cost
if alternative_route < distances[neighbor]:
distances[neighbor] = alternative_route
heappush(q, (alternative_route, neighbor))
return distances
n, m, s, t = [int(x) for x in stdin.readline().rstrip().split()]
verts = []
for i in range(m):
verts.append(tuple([int(x) for x in stdin.readline().rstrip().split()]))
rev_verts = []
for i in verts:
rev_verts.append((i[1], i[0]))
for i in rev_verts:
verts.append(i)
graph = Graph(verts)
s_dist = graph.dijkstra(s, t)
t_dist = graph.dijkstra(t, s)
SHORTEST_DIST = s_dist[t]
count = 0
for i in range(1, n + 1):
for j in range(i + 1, n + 1):
if j not in graph.neighbors[i] and \
i not in graph.neighbors[j] and \
s_dist[i] + t_dist[j] + 1 >= SHORTEST_DIST and \
s_dist[j] + t_dist[i] + 1 >= SHORTEST_DIST:
count = count + 1
print(count)
``` | output | 1 | 3,901 | 1 | 7,803 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little town Nsk consists of n junctions connected by m bidirectional roads. Each road connects two distinct junctions and no two roads connect the same pair of junctions. It is possible to get from any junction to any other junction by these roads. The distance between two junctions is equal to the minimum possible number of roads on a path between them.
In order to improve the transportation system, the city council asks mayor to build one new road. The problem is that the mayor has just bought a wonderful new car and he really enjoys a ride from his home, located near junction s to work located near junction t. Thus, he wants to build a new road in such a way that the distance between these two junctions won't decrease.
You are assigned a task to compute the number of pairs of junctions that are not connected by the road, such that if the new road between these two junctions is built the distance between s and t won't decrease.
Input
The firt line of the input contains integers n, m, s and t (2 β€ n β€ 1000, 1 β€ m β€ 1000, 1 β€ s, t β€ n, s β t) β the number of junctions and the number of roads in Nsk, as well as the indices of junctions where mayors home and work are located respectively. The i-th of the following m lines contains two integers ui and vi (1 β€ ui, vi β€ n, ui β vi), meaning that this road connects junctions ui and vi directly. It is guaranteed that there is a path between any two junctions and no two roads connect the same pair of junctions.
Output
Print one integer β the number of pairs of junctions not connected by a direct road, such that building a road between these two junctions won't decrease the distance between junctions s and t.
Examples
Input
5 4 1 5
1 2
2 3
3 4
4 5
Output
0
Input
5 4 3 5
1 2
2 3
3 4
4 5
Output
5
Input
5 6 1 5
1 2
1 3
1 4
4 5
3 5
2 5
Output
3 | instruction | 0 | 3,902 | 1 | 7,804 |
Tags: dfs and similar, graphs, shortest paths
Correct Solution:
```
class Node:
def __init__(self, label):
self.label, self.ways, self.distances = label, set(), dict()
def connect(self, other):
self.ways.add(other)
class Graph:
def __init__(self, count):
self.nodes = [Node(i) for i in range(count)]
def connect(self, a, b):
node_a, node_b = self.nodes[a], self.nodes[b]
node_a.connect(node_b)
node_b.connect(node_a)
def fill_distances(self, start):
looked, queue, next_queue = {start}, {start}, set()
start.distances[start] = 0
while len(queue) + len(next_queue) > 0:
for node in queue:
for neighbour in node.ways:
if neighbour not in looked:
looked.add(neighbour)
next_queue.add(neighbour)
neighbour.distances[start] = node.distances[start] + 1
queue, next_queue = next_queue, set()
def repeat(elem):
while True:
yield elem
def readline(types=repeat(int)):
return map(lambda x: x[0](x[1]), zip(types, input().split()))
def readinput():
nodes, edges, start, finish = readline()
start, finish = start - 1, finish - 1
graph = Graph(nodes)
for i in range(edges):
a, b = readline()
a, b = a - 1, b - 1
graph.connect(a, b)
return graph, graph.nodes[start], graph.nodes[finish]
def main():
graph, start, finish = readinput()
graph.fill_distances(start)
graph.fill_distances(finish)
distance = start.distances[finish]
answer = 0
for i in range(len(graph.nodes)):
for j in range(i + 1, len(graph.nodes)):
node_a, node_b = graph.nodes[i], graph.nodes[j]
if node_a in node_b.ways:
continue
if node_a.distances[start] + 1 + node_b.distances[finish] < distance:
continue
if node_a.distances[finish] + 1 + node_b.distances[start] < distance:
continue
answer += 1
print(answer)
main()
``` | output | 1 | 3,902 | 1 | 7,805 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little town Nsk consists of n junctions connected by m bidirectional roads. Each road connects two distinct junctions and no two roads connect the same pair of junctions. It is possible to get from any junction to any other junction by these roads. The distance between two junctions is equal to the minimum possible number of roads on a path between them.
In order to improve the transportation system, the city council asks mayor to build one new road. The problem is that the mayor has just bought a wonderful new car and he really enjoys a ride from his home, located near junction s to work located near junction t. Thus, he wants to build a new road in such a way that the distance between these two junctions won't decrease.
You are assigned a task to compute the number of pairs of junctions that are not connected by the road, such that if the new road between these two junctions is built the distance between s and t won't decrease.
Input
The firt line of the input contains integers n, m, s and t (2 β€ n β€ 1000, 1 β€ m β€ 1000, 1 β€ s, t β€ n, s β t) β the number of junctions and the number of roads in Nsk, as well as the indices of junctions where mayors home and work are located respectively. The i-th of the following m lines contains two integers ui and vi (1 β€ ui, vi β€ n, ui β vi), meaning that this road connects junctions ui and vi directly. It is guaranteed that there is a path between any two junctions and no two roads connect the same pair of junctions.
Output
Print one integer β the number of pairs of junctions not connected by a direct road, such that building a road between these two junctions won't decrease the distance between junctions s and t.
Examples
Input
5 4 1 5
1 2
2 3
3 4
4 5
Output
0
Input
5 4 3 5
1 2
2 3
3 4
4 5
Output
5
Input
5 6 1 5
1 2
1 3
1 4
4 5
3 5
2 5
Output
3 | instruction | 0 | 3,903 | 1 | 7,806 |
Tags: dfs and similar, graphs, shortest paths
Correct Solution:
```
import sys
from collections import deque
readline = sys.stdin.readline
readlines = sys.stdin.readlines
ns = lambda: readline().rstrip()
ni = lambda: int(readline().rstrip())
nm = lambda: map(int, readline().split())
nl = lambda: list(map(int, readline().split()))
prn = lambda x: print(*x, sep='\n')
def bfs(G, s, t=None):
"""
G[v] = [x1, x2,...]
"""
dist = [-1]*len(G)
dist[s] = 0
q = deque([s])
while q:
v = q.popleft()
for x in G[v]:
if dist[x] < 0 or dist[x] > dist[v] + 1:
dist[x] = dist[v] + 1
q.append(x)
if t is None:
return dist
else:
return dist[t]
def solve():
n, m, s, t = nm()
s -= 1; t -= 1
G = [list() for _ in range(n)]
for _ in range(m):
u, v = nm()
u -= 1; v -= 1
G[u].append(v)
G[v].append(u)
dss = bfs(G, s)
dst = bfs(G, t)
ans = 0
sp = dss[t]
for i in range(n-1):
for j in range(i+1, n):
if dss[i] + dst[j] + 1 >= sp and dss[j] + dst[i] + 1 >= sp:
ans += 1
print(ans - m)
return
solve()
# T = ni()
# for _ in range(T):
# solve()
``` | output | 1 | 3,903 | 1 | 7,807 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little town Nsk consists of n junctions connected by m bidirectional roads. Each road connects two distinct junctions and no two roads connect the same pair of junctions. It is possible to get from any junction to any other junction by these roads. The distance between two junctions is equal to the minimum possible number of roads on a path between them.
In order to improve the transportation system, the city council asks mayor to build one new road. The problem is that the mayor has just bought a wonderful new car and he really enjoys a ride from his home, located near junction s to work located near junction t. Thus, he wants to build a new road in such a way that the distance between these two junctions won't decrease.
You are assigned a task to compute the number of pairs of junctions that are not connected by the road, such that if the new road between these two junctions is built the distance between s and t won't decrease.
Input
The firt line of the input contains integers n, m, s and t (2 β€ n β€ 1000, 1 β€ m β€ 1000, 1 β€ s, t β€ n, s β t) β the number of junctions and the number of roads in Nsk, as well as the indices of junctions where mayors home and work are located respectively. The i-th of the following m lines contains two integers ui and vi (1 β€ ui, vi β€ n, ui β vi), meaning that this road connects junctions ui and vi directly. It is guaranteed that there is a path between any two junctions and no two roads connect the same pair of junctions.
Output
Print one integer β the number of pairs of junctions not connected by a direct road, such that building a road between these two junctions won't decrease the distance between junctions s and t.
Examples
Input
5 4 1 5
1 2
2 3
3 4
4 5
Output
0
Input
5 4 3 5
1 2
2 3
3 4
4 5
Output
5
Input
5 6 1 5
1 2
1 3
1 4
4 5
3 5
2 5
Output
3 | instruction | 0 | 3,904 | 1 | 7,808 |
Tags: dfs and similar, graphs, shortest paths
Correct Solution:
```
if __name__ == '__main__':
n, m, u, v = map(int, input().split())
graph = [[] for _ in range(n)]
mtx = [[0] * n for _ in range(n)]
for _ in range(m):
a, b = map(int, input().split())
a -= 1
b -= 1
graph[a].append(b)
graph[b].append(a)
mtx[a][b] = 1
mtx[b][a] = 1
q = [u - 1]
vec1 = [0] * n
vec1[u - 1] = 1
while q:
c = q.pop(0)
for i in graph[c]:
if not vec1[i]:
vec1[i] = vec1[c] + 1
q.append(i)
q = [v - 1]
vec2 = [0] * n
vec2[v - 1] = 1
while q:
c = q.pop(0)
for i in graph[c]:
if not vec2[i]:
vec2[i] = vec2[c] + 1
q.append(i)
for i in range(n):
vec1[i] -= 1
vec2[i] -= 1
res = 0
for i in range(n):
for j in range(i + 1, n):
if not mtx[i][j] and min(vec2[j] + vec1[i] + 1, vec2[i] + vec1[j] + 1) >= vec1[v - 1]:
res += 1
print(res)
``` | output | 1 | 3,904 | 1 | 7,809 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little town Nsk consists of n junctions connected by m bidirectional roads. Each road connects two distinct junctions and no two roads connect the same pair of junctions. It is possible to get from any junction to any other junction by these roads. The distance between two junctions is equal to the minimum possible number of roads on a path between them.
In order to improve the transportation system, the city council asks mayor to build one new road. The problem is that the mayor has just bought a wonderful new car and he really enjoys a ride from his home, located near junction s to work located near junction t. Thus, he wants to build a new road in such a way that the distance between these two junctions won't decrease.
You are assigned a task to compute the number of pairs of junctions that are not connected by the road, such that if the new road between these two junctions is built the distance between s and t won't decrease.
Input
The firt line of the input contains integers n, m, s and t (2 β€ n β€ 1000, 1 β€ m β€ 1000, 1 β€ s, t β€ n, s β t) β the number of junctions and the number of roads in Nsk, as well as the indices of junctions where mayors home and work are located respectively. The i-th of the following m lines contains two integers ui and vi (1 β€ ui, vi β€ n, ui β vi), meaning that this road connects junctions ui and vi directly. It is guaranteed that there is a path between any two junctions and no two roads connect the same pair of junctions.
Output
Print one integer β the number of pairs of junctions not connected by a direct road, such that building a road between these two junctions won't decrease the distance between junctions s and t.
Examples
Input
5 4 1 5
1 2
2 3
3 4
4 5
Output
0
Input
5 4 3 5
1 2
2 3
3 4
4 5
Output
5
Input
5 6 1 5
1 2
1 3
1 4
4 5
3 5
2 5
Output
3 | instruction | 0 | 3,905 | 1 | 7,810 |
Tags: dfs and similar, graphs, shortest paths
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_left(a, x)
if i != len(a):
return i
else:
return -1
def bfs(n,gp,st):
q=deque([st])
dist=[-1]*(n+1)
dist[st]=0
while q:
node=q.popleft()
for x in gp[node]:
if dist[x]==-1:
dist[x]=dist[node]+1
q.append(x)
return dist
def main():
try:
n,m,st,end=In()
gp=defaultdict(set)
for i in range(m):
a,b=In()
gp[a].add(b)
gp[b].add(a)
bfs1=bfs(n,gp,st)
bfs2=bfs(n,gp,end)
length=bfs1[end]
cnt=0
for i in range(1,n+1):
for j in range(i+1,n+1):
if j in gp[i]:
continue
else:
if bfs1[i]+bfs2[j]+1<length:
continue
elif bfs1[j]+bfs2[i]+1<length:
continue
else:
cnt+=1
print(cnt)
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 | 3,905 | 1 | 7,811 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little town Nsk consists of n junctions connected by m bidirectional roads. Each road connects two distinct junctions and no two roads connect the same pair of junctions. It is possible to get from any junction to any other junction by these roads. The distance between two junctions is equal to the minimum possible number of roads on a path between them.
In order to improve the transportation system, the city council asks mayor to build one new road. The problem is that the mayor has just bought a wonderful new car and he really enjoys a ride from his home, located near junction s to work located near junction t. Thus, he wants to build a new road in such a way that the distance between these two junctions won't decrease.
You are assigned a task to compute the number of pairs of junctions that are not connected by the road, such that if the new road between these two junctions is built the distance between s and t won't decrease.
Input
The firt line of the input contains integers n, m, s and t (2 β€ n β€ 1000, 1 β€ m β€ 1000, 1 β€ s, t β€ n, s β t) β the number of junctions and the number of roads in Nsk, as well as the indices of junctions where mayors home and work are located respectively. The i-th of the following m lines contains two integers ui and vi (1 β€ ui, vi β€ n, ui β vi), meaning that this road connects junctions ui and vi directly. It is guaranteed that there is a path between any two junctions and no two roads connect the same pair of junctions.
Output
Print one integer β the number of pairs of junctions not connected by a direct road, such that building a road between these two junctions won't decrease the distance between junctions s and t.
Examples
Input
5 4 1 5
1 2
2 3
3 4
4 5
Output
0
Input
5 4 3 5
1 2
2 3
3 4
4 5
Output
5
Input
5 6 1 5
1 2
1 3
1 4
4 5
3 5
2 5
Output
3 | instruction | 0 | 3,906 | 1 | 7,812 |
Tags: dfs and similar, graphs, shortest paths
Correct Solution:
```
n,m,s,t = map(int, input().split())
G = [[] for _ in range(n+1)]
for i in range(m):
a,b = map(int, input().split())
G[a].append(b)
G[b].append(a)
dists = [n+1]*(n+1)
distt = [n+1]*(n+1)
# BFS find distance
T = [s]
count = 0
while T:
newT = []
for i in T:
dists[i] = min(dists[i],count)
for j in G[i]:
if dists[j] == n+1:
newT.append(j)
count+=1
T = newT
T = [t]
count = 0
while T:
newT = []
for i in T:
distt[i] = min(distt[i],count)
for j in G[i]:
if distt[j] == n+1:
newT.append(j)
count+=1
T = newT
count = 0
mm = dists[t]
for i in range(1,n+1):
for j in range(i+1,n+1):
if j in G[i]:
continue
if min(dists[i] + distt[j] + 1, dists[j] + distt[i] + 1) < mm:
continue
count += 1
print(count)
``` | output | 1 | 3,906 | 1 | 7,813 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little town Nsk consists of n junctions connected by m bidirectional roads. Each road connects two distinct junctions and no two roads connect the same pair of junctions. It is possible to get from any junction to any other junction by these roads. The distance between two junctions is equal to the minimum possible number of roads on a path between them.
In order to improve the transportation system, the city council asks mayor to build one new road. The problem is that the mayor has just bought a wonderful new car and he really enjoys a ride from his home, located near junction s to work located near junction t. Thus, he wants to build a new road in such a way that the distance between these two junctions won't decrease.
You are assigned a task to compute the number of pairs of junctions that are not connected by the road, such that if the new road between these two junctions is built the distance between s and t won't decrease.
Input
The firt line of the input contains integers n, m, s and t (2 β€ n β€ 1000, 1 β€ m β€ 1000, 1 β€ s, t β€ n, s β t) β the number of junctions and the number of roads in Nsk, as well as the indices of junctions where mayors home and work are located respectively. The i-th of the following m lines contains two integers ui and vi (1 β€ ui, vi β€ n, ui β vi), meaning that this road connects junctions ui and vi directly. It is guaranteed that there is a path between any two junctions and no two roads connect the same pair of junctions.
Output
Print one integer β the number of pairs of junctions not connected by a direct road, such that building a road between these two junctions won't decrease the distance between junctions s and t.
Examples
Input
5 4 1 5
1 2
2 3
3 4
4 5
Output
0
Input
5 4 3 5
1 2
2 3
3 4
4 5
Output
5
Input
5 6 1 5
1 2
1 3
1 4
4 5
3 5
2 5
Output
3 | instruction | 0 | 3,907 | 1 | 7,814 |
Tags: dfs and similar, graphs, shortest paths
Correct Solution:
```
n,m,s,e = map(int,input().split())
s -= 1
e -= 1
md = []
g = []
for i in range(n):
md.append([-1,-1])
g.append([])
for i in range(m):
u,v = map(int,input().split())
g[u-1].append(v-1)
g[v-1].append(u-1)
#bfs
md[s][0] = 0
d = 0
st = [s]
c = 1
#print('s')
while c < n:
#print(c)
d += 1
st2 = []
for node in st:
for p in g[node]:
if md[p][0] == -1:
st2.append(p)
md[p][0] = d
c+=len(st2)
st = st2[:]
#bfs
md[e][1] = 0
d = 0
st = [e]
c = 1
#print('s')
while c < n:
#print(c)
d += 1
st2 = []
for node in st:
for p in g[node]:
if md[p][1] == -1:
st2.append(p)
md[p][1] = d
c+=len(st2)
st = st2[:]
#print(md)
dis = md[e][0]
t = 0
for i in range(n):
for j in range(i):
if j in g[i]:continue
if dis <= min(md[i][0] + md[j][1],md[j][0] + md[i][1])+1:
t += 1
print(t)
``` | output | 1 | 3,907 | 1 | 7,815 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little town Nsk consists of n junctions connected by m bidirectional roads. Each road connects two distinct junctions and no two roads connect the same pair of junctions. It is possible to get from any junction to any other junction by these roads. The distance between two junctions is equal to the minimum possible number of roads on a path between them.
In order to improve the transportation system, the city council asks mayor to build one new road. The problem is that the mayor has just bought a wonderful new car and he really enjoys a ride from his home, located near junction s to work located near junction t. Thus, he wants to build a new road in such a way that the distance between these two junctions won't decrease.
You are assigned a task to compute the number of pairs of junctions that are not connected by the road, such that if the new road between these two junctions is built the distance between s and t won't decrease.
Input
The firt line of the input contains integers n, m, s and t (2 β€ n β€ 1000, 1 β€ m β€ 1000, 1 β€ s, t β€ n, s β t) β the number of junctions and the number of roads in Nsk, as well as the indices of junctions where mayors home and work are located respectively. The i-th of the following m lines contains two integers ui and vi (1 β€ ui, vi β€ n, ui β vi), meaning that this road connects junctions ui and vi directly. It is guaranteed that there is a path between any two junctions and no two roads connect the same pair of junctions.
Output
Print one integer β the number of pairs of junctions not connected by a direct road, such that building a road between these two junctions won't decrease the distance between junctions s and t.
Examples
Input
5 4 1 5
1 2
2 3
3 4
4 5
Output
0
Input
5 4 3 5
1 2
2 3
3 4
4 5
Output
5
Input
5 6 1 5
1 2
1 3
1 4
4 5
3 5
2 5
Output
3
Submitted Solution:
```
def get_amount_variants(routes, n, s, t):
"""
:param List[List[int]] routes:
:param int n:
:param int s:
:param int t:
:return: int
"""
connects = [[] for _ in range(n + 1)]
for st, end in routes:
connects[st].append(end)
connects[end].append(st)
w_h = get_shortest_ways(connects, s)
w_j = get_shortest_ways(connects, t)
amount = 0
for i in range(1, n + 1):
for j in range(i + 1, n + 1):
if min(w_h[i] + w_j[j], w_h[j] + w_j[i]) + 1 >= w_h[t] and i not in connects[j]:
amount += 1
return amount
def get_shortest_ways(connects, st):
res = [int(1e9) if _ != st else 0 for _ in range(len(connects) + 1)]
available = [(x, 0) for x in connects[st]]
while len(available) > 0:
point, weight = available.pop(0)
if res[point] != 0 and res[point] < weight + 1:
continue
res[point] = weight + 1
available += [(x, weight + 1) for x in connects[point] if res[x] == int(1e9) and x != st]
return res
n, m, s, t = map(int, input().strip().split())
routes = []
for i in range(m):
routes.append(map(int, input().split()))
print(get_amount_variants(routes, n, s, t))
``` | instruction | 0 | 3,908 | 1 | 7,816 |
Yes | output | 1 | 3,908 | 1 | 7,817 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little town Nsk consists of n junctions connected by m bidirectional roads. Each road connects two distinct junctions and no two roads connect the same pair of junctions. It is possible to get from any junction to any other junction by these roads. The distance between two junctions is equal to the minimum possible number of roads on a path between them.
In order to improve the transportation system, the city council asks mayor to build one new road. The problem is that the mayor has just bought a wonderful new car and he really enjoys a ride from his home, located near junction s to work located near junction t. Thus, he wants to build a new road in such a way that the distance between these two junctions won't decrease.
You are assigned a task to compute the number of pairs of junctions that are not connected by the road, such that if the new road between these two junctions is built the distance between s and t won't decrease.
Input
The firt line of the input contains integers n, m, s and t (2 β€ n β€ 1000, 1 β€ m β€ 1000, 1 β€ s, t β€ n, s β t) β the number of junctions and the number of roads in Nsk, as well as the indices of junctions where mayors home and work are located respectively. The i-th of the following m lines contains two integers ui and vi (1 β€ ui, vi β€ n, ui β vi), meaning that this road connects junctions ui and vi directly. It is guaranteed that there is a path between any two junctions and no two roads connect the same pair of junctions.
Output
Print one integer β the number of pairs of junctions not connected by a direct road, such that building a road between these two junctions won't decrease the distance between junctions s and t.
Examples
Input
5 4 1 5
1 2
2 3
3 4
4 5
Output
0
Input
5 4 3 5
1 2
2 3
3 4
4 5
Output
5
Input
5 6 1 5
1 2
1 3
1 4
4 5
3 5
2 5
Output
3
Submitted Solution:
```
import sys
input=sys.stdin.readline
from collections import deque
n,m,s,t=map(int,input().split())
s-=1;t-=1
g=[[] for i in range(n)]
gg=[set() for i in range(n)]
for _ in range(m):
u,v=map(int,input().split())
g[u-1].append(v-1)
gg[u-1].add(v-1)
g[v-1].append(u-1)
gg[v-1].add(u-1)
def bfs01(x,d):
dq=deque([x])
d[x]=0
while dq:
ver=dq.popleft()
for to in g[ver]:
if d[to]==-1:
dq.append(to)
d[to]=d[ver]+1
return d
cnt=0
d_s=bfs01(s,[-1]*n)
d_t=bfs01(t,[-1]*n)
l=d_s[t]
for i in range(n):
for j in range(i+1,n):
if j in gg[i] or i in gg[j]:
continue
if l<=min(l,d_s[i]+1+d_t[j],d_s[j]+1+d_t[i]):
cnt+=1
print(cnt)
``` | instruction | 0 | 3,909 | 1 | 7,818 |
Yes | output | 1 | 3,909 | 1 | 7,819 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little town Nsk consists of n junctions connected by m bidirectional roads. Each road connects two distinct junctions and no two roads connect the same pair of junctions. It is possible to get from any junction to any other junction by these roads. The distance between two junctions is equal to the minimum possible number of roads on a path between them.
In order to improve the transportation system, the city council asks mayor to build one new road. The problem is that the mayor has just bought a wonderful new car and he really enjoys a ride from his home, located near junction s to work located near junction t. Thus, he wants to build a new road in such a way that the distance between these two junctions won't decrease.
You are assigned a task to compute the number of pairs of junctions that are not connected by the road, such that if the new road between these two junctions is built the distance between s and t won't decrease.
Input
The firt line of the input contains integers n, m, s and t (2 β€ n β€ 1000, 1 β€ m β€ 1000, 1 β€ s, t β€ n, s β t) β the number of junctions and the number of roads in Nsk, as well as the indices of junctions where mayors home and work are located respectively. The i-th of the following m lines contains two integers ui and vi (1 β€ ui, vi β€ n, ui β vi), meaning that this road connects junctions ui and vi directly. It is guaranteed that there is a path between any two junctions and no two roads connect the same pair of junctions.
Output
Print one integer β the number of pairs of junctions not connected by a direct road, such that building a road between these two junctions won't decrease the distance between junctions s and t.
Examples
Input
5 4 1 5
1 2
2 3
3 4
4 5
Output
0
Input
5 4 3 5
1 2
2 3
3 4
4 5
Output
5
Input
5 6 1 5
1 2
1 3
1 4
4 5
3 5
2 5
Output
3
Submitted Solution:
```
from collections import defaultdict, deque
from sys import stdin, stdout
def In():return(map(int,stdin.readline().split()))
def bfs(n, graph, start):
q = deque([start])
dist = [-1]*(n+1)
dist[start] = 0
while q:
current = q.popleft()
for neigh in graph[current]:
if dist[neigh] == -1:
dist[neigh] = dist[current] + 1
q.append(neigh)
return dist
def main():
n, m, s, t = In()
graph = defaultdict(set)
for i in range(m):
a, b = In()
graph[a].add(b)
graph[b].add(a)
ds = bfs(n, graph, s)
dt = bfs(n, graph, t)
res = 0
aim = ds[t]
for i in range(1, n+1):
for j in range(i+1, n+1):
if j not in graph[i]:
if ds[i]+dt[j]+1 < aim or ds[j]+dt[i] + 1 < aim:
continue
else:
res += 1
print(res)
if __name__ == '__main__':
main()
``` | instruction | 0 | 3,910 | 1 | 7,820 |
Yes | output | 1 | 3,910 | 1 | 7,821 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little town Nsk consists of n junctions connected by m bidirectional roads. Each road connects two distinct junctions and no two roads connect the same pair of junctions. It is possible to get from any junction to any other junction by these roads. The distance between two junctions is equal to the minimum possible number of roads on a path between them.
In order to improve the transportation system, the city council asks mayor to build one new road. The problem is that the mayor has just bought a wonderful new car and he really enjoys a ride from his home, located near junction s to work located near junction t. Thus, he wants to build a new road in such a way that the distance between these two junctions won't decrease.
You are assigned a task to compute the number of pairs of junctions that are not connected by the road, such that if the new road between these two junctions is built the distance between s and t won't decrease.
Input
The firt line of the input contains integers n, m, s and t (2 β€ n β€ 1000, 1 β€ m β€ 1000, 1 β€ s, t β€ n, s β t) β the number of junctions and the number of roads in Nsk, as well as the indices of junctions where mayors home and work are located respectively. The i-th of the following m lines contains two integers ui and vi (1 β€ ui, vi β€ n, ui β vi), meaning that this road connects junctions ui and vi directly. It is guaranteed that there is a path between any two junctions and no two roads connect the same pair of junctions.
Output
Print one integer β the number of pairs of junctions not connected by a direct road, such that building a road between these two junctions won't decrease the distance between junctions s and t.
Examples
Input
5 4 1 5
1 2
2 3
3 4
4 5
Output
0
Input
5 4 3 5
1 2
2 3
3 4
4 5
Output
5
Input
5 6 1 5
1 2
1 3
1 4
4 5
3 5
2 5
Output
3
Submitted Solution:
```
import sys
import heapq
nnode,nedge,source,dest=map(int,sys.stdin.readline().split())
source-=1;dest-=1
adjl=[[] for _ in range(nnode)]
for _ in range(nedge):
u,v=map(int,sys.stdin.readline().split())
u-=1;v-=1
adjl[u].append(v)
adjl[v].append(u)
# why not BFS? >.<
def dijkstra_from(source):
pq=[]
dist=[10**9]*nnode
dist[source]=0
heapq.heappush(pq,(dist[source],source))
while pq:
dist_node,node=heapq.heappop(pq)
if dist[node]!=dist_node: continue
for adj in adjl[node]:
if dist[adj]>dist_node+1:
dist[adj]=dist_node+1
heapq.heappush(pq,(dist[adj],adj))
return dist
d_src=dijkstra_from(source)
d_dst=dijkstra_from(dest)
assert d_dst[source] == d_src[dest]
ans=0
for u in range(nnode):
adj_to_u=[False]*u
for v in adjl[u]:
if v<u:
adj_to_u[v]=True
for v in range(u):
if not adj_to_u[v]:
if min(
d_dst[u]+d_src[v]+1,
d_src[u]+d_dst[v]+1
)<d_src[dest]: continue
ans+=1
print(ans)
``` | instruction | 0 | 3,911 | 1 | 7,822 |
Yes | output | 1 | 3,911 | 1 | 7,823 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little town Nsk consists of n junctions connected by m bidirectional roads. Each road connects two distinct junctions and no two roads connect the same pair of junctions. It is possible to get from any junction to any other junction by these roads. The distance between two junctions is equal to the minimum possible number of roads on a path between them.
In order to improve the transportation system, the city council asks mayor to build one new road. The problem is that the mayor has just bought a wonderful new car and he really enjoys a ride from his home, located near junction s to work located near junction t. Thus, he wants to build a new road in such a way that the distance between these two junctions won't decrease.
You are assigned a task to compute the number of pairs of junctions that are not connected by the road, such that if the new road between these two junctions is built the distance between s and t won't decrease.
Input
The firt line of the input contains integers n, m, s and t (2 β€ n β€ 1000, 1 β€ m β€ 1000, 1 β€ s, t β€ n, s β t) β the number of junctions and the number of roads in Nsk, as well as the indices of junctions where mayors home and work are located respectively. The i-th of the following m lines contains two integers ui and vi (1 β€ ui, vi β€ n, ui β vi), meaning that this road connects junctions ui and vi directly. It is guaranteed that there is a path between any two junctions and no two roads connect the same pair of junctions.
Output
Print one integer β the number of pairs of junctions not connected by a direct road, such that building a road between these two junctions won't decrease the distance between junctions s and t.
Examples
Input
5 4 1 5
1 2
2 3
3 4
4 5
Output
0
Input
5 4 3 5
1 2
2 3
3 4
4 5
Output
5
Input
5 6 1 5
1 2
1 3
1 4
4 5
3 5
2 5
Output
3
Submitted Solution:
```
n, m, s, t = map(int, input().split())
G = [[] for i in range(n + 1)]
for i in range(m):
u, v = map(int, input().split())
G[u].append(v)
G[v].append(u)
def bfs(x, d):
q = [x]
while q:
c = q.pop()
for y in G[c]:
if not d[y]:
d[y] = d[c] + 1
q.insert(0, y)
d[x] = 0
ds = [0 for i in range(n + 1)]
dt = [0 for i in range(n + 1)]
bfs(s, ds)
bfs(t, dt)
D = ds[t]
pairs = 0
for u in range(n - 1):
for v in range(u + 1, n):
min_long = min(ds[u] + dt[v] + 1, ds[v] + dt[u] + 1)
if min_long >= D:
pairs += 1
print(pairs - m)
``` | instruction | 0 | 3,912 | 1 | 7,824 |
No | output | 1 | 3,912 | 1 | 7,825 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little town Nsk consists of n junctions connected by m bidirectional roads. Each road connects two distinct junctions and no two roads connect the same pair of junctions. It is possible to get from any junction to any other junction by these roads. The distance between two junctions is equal to the minimum possible number of roads on a path between them.
In order to improve the transportation system, the city council asks mayor to build one new road. The problem is that the mayor has just bought a wonderful new car and he really enjoys a ride from his home, located near junction s to work located near junction t. Thus, he wants to build a new road in such a way that the distance between these two junctions won't decrease.
You are assigned a task to compute the number of pairs of junctions that are not connected by the road, such that if the new road between these two junctions is built the distance between s and t won't decrease.
Input
The firt line of the input contains integers n, m, s and t (2 β€ n β€ 1000, 1 β€ m β€ 1000, 1 β€ s, t β€ n, s β t) β the number of junctions and the number of roads in Nsk, as well as the indices of junctions where mayors home and work are located respectively. The i-th of the following m lines contains two integers ui and vi (1 β€ ui, vi β€ n, ui β vi), meaning that this road connects junctions ui and vi directly. It is guaranteed that there is a path between any two junctions and no two roads connect the same pair of junctions.
Output
Print one integer β the number of pairs of junctions not connected by a direct road, such that building a road between these two junctions won't decrease the distance between junctions s and t.
Examples
Input
5 4 1 5
1 2
2 3
3 4
4 5
Output
0
Input
5 4 3 5
1 2
2 3
3 4
4 5
Output
5
Input
5 6 1 5
1 2
1 3
1 4
4 5
3 5
2 5
Output
3
Submitted Solution:
```
from collections import defaultdict
nodes,edges,start,end=map(int,input().split())
shortest=[-1]*(nodes+1)
shortest[start]=0
dic=defaultdict(set)
for i in range(edges):
x,y=map(int,input().split())
dic[x].add(y)
dic[y].add(x)
queue=[start]
def bfs(queue):
j=0
while(j<len(queue)):
node=queue[j]
for i in dic[node]:
if shortest[i]==-1:
shortest[i]=shortest[node]+1
queue.append(i)
j+=1
bfs(queue)
shorteststart=shortest[:]
shortest=[-1]*(nodes+1)
shortest[end]=0
queue=[end]
bfs(queue)
shortestend=shortest[:]
output=0
mindistance=shorteststart[end]
for i in range(1,nodes+1):
for j in range(i+1,nodes+1):
if j not in dic[i]:
if shorteststart[i]+1+shortestend[j]>=mindistance:
output+=1
print(output)
``` | instruction | 0 | 3,913 | 1 | 7,826 |
No | output | 1 | 3,913 | 1 | 7,827 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little town Nsk consists of n junctions connected by m bidirectional roads. Each road connects two distinct junctions and no two roads connect the same pair of junctions. It is possible to get from any junction to any other junction by these roads. The distance between two junctions is equal to the minimum possible number of roads on a path between them.
In order to improve the transportation system, the city council asks mayor to build one new road. The problem is that the mayor has just bought a wonderful new car and he really enjoys a ride from his home, located near junction s to work located near junction t. Thus, he wants to build a new road in such a way that the distance between these two junctions won't decrease.
You are assigned a task to compute the number of pairs of junctions that are not connected by the road, such that if the new road between these two junctions is built the distance between s and t won't decrease.
Input
The firt line of the input contains integers n, m, s and t (2 β€ n β€ 1000, 1 β€ m β€ 1000, 1 β€ s, t β€ n, s β t) β the number of junctions and the number of roads in Nsk, as well as the indices of junctions where mayors home and work are located respectively. The i-th of the following m lines contains two integers ui and vi (1 β€ ui, vi β€ n, ui β vi), meaning that this road connects junctions ui and vi directly. It is guaranteed that there is a path between any two junctions and no two roads connect the same pair of junctions.
Output
Print one integer β the number of pairs of junctions not connected by a direct road, such that building a road between these two junctions won't decrease the distance between junctions s and t.
Examples
Input
5 4 1 5
1 2
2 3
3 4
4 5
Output
0
Input
5 4 3 5
1 2
2 3
3 4
4 5
Output
5
Input
5 6 1 5
1 2
1 3
1 4
4 5
3 5
2 5
Output
3
Submitted Solution:
```
n, m, s, t = map(int, input().split())
G = [[] for i in range(n + 1)]
for i in range(m):
u, v = map(int, input().split())
G[u].append(v)
G[v].append(u)
def bfs(x, d):
q = [x]
while q:
c = q.pop()
for y in G[c]:
if not d[y]:
d[y] = d[c] + 1
q.insert(0, y)
d[x] = 0
ds = [0 for i in range(n + 1)]
dt = [0 for i in range(n + 1)]
bfs(s, ds)
bfs(t, dt)
D = ds[t]
pairs = 0
for u in range(n - 1):
for v in range(u + 1, n):
min_long = min(ds[u] + dt[v] + 1, ds[v] + dt[u] + 1)
if min_long >= D:
pairs += 1
if pairs == 0:
print(pairs)
else:
print(pairs - m)
``` | instruction | 0 | 3,914 | 1 | 7,828 |
No | output | 1 | 3,914 | 1 | 7,829 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little town Nsk consists of n junctions connected by m bidirectional roads. Each road connects two distinct junctions and no two roads connect the same pair of junctions. It is possible to get from any junction to any other junction by these roads. The distance between two junctions is equal to the minimum possible number of roads on a path between them.
In order to improve the transportation system, the city council asks mayor to build one new road. The problem is that the mayor has just bought a wonderful new car and he really enjoys a ride from his home, located near junction s to work located near junction t. Thus, he wants to build a new road in such a way that the distance between these two junctions won't decrease.
You are assigned a task to compute the number of pairs of junctions that are not connected by the road, such that if the new road between these two junctions is built the distance between s and t won't decrease.
Input
The firt line of the input contains integers n, m, s and t (2 β€ n β€ 1000, 1 β€ m β€ 1000, 1 β€ s, t β€ n, s β t) β the number of junctions and the number of roads in Nsk, as well as the indices of junctions where mayors home and work are located respectively. The i-th of the following m lines contains two integers ui and vi (1 β€ ui, vi β€ n, ui β vi), meaning that this road connects junctions ui and vi directly. It is guaranteed that there is a path between any two junctions and no two roads connect the same pair of junctions.
Output
Print one integer β the number of pairs of junctions not connected by a direct road, such that building a road between these two junctions won't decrease the distance between junctions s and t.
Examples
Input
5 4 1 5
1 2
2 3
3 4
4 5
Output
0
Input
5 4 3 5
1 2
2 3
3 4
4 5
Output
5
Input
5 6 1 5
1 2
1 3
1 4
4 5
3 5
2 5
Output
3
Submitted Solution:
```
n,m,s,t = map(int,input().split())
dic = {}
hasEdge = []
for i in range(n):
dic[i] = []
for i in range(n):
hasEdge.append([])
for j in range(n):
hasEdge[-1].append(0)
for i in range(m):
a,b = map(int,input().split())
dic[a-1].append(b-1)
dic[b-1].append(a-1)
hasEdge[a-1][b-1] = 1
hasEdge[b-1][a-1] = 1
distS = {}
distD = {}
def shortestDist(source,n):
lis = []
sol = {}
def bfs(source):
global dic
nonlocal lis
nonlocal sol
lis.append(source)
sol[source] = 0
while(len(lis)!=0):
temp = lis.pop()
for i in dic[temp]:
if sol.get(i)==None:
sol[i] = sol[temp]+1
lis.append(i)
bfs(source)
for i in range(n):
if sol.get(i)==None:
sol[i] = float("Inf")
return sol
distS = shortestDist(s-1,n)
distD = shortestDist(t-1,n)
if distS[j]==float("Inf"):
print("Hai")
# for checking if this is the case
else:
count = 0
for i in range(n):
for j in range(i+1,n):
if hasEdge[i][j]==0 and not(distS[i]+1+distD[j]<distS[t-1] or distS[j]+1+distD[i]<distS[t-1]):
count += 1
print(count)
``` | instruction | 0 | 3,915 | 1 | 7,830 |
No | output | 1 | 3,915 | 1 | 7,831 |
Provide a correct Python 3 solution for this coding contest problem.
In Republic of Atcoder, there are N prefectures, and a total of M cities that belong to those prefectures.
City i is established in year Y_i and belongs to Prefecture P_i.
You can assume that there are no multiple cities that are established in the same year.
It is decided to allocate a 12-digit ID number to each city.
If City i is the x-th established city among the cities that belong to Prefecture i, the first six digits of the ID number of City i is P_i, and the last six digits of the ID number is x.
Here, if P_i or x (or both) has less than six digits, zeros are added to the left until it has six digits.
Find the ID numbers for all the cities.
Note that there can be a prefecture with no cities.
Constraints
* 1 \leq N \leq 10^5
* 1 \leq M \leq 10^5
* 1 \leq P_i \leq N
* 1 \leq Y_i \leq 10^9
* Y_i are all different.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M
P_1 Y_1
:
P_M Y_M
Output
Print the ID numbers for all the cities, in ascending order of indices (City 1, City 2, ...).
Examples
Input
2 3
1 32
2 63
1 12
Output
000001000002
000002000001
000001000001
Input
2 3
2 55
2 77
2 99
Output
000002000001
000002000002
000002000003 | instruction | 0 | 4,028 | 1 | 8,056 |
"Correct Solution:
```
import collections
import bisect
N, M = map(int, input().split())
P = [list(map(int, input().split())) for i in range(M)]
ans = collections.defaultdict(list)
for p, y in sorted(P):
ans[p] += [y]
for p, y in P:
print("%06d%06d"%(p, bisect.bisect(ans[p], y)))
``` | output | 1 | 4,028 | 1 | 8,057 |
Provide a correct Python 3 solution for this coding contest problem.
In Republic of Atcoder, there are N prefectures, and a total of M cities that belong to those prefectures.
City i is established in year Y_i and belongs to Prefecture P_i.
You can assume that there are no multiple cities that are established in the same year.
It is decided to allocate a 12-digit ID number to each city.
If City i is the x-th established city among the cities that belong to Prefecture i, the first six digits of the ID number of City i is P_i, and the last six digits of the ID number is x.
Here, if P_i or x (or both) has less than six digits, zeros are added to the left until it has six digits.
Find the ID numbers for all the cities.
Note that there can be a prefecture with no cities.
Constraints
* 1 \leq N \leq 10^5
* 1 \leq M \leq 10^5
* 1 \leq P_i \leq N
* 1 \leq Y_i \leq 10^9
* Y_i are all different.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M
P_1 Y_1
:
P_M Y_M
Output
Print the ID numbers for all the cities, in ascending order of indices (City 1, City 2, ...).
Examples
Input
2 3
1 32
2 63
1 12
Output
000001000002
000002000001
000001000001
Input
2 3
2 55
2 77
2 99
Output
000002000001
000002000002
000002000003 | instruction | 0 | 4,029 | 1 | 8,058 |
"Correct Solution:
```
N, M = map(int,input().split())
ls = [[] for _ in range(N)]
for i in range(M):
p, y = map(int,input().split())
ls[p-1].append((y, i))
ids = [None]*M
for i in range(N):
ls[i].sort()
for j in range(len(ls[i])):
y,k = ls[i][j]
ids[k] = "{:0>6}{:0>6}".format(i+1,j+1)
print(*ids, sep="\n")
``` | output | 1 | 4,029 | 1 | 8,059 |
Provide a correct Python 3 solution for this coding contest problem.
In Republic of Atcoder, there are N prefectures, and a total of M cities that belong to those prefectures.
City i is established in year Y_i and belongs to Prefecture P_i.
You can assume that there are no multiple cities that are established in the same year.
It is decided to allocate a 12-digit ID number to each city.
If City i is the x-th established city among the cities that belong to Prefecture i, the first six digits of the ID number of City i is P_i, and the last six digits of the ID number is x.
Here, if P_i or x (or both) has less than six digits, zeros are added to the left until it has six digits.
Find the ID numbers for all the cities.
Note that there can be a prefecture with no cities.
Constraints
* 1 \leq N \leq 10^5
* 1 \leq M \leq 10^5
* 1 \leq P_i \leq N
* 1 \leq Y_i \leq 10^9
* Y_i are all different.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M
P_1 Y_1
:
P_M Y_M
Output
Print the ID numbers for all the cities, in ascending order of indices (City 1, City 2, ...).
Examples
Input
2 3
1 32
2 63
1 12
Output
000001000002
000002000001
000001000001
Input
2 3
2 55
2 77
2 99
Output
000002000001
000002000002
000002000003 | instruction | 0 | 4,030 | 1 | 8,060 |
"Correct Solution:
```
N, M = map(int, input().split())
p = [[] for i in range(M)]
counter = [0] * N
ans = [""] * M
for i in range(M):
k, y = map(int, input().split())
p[i] = [k, y, i]
p.sort(key=lambda x:x[1])
for k, y, i in p:
counter[k-1] += 1
ans[i] = "{:06d}{:06d}".format(k, counter[k-1])
for i in ans:
print(i)
``` | output | 1 | 4,030 | 1 | 8,061 |
Provide a correct Python 3 solution for this coding contest problem.
In Republic of Atcoder, there are N prefectures, and a total of M cities that belong to those prefectures.
City i is established in year Y_i and belongs to Prefecture P_i.
You can assume that there are no multiple cities that are established in the same year.
It is decided to allocate a 12-digit ID number to each city.
If City i is the x-th established city among the cities that belong to Prefecture i, the first six digits of the ID number of City i is P_i, and the last six digits of the ID number is x.
Here, if P_i or x (or both) has less than six digits, zeros are added to the left until it has six digits.
Find the ID numbers for all the cities.
Note that there can be a prefecture with no cities.
Constraints
* 1 \leq N \leq 10^5
* 1 \leq M \leq 10^5
* 1 \leq P_i \leq N
* 1 \leq Y_i \leq 10^9
* Y_i are all different.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M
P_1 Y_1
:
P_M Y_M
Output
Print the ID numbers for all the cities, in ascending order of indices (City 1, City 2, ...).
Examples
Input
2 3
1 32
2 63
1 12
Output
000001000002
000002000001
000001000001
Input
2 3
2 55
2 77
2 99
Output
000002000001
000002000002
000002000003 | instruction | 0 | 4,031 | 1 | 8,062 |
"Correct Solution:
```
import collections,bisect
N,M=map(int,input().split())
PY=[list(map(int,input().split())) for i in range(M)]
a=collections.defaultdict(list)
for city,year in sorted(PY):a[city]+=[year]
for city,year in PY:
z=bisect.bisect(a[city],year)
print("%06d%06d"%(city,z))
``` | output | 1 | 4,031 | 1 | 8,063 |
Provide a correct Python 3 solution for this coding contest problem.
In Republic of Atcoder, there are N prefectures, and a total of M cities that belong to those prefectures.
City i is established in year Y_i and belongs to Prefecture P_i.
You can assume that there are no multiple cities that are established in the same year.
It is decided to allocate a 12-digit ID number to each city.
If City i is the x-th established city among the cities that belong to Prefecture i, the first six digits of the ID number of City i is P_i, and the last six digits of the ID number is x.
Here, if P_i or x (or both) has less than six digits, zeros are added to the left until it has six digits.
Find the ID numbers for all the cities.
Note that there can be a prefecture with no cities.
Constraints
* 1 \leq N \leq 10^5
* 1 \leq M \leq 10^5
* 1 \leq P_i \leq N
* 1 \leq Y_i \leq 10^9
* Y_i are all different.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M
P_1 Y_1
:
P_M Y_M
Output
Print the ID numbers for all the cities, in ascending order of indices (City 1, City 2, ...).
Examples
Input
2 3
1 32
2 63
1 12
Output
000001000002
000002000001
000001000001
Input
2 3
2 55
2 77
2 99
Output
000002000001
000002000002
000002000003 | instruction | 0 | 4,032 | 1 | 8,064 |
"Correct Solution:
```
import bisect
n,m = map(int,input().split())
Q = []
P = [[] for _ in range(n)]
for i in range(m):
p,y = map(int,input().split())
Q.append([p,y])
P[p-1].append(y)
P_1 = [sorted(l) for l in P]
for p,y in Q:
a = str(p).zfill(6)
b = str(bisect.bisect(P_1[p-1], y)).zfill(6)
print(a+b)
``` | output | 1 | 4,032 | 1 | 8,065 |
Provide a correct Python 3 solution for this coding contest problem.
In Republic of Atcoder, there are N prefectures, and a total of M cities that belong to those prefectures.
City i is established in year Y_i and belongs to Prefecture P_i.
You can assume that there are no multiple cities that are established in the same year.
It is decided to allocate a 12-digit ID number to each city.
If City i is the x-th established city among the cities that belong to Prefecture i, the first six digits of the ID number of City i is P_i, and the last six digits of the ID number is x.
Here, if P_i or x (or both) has less than six digits, zeros are added to the left until it has six digits.
Find the ID numbers for all the cities.
Note that there can be a prefecture with no cities.
Constraints
* 1 \leq N \leq 10^5
* 1 \leq M \leq 10^5
* 1 \leq P_i \leq N
* 1 \leq Y_i \leq 10^9
* Y_i are all different.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M
P_1 Y_1
:
P_M Y_M
Output
Print the ID numbers for all the cities, in ascending order of indices (City 1, City 2, ...).
Examples
Input
2 3
1 32
2 63
1 12
Output
000001000002
000002000001
000001000001
Input
2 3
2 55
2 77
2 99
Output
000002000001
000002000002
000002000003 | instruction | 0 | 4,033 | 1 | 8,066 |
"Correct Solution:
```
N, M = map(int, input().split())
PY = [tuple(list(map(int, input().split()))+[i]) for i in range(M)]
PY.sort(key=lambda x: x[1])
ans = ['']*M
P = [0]*N
for p, y, i in PY:
ret = ''
p -= 1
P[p] += 1
ret += '{:0=6}'.format(p+1)
ret += '{:0=6}'.format(P[p])
ans[i] = ret
print(*ans, sep='\n')
``` | output | 1 | 4,033 | 1 | 8,067 |
Provide a correct Python 3 solution for this coding contest problem.
In Republic of Atcoder, there are N prefectures, and a total of M cities that belong to those prefectures.
City i is established in year Y_i and belongs to Prefecture P_i.
You can assume that there are no multiple cities that are established in the same year.
It is decided to allocate a 12-digit ID number to each city.
If City i is the x-th established city among the cities that belong to Prefecture i, the first six digits of the ID number of City i is P_i, and the last six digits of the ID number is x.
Here, if P_i or x (or both) has less than six digits, zeros are added to the left until it has six digits.
Find the ID numbers for all the cities.
Note that there can be a prefecture with no cities.
Constraints
* 1 \leq N \leq 10^5
* 1 \leq M \leq 10^5
* 1 \leq P_i \leq N
* 1 \leq Y_i \leq 10^9
* Y_i are all different.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M
P_1 Y_1
:
P_M Y_M
Output
Print the ID numbers for all the cities, in ascending order of indices (City 1, City 2, ...).
Examples
Input
2 3
1 32
2 63
1 12
Output
000001000002
000002000001
000001000001
Input
2 3
2 55
2 77
2 99
Output
000002000001
000002000002
000002000003 | instruction | 0 | 4,034 | 1 | 8,068 |
"Correct Solution:
```
n,m=map(int,input().split())
import bisect
l=[[] for _ in range(n)]
l2=[]
for i in range(m):
p,y=map(int,input().split())
bisect.insort_left(l[p-1],y)
l2.append([p,y])
for m in l2:
print("{:06d}".format(m[0]) +"{:06d}".format(bisect.bisect_left(l[m[0]-1],m[1])+1))
``` | output | 1 | 4,034 | 1 | 8,069 |
Provide a correct Python 3 solution for this coding contest problem.
In Republic of Atcoder, there are N prefectures, and a total of M cities that belong to those prefectures.
City i is established in year Y_i and belongs to Prefecture P_i.
You can assume that there are no multiple cities that are established in the same year.
It is decided to allocate a 12-digit ID number to each city.
If City i is the x-th established city among the cities that belong to Prefecture i, the first six digits of the ID number of City i is P_i, and the last six digits of the ID number is x.
Here, if P_i or x (or both) has less than six digits, zeros are added to the left until it has six digits.
Find the ID numbers for all the cities.
Note that there can be a prefecture with no cities.
Constraints
* 1 \leq N \leq 10^5
* 1 \leq M \leq 10^5
* 1 \leq P_i \leq N
* 1 \leq Y_i \leq 10^9
* Y_i are all different.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M
P_1 Y_1
:
P_M Y_M
Output
Print the ID numbers for all the cities, in ascending order of indices (City 1, City 2, ...).
Examples
Input
2 3
1 32
2 63
1 12
Output
000001000002
000002000001
000001000001
Input
2 3
2 55
2 77
2 99
Output
000002000001
000002000002
000002000003 | instruction | 0 | 4,035 | 1 | 8,070 |
"Correct Solution:
```
n,m=map(int,input().split())
py=[list(map(int,input().split()))+[i] for i in range(m)]
py.sort(key=lambda x:x[0]*10**6+x[1])
ne=[1]*(10**5+1)
ans=[]
for p,_,i in py:
ans.append((str(p).zfill(6)+str(ne[p]).zfill(6),i))
ne[p]+=1
ans.sort(key=lambda x:x[1])
for s,_ in ans:
print(s)
``` | output | 1 | 4,035 | 1 | 8,071 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In Republic of Atcoder, there are N prefectures, and a total of M cities that belong to those prefectures.
City i is established in year Y_i and belongs to Prefecture P_i.
You can assume that there are no multiple cities that are established in the same year.
It is decided to allocate a 12-digit ID number to each city.
If City i is the x-th established city among the cities that belong to Prefecture i, the first six digits of the ID number of City i is P_i, and the last six digits of the ID number is x.
Here, if P_i or x (or both) has less than six digits, zeros are added to the left until it has six digits.
Find the ID numbers for all the cities.
Note that there can be a prefecture with no cities.
Constraints
* 1 \leq N \leq 10^5
* 1 \leq M \leq 10^5
* 1 \leq P_i \leq N
* 1 \leq Y_i \leq 10^9
* Y_i are all different.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M
P_1 Y_1
:
P_M Y_M
Output
Print the ID numbers for all the cities, in ascending order of indices (City 1, City 2, ...).
Examples
Input
2 3
1 32
2 63
1 12
Output
000001000002
000002000001
000001000001
Input
2 3
2 55
2 77
2 99
Output
000002000001
000002000002
000002000003
Submitted Solution:
```
N,M = map(int,input().split())
PY=[list(map(int,input().split()))+[0] for _ in range(M)]
sort_PY=sorted(PY,key=lambda x:x[1])
c={}
for i in range(M):
p=sort_PY[i][0]
if(p in c):
c[p]+=1
else:
c[p]=1
sort_PY[i][2]=c[p]
for p,y,z in PY:
print(str(p).zfill(6)+str(z).zfill(6))
``` | instruction | 0 | 4,036 | 1 | 8,072 |
Yes | output | 1 | 4,036 | 1 | 8,073 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In Republic of Atcoder, there are N prefectures, and a total of M cities that belong to those prefectures.
City i is established in year Y_i and belongs to Prefecture P_i.
You can assume that there are no multiple cities that are established in the same year.
It is decided to allocate a 12-digit ID number to each city.
If City i is the x-th established city among the cities that belong to Prefecture i, the first six digits of the ID number of City i is P_i, and the last six digits of the ID number is x.
Here, if P_i or x (or both) has less than six digits, zeros are added to the left until it has six digits.
Find the ID numbers for all the cities.
Note that there can be a prefecture with no cities.
Constraints
* 1 \leq N \leq 10^5
* 1 \leq M \leq 10^5
* 1 \leq P_i \leq N
* 1 \leq Y_i \leq 10^9
* Y_i are all different.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M
P_1 Y_1
:
P_M Y_M
Output
Print the ID numbers for all the cities, in ascending order of indices (City 1, City 2, ...).
Examples
Input
2 3
1 32
2 63
1 12
Output
000001000002
000002000001
000001000001
Input
2 3
2 55
2 77
2 99
Output
000002000001
000002000002
000002000003
Submitted Solution:
```
import bisect
import collections
N, M = map(int, input().split())
PM = [[int(j) for j in input().split()] for i in range(M)]
A = collections.defaultdict(list)
for x, y in sorted(PM):
A[x] += [y]
for x, y in PM:
z = bisect.bisect(A[x], y)
print('%06d%06d'%(x,z))
``` | instruction | 0 | 4,037 | 1 | 8,074 |
Yes | output | 1 | 4,037 | 1 | 8,075 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In Republic of Atcoder, there are N prefectures, and a total of M cities that belong to those prefectures.
City i is established in year Y_i and belongs to Prefecture P_i.
You can assume that there are no multiple cities that are established in the same year.
It is decided to allocate a 12-digit ID number to each city.
If City i is the x-th established city among the cities that belong to Prefecture i, the first six digits of the ID number of City i is P_i, and the last six digits of the ID number is x.
Here, if P_i or x (or both) has less than six digits, zeros are added to the left until it has six digits.
Find the ID numbers for all the cities.
Note that there can be a prefecture with no cities.
Constraints
* 1 \leq N \leq 10^5
* 1 \leq M \leq 10^5
* 1 \leq P_i \leq N
* 1 \leq Y_i \leq 10^9
* Y_i are all different.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M
P_1 Y_1
:
P_M Y_M
Output
Print the ID numbers for all the cities, in ascending order of indices (City 1, City 2, ...).
Examples
Input
2 3
1 32
2 63
1 12
Output
000001000002
000002000001
000001000001
Input
2 3
2 55
2 77
2 99
Output
000002000001
000002000002
000002000003
Submitted Solution:
```
import sys
input=sys.stdin.readline
N,M=[int(n) for n in input().split()]
lis=[[i]+[int(n) for n in input().split()] for i in range(M)]
#print(lis)
l_2=sorted(lis, key=lambda x: x[2])
dic={}
for k,i,j in l_2:
dic[i]=dic.get(i,0)+1
lis[k]='{:0=6}{:0=6}'.format(i,dic[i])
for i in lis:print(i)
``` | instruction | 0 | 4,038 | 1 | 8,076 |
Yes | output | 1 | 4,038 | 1 | 8,077 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In Republic of Atcoder, there are N prefectures, and a total of M cities that belong to those prefectures.
City i is established in year Y_i and belongs to Prefecture P_i.
You can assume that there are no multiple cities that are established in the same year.
It is decided to allocate a 12-digit ID number to each city.
If City i is the x-th established city among the cities that belong to Prefecture i, the first six digits of the ID number of City i is P_i, and the last six digits of the ID number is x.
Here, if P_i or x (or both) has less than six digits, zeros are added to the left until it has six digits.
Find the ID numbers for all the cities.
Note that there can be a prefecture with no cities.
Constraints
* 1 \leq N \leq 10^5
* 1 \leq M \leq 10^5
* 1 \leq P_i \leq N
* 1 \leq Y_i \leq 10^9
* Y_i are all different.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M
P_1 Y_1
:
P_M Y_M
Output
Print the ID numbers for all the cities, in ascending order of indices (City 1, City 2, ...).
Examples
Input
2 3
1 32
2 63
1 12
Output
000001000002
000002000001
000001000001
Input
2 3
2 55
2 77
2 99
Output
000002000001
000002000002
000002000003
Submitted Solution:
```
import collections,bisect
N,M=map(int,input().split())
PY=[list(map(int,input().split())) for i in range(M)]
x=collections.defaultdict(list)
for city,year in sorted(PY):
x[city]+=[year]
for city,year in PY:
num=bisect.bisect(x[city],year)
print("%06d%06d"%(city,num))
``` | instruction | 0 | 4,039 | 1 | 8,078 |
Yes | output | 1 | 4,039 | 1 | 8,079 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In Republic of Atcoder, there are N prefectures, and a total of M cities that belong to those prefectures.
City i is established in year Y_i and belongs to Prefecture P_i.
You can assume that there are no multiple cities that are established in the same year.
It is decided to allocate a 12-digit ID number to each city.
If City i is the x-th established city among the cities that belong to Prefecture i, the first six digits of the ID number of City i is P_i, and the last six digits of the ID number is x.
Here, if P_i or x (or both) has less than six digits, zeros are added to the left until it has six digits.
Find the ID numbers for all the cities.
Note that there can be a prefecture with no cities.
Constraints
* 1 \leq N \leq 10^5
* 1 \leq M \leq 10^5
* 1 \leq P_i \leq N
* 1 \leq Y_i \leq 10^9
* Y_i are all different.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M
P_1 Y_1
:
P_M Y_M
Output
Print the ID numbers for all the cities, in ascending order of indices (City 1, City 2, ...).
Examples
Input
2 3
1 32
2 63
1 12
Output
000001000002
000002000001
000001000001
Input
2 3
2 55
2 77
2 99
Output
000002000001
000002000002
000002000003
Submitted Solution:
```
n,m = list(map(int,input().split()))
a = [[] for i in range(n+1)]
b = []
for i in range(m):
p,s = list(map(int,input().split()))
a[p].append(s)
b.append([p,s])
for i in range(n+1):
a[i].sort()
for i in range(m):
ken = b[i][0]
si = a[ken].index(b[i][1]) +1
ken = str(ken).zfill(6)
si = str(si).zfill(6)
print("".join([ken,si]))
``` | instruction | 0 | 4,040 | 1 | 8,080 |
No | output | 1 | 4,040 | 1 | 8,081 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In Republic of Atcoder, there are N prefectures, and a total of M cities that belong to those prefectures.
City i is established in year Y_i and belongs to Prefecture P_i.
You can assume that there are no multiple cities that are established in the same year.
It is decided to allocate a 12-digit ID number to each city.
If City i is the x-th established city among the cities that belong to Prefecture i, the first six digits of the ID number of City i is P_i, and the last six digits of the ID number is x.
Here, if P_i or x (or both) has less than six digits, zeros are added to the left until it has six digits.
Find the ID numbers for all the cities.
Note that there can be a prefecture with no cities.
Constraints
* 1 \leq N \leq 10^5
* 1 \leq M \leq 10^5
* 1 \leq P_i \leq N
* 1 \leq Y_i \leq 10^9
* Y_i are all different.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M
P_1 Y_1
:
P_M Y_M
Output
Print the ID numbers for all the cities, in ascending order of indices (City 1, City 2, ...).
Examples
Input
2 3
1 32
2 63
1 12
Output
000001000002
000002000001
000001000001
Input
2 3
2 55
2 77
2 99
Output
000002000001
000002000002
000002000003
Submitted Solution:
```
N,M = (int(x) for x in input().split())
p_y_list = []
for i in range(M):
p_y_list.append(tuple(int(x) for x in input().split()))
p_y_list.sort(key = lambda x:x[1])
p_y_list.sort(key = lambda x:x[0])
p_y_id_list = []
p = p_y_list[0][0]
y_c = 1
for i in p_y_list:
if i[0] == p:
p_y_id_list.append((i[0],y_c))
y_c += 1
else:
p = i[0]
y_c = 1
p_y_id_list.append((i[0],y_c))
p_y_id_list.sort(key = lambda x:x[1] , reverse =True)
p_y_id_list.sort(key = lambda x:x[0] , reverse =True)
for i in p_y_id_list:
print(str(i[0]).rjust(6,"0") + str(i[1]).rjust(6,"0"))
``` | instruction | 0 | 4,041 | 1 | 8,082 |
No | output | 1 | 4,041 | 1 | 8,083 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In Republic of Atcoder, there are N prefectures, and a total of M cities that belong to those prefectures.
City i is established in year Y_i and belongs to Prefecture P_i.
You can assume that there are no multiple cities that are established in the same year.
It is decided to allocate a 12-digit ID number to each city.
If City i is the x-th established city among the cities that belong to Prefecture i, the first six digits of the ID number of City i is P_i, and the last six digits of the ID number is x.
Here, if P_i or x (or both) has less than six digits, zeros are added to the left until it has six digits.
Find the ID numbers for all the cities.
Note that there can be a prefecture with no cities.
Constraints
* 1 \leq N \leq 10^5
* 1 \leq M \leq 10^5
* 1 \leq P_i \leq N
* 1 \leq Y_i \leq 10^9
* Y_i are all different.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M
P_1 Y_1
:
P_M Y_M
Output
Print the ID numbers for all the cities, in ascending order of indices (City 1, City 2, ...).
Examples
Input
2 3
1 32
2 63
1 12
Output
000001000002
000002000001
000001000001
Input
2 3
2 55
2 77
2 99
Output
000002000001
000002000002
000002000003
Submitted Solution:
```
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 15 01:01:58 2020
@author: liang
"""
#γΌγγγγ£γ³γ°οΌγ€γ³γγγ―γΉ
#str(1).zfill(6) + str(a.index(2) + 1).zfill(6)
N, M = map(int, input().split())
d = [list() for _ in range(N)]
P = list()
#insert O(M)
for i in range(M):
p, y = map(int,input().split())
d[p-1].append(y)
P.append((p,y))
#year sort O(N log N)
for i in range(N):
d[i].sort()
#search O(M)
for i in range(M):
p, y = P[i]
ans = str(p).zfill(6)+str(d[p-1].index(y)+1).zfill(6)
print(ans)
``` | instruction | 0 | 4,042 | 1 | 8,084 |
No | output | 1 | 4,042 | 1 | 8,085 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In Republic of Atcoder, there are N prefectures, and a total of M cities that belong to those prefectures.
City i is established in year Y_i and belongs to Prefecture P_i.
You can assume that there are no multiple cities that are established in the same year.
It is decided to allocate a 12-digit ID number to each city.
If City i is the x-th established city among the cities that belong to Prefecture i, the first six digits of the ID number of City i is P_i, and the last six digits of the ID number is x.
Here, if P_i or x (or both) has less than six digits, zeros are added to the left until it has six digits.
Find the ID numbers for all the cities.
Note that there can be a prefecture with no cities.
Constraints
* 1 \leq N \leq 10^5
* 1 \leq M \leq 10^5
* 1 \leq P_i \leq N
* 1 \leq Y_i \leq 10^9
* Y_i are all different.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M
P_1 Y_1
:
P_M Y_M
Output
Print the ID numbers for all the cities, in ascending order of indices (City 1, City 2, ...).
Examples
Input
2 3
1 32
2 63
1 12
Output
000001000002
000002000001
000001000001
Input
2 3
2 55
2 77
2 99
Output
000002000001
000002000002
000002000003
Submitted Solution:
```
N,M = map(int,input().split())
lis = [list(map(int,input().split())) for _ in range(M)]
ans_lis = [0] * M
lis_sort = sorted(lis)
i = 1
flag = 0
for _ in range(len(lis_sort)):
if flag != lis_sort[_][0]:
flag = lis_sort[_][0]
i = 1
ans_lis[lis.index(lis_sort[_])] = str(i)
i += 1
for x,y in zip(lis,ans_lis):
print('0'*(6-len(str(x[0]))),x[0],'0'*(6-len(y)),y,sep='')
``` | instruction | 0 | 4,043 | 1 | 8,086 |
No | output | 1 | 4,043 | 1 | 8,087 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Shichikuji is the new resident deity of the South Black Snail Temple. Her first job is as follows:
There are n new cities located in Prefecture X. Cities are numbered from 1 to n. City i is located x_i km North of the shrine and y_i km East of the shrine. It is possible that (x_i, y_i) = (x_j, y_j) even when i β j.
Shichikuji must provide electricity to each city either by building a power station in that city, or by making a connection between that city and another one that already has electricity. So the City has electricity if it has a power station in it or it is connected to a City which has electricity by a direct connection or via a chain of connections.
* Building a power station in City i will cost c_i yen;
* Making a connection between City i and City j will cost k_i + k_j yen per km of wire used for the connection. However, wires can only go the cardinal directions (North, South, East, West). Wires can cross each other. Each wire must have both of its endpoints in some cities. If City i and City j are connected by a wire, the wire will go through any shortest path from City i to City j. Thus, the length of the wire if City i and City j are connected is |x_i - x_j| + |y_i - y_j| km.
Shichikuji wants to do this job spending as little money as possible, since according to her, there isn't really anything else in the world other than money. However, she died when she was only in fifth grade so she is not smart enough for this. And thus, the new resident deity asks for your help.
And so, you have to provide Shichikuji with the following information: minimum amount of yen needed to provide electricity to all cities, the cities in which power stations will be built, and the connections to be made.
If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them.
Input
First line of input contains a single integer n (1 β€ n β€ 2000) β the number of cities.
Then, n lines follow. The i-th line contains two space-separated integers x_i (1 β€ x_i β€ 10^6) and y_i (1 β€ y_i β€ 10^6) β the coordinates of the i-th city.
The next line contains n space-separated integers c_1, c_2, ..., c_n (1 β€ c_i β€ 10^9) β the cost of building a power station in the i-th city.
The last line contains n space-separated integers k_1, k_2, ..., k_n (1 β€ k_i β€ 10^9).
Output
In the first line print a single integer, denoting the minimum amount of yen needed.
Then, print an integer v β the number of power stations to be built.
Next, print v space-separated integers, denoting the indices of cities in which a power station will be built. Each number should be from 1 to n and all numbers should be pairwise distinct. You can print the numbers in arbitrary order.
After that, print an integer e β the number of connections to be made.
Finally, print e pairs of integers a and b (1 β€ a, b β€ n, a β b), denoting that a connection between City a and City b will be made. Each unordered pair of cities should be included at most once (for each (a, b) there should be no more (a, b) or (b, a) pairs). You can print the pairs in arbitrary order.
If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them.
Examples
Input
3
2 3
1 1
3 2
3 2 3
3 2 3
Output
8
3
1 2 3
0
Input
3
2 1
1 2
3 3
23 2 23
3 2 3
Output
27
1
2
2
1 2
2 3
Note
For the answers given in the samples, refer to the following diagrams (cities with power stations are colored green, other cities are colored blue, and wires are colored red):
<image>
For the first example, the cost of building power stations in all cities is 3 + 2 + 3 = 8. It can be shown that no configuration costs less than 8 yen.
For the second example, the cost of building a power station in City 2 is 2. The cost of connecting City 1 and City 2 is 2 β
(3 + 2) = 10. The cost of connecting City 2 and City 3 is 3 β
(2 + 3) = 15. Thus the total cost is 2 + 10 + 15 = 27. It can be shown that no configuration costs less than 27 yen. | instruction | 0 | 4,271 | 1 | 8,542 |
Tags: dsu, graphs, greedy, shortest paths, trees
Correct Solution:
```
import bisect
import functools
import math
import sys
from collections import defaultdict
# input = sys.stdin.readline
rt = lambda: map(int, input().split())
ri = lambda: int(input())
rl = lambda: list(map(int, input().split()))
def dist(x1, y1, x2, y2):
return abs(x1-x2)+abs(y1-y2)
def main():
n = ri()
x, y = [0] * n, [0] * n
for i in range(n):
x[i], y[i] = rt()
c = rl()
k = rl()
val = c.copy()
used = [False] * n
link = [-1] * n
to_build = []
for _ in range(n): # each step removes 1 city
# find min
min_index = -1
min_val = math.inf
for i in range(n):
if not used[i] and val[i] < min_val:
min_index = i
min_val = val[i]
used[min_index] = True
if link[min_index] == -1:
to_build.append(min_index+1)
for i in range(n):
if not used[i]:
to_link = (k[i]+k[min_index])*dist(x[i], y[i], x[min_index], y[min_index])
if to_link < val[i]:
val[i] = to_link
link[i] = min_index
print(sum(val))
print(len(to_build))
print(*to_build)
print(len([x for x in link if x > -1]))
for i in range(n):
if link[i] > -1:
print(i+1, link[i]+1)
if __name__ == '__main__':
main()
``` | output | 1 | 4,271 | 1 | 8,543 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.