message stringlengths 2 49.9k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 446 108k | cluster float64 13 13 | __index_level_0__ int64 892 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 graph G. G has N vertices and M edges. The vertices are numbered from 1 through N, and the i-th edge (1 ≤ i ≤ M) connects Vertex a_i and b_i. G does not have self-loops and multiple edges.
You can repeatedly perform the operation of adding an edge between two vertices. However, G must not have self-loops or multiple edges as the result. Also, if Vertex 1 and 2 are connected directly or indirectly by edges, your body will be exposed to a voltage of 1000000007 volts. This must also be avoided.
Under these conditions, at most how many edges can you add? Note that Vertex 1 and 2 are never connected directly or indirectly in the beginning.
Constraints
* 2 ≤ N ≤ 10^5
* 0 ≤ M ≤ 10^5
* 1 ≤ a_i < b_i ≤ N
* All pairs (a_i, b_i) are distinct.
* Vertex 1 and 2 in G are not connected directly or indirectly by edges.
Input
Input is given from Standard Input in the following format:
N M
a_1 b_1
:
a_M b_M
Output
Print the maximum number of edges that can be added.
Examples
Input
4 1
1 3
Output
2
Input
2 0
Output
0
Input
9 6
1 4
1 8
2 5
3 6
4 8
5 7
Output
12
Submitted Solution:
```
class UnionFind:
def __init__(self, numV):
self.pars = list(range(numV))
self.ranks = [0] * numV
self.sizes = [1] * numV
self.numEs = [0] * numV
def find(self, x):
if self.pars[x] == x: return x
else:
self.pars[x] = self.find(self.pars[x])
return self.pars[x]
def union(self, x, y):
x, y = self.find(x), self.find(y)
if x == y:
self.numEs[x] += 1
elif self.ranks[x] < self.ranks[y]:
self.pars[x] = y
self.sizes[y] += self.sizes[x]
self.numEs[y] += self.numEs[x] + 1
else:
self.pars[y] = x
self.sizes[x] += self.sizes[y]
self.numEs[x] += self.numEs[y] + 1
if self.ranks[x] == self.ranks[y]:
self.ranks[x] += 1
def same(self, x, y):
return self.find(x) == self.find(y)
N, M = map(int, input().split())
ABs = [tuple(map(int, input().split())) for _ in range(M)]
UF = UnionFind(N)
for A, B in ABs:
UF.union(A-1, B-1)
for v in range(N):
UF.find(v)
par1 = UF.find(0)
par2 = UF.find(1)
pars = set(UF.pars)
sizeOther = numEOther = 0
for par in pars:
if par == par1:
size1 = UF.sizes[par]
numE1 = UF.numEs[par]
elif par == par2:
size2 = UF.sizes[par]
numE2 = UF.numEs[par]
else:
sizeOther += UF.sizes[par]
numEOther += UF.numEs[par]
size = size1 + sizeOther
numE = numE1 + numEOther
ans1 = size*(size-1)//2-numE + size2*(size2-1)//2-numE2
size = size2 + sizeOther
numE = numE2 + numEOther
ans2 = size*(size-1)//2-numE + size1*(size1-1)//2-numE1
print(max(ans1, ans2))
``` | instruction | 0 | 71,480 | 13 | 142,960 |
Yes | output | 1 | 71,480 | 13 | 142,961 |
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 graph G. G has N vertices and M edges. The vertices are numbered from 1 through N, and the i-th edge (1 ≤ i ≤ M) connects Vertex a_i and b_i. G does not have self-loops and multiple edges.
You can repeatedly perform the operation of adding an edge between two vertices. However, G must not have self-loops or multiple edges as the result. Also, if Vertex 1 and 2 are connected directly or indirectly by edges, your body will be exposed to a voltage of 1000000007 volts. This must also be avoided.
Under these conditions, at most how many edges can you add? Note that Vertex 1 and 2 are never connected directly or indirectly in the beginning.
Constraints
* 2 ≤ N ≤ 10^5
* 0 ≤ M ≤ 10^5
* 1 ≤ a_i < b_i ≤ N
* All pairs (a_i, b_i) are distinct.
* Vertex 1 and 2 in G are not connected directly or indirectly by edges.
Input
Input is given from Standard Input in the following format:
N M
a_1 b_1
:
a_M b_M
Output
Print the maximum number of edges that can be added.
Examples
Input
4 1
1 3
Output
2
Input
2 0
Output
0
Input
9 6
1 4
1 8
2 5
3 6
4 8
5 7
Output
12
Submitted Solution:
```
class UnionFind:
def __init__(self, n):
self.par = [i for i in range(n+1)]
self.rank = [0] * (n+1)
# 検索
def find(self, x):
if self.par[x] == x:
return x
else:
self.par[x] = self.find(self.par[x])
return self.par[x]
# 併合
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if self.rank[x] < self.rank[y]:
self.par[x] = y
else:
self.par[y] = x
if self.rank[x] == self.rank[y]:
self.rank[x] += 1
# 同じ集合に属するか判定
def same_check(self, x, y):
return self.find(x) == self.find(y)
def ans(self):
print(len(set(self.par))-1)
n,m=map(int,input().split())
uf=UnionFind(n)
for i in range(m):
a,b=map(int,input().split())
uf.union(a,b)
a=1
b=1
c=0
for i in range(3,n+1):
if uf.same_check(1,i):
a+=1
elif uf.same_check(2,i):
b+=1
else:
c+=1
if a>b:
a+=c
else:
b+=c
print(a*(a-1)//2+b*(b-1)//2-m)
``` | instruction | 0 | 71,481 | 13 | 142,962 |
Yes | output | 1 | 71,481 | 13 | 142,963 |
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 graph G. G has N vertices and M edges. The vertices are numbered from 1 through N, and the i-th edge (1 ≤ i ≤ M) connects Vertex a_i and b_i. G does not have self-loops and multiple edges.
You can repeatedly perform the operation of adding an edge between two vertices. However, G must not have self-loops or multiple edges as the result. Also, if Vertex 1 and 2 are connected directly or indirectly by edges, your body will be exposed to a voltage of 1000000007 volts. This must also be avoided.
Under these conditions, at most how many edges can you add? Note that Vertex 1 and 2 are never connected directly or indirectly in the beginning.
Constraints
* 2 ≤ N ≤ 10^5
* 0 ≤ M ≤ 10^5
* 1 ≤ a_i < b_i ≤ N
* All pairs (a_i, b_i) are distinct.
* Vertex 1 and 2 in G are not connected directly or indirectly by edges.
Input
Input is given from Standard Input in the following format:
N M
a_1 b_1
:
a_M b_M
Output
Print the maximum number of edges that can be added.
Examples
Input
4 1
1 3
Output
2
Input
2 0
Output
0
Input
9 6
1 4
1 8
2 5
3 6
4 8
5 7
Output
12
Submitted Solution:
```
import collections
n, m = [ int(v) for v in input().split() ]
connect_list = [ [] for i in range(n) ]
for i in range(m):
a, b = [ int(v)-1 for v in input().split() ]
connect_list[a].append(b)
connect_list[b].append(a)
def dfs(a):
color = [ 0 for i in range(n) ]
color[a] = 1
stack = collections.deque([a])
r = 0
while stack:
s = stack.pop()
color[s] = 2
r += 1
for i in connect_list[s]:
if color[i] == 0:
color[i] = 1
stack.append(i)
return r
x, y = dfs(0), dfs(1)
x, y = max(x, y), min(x, y)
def part_edge(a):
return a*(a-1)//2
x = n - y
total_edge = part_edge(x) + part_edge(y)
print(total_edge-m)
``` | instruction | 0 | 71,482 | 13 | 142,964 |
Yes | output | 1 | 71,482 | 13 | 142,965 |
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 graph G. G has N vertices and M edges. The vertices are numbered from 1 through N, and the i-th edge (1 ≤ i ≤ M) connects Vertex a_i and b_i. G does not have self-loops and multiple edges.
You can repeatedly perform the operation of adding an edge between two vertices. However, G must not have self-loops or multiple edges as the result. Also, if Vertex 1 and 2 are connected directly or indirectly by edges, your body will be exposed to a voltage of 1000000007 volts. This must also be avoided.
Under these conditions, at most how many edges can you add? Note that Vertex 1 and 2 are never connected directly or indirectly in the beginning.
Constraints
* 2 ≤ N ≤ 10^5
* 0 ≤ M ≤ 10^5
* 1 ≤ a_i < b_i ≤ N
* All pairs (a_i, b_i) are distinct.
* Vertex 1 and 2 in G are not connected directly or indirectly by edges.
Input
Input is given from Standard Input in the following format:
N M
a_1 b_1
:
a_M b_M
Output
Print the maximum number of edges that can be added.
Examples
Input
4 1
1 3
Output
2
Input
2 0
Output
0
Input
9 6
1 4
1 8
2 5
3 6
4 8
5 7
Output
12
Submitted Solution:
```
N,M=map(int,input().split())
P=[i for i in range(N+1)]
size=[1 for i in range(N+1)]
size[1]=10**6
size[2]=10**6
def find(a):
if a==P[a]:
return a
else:
return find(P[a])
def union(b,c):
B=find(b)
C=find(c)
if size[C]>size[B]:
P[B]=P[C]
size[C]+=size[B]
else:
P[C]=P[B]
size[B]+=size[C]
L=[]
for i in range(M):
a,b=map(int,input().split())
L.append([a,b])
union(a,b)
One=0
Two=0
for i in range(1,N+1):
if P[i]==2:
Two+=1
elif P[i]==1:
One+=1
if One>Two:
One=N-Two
else:
Two=N-One
print(One*(One-1)//2+Two*(Two-1)//2- M)
``` | instruction | 0 | 71,483 | 13 | 142,966 |
No | output | 1 | 71,483 | 13 | 142,967 |
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 graph G. G has N vertices and M edges. The vertices are numbered from 1 through N, and the i-th edge (1 ≤ i ≤ M) connects Vertex a_i and b_i. G does not have self-loops and multiple edges.
You can repeatedly perform the operation of adding an edge between two vertices. However, G must not have self-loops or multiple edges as the result. Also, if Vertex 1 and 2 are connected directly or indirectly by edges, your body will be exposed to a voltage of 1000000007 volts. This must also be avoided.
Under these conditions, at most how many edges can you add? Note that Vertex 1 and 2 are never connected directly or indirectly in the beginning.
Constraints
* 2 ≤ N ≤ 10^5
* 0 ≤ M ≤ 10^5
* 1 ≤ a_i < b_i ≤ N
* All pairs (a_i, b_i) are distinct.
* Vertex 1 and 2 in G are not connected directly or indirectly by edges.
Input
Input is given from Standard Input in the following format:
N M
a_1 b_1
:
a_M b_M
Output
Print the maximum number of edges that can be added.
Examples
Input
4 1
1 3
Output
2
Input
2 0
Output
0
Input
9 6
1 4
1 8
2 5
3 6
4 8
5 7
Output
12
Submitted Solution:
```
class UnionFind:
def __init__(self, n):
self.par = [i for i in range(n)]
self.node_size = [1] * n
self.edge_size = [0] * n
self.rank = [0] * n
def find(self, x):
if self.par[x] == x:
return x
else:
self.par[x] = self.find(self.par[x])
return self.par[x]
def same_check(self, x, y):
return self.find(x) == self.find(y)
def get_node_size(self, x):
return self.node_size[self.find(x)]
def get_edge_size(self, x):
return self.edge_size[self.find(x)]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
self.edge_size[x] += 1
else:
if self.rank[x] < self.rank[y]:
self.par[x] = y
self.edge_size[y] += self.edge_size[x] + 1
self.node_size[y] += self.node_sizes[x]
else:
self.par[y] = x
self.edge_size[x] += self.edge_size[y] + 1
self.node_size[x] += self.node_size[y]
if self.rank[x] == self.rank[y]:
self.rank[x] += 1
n, m = [int(item) for item in input().split()]
UF = UnionFind(n)
for i in range(m):
x, y = [int(item) - 1 for item in input().split()]
UF.union(x, y)
unconnected_node = 0
unconnected_edge = 0
seen = set()
for i in range(n):
if not UF.same_check(0, i) and not UF.same_check(1, i):
group = UF.find(i)
if group not in seen:
unconnected_edge += UF.edge_size[group]
unconnected_node += UF.node_size[group]
seen.add(group)
if UF.get_node_size(0) > UF.get_node_size(1):
large = 0
small = 1
else:
large = 1
small = 0
A = UF.get_node_size(large) + unconnected_node
B = UF.get_node_size(small)
ans = A * (A - 1) // 2 + B * (B - 1) // 2
ans -= UF.get_edge_size(large) + UF.get_edge_size(small) + unconnected_edge
print(ans)
``` | instruction | 0 | 71,484 | 13 | 142,968 |
No | output | 1 | 71,484 | 13 | 142,969 |
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 graph G. G has N vertices and M edges. The vertices are numbered from 1 through N, and the i-th edge (1 ≤ i ≤ M) connects Vertex a_i and b_i. G does not have self-loops and multiple edges.
You can repeatedly perform the operation of adding an edge between two vertices. However, G must not have self-loops or multiple edges as the result. Also, if Vertex 1 and 2 are connected directly or indirectly by edges, your body will be exposed to a voltage of 1000000007 volts. This must also be avoided.
Under these conditions, at most how many edges can you add? Note that Vertex 1 and 2 are never connected directly or indirectly in the beginning.
Constraints
* 2 ≤ N ≤ 10^5
* 0 ≤ M ≤ 10^5
* 1 ≤ a_i < b_i ≤ N
* All pairs (a_i, b_i) are distinct.
* Vertex 1 and 2 in G are not connected directly or indirectly by edges.
Input
Input is given from Standard Input in the following format:
N M
a_1 b_1
:
a_M b_M
Output
Print the maximum number of edges that can be added.
Examples
Input
4 1
1 3
Output
2
Input
2 0
Output
0
Input
9 6
1 4
1 8
2 5
3 6
4 8
5 7
Output
12
Submitted Solution:
```
N,M=map(int,input().split())
P=[i for i in range(N+1)]
size=[1 for i in range(N+1)]
size[1]=10**6
size[2]=10**6
def find(a):
if a==P[a]:
return a
else:
return find(P[a])
def union(b,c):
B=find(b)
C=find(c)
if size[C]>size[B]:
P[B]=P[C]
size[C]+=size[B]
else:
P[C]=P[B]
size[B]+=size[C]
L=[]
for i in range(M):
a,b=map(int,input().split())
L.append([a,b])
union(a,b)
One=0
Two=0
Other=0
for i in range(1,N+1):
if P[i]==2:
Two+=1
elif P[i]==1:
One+=1
else:
Other+=1
if One>Two:
One+=Other
else:
Two+=Other
print(One*(One-1)//2+Two*(Two-1)//2- M)
``` | instruction | 0 | 71,485 | 13 | 142,970 |
No | output | 1 | 71,485 | 13 | 142,971 |
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 graph G. G has N vertices and M edges. The vertices are numbered from 1 through N, and the i-th edge (1 ≤ i ≤ M) connects Vertex a_i and b_i. G does not have self-loops and multiple edges.
You can repeatedly perform the operation of adding an edge between two vertices. However, G must not have self-loops or multiple edges as the result. Also, if Vertex 1 and 2 are connected directly or indirectly by edges, your body will be exposed to a voltage of 1000000007 volts. This must also be avoided.
Under these conditions, at most how many edges can you add? Note that Vertex 1 and 2 are never connected directly or indirectly in the beginning.
Constraints
* 2 ≤ N ≤ 10^5
* 0 ≤ M ≤ 10^5
* 1 ≤ a_i < b_i ≤ N
* All pairs (a_i, b_i) are distinct.
* Vertex 1 and 2 in G are not connected directly or indirectly by edges.
Input
Input is given from Standard Input in the following format:
N M
a_1 b_1
:
a_M b_M
Output
Print the maximum number of edges that can be added.
Examples
Input
4 1
1 3
Output
2
Input
2 0
Output
0
Input
9 6
1 4
1 8
2 5
3 6
4 8
5 7
Output
12
Submitted Solution:
```
n, m = [ int(v) for v in input().split() ]
connect_list = [ [] for i in range(n) ]
for i in range(m):
a, b = [ int(v)-1 for v in input().split() ]
connect_list[a].append(b)
connect_list[b].append(a)
def dfs(a):
color = [ 0 for i in range(n) ]
color[a] = 1
stack = collections.deque([a])
r = 0
while stack:
s = stack.pop()
color[s] = 2
r += 1
for i in connect_list[s]:
if color[i] == 0:
color[i] = 1
stack.append(i)
return r
x, y = dfs(0), dfs(1)
x, y = max(x, y), min(x, y)
def part_edge(a):
return a*(a-1)//2
x = n - y
total_edge = part_edge(x) + part_edge(y)
print(total_edge-m)
``` | instruction | 0 | 71,486 | 13 | 142,972 |
No | output | 1 | 71,486 | 13 | 142,973 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We will recursively define uninity of a tree, as follows: (Uni is a Japanese word for sea urchins.)
* A tree consisting of one vertex is a tree of uninity 0.
* Suppose there are zero or more trees of uninity k, and a vertex v. If a vertex is selected from each tree of uninity k and connected to v with an edge, the resulting tree is a tree of uninity k+1.
It can be shown that a tree of uninity k is also a tree of uninity k+1,k+2,..., and so forth.
You are given a tree consisting of N vertices. The vertices of the tree are numbered 1 through N, and the i-th of the N-1 edges connects vertices a_i and b_i.
Find the minimum k such that the given tree is a tree of uninity k.
Constraints
* 2 ≦ N ≦ 10^5
* 1 ≦ a_i, b_i ≦ N(1 ≦ i ≦ N-1)
* The given graph is a tree.
Input
The input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
Print the minimum k such that the given tree is a tree of uninity k.
Examples
Input
7
1 2
2 3
2 4
4 6
6 7
7 5
Output
2
Input
12
1 2
2 3
2 4
4 5
5 6
6 7
7 8
5 9
9 10
10 11
11 12
Output
3
Submitted Solution:
```
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N = int(readline())
m = map(int,read().split())
AB = zip(m,m)
graph = [[] for _ in range(N+1)]
for a,b in AB:
graph[a].append(b)
graph[b].append(a)
graph
root = 1
parent = [0] * (N+1)
order = []
stack = [root]
while stack:
x = stack.pop()
order.append(x)
for y in graph[x]:
if y == parent[x]:
continue
parent[y] = x
stack.append(y)
uninity = [0] * (N+1)
dp = [(1<<60)-1] * (N+1) # 使用可能なbitの集合
for x in order[::-1]:
p = parent[x]
# 使用可能なmin
lsb = dp[x] & (-dp[x])
uninity[x] = lsb
dp[x] ^= lsb
dp[x] |= (lsb - 1)
dp[p] &= dp[x]
x = max(uninity).bit_length() - 1
print(x)
``` | instruction | 0 | 71,491 | 13 | 142,982 |
No | output | 1 | 71,491 | 13 | 142,983 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We will recursively define uninity of a tree, as follows: (Uni is a Japanese word for sea urchins.)
* A tree consisting of one vertex is a tree of uninity 0.
* Suppose there are zero or more trees of uninity k, and a vertex v. If a vertex is selected from each tree of uninity k and connected to v with an edge, the resulting tree is a tree of uninity k+1.
It can be shown that a tree of uninity k is also a tree of uninity k+1,k+2,..., and so forth.
You are given a tree consisting of N vertices. The vertices of the tree are numbered 1 through N, and the i-th of the N-1 edges connects vertices a_i and b_i.
Find the minimum k such that the given tree is a tree of uninity k.
Constraints
* 2 ≦ N ≦ 10^5
* 1 ≦ a_i, b_i ≦ N(1 ≦ i ≦ N-1)
* The given graph is a tree.
Input
The input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
Print the minimum k such that the given tree is a tree of uninity k.
Examples
Input
7
1 2
2 3
2 4
4 6
6 7
7 5
Output
2
Input
12
1 2
2 3
2 4
4 5
5 6
6 7
7 8
5 9
9 10
10 11
11 12
Output
3
Submitted Solution:
```
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
import numpy as np
N = int(readline())
m = map(int,read().split())
AB = zip(m,m)
graph = [[] for _ in range(N+1)]
for a,b in AB:
graph[a].append(b)
graph[b].append(a)
root = 1
parent = [0] * (N+1)
order = []
stack = [root]
while stack:
x = stack.pop()
order.append(x)
for y in graph[x]:
if y == parent[x]:
continue
parent[y] = x
stack.append(y)
uninity = [0] * (N+1)
dp = [np.zeros(30,np.int64) for _ in range(N+1)]
answer = -1
for x in order[::-1]:
p = parent[x]
A = dp[x]
twice = (A >= 2)
if np.any(twice):
k = np.where(twice)[0].max()
A[:k] = 1
lsb = np.where(A == 0)[0].min()
if answer < lsb:
answer += 1
uninity[x] = lsb
A[lsb] = 1
A[:lsb] = 0
A[A>0] = 1
dp[p] += A
print(answer)
``` | instruction | 0 | 71,492 | 13 | 142,984 |
No | output | 1 | 71,492 | 13 | 142,985 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We will recursively define uninity of a tree, as follows: (Uni is a Japanese word for sea urchins.)
* A tree consisting of one vertex is a tree of uninity 0.
* Suppose there are zero or more trees of uninity k, and a vertex v. If a vertex is selected from each tree of uninity k and connected to v with an edge, the resulting tree is a tree of uninity k+1.
It can be shown that a tree of uninity k is also a tree of uninity k+1,k+2,..., and so forth.
You are given a tree consisting of N vertices. The vertices of the tree are numbered 1 through N, and the i-th of the N-1 edges connects vertices a_i and b_i.
Find the minimum k such that the given tree is a tree of uninity k.
Constraints
* 2 ≦ N ≦ 10^5
* 1 ≦ a_i, b_i ≦ N(1 ≦ i ≦ N-1)
* The given graph is a tree.
Input
The input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
Print the minimum k such that the given tree is a tree of uninity k.
Examples
Input
7
1 2
2 3
2 4
4 6
6 7
7 5
Output
2
Input
12
1 2
2 3
2 4
4 5
5 6
6 7
7 8
5 9
9 10
10 11
11 12
Output
3
Submitted Solution:
```
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def calc(rt):
e = edge[rt]
f[rt] = 1
g[rt] = 1
g1 = 0
g2 = 0
for son in e:
if(f[son] == 0):
calc(son)
res = f[son]
if(res > f[rt]):
f[rt] = res
res = g[son]
if res + 1 > g[rt]:
g[rt] = res + 1
if(res > g1):
g2 = g1
g1 = res
elif (res > g2):
g2 = res
if g1 + g2 + 1 > f[rt]:
f[rt] = g1 + g2 + 1
if g[rt] > f[rt]:
f[rt] = g[rt]
n = int(input())
edge = []
f = []
g = []
for i in range(0,n):
edge.append(set())
f.append(0)
g.append(0)
for i in range(1,n):
e = input().split(' ')
y = int(e[0]) - 1
x = int(e[1]) - 1
edge[x].add(y)
edge[y].add(x)
calc(0)
length = f[0]
ans = 0
l = 1
while l < length:
ans = ans + 1
l = l + l + 1
print(ans)
``` | instruction | 0 | 71,493 | 13 | 142,986 |
No | output | 1 | 71,493 | 13 | 142,987 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day, Takahashi was given the following problem from Aoki:
* You are given a tree with N vertices and an integer K. The vertices are numbered 1 through N. The edges are represented by pairs of integers (a_i, b_i).
* For a set S of vertices in the tree, let f(S) be the minimum number of the vertices in a subtree of the given tree that contains all vertices in S.
* There are <image> ways to choose K vertices from the trees. For each of them, let S be the set of the chosen vertices, and find the sum of f(S) over all <image> ways.
* Since the answer may be extremely large, print it modulo 924844033(prime).
Since it was too easy for him, he decided to solve this problem for all K = 1,2,...,N.
Constraints
* 2 ≦ N ≦ 200,000
* 1 ≦ a_i, b_i ≦ N
* The given graph is a tree.
Input
The input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}
Output
Print N lines. The i-th line should contain the answer to the problem where K=i, modulo 924844033.
Examples
Input
3
1 2
2 3
Output
3
7
3
Input
4
1 2
1 3
1 4
Output
4
15
13
4
Input
7
1 2
2 3
2 4
4 5
4 6
6 7
Output
7
67
150
179
122
45
7
Submitted Solution:
```
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
import numpy as np
N = int(readline())
m = map(int,read().split())
AB = zip(m,m)
MOD = 998244353
graph = [[] for _ in range(N+1)]
for a,b in AB:
graph[a].append(b)
graph[b].append(a)
root = 1
parent = [0] * (N+1)
order = []
stack = [root]
while stack:
x = stack.pop()
order.append(x)
for y in graph[x]:
if y == parent[x]:
continue
parent[y] = x
stack.append(y)
size = [1] * (N+1) # size of subtree
for v in order[::-1]:
size[parent[v]] += size[v]
P = [0] * N
for s in size[2:]:
P[s] += 1
P[N-s] += 1
class ModArray(np.ndarray):
def __new__(cls, input_array, info=None):
obj = np.asarray(input_array, dtype=np.int64).view(cls)
return obj
@classmethod
def zeros(cls, *args):
obj = np.zeros(*args, dtype=np.int64)
return obj.view(cls)
@classmethod
def ones(cls, *args):
obj = np.ones(*args, dtype=np.int64)
return obj.view(cls)
@classmethod
def arange(cls, *args):
obj = np.arange(*args, dtype=np.int64) % MOD
return obj.view(cls)
@classmethod
def powers(cls, a, N):
B = N.bit_length()
x = cls.ones(1<<B)
for n in range(B):
x[1<<n:1<<(n+1)] = x[:1<<n] * a
a *= a; a %= MOD
return x[:N]
@classmethod
def _set_constant_array(cls, N):
x = cls.arange(N); x[0] = 1
fact = x.cumprod()
x = cls.arange(N,0,-1); x[0] = pow(int(fact[-1]), MOD-2, MOD)
fact_inv = x.cumprod()[::-1]
inv = cls.zeros(N)
inv[1:N] = fact_inv[1:N] * fact[0:N-1]
fact.flags.writeable = False
fact_inv.flags.writeable = False
inv.flags.writeable = False
cls._fact = fact; cls._fact_inv = fact_inv; cls._inverse = inv
@classmethod
def fact(cls, N):
if (getattr(cls, '_fact', None) is None) or len(cls._fact) < N:
cls._set_constant_array(max(N, 10 ** 6))
return cls._fact[:N]
@classmethod
def fact_inv(cls, N):
if (getattr(cls, '_fact', None) is None) or len(cls._fact) < N:
cls._set_constant_array(max(N, 10 ** 6))
return cls._fact_inv[:N]
@classmethod
def inverse(cls, N):
if (getattr(cls, '_fact', None) is None) or len(cls._fact) < N:
cls._set_constant_array(max(N, 10 ** 6))
return cls._inverse[:N]
@classmethod
def convolve_small(cls, f, g):
Lf = len(f); Lg = len(g); L = Lf + Lg - 1
if min(Lf, Lg) < 100 or Lf + Lg < 300:
return (np.convolve(f,g) % MOD).view(cls)
else:
fft = np.fft.rfft; ifft = np.fft.irfft; n = 1 << L.bit_length()
return (np.rint(ifft(fft(f, n) * fft(g, n))[:L]).astype(np.int64) % MOD).view(cls)
@classmethod
def convolve(cls, f, g, fft_killer=False):
Lf = len(f); Lg = len(g)
if Lf < Lg:
f, g = g, f
Lf, Lg = Lg, Lf
if Lg <= (1 << 17) or (not fft_killer):
fl = f & (1 << 15) - 1; fh = f >> 15
gl = g & (1 << 15) - 1; gh = g >> 15
x = cls.convolve_small(fl, gl)
z = cls.convolve_small(fh, gh)
y = cls.convolve_small(fl+fh, gl+gh) - x - z
return x + (y << 15) + (z << 30)
g = g.resize(Lf)
n = Lf // 2
fl = f[:n]; fh = f[n:].copy()
gl = g[:n]; gh = g[n:].copy()
x = ModArray.convolve(fl, gl)
z = ModArray.convolve(fh, gh)
fh[:len(fl)] += fl; gh[:len(gl)] += gl
y = ModArray.convolve(fh, gh)
P = x.resize(Lf + Lf)
P[n : n+len(x)] -= x
P[n : n+len(y)] += y
P[n : n+len(z)] -= z
P[n+n : n+n+len(z)] += z
return P[:Lf+Lg-1]
def print(self, sep=' '):
print(sep.join(self.astype(str)))
def resize(self, N):
L = len(self)
if L >= N:
return self[:N]
A = np.resize(self, N).view(self.__class__)
A[L:] = 0
return A
def diff(self):
return np.diff(self) % MOD
def cumprod(self):
L = len(self); Lsq = int(L**.5+1)
A = self.resize(Lsq**2).reshape(Lsq, Lsq)
for n in range(1,Lsq):
A[:,n] *= A[:,n-1]
for n in range(1,Lsq):
A[n] *= A[n-1,-1]
return A.ravel()[:L]
def __array_wrap__(self, out_arr, context=None):
if out_arr.dtype == np.int64:
if context and context[0] == np.mod:
return out_arr
np.mod(out_arr, MOD, out=out_arr)
return out_arr
else:
return np.asarray(out_arr)
P = ModArray(P)
fact = ModArray.fact(N+10)
fact_inv = ModArray.fact_inv(N+10)
Q = ModArray.convolve(P * fact[:N], fact_inv[:N][::-1])[N-1:]
Q *= fact_inv[:N]
x = fact[N] * fact_inv[:N+1] * fact_inv[:N+1][::-1] * N
x[:-1] -= Q
print('\n'.join(x[1:].astype(str)))
``` | instruction | 0 | 71,494 | 13 | 142,988 |
No | output | 1 | 71,494 | 13 | 142,989 |
Provide a correct Python 3 solution for this coding contest problem.
There is a complete graph of m vertices. Initially, the edges of the complete graph are uncolored. Sunuke did the following for each i (1 ≤ i ≤ n): Select ai vertices from the complete graph and color all edges connecting the selected vertices with color i. None of the sides were painted in multiple colors. Find the minimum value that can be considered as m.
Constraints
* 1 ≤ n ≤ 5
* 2 ≤ ai ≤ 109
Input
n
a1
.. ..
an
Output
Output the minimum value of m on one line.
Examples
Input
2
3
3
Output
5
Input
5
2
3
4
5
6
Output
12 | instruction | 0 | 71,576 | 13 | 143,152 |
"Correct Solution:
```
N = int(input())
A = [int(input()) for i in range(N)]
INF = 10**18
N2 = 2**N
def dfs(i, D):
if i == N:
return sum(D)
b = 1 << i
a = A[i]
def sel(j, state, u):
if j == N2:
D2 = D[:]
for e in u:
D2[e] -= 1
D2[e | b] += 1
D2[b] = a - len(u)
return dfs(i+1, D2)
r = sel(j+1, state, u)
if D[j] > 0 and state & j == 0 and len(u) < a:
u.append(j)
r = min(r, sel(j+1, state | j, u))
u.pop()
return r
return sel(0, 0, [])
print(dfs(0, [0]*N2))
``` | output | 1 | 71,576 | 13 | 143,153 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a weighed undirected connected graph, consisting of n vertices and m edges.
You should answer q queries, the i-th query is to find the shortest distance between vertices u_i and v_i.
Input
The first line contains two integers n and m~(1 ≤ n, m ≤ 10^5, m - n ≤ 20) — the number of vertices and edges in the graph.
Next m lines contain the edges: the i-th edge is a triple of integers v_i, u_i, d_i~(1 ≤ u_i, v_i ≤ n, 1 ≤ d_i ≤ 10^9, u_i ≠ v_i). This triple means that there is an edge between vertices u_i and v_i of weight d_i. It is guaranteed that graph contains no self-loops and multiple edges.
The next line contains a single integer q~(1 ≤ q ≤ 10^5) — the number of queries.
Each of the next q lines contains two integers u_i and v_i~(1 ≤ u_i, v_i ≤ n) — descriptions of the queries.
Pay attention to the restriction m - n ~ ≤ ~ 20.
Output
Print q lines.
The i-th line should contain the answer to the i-th query — the shortest distance between vertices u_i and v_i.
Examples
Input
3 3
1 2 3
2 3 1
3 1 5
3
1 2
1 3
2 3
Output
3
4
1
Input
8 13
1 2 4
2 3 6
3 4 1
4 5 12
5 6 3
6 7 8
7 8 7
1 4 1
1 8 3
2 6 9
2 7 1
4 6 3
6 8 2
8
1 5
1 7
2 3
2 8
3 7
3 4
6 8
7 8
Output
7
5
6
7
7
1
2
7
Submitted Solution:
```
import sys
from array import array # noqa: F401
from collections import deque
from heapq import heappop, heappush
def readline() -> str: return sys.stdin.buffer.readline().decode('utf-8')
n, m = map(int, readline().split())
adj = [[] for _ in range(n)]
cost = [[] for _ in range(n)]
for u, v, d in (map(int, readline().split()) for _ in range(m)):
adj[u-1].append(v-1)
adj[v-1].append(u-1)
cost[u-1].append(d)
cost[v-1].append(d)
dq = deque([0])
visited = array('b', [1] + [0]*(n-1))
extra_edge = []
extra_vertex = set()
anc_size = 17
depth = array('i', [0])*n
anc = [array('i', [0])*anc_size for _ in range(n)]
tree_cost = array('q', [0])*n
while dq:
v = dq.popleft()
for dest, c in zip(adj[v], cost[v]):
par = u = anc[v][0]
for i in range(1, anc_size):
u = anc[v][i] = anc[u][i-1]
if dest == par:
continue
if visited[dest]:
extra_edge.append((v, dest, c))
extra_vertex.update((v, dest))
continue
tree_cost[dest] = tree_cost[v] + c
visited[dest] = 1
anc[dest][0] = v
depth[dest] = depth[v]+1
dq.append(dest)
v_to_i, i_to_v, vi = dict(), dict(), 0
dists = []
extra_vertex = list(extra_vertex)
ext_n = len(extra_vertex)
for v in extra_vertex:
hq = [(0, v)]
dist = array('q', [10**18]) * n
dist[v] = 0
while hq:
cw, cv = heappop(hq)
if dist[cv] < cw:
continue
for dest, w in zip(adj[cv], cost[cv]):
if dist[dest] > cw + w:
dist[dest] = cw + w
heappush(hq, (cw + w, dest))
dists.append(dist)
v_to_i[v] = vi
i_to_v[vi] = v
vi += 1
def climb(v: int, h: int) -> int:
for i in range(anc_size):
if h & (1 << i):
v = anc[v][i]
return v
def get(x: int, y: int) -> int:
if depth[x] < depth[y]:
x, y = y, x
x = climb(x, depth[x] - depth[y])
while x != y:
for j in range(1, anc_size):
if anc[x][j] == anc[y][j]:
x, y = anc[x][j-1], anc[y][j-1]
break
return x
def calc(x: int, y: int) -> int:
lca = get(x, y)
return tree_cost[x] + tree_cost[y] - tree_cost[lca]
q = int(readline())
ans = [0]*q
for i, (u, v) in enumerate(map(int, readline().split()) for _ in range(q)):
u -= 1
v -= 1
if u in v_to_i:
ans[i] = dists[v_to_i[u]][v]
continue
if v in v_to_i:
ans[i] = dists[v_to_i[v]][u]
continue
res = calc(u, v)
for _i, eu in enumerate(extra_vertex):
for ev in extra_vertex[_i:]:
ei, ej = v_to_i[eu], v_to_i[ev]
res = min(
res,
dists[ei][u] + dists[ei][ev] + dists[ej][v],
dists[ej][u] + dists[ei][ev] + dists[ei][v]
)
ans[i] = res
sys.stdout.buffer.write(('\n'.join(map(str, ans))).encode('utf-8'))
``` | instruction | 0 | 71,656 | 13 | 143,312 |
No | output | 1 | 71,656 | 13 | 143,313 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a weighed undirected connected graph, consisting of n vertices and m edges.
You should answer q queries, the i-th query is to find the shortest distance between vertices u_i and v_i.
Input
The first line contains two integers n and m~(1 ≤ n, m ≤ 10^5, m - n ≤ 20) — the number of vertices and edges in the graph.
Next m lines contain the edges: the i-th edge is a triple of integers v_i, u_i, d_i~(1 ≤ u_i, v_i ≤ n, 1 ≤ d_i ≤ 10^9, u_i ≠ v_i). This triple means that there is an edge between vertices u_i and v_i of weight d_i. It is guaranteed that graph contains no self-loops and multiple edges.
The next line contains a single integer q~(1 ≤ q ≤ 10^5) — the number of queries.
Each of the next q lines contains two integers u_i and v_i~(1 ≤ u_i, v_i ≤ n) — descriptions of the queries.
Pay attention to the restriction m - n ~ ≤ ~ 20.
Output
Print q lines.
The i-th line should contain the answer to the i-th query — the shortest distance between vertices u_i and v_i.
Examples
Input
3 3
1 2 3
2 3 1
3 1 5
3
1 2
1 3
2 3
Output
3
4
1
Input
8 13
1 2 4
2 3 6
3 4 1
4 5 12
5 6 3
6 7 8
7 8 7
1 4 1
1 8 3
2 6 9
2 7 1
4 6 3
6 8 2
8
1 5
1 7
2 3
2 8
3 7
3 4
6 8
7 8
Output
7
5
6
7
7
1
2
7
Submitted Solution:
```
import sys
from array import array # noqa: F401
from collections import deque
from heapq import heappop, heappush
def readline() -> str: return sys.stdin.buffer.readline().decode('utf-8')
n, m = map(int, readline().split())
adj = [[] for _ in range(n)]
cost = [[] for _ in range(n)]
for u, v, d in (map(int, readline().split()) for _ in range(m)):
adj[u-1].append(v-1)
adj[v-1].append(u-1)
cost[u-1].append(d)
cost[v-1].append(d)
dq = deque([0])
visited = array('b', [1] + [0]*(n-1))
extra_edge = []
extra_vertex = set()
anc_size = 17
depth = array('i', [0])*n
anc = [array('i', [0])*anc_size for _ in range(n)]
tree_cost = array('q', [0])*n
while dq:
v = dq.popleft()
for dest, c in zip(adj[v], cost[v]):
par = u = anc[v][0]
for i in range(1, anc_size):
u = anc[v][i] = anc[u][i-1]
if dest == par:
continue
if visited[dest]:
extra_edge.append((v, dest, c))
extra_vertex.update((v, dest))
continue
tree_cost[dest] = tree_cost[v] + c
visited[dest] = 1
anc[dest][0] = v
depth[dest] = depth[v]+1
dq.append(dest)
v_to_i, i_to_v, vi = dict(), dict(), 0
dists = []
for v in extra_vertex:
hq = [(0, v)]
dist = array('q', [10**18]) * n
dist[v] = 0
while hq:
cw, cv = heappop(hq)
if dist[cv] < cw:
continue
for dest, w in zip(adj[cv], cost[cv]):
if dist[dest] > cw + w:
dist[dest] = cw + w
heappush(hq, (cw + w, dest))
dists.append(dist)
v_to_i[v] = vi
i_to_v[vi] = v
vi += 1
def climb(v: int, h: int) -> int:
for i in range(anc_size):
if h & (1 << i):
v = anc[v][i]
return v
def get(x: int, y: int) -> int:
if depth[x] < depth[y]:
x, y = y, x
x = climb(x, depth[x] - depth[y])
while x != y:
for j in range(1, anc_size):
if anc[x][j] == anc[y][j]:
x, y = anc[x][j-1], anc[y][j-1]
break
return x
def calc(x: int, y: int) -> int:
lca = get(x, y)
return tree_cost[x] + tree_cost[y] - tree_cost[lca]
q = int(readline())
ans = [0]*q
for i, (u, v) in enumerate(map(int, readline().split()) for _ in range(q)):
u -= 1
v -= 1
res = calc(u, v)
for eu, ev, w in extra_edge:
ei, ej = v_to_i[eu], v_to_i[ev]
res = min(
res,
dists[ei][u] + dists[ei][ev] + dists[ej][v],
dists[ej][u] + dists[ei][ev] + dists[ei][v]
)
ans[i] = res
sys.stdout.buffer.write(('\n'.join(map(str, ans))).encode('utf-8'))
``` | instruction | 0 | 71,657 | 13 | 143,314 |
No | output | 1 | 71,657 | 13 | 143,315 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a weighed undirected connected graph, consisting of n vertices and m edges.
You should answer q queries, the i-th query is to find the shortest distance between vertices u_i and v_i.
Input
The first line contains two integers n and m~(1 ≤ n, m ≤ 10^5, m - n ≤ 20) — the number of vertices and edges in the graph.
Next m lines contain the edges: the i-th edge is a triple of integers v_i, u_i, d_i~(1 ≤ u_i, v_i ≤ n, 1 ≤ d_i ≤ 10^9, u_i ≠ v_i). This triple means that there is an edge between vertices u_i and v_i of weight d_i. It is guaranteed that graph contains no self-loops and multiple edges.
The next line contains a single integer q~(1 ≤ q ≤ 10^5) — the number of queries.
Each of the next q lines contains two integers u_i and v_i~(1 ≤ u_i, v_i ≤ n) — descriptions of the queries.
Pay attention to the restriction m - n ~ ≤ ~ 20.
Output
Print q lines.
The i-th line should contain the answer to the i-th query — the shortest distance between vertices u_i and v_i.
Examples
Input
3 3
1 2 3
2 3 1
3 1 5
3
1 2
1 3
2 3
Output
3
4
1
Input
8 13
1 2 4
2 3 6
3 4 1
4 5 12
5 6 3
6 7 8
7 8 7
1 4 1
1 8 3
2 6 9
2 7 1
4 6 3
6 8 2
8
1 5
1 7
2 3
2 8
3 7
3 4
6 8
7 8
Output
7
5
6
7
7
1
2
7
Submitted Solution:
```
nm = input()
ns = [int(s) for s in nm.split()]
n = ns[0]
m = ns[1]
inf = 10**10
dist = [[inf for i in range(0, n)] for j in range(0, n)]
for i in range(0, m):
line = input()
nums = [int(s) for s in line.split()]
i = nums[0]-1
j = nums[1]-1
w = nums[2]
dist[i][j] = w
dist[j][i] = w
q = int(input())
queries = []
for i in range(0,q):
line = input()
nums = [int(s) for s in line.split()]
u = nums[0]-1
v = nums[1]-1
queries.append((u,v))
# shortest path
for k in range(n):
for i in range(n):
for j in range(n):
val = min(dist[i][j], dist[i][k] + dist[k][j])
dist[i][j] = val
dist[j][i] = val
for (u, v) in queries:
print(dist[u][v])
``` | instruction | 0 | 71,658 | 13 | 143,316 |
No | output | 1 | 71,658 | 13 | 143,317 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a weighed undirected connected graph, consisting of n vertices and m edges.
You should answer q queries, the i-th query is to find the shortest distance between vertices u_i and v_i.
Input
The first line contains two integers n and m~(1 ≤ n, m ≤ 10^5, m - n ≤ 20) — the number of vertices and edges in the graph.
Next m lines contain the edges: the i-th edge is a triple of integers v_i, u_i, d_i~(1 ≤ u_i, v_i ≤ n, 1 ≤ d_i ≤ 10^9, u_i ≠ v_i). This triple means that there is an edge between vertices u_i and v_i of weight d_i. It is guaranteed that graph contains no self-loops and multiple edges.
The next line contains a single integer q~(1 ≤ q ≤ 10^5) — the number of queries.
Each of the next q lines contains two integers u_i and v_i~(1 ≤ u_i, v_i ≤ n) — descriptions of the queries.
Pay attention to the restriction m - n ~ ≤ ~ 20.
Output
Print q lines.
The i-th line should contain the answer to the i-th query — the shortest distance between vertices u_i and v_i.
Examples
Input
3 3
1 2 3
2 3 1
3 1 5
3
1 2
1 3
2 3
Output
3
4
1
Input
8 13
1 2 4
2 3 6
3 4 1
4 5 12
5 6 3
6 7 8
7 8 7
1 4 1
1 8 3
2 6 9
2 7 1
4 6 3
6 8 2
8
1 5
1 7
2 3
2 8
3 7
3 4
6 8
7 8
Output
7
5
6
7
7
1
2
7
Submitted Solution:
```
import sys
from array import array # noqa: F401
from collections import deque
from heapq import heappop, heappush
def readline() -> str: return sys.stdin.buffer.readline().decode('utf-8')
n, m = map(int, readline().split())
adj = [[] for _ in range(n)]
cost = [[] for _ in range(n)]
for u, v, d in (map(int, readline().split()) for _ in range(m)):
adj[u-1].append(v-1)
adj[v-1].append(u-1)
cost[u-1].append(d)
cost[v-1].append(d)
dq = deque([0])
visited = array('b', [1] + [0]*(n-1))
extra_edge = []
extra_vertex = set()
anc_size = 17
depth = array('i', [0])*n
anc = [array('i', [0])*anc_size for _ in range(n)]
tree_cost = array('q', [0])*n
while dq:
v = dq.popleft()
for dest, c in zip(adj[v], cost[v]):
par = u = anc[v][0]
for i in range(1, anc_size):
u = anc[v][i] = anc[u][i-1]
if dest == par:
continue
if visited[dest]:
extra_edge.append((v, dest, c))
extra_vertex.update((v, dest))
continue
tree_cost[dest] = tree_cost[v] + c
visited[dest] = 1
anc[dest][0] = v
depth[dest] = depth[v]+1
dq.append(dest)
v_to_i, i_to_v, vi = dict(), dict(), 0
dists = []
extra_vertex = list(extra_vertex)
ext_n = len(extra_vertex)
for v in extra_vertex:
hq = [(0, v)]
dist = array('q', [10**18]) * n
dist[v] = 0
while hq:
cw, cv = heappop(hq)
if dist[cv] < cw:
continue
for dest, w in zip(adj[cv], cost[cv]):
if dist[dest] > cw + w:
dist[dest] = cw + w
heappush(hq, (cw + w, dest))
dists.append(dist)
v_to_i[v] = vi
i_to_v[vi] = v
vi += 1
def climb(v: int, h: int) -> int:
for i in range(anc_size):
if h & (1 << i):
v = anc[v][i]
return v
def get(x: int, y: int) -> int:
if depth[x] < depth[y]:
x, y = y, x
x = climb(x, depth[x] - depth[y])
while x != y:
for j in range(1, anc_size):
if anc[x][j] == anc[y][j]:
x, y = anc[x][j-1], anc[y][j-1]
break
return x
def calc(x: int, y: int) -> int:
lca = get(x, y)
return tree_cost[x] + tree_cost[y] - tree_cost[lca]
q = int(readline())
ans = [0]*q
for i, (u, v) in enumerate(map(int, readline().split()) for _ in range(q)):
u -= 1
v -= 1
if u in v_to_i:
ans[i] = dists[v_to_i[u]][v]
continue
if v in v_to_i:
ans[i] = dists[v_to_i[v]][u]
continue
res = calc(u, v)
for eu in extra_vertex:
for ev in extra_vertex:
ei, ej = v_to_i[eu], v_to_i[ev]
res = min(
res,
dists[ei][u] + dists[ei][ev] + dists[ej][v],
)
ans[i] = res
sys.stdout.buffer.write(('\n'.join(map(str, ans))).encode('utf-8'))
``` | instruction | 0 | 71,659 | 13 | 143,318 |
No | output | 1 | 71,659 | 13 | 143,319 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either 0 or 1; exactly m edges have weight 1, and all others have weight 0.
Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
Input
The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ min((n(n-1))/(2),10^5)), the number of vertices and the number of edges of weight 1 in the graph.
The i-th of the next m lines contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i), the endpoints of the i-th edge of weight 1.
It is guaranteed that no edge appears twice in the input.
Output
Output a single integer, the weight of the minimum spanning tree of the graph.
Examples
Input
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
Output
2
Input
3 0
Output
0
Note
The graph from the first sample is shown below. Dashed edges have weight 0, other edges have weight 1. One of the minimum spanning trees is highlighted in orange and has total weight 2.
<image>
In the second sample, all edges have weight 0 so any spanning tree has total weight 0. | instruction | 0 | 71,754 | 13 | 143,508 |
Tags: dfs and similar, dsu, graphs, sortings
Correct Solution:
```
#!/usr/bin/env python3
from collections import deque
import sys
sys.setrecursionlimit(10**8)
input = sys.stdin.readline
n, m = [int(item) for item in input().split()]
ans = 0
edge = set()
for i in range(m):
a, b = [int(item) - 1 for item in input().split()]
edge.add((a, b))
edge.add((b, a))
ans = 0
visited = [0] * n
for i in range(n):
if visited[i]:
continue
ans += 1
dq = deque()
unseen = set(item for item in range(n))
dq.append(i)
unseen.remove(i)
while dq:
v = dq.popleft()
visited[v] = 1
to_remove = []
for item in unseen:
if (v, item) not in edge:
dq.append(item)
to_remove.append(item)
for item in to_remove:
unseen.remove(item)
print(ans - 1)
``` | output | 1 | 71,754 | 13 | 143,509 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either 0 or 1; exactly m edges have weight 1, and all others have weight 0.
Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
Input
The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ min((n(n-1))/(2),10^5)), the number of vertices and the number of edges of weight 1 in the graph.
The i-th of the next m lines contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i), the endpoints of the i-th edge of weight 1.
It is guaranteed that no edge appears twice in the input.
Output
Output a single integer, the weight of the minimum spanning tree of the graph.
Examples
Input
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
Output
2
Input
3 0
Output
0
Note
The graph from the first sample is shown below. Dashed edges have weight 0, other edges have weight 1. One of the minimum spanning trees is highlighted in orange and has total weight 2.
<image>
In the second sample, all edges have weight 0 so any spanning tree has total weight 0. | instruction | 0 | 71,755 | 13 | 143,510 |
Tags: dfs and similar, dsu, graphs, sortings
Correct Solution:
```
import sys
import math
from collections import defaultdict,Counter,deque
# input=sys.stdin.readline
# def print(x):
# sys.stdout.write(str(x)+"\n")
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# sys.stdout=open("CP2/output.txt",'w')
# sys.stdin=open("CP2/input.txt",'r')
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
@bootstrap
def find(u):
s=[]
for j in visit:
if j not in l[u]:
s.append(j)
for j in s:
visit.remove(j)
for j in s:
yield find(j)
yield 0
# mod=pow(10,9)+7
n,m=map(int,input().split())
l=defaultdict(set)
for i in range(m):
a,b=map(int,input().split())
l[a].add(b)
l[b].add(a)
ans=0
# print(l)
visit=set(range(1,n+1))
for j in range(1,n+1):
if j in visit:
ans+=1
visit.remove(j)
find(j)
print(ans-1)
``` | output | 1 | 71,755 | 13 | 143,511 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either 0 or 1; exactly m edges have weight 1, and all others have weight 0.
Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
Input
The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ min((n(n-1))/(2),10^5)), the number of vertices and the number of edges of weight 1 in the graph.
The i-th of the next m lines contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i), the endpoints of the i-th edge of weight 1.
It is guaranteed that no edge appears twice in the input.
Output
Output a single integer, the weight of the minimum spanning tree of the graph.
Examples
Input
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
Output
2
Input
3 0
Output
0
Note
The graph from the first sample is shown below. Dashed edges have weight 0, other edges have weight 1. One of the minimum spanning trees is highlighted in orange and has total weight 2.
<image>
In the second sample, all edges have weight 0 so any spanning tree has total weight 0. | instruction | 0 | 71,756 | 13 | 143,512 |
Tags: dfs and similar, dsu, graphs, sortings
Correct Solution:
```
from sys import stdin, stdout
from collections import Counter, deque
from bisect import bisect_left
from itertools import product
input = stdin.buffer.readline
n, m = map(int, input().split())
e = [set() for _ in range(n+1)]
for _ in range(m):
a, b = map(int, input().split())
e[a].add(b)
e[b].add(a)
res, cc = 0, set(range(1, n+1))
for u in range(1, n+1):
for v in cc:
if v not in e[u] and u != v:
e[v].intersection_update(e[u])
cc.remove(u)
break
else:
cc.remove(u)
res += 1
print(res-1)
``` | output | 1 | 71,756 | 13 | 143,513 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either 0 or 1; exactly m edges have weight 1, and all others have weight 0.
Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
Input
The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ min((n(n-1))/(2),10^5)), the number of vertices and the number of edges of weight 1 in the graph.
The i-th of the next m lines contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i), the endpoints of the i-th edge of weight 1.
It is guaranteed that no edge appears twice in the input.
Output
Output a single integer, the weight of the minimum spanning tree of the graph.
Examples
Input
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
Output
2
Input
3 0
Output
0
Note
The graph from the first sample is shown below. Dashed edges have weight 0, other edges have weight 1. One of the minimum spanning trees is highlighted in orange and has total weight 2.
<image>
In the second sample, all edges have weight 0 so any spanning tree has total weight 0. | instruction | 0 | 71,757 | 13 | 143,514 |
Tags: dfs and similar, dsu, graphs, sortings
Correct Solution:
```
# from sys import stdin
# def rl():
# return [int(w) for w in stdin.readline().split()]
from bisect import bisect_right
from bisect import bisect_left
from collections import defaultdict
from math import sqrt,factorial,gcd,log2,inf,ceil
# map(int,input().split())
# l = list(map(int,input().split()))
import sys
sys.setrecursionlimit(10**9)
n,m = map(int,input().split())
hash = defaultdict(set)
for i in range(m):
a,b = map(int,input().split())
hash[a].add(b)
hash[b].add(a)
count = 0
un = {i+1 for i in range(n)}
while un:
queue = {un.pop()}
while queue:
z = queue.pop()
nxt = [u for u in un if u not in hash[z]]
un.difference_update(nxt)
queue.update(nxt)
count+=1
print(count-1)
``` | output | 1 | 71,757 | 13 | 143,515 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either 0 or 1; exactly m edges have weight 1, and all others have weight 0.
Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
Input
The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ min((n(n-1))/(2),10^5)), the number of vertices and the number of edges of weight 1 in the graph.
The i-th of the next m lines contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i), the endpoints of the i-th edge of weight 1.
It is guaranteed that no edge appears twice in the input.
Output
Output a single integer, the weight of the minimum spanning tree of the graph.
Examples
Input
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
Output
2
Input
3 0
Output
0
Note
The graph from the first sample is shown below. Dashed edges have weight 0, other edges have weight 1. One of the minimum spanning trees is highlighted in orange and has total weight 2.
<image>
In the second sample, all edges have weight 0 so any spanning tree has total weight 0. | instruction | 0 | 71,758 | 13 | 143,516 |
Tags: dfs and similar, dsu, graphs, sortings
Correct Solution:
```
import sys
input = sys.stdin.readline
N, M = map(int, input().split())
E = [[] for _ in range(N+1)]
for _ in range(M):
v, u = map(int, input().split())
E[v].append(u)
E[u].append(v)
Open = [True] * (N+1)
Rem = set(range(1, N+1))
def bfs(v):
Open[v] = True
global Rem
Rem.remove(v)
q = [v]
while q:
v = q.pop()
set_E_v = set(E[v])
for u in (Rem - set_E_v):
if Open[u]:
Open[u] = False
q.append(u)
Rem &= set_E_v
ans = -1
for v in range(1, N+1):
if Open[v]:
ans += 1
bfs(v)
print(ans)
``` | output | 1 | 71,758 | 13 | 143,517 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either 0 or 1; exactly m edges have weight 1, and all others have weight 0.
Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
Input
The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ min((n(n-1))/(2),10^5)), the number of vertices and the number of edges of weight 1 in the graph.
The i-th of the next m lines contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i), the endpoints of the i-th edge of weight 1.
It is guaranteed that no edge appears twice in the input.
Output
Output a single integer, the weight of the minimum spanning tree of the graph.
Examples
Input
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
Output
2
Input
3 0
Output
0
Note
The graph from the first sample is shown below. Dashed edges have weight 0, other edges have weight 1. One of the minimum spanning trees is highlighted in orange and has total weight 2.
<image>
In the second sample, all edges have weight 0 so any spanning tree has total weight 0. | instruction | 0 | 71,759 | 13 | 143,518 |
Tags: dfs and similar, dsu, graphs, sortings
Correct Solution:
```
class UnionFind(object):
__slots__ = ['nodes']
def __init__(self, n: int):
self.nodes = [-1]*n
def size(self, x: int) -> int:
return -self.nodes[self.find(x)]
def find(self, x: int) -> int:
if self.nodes[x] < 0:
return x
else:
self.nodes[x] = self.find(self.nodes[x])
return self.nodes[x]
def unite(self, x: int, y: int) -> bool:
root_x, root_y, nodes = self.find(x), self.find(y), self.nodes
if root_x != root_y:
if nodes[root_x] > nodes[root_y]:
root_x, root_y = root_y, root_x
nodes[root_x] += nodes[root_y]
nodes[root_y] = root_x
return root_x != root_y
if __name__ == '__main__':
import sys
from collections import Counter
n, m = map(int, input().split())
rev_edges = [[] for _ in range(n)]
for s, t in (map(int, l.split()) for l in sys.stdin):
if s < t:
rev_edges[t-1].append(s-1)
else:
rev_edges[s-1].append(t-1)
uf = UnionFind(n)
find, unite, size = uf.find, uf.unite, uf.size
zero_union = set()
for v in range(n):
cnt = Counter()
for src in rev_edges[v]:
cnt[find(src)] += 1
for zero_v in zero_union:
root = find(zero_v)
if size(root) > cnt[root]:
unite(root, v)
zero_union = set(find(v_) for v_ in zero_union) | {find(v)}
print(len(zero_union)-1)
``` | output | 1 | 71,759 | 13 | 143,519 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either 0 or 1; exactly m edges have weight 1, and all others have weight 0.
Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
Input
The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ min((n(n-1))/(2),10^5)), the number of vertices and the number of edges of weight 1 in the graph.
The i-th of the next m lines contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i), the endpoints of the i-th edge of weight 1.
It is guaranteed that no edge appears twice in the input.
Output
Output a single integer, the weight of the minimum spanning tree of the graph.
Examples
Input
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
Output
2
Input
3 0
Output
0
Note
The graph from the first sample is shown below. Dashed edges have weight 0, other edges have weight 1. One of the minimum spanning trees is highlighted in orange and has total weight 2.
<image>
In the second sample, all edges have weight 0 so any spanning tree has total weight 0. | instruction | 0 | 71,760 | 13 | 143,520 |
Tags: dfs and similar, dsu, graphs, sortings
Correct Solution:
```
from sys import stdin
def rl():
return [int(w) for w in stdin.readline().split()]
n,m = rl()
he = [set() for _ in range(n+1)]
for _ in range(m):
a,b = rl()
he[a].add(b)
he[b].add(a)
unvisited = set(range(1,n+1))
ccs = 0
while unvisited:
fringe = {unvisited.pop()}
while fringe:
v = fringe.pop()
nxt = [u for u in unvisited if u not in he[v]]
unvisited.difference_update(nxt)
fringe.update(nxt)
ccs += 1
print(ccs-1)
``` | output | 1 | 71,760 | 13 | 143,521 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either 0 or 1; exactly m edges have weight 1, and all others have weight 0.
Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
Input
The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ min((n(n-1))/(2),10^5)), the number of vertices and the number of edges of weight 1 in the graph.
The i-th of the next m lines contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i), the endpoints of the i-th edge of weight 1.
It is guaranteed that no edge appears twice in the input.
Output
Output a single integer, the weight of the minimum spanning tree of the graph.
Examples
Input
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
Output
2
Input
3 0
Output
0
Note
The graph from the first sample is shown below. Dashed edges have weight 0, other edges have weight 1. One of the minimum spanning trees is highlighted in orange and has total weight 2.
<image>
In the second sample, all edges have weight 0 so any spanning tree has total weight 0. | instruction | 0 | 71,761 | 13 | 143,522 |
Tags: dfs and similar, dsu, graphs, sortings
Correct Solution:
```
import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
n,m = map(int, input().split())
G = [set() for i in range(n)]
for i in range(m):
a,b = map(int, input().split())
a,b = a-1,b-1
G[a].add(b)
G[b].add(a)
ans = 0
unused = set(range(n))
while unused:
cur = {unused.pop()}
while cur:
i = cur.pop()
nxt = {j for j in unused if j not in G[i]}
unused.difference_update(nxt)
cur.update(nxt)
ans += 1
print(ans-1)
``` | output | 1 | 71,761 | 13 | 143,523 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either 0 or 1; exactly m edges have weight 1, and all others have weight 0.
Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
Input
The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ min((n(n-1))/(2),10^5)), the number of vertices and the number of edges of weight 1 in the graph.
The i-th of the next m lines contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i), the endpoints of the i-th edge of weight 1.
It is guaranteed that no edge appears twice in the input.
Output
Output a single integer, the weight of the minimum spanning tree of the graph.
Examples
Input
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
Output
2
Input
3 0
Output
0
Note
The graph from the first sample is shown below. Dashed edges have weight 0, other edges have weight 1. One of the minimum spanning trees is highlighted in orange and has total weight 2.
<image>
In the second sample, all edges have weight 0 so any spanning tree has total weight 0.
Submitted Solution:
```
import collections as cc
import sys
input=sys.stdin.readline
#sys.setrecursionlimit(10**9)
I=lambda:list(map(int,input().split()))
n,m=I()
g=[set() for i in range(n+1)]
xx=[0]*(n+1)
for i in range(m):
x,y=I()
g[x].add(y)
g[y].add(x)
parent=[i for i in range(n+1)]
def find(x):
#print(x,parent[x])
while x!=parent[x]:
x=parent[x]
return x
def union(x,y):
#print(x,y)
a=find(x)
b=find(y)
#print(a,b)
if a!=b:
parent[x]=parent[y]=min(a,b)
ff=cc.defaultdict(int)
used=cc.defaultdict(int)
for i in range(1,n+1):
if find(i)==i:
for j in range(1,n+1):
if j not in g[i]:
g[i]&=g[j]
for j in range(1,n+1):
if j not in g[i]:
union(i,j)
print(len(set([find(i) for i in range(1,n+1)]))-1)
``` | instruction | 0 | 71,762 | 13 | 143,524 |
Yes | output | 1 | 71,762 | 13 | 143,525 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either 0 or 1; exactly m edges have weight 1, and all others have weight 0.
Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
Input
The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ min((n(n-1))/(2),10^5)), the number of vertices and the number of edges of weight 1 in the graph.
The i-th of the next m lines contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i), the endpoints of the i-th edge of weight 1.
It is guaranteed that no edge appears twice in the input.
Output
Output a single integer, the weight of the minimum spanning tree of the graph.
Examples
Input
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
Output
2
Input
3 0
Output
0
Note
The graph from the first sample is shown below. Dashed edges have weight 0, other edges have weight 1. One of the minimum spanning trees is highlighted in orange and has total weight 2.
<image>
In the second sample, all edges have weight 0 so any spanning tree has total weight 0.
Submitted Solution:
```
import sys,math,itertools
from collections import Counter,deque,defaultdict
from bisect import bisect_left,bisect_right
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
n,m = inpl()
g = [set() for _ in range(n+1)]
for _ in range(m):
a,b = inpl()
a,b = a-1,b-1
g[a].add(b)
g[b].add(a)
seen = [False] * n
nd = set(x for x in range(n))
res = 0
def ch(i):
q = deque([i])
global nd
nd.remove(i)
while q:
nv = q.popleft()
now = g[nv]
for v in nd-now:
if seen[v]: continue
seen[v] = True
nd.remove(v)
q.append(v)
for i in range(n):
if seen[i]: continue
seen[i] = True
res += 1
ch(i)
print(res-1)
``` | instruction | 0 | 71,763 | 13 | 143,526 |
Yes | output | 1 | 71,763 | 13 | 143,527 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either 0 or 1; exactly m edges have weight 1, and all others have weight 0.
Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
Input
The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ min((n(n-1))/(2),10^5)), the number of vertices and the number of edges of weight 1 in the graph.
The i-th of the next m lines contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i), the endpoints of the i-th edge of weight 1.
It is guaranteed that no edge appears twice in the input.
Output
Output a single integer, the weight of the minimum spanning tree of the graph.
Examples
Input
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
Output
2
Input
3 0
Output
0
Note
The graph from the first sample is shown below. Dashed edges have weight 0, other edges have weight 1. One of the minimum spanning trees is highlighted in orange and has total weight 2.
<image>
In the second sample, all edges have weight 0 so any spanning tree has total weight 0.
Submitted Solution:
```
import sys
ip=lambda :sys.stdin.readline().rstrip()
from collections import defaultdict
def f(n):
isv[n]=True
if n in s:
s.remove(n)
a=[]
for i in s:
if not isv[i] and i not in d[n]:
a.append(i)
for i in a:
if i in s:
s.remove(i)
for i in a:
f(i)
n,m=map(int,ip().split())
d=defaultdict(lambda :dict())
s=set()
isv=[False]*(n)
for i in range(n):
s.add(i)
for _ in range(m):
u,v=map(int,ip().split())
u-=1
v-=1
d[u][v]=True
d[v][u]=True
ans=0
for i in range(n):
if not isv[i]:
f(i)
ans+=1
print(ans-1)
``` | instruction | 0 | 71,764 | 13 | 143,528 |
Yes | output | 1 | 71,764 | 13 | 143,529 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either 0 or 1; exactly m edges have weight 1, and all others have weight 0.
Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
Input
The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ min((n(n-1))/(2),10^5)), the number of vertices and the number of edges of weight 1 in the graph.
The i-th of the next m lines contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i), the endpoints of the i-th edge of weight 1.
It is guaranteed that no edge appears twice in the input.
Output
Output a single integer, the weight of the minimum spanning tree of the graph.
Examples
Input
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
Output
2
Input
3 0
Output
0
Note
The graph from the first sample is shown below. Dashed edges have weight 0, other edges have weight 1. One of the minimum spanning trees is highlighted in orange and has total weight 2.
<image>
In the second sample, all edges have weight 0 so any spanning tree has total weight 0.
Submitted Solution:
```
n, m, *t = map(int, open(0).read().split())
from collections import defaultdict
mp = defaultdict(int)
s1 = []
s2 = []
s1.append(1)
for i in range(2, n + 1):
s2.append(i)
for a, b in zip(*[iter(t)] * 2):
mp[(a, b)] = 1
mp[(b, a)] = 1
ans = 0
while len(s2):
ns1 = []
ss1 = set()
for i in s1:
for j in s2:
if mp[(i, j)]:
continue
ns1.append(j)
ss1.add(j)
s2 = list(set(s2)-ss1)
if len(ss1) == 0:
ans += 1
s1 = [s2.pop()]
else:
s1 = ns1
if len(s2) == 0 and len(s1) and ans>0:
ans += 1
print(max(0,ans-1))
``` | instruction | 0 | 71,765 | 13 | 143,530 |
Yes | output | 1 | 71,765 | 13 | 143,531 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either 0 or 1; exactly m edges have weight 1, and all others have weight 0.
Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
Input
The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ min((n(n-1))/(2),10^5)), the number of vertices and the number of edges of weight 1 in the graph.
The i-th of the next m lines contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i), the endpoints of the i-th edge of weight 1.
It is guaranteed that no edge appears twice in the input.
Output
Output a single integer, the weight of the minimum spanning tree of the graph.
Examples
Input
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
Output
2
Input
3 0
Output
0
Note
The graph from the first sample is shown below. Dashed edges have weight 0, other edges have weight 1. One of the minimum spanning trees is highlighted in orange and has total weight 2.
<image>
In the second sample, all edges have weight 0 so any spanning tree has total weight 0.
Submitted Solution:
```
n, m, *t = map(int, open(0).read().split())
from collections import defaultdict
mp = defaultdict(int)
s1 = []
s2 = []
s1.append(1)
for i in range(2, n + 1):
s2.append(i)
for a, b in zip(*[iter(t)] * 2):
mp[(a, b)] = 1
mp[(b, a)] = 1
ans = 0
while len(s2):
ns1 = []
ss1 = set()
for i in s1:
for j in s2:
if mp[(i, j)]:
continue
ns1.append(j)
ss1.add(j)
s2 = list(set(s2)-ss1)
# print(s1,ss1)
if len(ss1) == 0:
ans += 1
s1 = [s2.pop()]
else:
s1 = ns1
if len(s2) == 0 and len(s1):
ans += 1
print(ans-1)
``` | instruction | 0 | 71,766 | 13 | 143,532 |
No | output | 1 | 71,766 | 13 | 143,533 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either 0 or 1; exactly m edges have weight 1, and all others have weight 0.
Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
Input
The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ min((n(n-1))/(2),10^5)), the number of vertices and the number of edges of weight 1 in the graph.
The i-th of the next m lines contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i), the endpoints of the i-th edge of weight 1.
It is guaranteed that no edge appears twice in the input.
Output
Output a single integer, the weight of the minimum spanning tree of the graph.
Examples
Input
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
Output
2
Input
3 0
Output
0
Note
The graph from the first sample is shown below. Dashed edges have weight 0, other edges have weight 1. One of the minimum spanning trees is highlighted in orange and has total weight 2.
<image>
In the second sample, all edges have weight 0 so any spanning tree has total weight 0.
Submitted Solution:
```
import sys,math,itertools
from collections import Counter,deque,defaultdict
from bisect import bisect_left,bisect_right
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
n,m = inpl()
g = [set() for _ in range(n)]
for _ in range(m):
a,b = inpl()
a,b = a-1,b-1
g[a].add(b)
g[b].add(a)
d = defaultdict(list)
for i,x in enumerate(g):
tmp = tuple(list(x))
d[tmp].append(i)
res = 0
for key in list(d):
s = set()
for x in key: s.add(x)
for x in d[key]: s.add(x)
if len(s) == n: res += 1
print(res-1)
``` | instruction | 0 | 71,767 | 13 | 143,534 |
No | output | 1 | 71,767 | 13 | 143,535 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either 0 or 1; exactly m edges have weight 1, and all others have weight 0.
Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
Input
The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ min((n(n-1))/(2),10^5)), the number of vertices and the number of edges of weight 1 in the graph.
The i-th of the next m lines contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i), the endpoints of the i-th edge of weight 1.
It is guaranteed that no edge appears twice in the input.
Output
Output a single integer, the weight of the minimum spanning tree of the graph.
Examples
Input
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
Output
2
Input
3 0
Output
0
Note
The graph from the first sample is shown below. Dashed edges have weight 0, other edges have weight 1. One of the minimum spanning trees is highlighted in orange and has total weight 2.
<image>
In the second sample, all edges have weight 0 so any spanning tree has total weight 0.
Submitted Solution:
```
# q1
from collections import defaultdict
from math import sqrt,factorial,gcd,log2,inf,ceil
# map(int,input().split())
# l = list(map(int,input().split()))
mod = 10**9 + 7
ans = 0
def bfs_complement(n):
seti = {i+1 for i in range(1,n)}
# print(seti)
compo = 0
vis = [1]
while vis:
i = vis.pop(0)
ka = []
for j in seti:
if j not in hash[i] and i!=j:
vis.append(j)
ka.append(j)
for x in ka:
seti.remove(x)
if i in seti:
seti.remove(i)
if seti == set() or ka == []:
compo+=1
if ka == [] and seti!=set():
vis.append(seti.pop())
else:
break
return compo
# print(vis)
n,m = map(int,input().split())
hash = defaultdict(set)
for i in range(m):
a,b = map(int,input().split())
hash[a].add(b)
hash[b].add(a)
print(bfs_complement(n)-1)
``` | instruction | 0 | 71,768 | 13 | 143,536 |
No | output | 1 | 71,768 | 13 | 143,537 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either 0 or 1; exactly m edges have weight 1, and all others have weight 0.
Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
Input
The first line of the input contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ min((n(n-1))/(2),10^5)), the number of vertices and the number of edges of weight 1 in the graph.
The i-th of the next m lines contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i), the endpoints of the i-th edge of weight 1.
It is guaranteed that no edge appears twice in the input.
Output
Output a single integer, the weight of the minimum spanning tree of the graph.
Examples
Input
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
Output
2
Input
3 0
Output
0
Note
The graph from the first sample is shown below. Dashed edges have weight 0, other edges have weight 1. One of the minimum spanning trees is highlighted in orange and has total weight 2.
<image>
In the second sample, all edges have weight 0 so any spanning tree has total weight 0.
Submitted Solution:
```
class UnionFind(object):
__slots__ = ['nodes']
def __init__(self, n: int):
self.nodes = [-1]*n
def size(self, x: int) -> int:
return -self.nodes[self.find(x)]
def find(self, x: int) -> int:
if self.nodes[x] < 0:
return x
else:
self.nodes[x] = self.find(self.nodes[x])
return self.nodes[x]
def unite(self, x: int, y: int) -> bool:
root_x, root_y, nodes = self.find(x), self.find(y), self.nodes
if root_x != root_y:
if nodes[root_x] > nodes[root_y]:
root_x, root_y = root_y, root_x
nodes[root_x] += nodes[root_y]
nodes[root_y] = root_x
return root_x != root_y
if __name__ == '__main__':
import sys
from collections import Counter
n, m = map(int, input().split())
rev_edges = [[] for _ in range(n)]
for s, t in (map(int, l.split()) for l in sys.stdin):
rev_edges[t-1].append(s-1)
uf = UnionFind(n)
find, unite, size = uf.find, uf.unite, uf.size
zero_union = set()
for v in range(n):
cnt = Counter()
for src in rev_edges[v]:
cnt[find(src)] += 1
for zero_v in zero_union:
root = find(zero_v)
if size(root) > cnt[root]:
unite(root, v)
zero_union = set(find(v_) for v_ in zero_union) | {find(v)}
print(len(zero_union)-1)
``` | instruction | 0 | 71,769 | 13 | 143,538 |
No | output | 1 | 71,769 | 13 | 143,539 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Donghyun's new social network service (SNS) contains n users numbered 1, 2, …, n. Internally, their network is a tree graph, so there are n-1 direct connections between each user. Each user can reach every other users by using some sequence of direct connections. From now on, we will denote this primary network as T_1.
To prevent a possible server breakdown, Donghyun created a backup network T_2, which also connects the same n users via a tree graph. If a system breaks down, exactly one edge e ∈ T_1 becomes unusable. In this case, Donghyun will protect the edge e by picking another edge f ∈ T_2, and add it to the existing network. This new edge should make the network be connected again.
Donghyun wants to assign a replacement edge f ∈ T_2 for as many edges e ∈ T_1 as possible. However, since the backup network T_2 is fragile, f ∈ T_2 can be assigned as the replacement edge for at most one edge in T_1. With this restriction, Donghyun wants to protect as many edges in T_1 as possible.
Formally, let E(T) be an edge set of the tree T. We consider a bipartite graph with two parts E(T_1) and E(T_2). For e ∈ E(T_1), f ∈ E(T_2), there is an edge connecting \\{e, f\} if and only if graph T_1 - \\{e\} + \\{f\} is a tree. You should find a maximum matching in this bipartite graph.
Input
The first line contains an integer n (2 ≤ n ≤ 250 000), the number of users.
In the next n-1 lines, two integers a_i, b_i (1 ≤ a_i, b_i ≤ n) are given. Those two numbers denote the indices of the vertices connected by the corresponding edge in T_1.
In the next n-1 lines, two integers c_i, d_i (1 ≤ c_i, d_i ≤ n) are given. Those two numbers denote the indices of the vertices connected by the corresponding edge in T_2.
It is guaranteed that both edge sets form a tree of size n.
Output
In the first line, print the number m (0 ≤ m < n), the maximum number of edges that can be protected.
In the next m lines, print four integers a_i, b_i, c_i, d_i. Those four numbers denote that the edge (a_i, b_i) in T_1 is will be replaced with an edge (c_i, d_i) in T_2.
All printed edges should belong to their respective network, and they should link to distinct edges in their respective network. If one removes an edge (a_i, b_i) from T_1 and adds edge (c_i, d_i) from T_2, the network should remain connected. The order of printing the edges or the order of vertices in each edge does not matter.
If there are several solutions, you can print any.
Examples
Input
4
1 2
2 3
4 3
1 3
2 4
1 4
Output
3
3 2 4 2
2 1 1 3
4 3 1 4
Input
5
1 2
2 4
3 4
4 5
1 2
1 3
1 4
1 5
Output
4
2 1 1 2
3 4 1 3
4 2 1 4
5 4 1 5
Input
9
7 9
2 8
2 1
7 5
4 7
2 4
9 6
3 9
1 8
4 8
2 9
9 5
7 6
1 3
4 6
5 3
Output
8
4 2 9 2
9 7 6 7
5 7 5 9
6 9 4 6
8 2 8 4
3 9 3 5
2 1 1 8
7 4 1 3
Submitted Solution:
```
print(2)
``` | instruction | 0 | 71,786 | 13 | 143,572 |
No | output | 1 | 71,786 | 13 | 143,573 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Donghyun's new social network service (SNS) contains n users numbered 1, 2, …, n. Internally, their network is a tree graph, so there are n-1 direct connections between each user. Each user can reach every other users by using some sequence of direct connections. From now on, we will denote this primary network as T_1.
To prevent a possible server breakdown, Donghyun created a backup network T_2, which also connects the same n users via a tree graph. If a system breaks down, exactly one edge e ∈ T_1 becomes unusable. In this case, Donghyun will protect the edge e by picking another edge f ∈ T_2, and add it to the existing network. This new edge should make the network be connected again.
Donghyun wants to assign a replacement edge f ∈ T_2 for as many edges e ∈ T_1 as possible. However, since the backup network T_2 is fragile, f ∈ T_2 can be assigned as the replacement edge for at most one edge in T_1. With this restriction, Donghyun wants to protect as many edges in T_1 as possible.
Formally, let E(T) be an edge set of the tree T. We consider a bipartite graph with two parts E(T_1) and E(T_2). For e ∈ E(T_1), f ∈ E(T_2), there is an edge connecting \\{e, f\} if and only if graph T_1 - \\{e\} + \\{f\} is a tree. You should find a maximum matching in this bipartite graph.
Input
The first line contains an integer n (2 ≤ n ≤ 250 000), the number of users.
In the next n-1 lines, two integers a_i, b_i (1 ≤ a_i, b_i ≤ n) are given. Those two numbers denote the indices of the vertices connected by the corresponding edge in T_1.
In the next n-1 lines, two integers c_i, d_i (1 ≤ c_i, d_i ≤ n) are given. Those two numbers denote the indices of the vertices connected by the corresponding edge in T_2.
It is guaranteed that both edge sets form a tree of size n.
Output
In the first line, print the number m (0 ≤ m < n), the maximum number of edges that can be protected.
In the next m lines, print four integers a_i, b_i, c_i, d_i. Those four numbers denote that the edge (a_i, b_i) in T_1 is will be replaced with an edge (c_i, d_i) in T_2.
All printed edges should belong to their respective network, and they should link to distinct edges in their respective network. If one removes an edge (a_i, b_i) from T_1 and adds edge (c_i, d_i) from T_2, the network should remain connected. The order of printing the edges or the order of vertices in each edge does not matter.
If there are several solutions, you can print any.
Examples
Input
4
1 2
2 3
4 3
1 3
2 4
1 4
Output
3
3 2 4 2
2 1 1 3
4 3 1 4
Input
5
1 2
2 4
3 4
4 5
1 2
1 3
1 4
1 5
Output
4
2 1 1 2
3 4 1 3
4 2 1 4
5 4 1 5
Input
9
7 9
2 8
2 1
7 5
4 7
2 4
9 6
3 9
1 8
4 8
2 9
9 5
7 6
1 3
4 6
5 3
Output
8
4 2 9 2
9 7 6 7
5 7 5 9
6 9 4 6
8 2 8 4
3 9 3 5
2 1 1 8
7 4 1 3
Submitted Solution:
```
import sys
input = sys.stdin.readline
n = int(input())
#edges1 = [set() for ch in range(n)]
edges2 = [dict() for ch in range(n)]
edges = edges2
out = []
def MakeSet(x):
x.parent = x
x.rank = 0
def Union(x, y):
xRoot = Find(x)
yRoot = Find(y)
if xRoot.rank > yRoot.rank:
yRoot.parent = xRoot
#print('a')
#Doesn't work, doesn't pick right edge out of two options
for adj in edges2[yRoot.label]:
if adj in edges2[xRoot.label]:
out.append(edges2[xRoot.label][adj])
del edges2[adj][yRoot.label]
edges[xRoot.label][adj] = edges[yRoot.label][adj]
edges[adj][xRoot.label] = edges[xRoot.label][adj]
elif adj == xRoot.label:
out.append(edges2[yRoot.label][adj])
del edges[adj][yRoot.label]
else:
edges[xRoot.label][adj] = edges[yRoot.label][adj]
edges[adj][xRoot.label] = edges[xRoot.label][adj]
del edges2[adj][yRoot.label]
elif xRoot.rank < yRoot.rank:
xRoot.parent = yRoot
#print('b')
#Swapped
for adj in edges2[xRoot.label]:
if adj in edges2[yRoot.label]:
out.append(edges2[yRoot.label][adj])
del edges2[adj][xRoot.label]
edges[yRoot.label][adj] = edges[xRoot.label][adj]
edges[adj][yRoot.label] = edges[yRoot.label][adj]
elif adj == yRoot.label:
out.append(edges2[xRoot.label][adj])
else:
edges[yRoot.label][adj] = edges[xRoot.label][adj]
edges[adj][yRoot.label] = edges[yRoot.label][adj]
del edges2[adj][xRoot.label]
elif xRoot != yRoot:
yRoot.parent = xRoot
#print('c')
for adj in edges2[yRoot.label]:
if adj in edges2[xRoot.label]:
out.append(edges2[xRoot.label][adj])
del edges2[adj][yRoot.label]
edges[xRoot.label][adj] = edges[yRoot.label][adj]
edges[adj][xRoot.label] = edges[xRoot.label][adj]
elif adj == xRoot.label:
out.append(edges2[yRoot.label][adj])
del edges[adj][yRoot.label]
else:
edges[xRoot.label][adj] = edges[yRoot.label][adj]
edges[adj][xRoot.label] = edges[xRoot.label][adj]
del edges2[adj][yRoot.label]
xRoot.rank = xRoot.rank + 1
def Find(x):
if x.parent == x:
return x
else:
x.parent = Find(x.parent)
return x.parent
class Node:
def __init__ (self, label):
self.label = label
def __str__(self):
return self.label
nodes = [Node(ch) for ch in range(n)]
[MakeSet(node) for node in nodes]
order = []
for i in range(n - 1):
u, v = map(int, input().split())
name = str(u) + ' ' + str(v) + ' '
u -= 1
v -= 1
order.append((u, v, name))
#edges1[u].add(v)
#edges1[v].add(u)
for i in range(n - 1):
u, v = map(int, input().split())
name = str(u) + ' ' +str(v)
u -= 1
v -= 1
edges2[u][v] = name
edges2[v][u] = name
print(n - 1)
for u, v, name in order:
out.append(name)
Union(nodes[u], nodes[v])
out.append('\n')
#print(edges)
print(''.join(out))
``` | instruction | 0 | 71,787 | 13 | 143,574 |
No | output | 1 | 71,787 | 13 | 143,575 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Donghyun's new social network service (SNS) contains n users numbered 1, 2, …, n. Internally, their network is a tree graph, so there are n-1 direct connections between each user. Each user can reach every other users by using some sequence of direct connections. From now on, we will denote this primary network as T_1.
To prevent a possible server breakdown, Donghyun created a backup network T_2, which also connects the same n users via a tree graph. If a system breaks down, exactly one edge e ∈ T_1 becomes unusable. In this case, Donghyun will protect the edge e by picking another edge f ∈ T_2, and add it to the existing network. This new edge should make the network be connected again.
Donghyun wants to assign a replacement edge f ∈ T_2 for as many edges e ∈ T_1 as possible. However, since the backup network T_2 is fragile, f ∈ T_2 can be assigned as the replacement edge for at most one edge in T_1. With this restriction, Donghyun wants to protect as many edges in T_1 as possible.
Formally, let E(T) be an edge set of the tree T. We consider a bipartite graph with two parts E(T_1) and E(T_2). For e ∈ E(T_1), f ∈ E(T_2), there is an edge connecting \\{e, f\} if and only if graph T_1 - \\{e\} + \\{f\} is a tree. You should find a maximum matching in this bipartite graph.
Input
The first line contains an integer n (2 ≤ n ≤ 250 000), the number of users.
In the next n-1 lines, two integers a_i, b_i (1 ≤ a_i, b_i ≤ n) are given. Those two numbers denote the indices of the vertices connected by the corresponding edge in T_1.
In the next n-1 lines, two integers c_i, d_i (1 ≤ c_i, d_i ≤ n) are given. Those two numbers denote the indices of the vertices connected by the corresponding edge in T_2.
It is guaranteed that both edge sets form a tree of size n.
Output
In the first line, print the number m (0 ≤ m < n), the maximum number of edges that can be protected.
In the next m lines, print four integers a_i, b_i, c_i, d_i. Those four numbers denote that the edge (a_i, b_i) in T_1 is will be replaced with an edge (c_i, d_i) in T_2.
All printed edges should belong to their respective network, and they should link to distinct edges in their respective network. If one removes an edge (a_i, b_i) from T_1 and adds edge (c_i, d_i) from T_2, the network should remain connected. The order of printing the edges or the order of vertices in each edge does not matter.
If there are several solutions, you can print any.
Examples
Input
4
1 2
2 3
4 3
1 3
2 4
1 4
Output
3
3 2 4 2
2 1 1 3
4 3 1 4
Input
5
1 2
2 4
3 4
4 5
1 2
1 3
1 4
1 5
Output
4
2 1 1 2
3 4 1 3
4 2 1 4
5 4 1 5
Input
9
7 9
2 8
2 1
7 5
4 7
2 4
9 6
3 9
1 8
4 8
2 9
9 5
7 6
1 3
4 6
5 3
Output
8
4 2 9 2
9 7 6 7
5 7 5 9
6 9 4 6
8 2 8 4
3 9 3 5
2 1 1 8
7 4 1 3
Submitted Solution:
```
import sys
input = sys.stdin.readline
n = int(input())
#edges1 = [set() for ch in range(n)]
edges2 = [dict() for ch in range(n)]
edges = edges2
out = []
def MakeSet(x):
x.parent = x
x.rank = 0
def Union(x, y):
xRoot = Find(x)
yRoot = Find(y)
if xRoot.rank > yRoot.rank:
yRoot.parent = xRoot
#print('a')
#Doesn't work, doesn't pick right edge
for adj in edges2[yRoot.label]:
if adj in edges2[xRoot.label]:
out.append(edges2[xRoot.label][adj])
del edges2[adj][yRoot.label]
edges[xRoot.label][adj] = edges[yRoot.label][adj]
edges[adj][xRoot.label] = edges[xRoot.label][adj]
elif adj == xRoot.label:
out.append(edges2[yRoot.label][adj])
del edges[adj][yRoot.label]
else:
edges[xRoot.label][adj] = edges[yRoot.label][adj]
edges[adj][xRoot.label] = edges[xRoot.label][adj]
del edges2[adj][yRoot.label]
elif xRoot.rank < yRoot.rank:
xRoot.parent = yRoot
#print('b')
#Swapped
for adj in edges2[xRoot.label]:
if adj in edges2[yRoot.label]:
out.append(edges2[xRoot.label][adj])
del edges2[adj][yRoot.label]
edges[yRoot.label][adj] = edges[xRoot.label][adj]
edges[adj][yRoot.label] = edges[yRoot.label][adj]
elif adj == yRoot.label:
out.append(edges2[xRoot.label][adj])
else:
edges[yRoot.label][adj] = edges[xRoot.label][adj]
edges[adj][yRoot.label] = edges[yRoot.label][adj]
del edges2[adj][xRoot.label]
elif xRoot != yRoot:
yRoot.parent = xRoot
#print('c')
for adj in edges2[yRoot.label]:
if adj in edges2[xRoot.label]:
out.append(edges2[xRoot.label][adj])
del edges2[adj][yRoot.label]
edges[xRoot.label][adj] = edges[yRoot.label][adj]
edges[adj][xRoot.label] = edges[xRoot.label][adj]
elif adj == xRoot.label:
out.append(edges2[yRoot.label][adj])
del edges[adj][yRoot.label]
else:
edges[xRoot.label][adj] = edges[yRoot.label][adj]
edges[adj][xRoot.label] = edges[xRoot.label][adj]
del edges2[adj][yRoot.label]
xRoot.rank = xRoot.rank + 1
def Find(x):
if x.parent == x:
return x
else:
x.parent = Find(x.parent)
return x.parent
class Node:
def __init__ (self, label):
self.label = label
def __str__(self):
return self.label
nodes = [Node(ch) for ch in range(n)]
[MakeSet(node) for node in nodes]
order = []
for i in range(n - 1):
u, v = map(int, input().split())
name = str(u) + ' ' + str(v) + ' '
u -= 1
v -= 1
order.append((u, v, name))
#edges1[u].add(v)
#edges1[v].add(u)
for i in range(n - 1):
u, v = map(int, input().split())
name = str(u) + ' ' +str(v)
u -= 1
v -= 1
edges2[u][v] = name
edges2[v][u] = name
print(n - 1)
for u, v, name in order:
out.append(name)
Union(nodes[u], nodes[v])
out.append('\n')
#print(edges)
print(''.join(out))
``` | instruction | 0 | 71,788 | 13 | 143,576 |
No | output | 1 | 71,788 | 13 | 143,577 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Caisa is now at home and his son has a simple task for him.
Given a rooted tree with n vertices, numbered from 1 to n (vertex 1 is the root). Each vertex of the tree has a value. You should answer q queries. Each query is one of the following:
* Format of the query is "1 v". Let's write out the sequence of vertices along the path from the root to vertex v: u1, u2, ..., uk (u1 = 1; uk = v). You need to output such a vertex ui that gcd(value of ui, value of v) > 1 and i < k. If there are several possible vertices ui pick the one with maximum value of i. If there is no such vertex output -1.
* Format of the query is "2 v w". You must change the value of vertex v to w.
You are given all the queries, help Caisa to solve the problem.
Input
The first line contains two space-separated integers n, q (1 ≤ n, q ≤ 105).
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 2·106), where ai represent the value of node i.
Each of the next n - 1 lines contains two integers xi and yi (1 ≤ xi, yi ≤ n; xi ≠ yi), denoting the edge of the tree between vertices xi and yi.
Each of the next q lines contains a query in the format that is given above. For each query the following inequalities hold: 1 ≤ v ≤ n and 1 ≤ w ≤ 2·106. Note that: there are no more than 50 queries that changes the value of a vertex.
Output
For each query of the first type output the result of the query.
Examples
Input
4 6
10 8 4 3
1 2
2 3
3 4
1 1
1 2
1 3
1 4
2 1 9
1 4
Output
-1
1
2
-1
1
Note
gcd(x, y) is greatest common divisor of two integers x and y.
Submitted Solution:
```
from math import sqrt
from itertools import takewhile, chain
from collections import defaultdict
def main():
n, q = map(int, input().split())
values = list(chain([0], map(int, input().split())))
tree = [[] for _ in range(n + 1)]
for _ in range(n - 1):
x, y = map(int, input().split())
tree[x].append(y)
tree[y].append(x)
MAX = 2*10**6
eratos = [0, 1] * 10**6
eratos[0] = eratos[1] =0
eratos[2] = 1
primes = [2]
lpath = [0] * (n + 1)
lpath[0] = -1
answers = [0] * (n + 1)
pstack = defaultdict(list)
for i in range(3, int(sqrt(MAX)+1)):
if eratos[i]:
primes.append(i)
for j in range(i*i, MAX, 2*i):
eratos[j] = 1
def DFS(node):
dfs_stack = [(node, [])]
dfs_visited = set()
while dfs_stack:
node, sprimes = dfs_stack.pop()
if node not in dfs_visited:
dfs_visited.add(node)
dfs_stack.append((node, sprimes))
dfs_stack.extend((i, []) for i in tree[node])
i = 2
v = values[node]
answers[node] = 0
for i in takewhile(lambda p: p*p <= v, primes):
if v % i == 0:
if pstack[i]:
y = pstack[i][-1]
if lpath[y] > lpath[answers[node]]:
answers[node] = y
sprimes.append(i)
pstack[i].append(node)
while v % i == 0:
v //= i
if v > 1:
if pstack[v]:
y = pstack[v][-1]
if lpath[y] > lpath[answers[node]]:
answers[node] = y
sprimes.append(v)
pstack[v].append(node)
for j in tree[node]:
lpath[j] = lpath[node] + 1
else:
for j in sprimes:
pstack[j].pop()
DFS(1)
for _ in range(q):
cmd, *args = input().split()
if cmd == '1':
print(answers[int(args[0])] or -1)
else:
values[int(args[0])] = int(args[1])
DFS(1)
if __name__ == '__main__':
main()
``` | instruction | 0 | 72,035 | 13 | 144,070 |
No | output | 1 | 72,035 | 13 | 144,071 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Caisa is now at home and his son has a simple task for him.
Given a rooted tree with n vertices, numbered from 1 to n (vertex 1 is the root). Each vertex of the tree has a value. You should answer q queries. Each query is one of the following:
* Format of the query is "1 v". Let's write out the sequence of vertices along the path from the root to vertex v: u1, u2, ..., uk (u1 = 1; uk = v). You need to output such a vertex ui that gcd(value of ui, value of v) > 1 and i < k. If there are several possible vertices ui pick the one with maximum value of i. If there is no such vertex output -1.
* Format of the query is "2 v w". You must change the value of vertex v to w.
You are given all the queries, help Caisa to solve the problem.
Input
The first line contains two space-separated integers n, q (1 ≤ n, q ≤ 105).
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 2·106), where ai represent the value of node i.
Each of the next n - 1 lines contains two integers xi and yi (1 ≤ xi, yi ≤ n; xi ≠ yi), denoting the edge of the tree between vertices xi and yi.
Each of the next q lines contains a query in the format that is given above. For each query the following inequalities hold: 1 ≤ v ≤ n and 1 ≤ w ≤ 2·106. Note that: there are no more than 50 queries that changes the value of a vertex.
Output
For each query of the first type output the result of the query.
Examples
Input
4 6
10 8 4 3
1 2
2 3
3 4
1 1
1 2
1 3
1 4
2 1 9
1 4
Output
-1
1
2
-1
1
Note
gcd(x, y) is greatest common divisor of two integers x and y.
Submitted Solution:
```
from sys import stdin, setrecursionlimit
setrecursionlimit(1000000007)
_data = map(int, stdin.read().split())
V = 2100000
n, q = next(_data), next(_data)
a = [next(_data) for _ in range(n)]
g = [[] for _ in range(n)]
for _ in range(n - 1):
u, v = next(_data) - 1, next(_data) - 1
g[u].append(v)
g[v].append(u)
dss = [[] for _ in range(V)]
def divisors(k):
if dss[k]:
return dss[k]
i = 2
t = []
while i * i <= k:
if k % i == 0:
t.append(i)
if k // i != i:
t.append(k // i)
i += 1
t.append(k)
dss[k] = t
return t
ans = [-2] * n
scope = [[] for _ in range(V)]
def make(v, p):
ds = divisors(a[v])
r = -2
for d in ds:
if scope[d]:
r = max(r, scope[d][-1])
scope[d].append(v)
ans[v] = r
for u in g[v]:
if u != p:
make(u, v)
for d in ds:
scope[d].pop()
buf = []
make(0, 0)
for _ in range(q):
t = next(_data)
if t == 1:
v = next(_data) - 1
buf.append(ans[v] + 1)
elif t == 2:
v = next(_data) - 1
x = next(_data)
a[v] = x
make(0, 0)
else:
assert False
print('\n'.join(map(str, buf)))
``` | instruction | 0 | 72,036 | 13 | 144,072 |
No | output | 1 | 72,036 | 13 | 144,073 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Caisa is now at home and his son has a simple task for him.
Given a rooted tree with n vertices, numbered from 1 to n (vertex 1 is the root). Each vertex of the tree has a value. You should answer q queries. Each query is one of the following:
* Format of the query is "1 v". Let's write out the sequence of vertices along the path from the root to vertex v: u1, u2, ..., uk (u1 = 1; uk = v). You need to output such a vertex ui that gcd(value of ui, value of v) > 1 and i < k. If there are several possible vertices ui pick the one with maximum value of i. If there is no such vertex output -1.
* Format of the query is "2 v w". You must change the value of vertex v to w.
You are given all the queries, help Caisa to solve the problem.
Input
The first line contains two space-separated integers n, q (1 ≤ n, q ≤ 105).
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 2·106), where ai represent the value of node i.
Each of the next n - 1 lines contains two integers xi and yi (1 ≤ xi, yi ≤ n; xi ≠ yi), denoting the edge of the tree between vertices xi and yi.
Each of the next q lines contains a query in the format that is given above. For each query the following inequalities hold: 1 ≤ v ≤ n and 1 ≤ w ≤ 2·106. Note that: there are no more than 50 queries that changes the value of a vertex.
Output
For each query of the first type output the result of the query.
Examples
Input
4 6
10 8 4 3
1 2
2 3
3 4
1 1
1 2
1 3
1 4
2 1 9
1 4
Output
-1
1
2
-1
1
Note
gcd(x, y) is greatest common divisor of two integers x and y.
Submitted Solution:
```
from math import sqrt
from itertools import takewhile, chain
from collections import defaultdict
def main():
n, q = map(int, input().split())
values = list(chain([0], map(int, input().split())))
tree = [[] for _ in range(n + 1)]
for _ in range(n - 1):
x, y = map(int, input().split())
tree[x].append(y)
MAX = 2*10**6
eratos = [0, 1] * 10**6
eratos[0] = eratos[1] =0
eratos[2] = 1
primes = [2]
lpath = [0] * (n + 1)
lpath[0] = -1
answers = [0] * (n + 1)
pstack = defaultdict(list)
for i in range(3, int(sqrt(MAX)+1)):
if eratos[i]:
primes.append(i)
for j in range(i*i, MAX, 2*i):
eratos[j] = 1
def DFS(node):
dfs_stack = [(node, [])]
dfs_visited = set()
while dfs_stack:
node, sprimes = dfs_stack.pop()
if node not in dfs_visited:
dfs_visited.add(node)
dfs_stack.append((node, sprimes))
dfs_stack.extend((i, []) for i in tree[node])
i = 2
v = values[node]
answers[node] = 0
for i in takewhile(lambda p: p*p <= v, primes):
if v % i == 0:
if pstack[i]:
y = pstack[i][-1]
if lpath[y] > lpath[answers[node]]:
answers[node] = y
sprimes.append(i)
pstack[i].append(node)
while v % i == 0:
v //= i
if v > 1:
if pstack[v]:
y = pstack[v][-1]
if lpath[y] > lpath[answers[node]]:
answers[node] = y
sprimes.append(v)
pstack[v].append(node)
for j in tree[node]:
lpath[j] = lpath[node] + 1
else:
for j in sprimes:
pstack[j].pop()
DFS(1)
for _ in range(q):
cmd, *args = input().split()
if cmd == '1':
print(answers[int(args[0])] or -1)
else:
values[int(args[0])] = int(args[1])
DFS(1)
if __name__ == '__main__':
main()
``` | instruction | 0 | 72,037 | 13 | 144,074 |
No | output | 1 | 72,037 | 13 | 144,075 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Caisa is now at home and his son has a simple task for him.
Given a rooted tree with n vertices, numbered from 1 to n (vertex 1 is the root). Each vertex of the tree has a value. You should answer q queries. Each query is one of the following:
* Format of the query is "1 v". Let's write out the sequence of vertices along the path from the root to vertex v: u1, u2, ..., uk (u1 = 1; uk = v). You need to output such a vertex ui that gcd(value of ui, value of v) > 1 and i < k. If there are several possible vertices ui pick the one with maximum value of i. If there is no such vertex output -1.
* Format of the query is "2 v w". You must change the value of vertex v to w.
You are given all the queries, help Caisa to solve the problem.
Input
The first line contains two space-separated integers n, q (1 ≤ n, q ≤ 105).
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 2·106), where ai represent the value of node i.
Each of the next n - 1 lines contains two integers xi and yi (1 ≤ xi, yi ≤ n; xi ≠ yi), denoting the edge of the tree between vertices xi and yi.
Each of the next q lines contains a query in the format that is given above. For each query the following inequalities hold: 1 ≤ v ≤ n and 1 ≤ w ≤ 2·106. Note that: there are no more than 50 queries that changes the value of a vertex.
Output
For each query of the first type output the result of the query.
Examples
Input
4 6
10 8 4 3
1 2
2 3
3 4
1 1
1 2
1 3
1 4
2 1 9
1 4
Output
-1
1
2
-1
1
Note
gcd(x, y) is greatest common divisor of two integers x and y.
Submitted Solution:
```
from sys import stdin, setrecursionlimit
setrecursionlimit(1000000007)
_data = map(int, stdin.read().split())
V = 2100000
n, q = next(_data), next(_data)
a = [next(_data) for _ in range(n)]
g = [[] for _ in range(n)]
for _ in range(n - 1):
u, v = next(_data) - 1, next(_data) - 1
g[u].append(v)
g[v].append(u)
dss = [[] for _ in range(V)]
def divisors(k):
if dss[k]:
return dss[k]
i = 2
t = []
while i * i <= k:
if k % i == 0:
t.append(i)
if k // i != i:
t.append(k // i)
i += 1
t.append(k)
dss[k] = t
return t
ans = [-2] * n
scope = [[] for _ in range(V)]
def make(v, p):
ds = divisors(a[v])
r = -2
rv = 0
for d in ds:
if scope[d] and d > rv:
r = scope[d][-1]
scope[d].append(v)
ans[v] = r
for u in g[v]:
if u != p:
make(u, v)
for d in ds:
scope[d].pop()
buf = []
make(0, 0)
for _ in range(q):
t = next(_data)
if t == 1:
v = next(_data) - 1
buf.append(ans[v] + 1)
elif t == 2:
v = next(_data) - 1
x = next(_data)
a[v] = x
make(0, 0)
else:
assert False
print('\n'.join(map(str, buf)))
``` | instruction | 0 | 72,038 | 13 | 144,076 |
No | output | 1 | 72,038 | 13 | 144,077 |
Provide a correct Python 3 solution for this coding contest problem.
For a given weighted graph G(V, E) and a source r, find the source shortest path to each vertex from the source (SSSP: Single Source Shortest Path).
Constraints
* 1 ≤ |V| ≤ 100000
* 0 ≤ di ≤ 10000
* 0 ≤ |E| ≤ 500000
* There are no parallel edges
* There are no self-loops
Input
An edge-weighted graph G (V, E) and the source r.
|V| |E| r
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
|V| is the number of vertices and |E| is the number of edges in G. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. r is the source of the graph.
si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.
Output
Print the costs of SSSP in the following format.
c0
c1
:
c|V|-1
The output consists of |V| lines. Print the cost of the shortest path from the source r to each vertex 0, 1, ... |V|-1 in order. If there is no path from the source to a vertex, print INF.
Examples
Input
4 5 0
0 1 1
0 2 4
1 2 2
2 3 1
1 3 5
Output
0
1
3
4
Input
4 6 1
0 1 1
0 2 4
2 0 1
1 2 2
3 1 1
3 2 5
Output
3
0
2
INF | instruction | 0 | 72,463 | 13 | 144,926 |
"Correct Solution:
```
import heapq
INF = 10**9+1
def solve():
n_V,n_E,r = map(int, input().split())
graph = {v:[] for v in range(n_V)}
for _ in range(n_E):
u,v,w = map(int, input().split())
graph[u].append((v,w))
min_distances = [INF]*n_V; min_distances[r] = 0
prev = [None for _ in range(n_V)]
# (d(u),u)
queue = [(min_distances[v], v) for v in range(n_V)]
heapq.heapify(queue)
while queue:
_, dom = heapq.heappop(queue)
for cod, edge_weight in graph[dom]:
if min_distances[cod] > min_distances[dom] + edge_weight:
min_distances[cod] = min_distances[dom] + edge_weight
prev[cod] = dom
heapq.heappush(queue, (min_distances[cod], cod))
for d in min_distances:
print(d if d < INF else 'INF')
solve()
``` | output | 1 | 72,463 | 13 | 144,927 |
Provide a correct Python 3 solution for this coding contest problem.
For a given weighted graph G(V, E) and a source r, find the source shortest path to each vertex from the source (SSSP: Single Source Shortest Path).
Constraints
* 1 ≤ |V| ≤ 100000
* 0 ≤ di ≤ 10000
* 0 ≤ |E| ≤ 500000
* There are no parallel edges
* There are no self-loops
Input
An edge-weighted graph G (V, E) and the source r.
|V| |E| r
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
|V| is the number of vertices and |E| is the number of edges in G. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. r is the source of the graph.
si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.
Output
Print the costs of SSSP in the following format.
c0
c1
:
c|V|-1
The output consists of |V| lines. Print the cost of the shortest path from the source r to each vertex 0, 1, ... |V|-1 in order. If there is no path from the source to a vertex, print INF.
Examples
Input
4 5 0
0 1 1
0 2 4
1 2 2
2 3 1
1 3 5
Output
0
1
3
4
Input
4 6 1
0 1 1
0 2 4
2 0 1
1 2 2
3 1 1
3 2 5
Output
3
0
2
INF | instruction | 0 | 72,464 | 13 | 144,928 |
"Correct Solution:
```
import heapq
inf = 10000000000
n,m,r = map(int,input().split())
e = [[] for _ in range(n)]
for _ in range(m):
a,b,c = map(int,input().split())
e[a].append([b,c])
d = [inf]*n
d[r] = 0
pq = [[0,r]]
heapq.heapify(pq)
while len(pq):
pre = heapq.heappop(pq)
a,b = pre[0],pre[1]
if d[b]<a:continue
for i in range(len(e[b])):
next_index = e[b][i][0]
next_cost = d[b]+e[b][i][1]
if next_cost<d[next_index]:
d[next_index] = next_cost
heapq.heappush(pq,[next_cost,next_index])
for i in range(n):
if d[i]==inf:print ('INF')
else :print (d[i])
``` | output | 1 | 72,464 | 13 | 144,929 |
Provide a correct Python 3 solution for this coding contest problem.
For a given weighted graph G(V, E) and a source r, find the source shortest path to each vertex from the source (SSSP: Single Source Shortest Path).
Constraints
* 1 ≤ |V| ≤ 100000
* 0 ≤ di ≤ 10000
* 0 ≤ |E| ≤ 500000
* There are no parallel edges
* There are no self-loops
Input
An edge-weighted graph G (V, E) and the source r.
|V| |E| r
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
|V| is the number of vertices and |E| is the number of edges in G. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. r is the source of the graph.
si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.
Output
Print the costs of SSSP in the following format.
c0
c1
:
c|V|-1
The output consists of |V| lines. Print the cost of the shortest path from the source r to each vertex 0, 1, ... |V|-1 in order. If there is no path from the source to a vertex, print INF.
Examples
Input
4 5 0
0 1 1
0 2 4
1 2 2
2 3 1
1 3 5
Output
0
1
3
4
Input
4 6 1
0 1 1
0 2 4
2 0 1
1 2 2
3 1 1
3 2 5
Output
3
0
2
INF | instruction | 0 | 72,465 | 13 | 144,930 |
"Correct Solution:
```
from heapq import heappush,heappop,heapify
INF=10**30
def dijkstra(G,s,n):
que=[(0,s)]
dist=[INF]*n
dist[s]=0
while que:
mincost,u=heappop(que)
if(mincost>dist[u]):
continue
for c,v in G[u]:
if(dist[u]+c<dist[v]):
dist[v]=dist[u]+c
heappush(que,(dist[v],v))
return dist
V,E,r=map(int,input().split())
G=[[] for _ in range(V)]
for i in range(E):
s,t,d=map(int,input().split())
G[s].append((d,t))
dist=dijkstra(G,r,V)
for i in range(V):
print(dist[i] if dist[i]!=INF else 'INF')
``` | output | 1 | 72,465 | 13 | 144,931 |
Provide a correct Python 3 solution for this coding contest problem.
For a given weighted graph G(V, E) and a source r, find the source shortest path to each vertex from the source (SSSP: Single Source Shortest Path).
Constraints
* 1 ≤ |V| ≤ 100000
* 0 ≤ di ≤ 10000
* 0 ≤ |E| ≤ 500000
* There are no parallel edges
* There are no self-loops
Input
An edge-weighted graph G (V, E) and the source r.
|V| |E| r
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
|V| is the number of vertices and |E| is the number of edges in G. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. r is the source of the graph.
si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.
Output
Print the costs of SSSP in the following format.
c0
c1
:
c|V|-1
The output consists of |V| lines. Print the cost of the shortest path from the source r to each vertex 0, 1, ... |V|-1 in order. If there is no path from the source to a vertex, print INF.
Examples
Input
4 5 0
0 1 1
0 2 4
1 2 2
2 3 1
1 3 5
Output
0
1
3
4
Input
4 6 1
0 1 1
0 2 4
2 0 1
1 2 2
3 1 1
3 2 5
Output
3
0
2
INF | instruction | 0 | 72,466 | 13 | 144,932 |
"Correct Solution:
```
def main():
V,E,r,*L = map(int,open(0).read().split())
INF = float("inf")
G = [[] for _ in range(V)]
for s,t,c in zip(*[iter(L)]*3):
G[s].append((t,c))
for i in dijkstra(G,r):
if i==INF:
print("INF")
else:
print(i)
from heapq import heappop,heappush
def dijkstra(G:list, source=0):
INF = float("inf")
V = len(G)
D = [INF]*V
D[source] = 0
vis = [False]*V
H = [(0,source)]
while H:
dist, cur = heappop(H)
if vis[cur]:
continue
vis[cur] = True
for nxt, cost in G[cur]:
t = dist + cost
if D[nxt] > t:
D[nxt] = t
heappush(H, (t, nxt))
return D
if __name__=="__main__":main()
``` | output | 1 | 72,466 | 13 | 144,933 |
Provide a correct Python 3 solution for this coding contest problem.
For a given weighted graph G(V, E) and a source r, find the source shortest path to each vertex from the source (SSSP: Single Source Shortest Path).
Constraints
* 1 ≤ |V| ≤ 100000
* 0 ≤ di ≤ 10000
* 0 ≤ |E| ≤ 500000
* There are no parallel edges
* There are no self-loops
Input
An edge-weighted graph G (V, E) and the source r.
|V| |E| r
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
|V| is the number of vertices and |E| is the number of edges in G. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. r is the source of the graph.
si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.
Output
Print the costs of SSSP in the following format.
c0
c1
:
c|V|-1
The output consists of |V| lines. Print the cost of the shortest path from the source r to each vertex 0, 1, ... |V|-1 in order. If there is no path from the source to a vertex, print INF.
Examples
Input
4 5 0
0 1 1
0 2 4
1 2 2
2 3 1
1 3 5
Output
0
1
3
4
Input
4 6 1
0 1 1
0 2 4
2 0 1
1 2 2
3 1 1
3 2 5
Output
3
0
2
INF | instruction | 0 | 72,467 | 13 | 144,934 |
"Correct Solution:
```
'''
????????£????????????????????????
'''
import queue
v,e,s=map(int,input().split())
edge=[]
inf =1000000100
for i in range(v):
edge.append([])
for i in range(e):
vs,vt,d=map(int,input().split())
edge[vs].append((vt,d))
dis=[]
for i in range(v):
dis.append(inf)
dis[s]=0
q = queue.PriorityQueue()
q.put((0,s))
'''
while(not q.empty()):
now=q.get()
nowv=now[1]
for (vt,d) in edge[nowv]:
if dis[vt]>dis[nowv]+d:
dis[vt]=dis[nowv]+d
q.put((dis[vt],vt))
'''
finished=0
while(finished<v and not q.empty()):
now=q.get()
nowv=now[1]
if now[0]>dis[nowv]: continue
for (vt,d) in edge[nowv]:
if dis[vt]>dis[nowv]+d:
dis[vt]=dis[nowv]+d
q.put((dis[vt],vt))
finished+=1
for i in range(v):
if dis[i]>=inf:
print("INF")
else:
print(dis[i])
``` | output | 1 | 72,467 | 13 | 144,935 |
Provide a correct Python 3 solution for this coding contest problem.
For a given weighted graph G(V, E) and a source r, find the source shortest path to each vertex from the source (SSSP: Single Source Shortest Path).
Constraints
* 1 ≤ |V| ≤ 100000
* 0 ≤ di ≤ 10000
* 0 ≤ |E| ≤ 500000
* There are no parallel edges
* There are no self-loops
Input
An edge-weighted graph G (V, E) and the source r.
|V| |E| r
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
|V| is the number of vertices and |E| is the number of edges in G. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. r is the source of the graph.
si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.
Output
Print the costs of SSSP in the following format.
c0
c1
:
c|V|-1
The output consists of |V| lines. Print the cost of the shortest path from the source r to each vertex 0, 1, ... |V|-1 in order. If there is no path from the source to a vertex, print INF.
Examples
Input
4 5 0
0 1 1
0 2 4
1 2 2
2 3 1
1 3 5
Output
0
1
3
4
Input
4 6 1
0 1 1
0 2 4
2 0 1
1 2 2
3 1 1
3 2 5
Output
3
0
2
INF | instruction | 0 | 72,468 | 13 | 144,936 |
"Correct Solution:
```
#=============================================================================
# ダイクストラ法
#=============================================================================
import heapq
N,M,s=map(int,input().split())
Graph=[[] for _ in range(N+1)]
dig=["INF" for _ in range(N+1)]
see=[False for _ in range(N+1)]
for _ in range(M):
a,b,w=map(int,input().split())
Graph[a].append([w,b])
# Graph[b].append([w,a])
pq=[]
#s=0
dig[s]=0
see[s]=True
for nv in Graph[s]:
heapq.heappush(pq,nv)
while len(pq):
v=heapq.heappop(pq)
if see[v[1]]:
continue
see[v[1]]=True
dig[v[1]]=v[0]
for nv in Graph[v[1]]:
if not see[nv[1]]:
heapq.heappush(pq,[dig[v[1]]+nv[0],nv[1]])
for i in range(N):
print(dig[i])
``` | output | 1 | 72,468 | 13 | 144,937 |
Provide a correct Python 3 solution for this coding contest problem.
For a given weighted graph G(V, E) and a source r, find the source shortest path to each vertex from the source (SSSP: Single Source Shortest Path).
Constraints
* 1 ≤ |V| ≤ 100000
* 0 ≤ di ≤ 10000
* 0 ≤ |E| ≤ 500000
* There are no parallel edges
* There are no self-loops
Input
An edge-weighted graph G (V, E) and the source r.
|V| |E| r
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
|V| is the number of vertices and |E| is the number of edges in G. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. r is the source of the graph.
si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.
Output
Print the costs of SSSP in the following format.
c0
c1
:
c|V|-1
The output consists of |V| lines. Print the cost of the shortest path from the source r to each vertex 0, 1, ... |V|-1 in order. If there is no path from the source to a vertex, print INF.
Examples
Input
4 5 0
0 1 1
0 2 4
1 2 2
2 3 1
1 3 5
Output
0
1
3
4
Input
4 6 1
0 1 1
0 2 4
2 0 1
1 2 2
3 1 1
3 2 5
Output
3
0
2
INF | instruction | 0 | 72,469 | 13 | 144,938 |
"Correct Solution:
```
from heapq import heappush, heappop
INF = 10 ** 12
V, E, r = map(int, input().split())
graph = [[] for _ in range(V)]
dist_all = [INF] * V
dist_all[r] = 0
for i in range(E):
start, end, dist1 = map(int, input().split())
graph[start].append([end, dist1])
q = []
heappush(q, (0, r))
while q:
dist, node = heappop(q)
for to, cost in graph[node]:
if(dist_all[to] > dist + cost):
dist_all[to] = dist + cost
heappush(q, (dist+cost, to))
for i in range(V):
if(dist_all[i] == INF):
print('INF')
else:
print(dist_all[i])
``` | output | 1 | 72,469 | 13 | 144,939 |
Provide a correct Python 3 solution for this coding contest problem.
For a given weighted graph G(V, E) and a source r, find the source shortest path to each vertex from the source (SSSP: Single Source Shortest Path).
Constraints
* 1 ≤ |V| ≤ 100000
* 0 ≤ di ≤ 10000
* 0 ≤ |E| ≤ 500000
* There are no parallel edges
* There are no self-loops
Input
An edge-weighted graph G (V, E) and the source r.
|V| |E| r
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
|V| is the number of vertices and |E| is the number of edges in G. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. r is the source of the graph.
si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.
Output
Print the costs of SSSP in the following format.
c0
c1
:
c|V|-1
The output consists of |V| lines. Print the cost of the shortest path from the source r to each vertex 0, 1, ... |V|-1 in order. If there is no path from the source to a vertex, print INF.
Examples
Input
4 5 0
0 1 1
0 2 4
1 2 2
2 3 1
1 3 5
Output
0
1
3
4
Input
4 6 1
0 1 1
0 2 4
2 0 1
1 2 2
3 1 1
3 2 5
Output
3
0
2
INF | instruction | 0 | 72,470 | 13 | 144,940 |
"Correct Solution:
```
import heapq
v, e, r = map(int, input().split())
g = [[] for _ in range(v)]
for i in range(e):
s, t, d = map(int, input().split())
g[s].append((d, t))#(重み, 次の頂点)
dist = [float("inf")] * v
visited = [False] * v
dist[r] = 0
visited[r] = True
candidate = []
for i in g[r]:
heapq.heappush(candidate, i)
while len(candidate):
#まだ使われていない頂点から最小のものを探す
minedge = heapq.heappop(candidate)#(重み, 頂点)
if visited[minedge[1]]:
continue
c = minedge[1]
dist[c] = minedge[0]
visited[c] = True
for i in g[c]:
if not visited[i[1]]:
heapq.heappush(candidate, (dist[c] + i[0], i[1]))
for i in dist:
if i == float("inf"):
print("INF")
else:
print(i)
``` | output | 1 | 72,470 | 13 | 144,941 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a given weighted graph G(V, E) and a source r, find the source shortest path to each vertex from the source (SSSP: Single Source Shortest Path).
Constraints
* 1 ≤ |V| ≤ 100000
* 0 ≤ di ≤ 10000
* 0 ≤ |E| ≤ 500000
* There are no parallel edges
* There are no self-loops
Input
An edge-weighted graph G (V, E) and the source r.
|V| |E| r
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
|V| is the number of vertices and |E| is the number of edges in G. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. r is the source of the graph.
si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.
Output
Print the costs of SSSP in the following format.
c0
c1
:
c|V|-1
The output consists of |V| lines. Print the cost of the shortest path from the source r to each vertex 0, 1, ... |V|-1 in order. If there is no path from the source to a vertex, print INF.
Examples
Input
4 5 0
0 1 1
0 2 4
1 2 2
2 3 1
1 3 5
Output
0
1
3
4
Input
4 6 1
0 1 1
0 2 4
2 0 1
1 2 2
3 1 1
3 2 5
Output
3
0
2
INF
Submitted Solution:
```
from collections import defaultdict
from collections import deque
from sys import stdin
def sp(G,R,V):
d = {}
INF = float('inf')
for i in range(V):
d[i] = INF
d[R] = 0
q = deque([(R)])
while q:
u = q.popleft()
for v in G[u]:
if d[v[0]] > d[u] + v[1]:
d[v[0]] = d[u] + v[1]
q.append(v[0])
return d
V, E, R = tuple(int(x) for x in stdin.readline().split(' '))
G = defaultdict(list)
for case in range(E):
s, t, w = tuple(int(x) for x in stdin.readline().split(' '))
G[s].append((t,w))
d = sp(G, R, V)
for k in range(V):
if d[k] == float('inf'):
print("INF")
else:
print(d[k])
``` | instruction | 0 | 72,471 | 13 | 144,942 |
Yes | output | 1 | 72,471 | 13 | 144,943 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a given weighted graph G(V, E) and a source r, find the source shortest path to each vertex from the source (SSSP: Single Source Shortest Path).
Constraints
* 1 ≤ |V| ≤ 100000
* 0 ≤ di ≤ 10000
* 0 ≤ |E| ≤ 500000
* There are no parallel edges
* There are no self-loops
Input
An edge-weighted graph G (V, E) and the source r.
|V| |E| r
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
|V| is the number of vertices and |E| is the number of edges in G. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. r is the source of the graph.
si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.
Output
Print the costs of SSSP in the following format.
c0
c1
:
c|V|-1
The output consists of |V| lines. Print the cost of the shortest path from the source r to each vertex 0, 1, ... |V|-1 in order. If there is no path from the source to a vertex, print INF.
Examples
Input
4 5 0
0 1 1
0 2 4
1 2 2
2 3 1
1 3 5
Output
0
1
3
4
Input
4 6 1
0 1 1
0 2 4
2 0 1
1 2 2
3 1 1
3 2 5
Output
3
0
2
INF
Submitted Solution:
```
import heapq
INF = 10 ** 9
V, E, r = map(int, input().split())
edge_list = [[] for _ in range(V)]
dist_list = [INF] * V
for _ in range(E):
s, t, d = map(int, input().split())
edge_list[s].append((t, d))
q = []
heapq.heapify(q)
heapq.heappush(q, (0, r))
dist_list[r] = 0
while len(q) != 0:
dist, node = heapq.heappop(q)
for to, cost in edge_list[node]:
if dist + cost < dist_list[to]:
dist_list[to] = dist + cost
heapq.heappush(q, (dist + cost, to))
for dist in dist_list:
if dist == INF:
print("INF")
else:
print(dist)
``` | instruction | 0 | 72,472 | 13 | 144,944 |
Yes | output | 1 | 72,472 | 13 | 144,945 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a given weighted graph G(V, E) and a source r, find the source shortest path to each vertex from the source (SSSP: Single Source Shortest Path).
Constraints
* 1 ≤ |V| ≤ 100000
* 0 ≤ di ≤ 10000
* 0 ≤ |E| ≤ 500000
* There are no parallel edges
* There are no self-loops
Input
An edge-weighted graph G (V, E) and the source r.
|V| |E| r
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
|V| is the number of vertices and |E| is the number of edges in G. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. r is the source of the graph.
si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.
Output
Print the costs of SSSP in the following format.
c0
c1
:
c|V|-1
The output consists of |V| lines. Print the cost of the shortest path from the source r to each vertex 0, 1, ... |V|-1 in order. If there is no path from the source to a vertex, print INF.
Examples
Input
4 5 0
0 1 1
0 2 4
1 2 2
2 3 1
1 3 5
Output
0
1
3
4
Input
4 6 1
0 1 1
0 2 4
2 0 1
1 2 2
3 1 1
3 2 5
Output
3
0
2
INF
Submitted Solution:
```
from heapq import *
import sys
I=sys.stdin.readlines()
V,E,r=map(int,I[0].split())
s,t,d=0,0,0
G=[[] for i in range(V)]
for i in range(E):
s,t,d=map(int,I[i+1].split())
G[s].append((t,d))
D=[0]*V
INF=10**9+1
def ijk(s):
global V,D,G,INF
Q=[]
heapify(Q)
for i in range(V):
D[i]=INF
D[s]=0
v,p,e=0,0,0
heappush(Q,(0,s))
while len(Q):
p=heappop(Q)
v=p[1]
if D[v]<p[0]:
continue
for i in range(len(G[v])):
e=G[v][i]
if D[e[0]]>D[v]+e[1]:
D[e[0]]=D[v]+e[1]
heappush(Q,(D[e[0]],e[0]))
ijk(r)
for i in range(V):
if D[i]==INF:
print('INF')
else:
print(D[i])
``` | instruction | 0 | 72,473 | 13 | 144,946 |
Yes | output | 1 | 72,473 | 13 | 144,947 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.