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 |
|---|---|---|---|---|---|
Provide a correct Python 3 solution for this coding contest problem.
We have an undirected weighted graph with N vertices and M edges. The i-th edge in the graph connects Vertex U_i and Vertex V_i, and has a weight of W_i. Additionally, you are given an integer X.
Find the number of ways to paint each edge in this graph either white or black such that the following condition is met, modulo 10^9 + 7:
* The graph has a spanning tree that contains both an edge painted white and an edge painted black. Furthermore, among such spanning trees, the one with the smallest weight has a weight of X.
Here, the weight of a spanning tree is the sum of the weights of the edges contained in the spanning tree.
Constraints
* 1 \leq N \leq 1 000
* 1 \leq M \leq 2 000
* 1 \leq U_i, V_i \leq N (1 \leq i \leq M)
* 1 \leq W_i \leq 10^9 (1 \leq i \leq M)
* If i \neq j, then (U_i, V_i) \neq (U_j, V_j) and (U_i, V_i) \neq (V_j, U_j).
* U_i \neq V_i (1 \leq i \leq M)
* The given graph is connected.
* 1 \leq X \leq 10^{12}
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N M
X
U_1 V_1 W_1
U_2 V_2 W_2
:
U_M V_M W_M
Output
Print the answer.
Examples
Input
3 3
2
1 2 1
2 3 1
3 1 1
Output
6
Input
3 3
3
1 2 1
2 3 1
3 1 2
Output
2
Input
5 4
1
1 2 3
1 3 3
2 4 6
2 5 8
Output
0
Input
8 10
49
4 6 10
8 4 11
5 8 9
1 8 10
3 8 128773450
7 8 10
4 2 4
3 4 1
3 1 13
5 2 2
Output
4 | instruction | 0 | 34,105 | 13 | 68,210 |
"Correct Solution:
```
class UnionFindVerSize():
def __init__(self, N):
self._parent = [n for n in range(0, N)]
self._size = [1] * N
def find_root(self, x):
if self._parent[x] == x: return x
self._parent[x] = self.find_root(self._parent[x])
return self._parent[x]
def unite(self, x, y):
gx = self.find_root(x)
gy = self.find_root(y)
if gx == gy: return
if self._size[gx] < self._size[gy]:
self._parent[gx] = gy
self._size[gy] += self._size[gx]
else:
self._parent[gy] = gx
self._size[gx] += self._size[gy]
def get_size(self, x):
return self._size[self.find_root(x)]
def is_same_group(self, x, y):
return self.find_root(x) == self.find_root(y)
def calc_group_num(self):
N = len(self._parent)
ans = 0
for i in range(N):
if self.find_root(i) == i:
ans += 1
return ans
import sys
input=sys.stdin.buffer.readline
N,M=map(int,input().split())
X=int(input())
mod=10**9+7
Edge=[]
EEdge=[]
for i in range(M):
a,b,c=map(int,input().split())
Edge.append((c,a-1,b-1))
EEdge.append((c,a-1,b-1))
Edge.sort()
base=0
edge=[[] for i in range(N)]
uf=UnionFindVerSize(N)
for c,a,b in Edge:
if not uf.is_same_group(a,b):
uf.unite(a,b)
base+=c
edge[a].append((b,c))
edge[b].append((a,c))
weight=[0]*N
depth=[0]*N
parent=[0]*N
rmq=[0]*N
def wdfs(v,pv):
for nv,cost in edge[v]:
if nv!=pv:
parent[nv]=v
depth[nv]=depth[v]+1
weight[nv]=cost
rmq[nv]=max(weight[nv],weight[v])
wdfs(nv,v)
wdfs(0,-1)
LV = (N-1).bit_length()
def construct(prv):
kprv = [prv]
S = prv
for k in range(LV):
T = [0]*N
for i in range(N):
if S[i] is None:
continue
T[i] = S[S[i]]
kprv.append(T)
S = T
return kprv
kprv=construct(parent)
def constructkrmq(r):
krmq=[r]
S=r
for k in range(LV):
T=[0]*N
for i in range(N):
if S[i] is None:
continue
T[i]=max(S[i],S[kprv[k][i]])
krmq.append(T)
S=T
return krmq
krmq=constructkrmq(rmq)
def lca(u, v):
dd = depth[v] - depth[u]
if dd < 0:
u, v = v, u
dd = -dd
# assert depth[u] <= depth[v]
for k in range(LV+1):
if dd & 1:
v = kprv[k][v]
dd >>= 1
# assert depth[u] == depth[v]
if u == v:
return u
for k in range(LV-1, -1, -1):
pu = kprv[k][u]; pv = kprv[k][v]
if pu != pv:
u = pu; v = pv
# assert kprv[0][u] == kprv[0][v]
return kprv[0][u]
def RMQ(u,v):
#assert depth[u]>depth[v]
if depth[u]==depth[v]:
return 0
num=depth[u]-depth[v]-1
pos=u
res=weight[u]
for i in range(LV-1,-1,-1):
if num>>i &1==1:
res=max(res,krmq[i][pos])
pos=kprv[i][pos]
return res
up=0
down=0
same=0
for c,u,v in EEdge:
LCA=lca(u,v)
minus=max(RMQ(u,LCA),RMQ(v,LCA))
if base-minus+c>X:
up+=1
elif base-minus+c<X:
down+=1
else:
same+=1
if down==0:
if same==0:
print(0)
else:
ans=pow(2,M,mod)-2*pow(2,up,mod)
print(ans%mod)
else:
ans=2*(pow(2,same,mod)-1)*pow(2,up,mod)
print(ans%mod)
``` | output | 1 | 34,105 | 13 | 68,211 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have an undirected weighted graph with N vertices and M edges. The i-th edge in the graph connects Vertex U_i and Vertex V_i, and has a weight of W_i. Additionally, you are given an integer X.
Find the number of ways to paint each edge in this graph either white or black such that the following condition is met, modulo 10^9 + 7:
* The graph has a spanning tree that contains both an edge painted white and an edge painted black. Furthermore, among such spanning trees, the one with the smallest weight has a weight of X.
Here, the weight of a spanning tree is the sum of the weights of the edges contained in the spanning tree.
Constraints
* 1 \leq N \leq 1 000
* 1 \leq M \leq 2 000
* 1 \leq U_i, V_i \leq N (1 \leq i \leq M)
* 1 \leq W_i \leq 10^9 (1 \leq i \leq M)
* If i \neq j, then (U_i, V_i) \neq (U_j, V_j) and (U_i, V_i) \neq (V_j, U_j).
* U_i \neq V_i (1 \leq i \leq M)
* The given graph is connected.
* 1 \leq X \leq 10^{12}
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N M
X
U_1 V_1 W_1
U_2 V_2 W_2
:
U_M V_M W_M
Output
Print the answer.
Examples
Input
3 3
2
1 2 1
2 3 1
3 1 1
Output
6
Input
3 3
3
1 2 1
2 3 1
3 1 2
Output
2
Input
5 4
1
1 2 3
1 3 3
2 4 6
2 5 8
Output
0
Input
8 10
49
4 6 10
8 4 11
5 8 9
1 8 10
3 8 128773450
7 8 10
4 2 4
3 4 1
3 1 13
5 2 2
Output
4
Submitted Solution:
```
import sys
from operator import itemgetter
class UnionFind:
def __init__(self, n):
self.table = [-1] * n
def _root(self, x):
if self.table[x] < 0:
return x
else:
self.table[x] = self._root(self.table[x])
return self.table[x]
def find(self, x, y):
return self._root(x) == self._root(y)
def union(self, x, y):
r1 = self._root(x)
r2 = self._root(y)
if r1 == r2:
return
d1 = self.table[r1]
d2 = self.table[r2]
if d1 <= d2:
self.table[r2] = r1
self.table[r1] += d2
else:
self.table[r1] = r2
self.table[r2] += d1
class LcaDoubling:
"""
links[v] = { (u, w), (u, w), ... } (u:隣接頂点, w:辺の重み)
というグラフ情報から、ダブリングによるLCAを構築。
任意の2頂点のLCAおよび「パスに含まれる最長辺の長さ」を取得できるようにする
"""
def __init__(self, n, links, root=0):
self.depths = [-1] * n
self.max_paths = [[-1] * (n + 1)]
self.ancestors = [[-1] * (n + 1)] # 頂点数より1個長くし、存在しないことを-1で表す。末尾(-1)要素は常に-1
self._init_dfs(n, links, root)
prev_ancestors = self.ancestors[-1]
prev_max_paths = self.max_paths[-1]
max_depth = max(self.depths)
d = 1
while d < max_depth:
next_ancestors = [prev_ancestors[p] for p in prev_ancestors]
next_max_paths = [max(prev_max_paths[p], prev_max_paths[q]) for p, q in enumerate(prev_ancestors)]
self.ancestors.append(next_ancestors)
self.max_paths.append(next_max_paths)
d <<= 1
prev_ancestors = next_ancestors
prev_max_paths = next_max_paths
def _init_dfs(self, n, links, root):
q = [(root, -1, 0, 0)]
direct_ancestors = self.ancestors[0]
direct_max_paths = self.max_paths[0]
while q:
v, p, dep, max_path = q.pop()
direct_ancestors[v] = p
self.depths[v] = dep
direct_max_paths[v] = max_path
q.extend((u, v, dep + 1, w) for u, w in links[v] if u != p)
return direct_ancestors
def get_lca_with_max_path(self, u, v):
du, dv = self.depths[u], self.depths[v]
if du > dv:
u, v = v, u
du, dv = dv, du
tu = u
tv, max_path = self.upstream(v, dv - du)
if u == tv:
return u, max_path
for k in range(du.bit_length() - 1, -1, -1):
mu = self.ancestors[k][tu]
mv = self.ancestors[k][tv]
if mu != mv:
max_path = max(max_path, self.max_paths[k][tu], self.max_paths[k][tv])
tu = mu
tv = mv
lca = self.ancestors[0][tu]
assert lca == self.ancestors[0][tv]
max_path = max(max_path, self.max_paths[0][tu], self.max_paths[0][tv])
return lca, max_path
def upstream(self, v, k):
i = 0
mp = 0
while k:
if k & 1:
mp = max(mp, self.max_paths[i][v])
v = self.ancestors[i][v]
k >>= 1
i += 1
return v, mp
def construct_spanning_tree(n, uvw):
uft = UnionFind(n)
spanning_links = [set() for _ in range(n)]
not_spanning_links = []
adopted_count = 0
adopted_weight = 0
i = 0
while adopted_count < n - 1:
u, v, w = uvw[i]
if uft.find(u, v):
not_spanning_links.append(uvw[i])
else:
spanning_links[u].add((v, w))
spanning_links[v].add((u, w))
uft.union(u, v)
adopted_count += 1
adopted_weight += w
i += 1
not_spanning_links.extend(uvw[i:])
return adopted_weight, spanning_links, not_spanning_links
def solve(n, m, x, uvw):
# 最小全域木(MST)のコスト総和がXと一致するなら、MSTに白黒含めれば良い(ただし同率の辺は考慮)
# そうでないなら、MST以外の辺を使えるのはせいぜい1本まで→各辺の取り替えコスト増加分を見る
# MST以外の辺(u, v)を採用する際に代わりに除かれる辺は、MST上で{u, v}を結ぶパスの最大コスト辺
mst_weight, spanning_links, not_spanning_links = construct_spanning_tree(n, uvw)
# print(mst_weight)
# print(spanning_links)
# print(not_spanning_links)
if x < mst_weight:
return 0
diff = x - mst_weight
lcad = LcaDoubling(n, spanning_links)
lower_count, exact_count, upper_count = 0, 0, 0
for u, v, w in not_spanning_links:
lca, mp = lcad.get_lca_with_max_path(u, v)
inc = w - mp
# print(u, v, w, lca, mp, inc)
if inc < diff:
lower_count += 1
elif inc > diff:
upper_count += 1
else:
exact_count += 1
MOD = 10 ** 9 + 7
# x >= mst_weight の場合、MSTの辺は全て同じ色として
# lower_count も全てそれと同じ色
# exact_count は「全てがMSTと同じ色」でない限りどのような塗り方でもよい
# upper_count はどのような塗り方でもよい
replace_to_exact_link = 2 * (pow(2, exact_count, MOD) - 1) * pow(2, upper_count, MOD) % MOD
if diff > 0:
return replace_to_exact_link
# x == mst_weight の場合は、MSTが全て同じ色でない限りどのような塗り方でもよいパターンも追加
use_first_spanning = (pow(2, n - 1, MOD) - 2) * pow(2, m - n + 1, MOD) % MOD
return (use_first_spanning + replace_to_exact_link) % MOD
n, m = map(int, input().split())
x = int(input())
uvw = []
for line in sys.stdin:
u, v, w = map(int, line.split())
u -= 1
v -= 1
uvw.append((u, v, w))
uvw.sort(key=itemgetter(2))
print(solve(n, m, x, uvw))
``` | instruction | 0 | 34,106 | 13 | 68,212 |
Yes | output | 1 | 34,106 | 13 | 68,213 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have an undirected weighted graph with N vertices and M edges. The i-th edge in the graph connects Vertex U_i and Vertex V_i, and has a weight of W_i. Additionally, you are given an integer X.
Find the number of ways to paint each edge in this graph either white or black such that the following condition is met, modulo 10^9 + 7:
* The graph has a spanning tree that contains both an edge painted white and an edge painted black. Furthermore, among such spanning trees, the one with the smallest weight has a weight of X.
Here, the weight of a spanning tree is the sum of the weights of the edges contained in the spanning tree.
Constraints
* 1 \leq N \leq 1 000
* 1 \leq M \leq 2 000
* 1 \leq U_i, V_i \leq N (1 \leq i \leq M)
* 1 \leq W_i \leq 10^9 (1 \leq i \leq M)
* If i \neq j, then (U_i, V_i) \neq (U_j, V_j) and (U_i, V_i) \neq (V_j, U_j).
* U_i \neq V_i (1 \leq i \leq M)
* The given graph is connected.
* 1 \leq X \leq 10^{12}
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N M
X
U_1 V_1 W_1
U_2 V_2 W_2
:
U_M V_M W_M
Output
Print the answer.
Examples
Input
3 3
2
1 2 1
2 3 1
3 1 1
Output
6
Input
3 3
3
1 2 1
2 3 1
3 1 2
Output
2
Input
5 4
1
1 2 3
1 3 3
2 4 6
2 5 8
Output
0
Input
8 10
49
4 6 10
8 4 11
5 8 9
1 8 10
3 8 128773450
7 8 10
4 2 4
3 4 1
3 1 13
5 2 2
Output
4
Submitted Solution:
```
import sys
input = sys.stdin.readline
MOD = 10 ** 9 + 7
N,M = map(int,input().split())
X = int(input())
UVW = [[int(x) for x in input().split()] for _ in range(M)]
UVW.sort(key = lambda x: x[2])
root = list(range(N+1))
def find_root(x):
y = root[x]
if x == y:
return x
z = find_root(y)
root[x] = z
return z
# min spanning tree
tree = [set() for _ in range(N+1)]
min_tree_size = 0
for u,v,w in UVW:
ru = find_root(u)
rv = find_root(v)
if ru == rv:
continue
root[ru] = rv
min_tree_size += w
tree[u].add((v,w))
tree[v].add((u,w))
# treeにおける2頂点の間の辺の最大値を求めたい
# LCA。2^n個手前およびそこまでの最大値を覚える
parent = [[0] * 12 for _ in range(N+1)]
max_wt = [[0] * 12 for _ in range(N+1)]
depth = [0] * (N+1)
def dfs(v=1,p=0,dep=0,w=0):
parent[v][0] = p
depth[v] = dep
max_wt[v][0] = w
for n in range(1,11):
parent[v][n] = parent[parent[v][n-1]][n-1]
max_wt[v][n] = max(max_wt[v][n-1], max_wt[parent[v][n-1]][n-1])
for u,w in tree[v]:
if u == p:
continue
dfs(u,v,dep+1,w)
dfs()
def max_wt_between(x,y):
# LCA しながら重みの最大値を得る
wt = 0
dx,dy = depth[x], depth[y]
if dx > dy:
x,y = y,x
dx,dy = dy,dx
while dy > dx:
diff = dy - dx
step = diff & (-diff)
n = step.bit_length() - 1
wt = max(wt, max_wt[y][n])
y = parent[y][n]
dy -= step
if x == y:
return wt
step = 1 << 11
while step:
n = step.bit_length() - 1
rx,ry = parent[x][n], parent[y][n]
if rx != ry:
wt = max(wt, max_wt[x][n], max_wt[y][n])
x,y = rx,ry
step >>= 1
return max(wt, max_wt[x][0], max_wt[y][0])
# 各edgeに対して、その辺を含む最小の全域木の大きさを求める
min_size = []
for u,v,w in UVW:
if (v,w) in tree[u]:
min_size.append(min_tree_size)
else:
x = max_wt_between(u,v)
min_size.append(min_tree_size + w - x)
sm = sum(1 if s < X else 0 for s in min_size)
eq = sum(1 if s == X else 0 for s in min_size)
gr = sum(1 if s > X else 0 for s in min_size)
if eq == 0:
answer = 0
elif sm == 0:
# eq 内の辺が完全同色でなければよい
answer = (pow(2,eq,MOD) - 2) * pow(2,gr,MOD) % MOD
else:
# sm 内が完全同色でなければならない。
# eq 内は、smの色と異なる色を持っていれば何でもよい
answer = 2 * (pow(2,eq,MOD) - 1) * pow(2,gr,MOD) % MOD
print(answer)
``` | instruction | 0 | 34,107 | 13 | 68,214 |
Yes | output | 1 | 34,107 | 13 | 68,215 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have an undirected weighted graph with N vertices and M edges. The i-th edge in the graph connects Vertex U_i and Vertex V_i, and has a weight of W_i. Additionally, you are given an integer X.
Find the number of ways to paint each edge in this graph either white or black such that the following condition is met, modulo 10^9 + 7:
* The graph has a spanning tree that contains both an edge painted white and an edge painted black. Furthermore, among such spanning trees, the one with the smallest weight has a weight of X.
Here, the weight of a spanning tree is the sum of the weights of the edges contained in the spanning tree.
Constraints
* 1 \leq N \leq 1 000
* 1 \leq M \leq 2 000
* 1 \leq U_i, V_i \leq N (1 \leq i \leq M)
* 1 \leq W_i \leq 10^9 (1 \leq i \leq M)
* If i \neq j, then (U_i, V_i) \neq (U_j, V_j) and (U_i, V_i) \neq (V_j, U_j).
* U_i \neq V_i (1 \leq i \leq M)
* The given graph is connected.
* 1 \leq X \leq 10^{12}
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N M
X
U_1 V_1 W_1
U_2 V_2 W_2
:
U_M V_M W_M
Output
Print the answer.
Examples
Input
3 3
2
1 2 1
2 3 1
3 1 1
Output
6
Input
3 3
3
1 2 1
2 3 1
3 1 2
Output
2
Input
5 4
1
1 2 3
1 3 3
2 4 6
2 5 8
Output
0
Input
8 10
49
4 6 10
8 4 11
5 8 9
1 8 10
3 8 128773450
7 8 10
4 2 4
3 4 1
3 1 13
5 2 2
Output
4
Submitted Solution:
```
import sys
from bisect import *
sys.setrecursionlimit(10 ** 6)
input = sys.stdin.readline
def main():
md = 10 ** 9 + 7
def get_group(k):
g = pd[k]
if g < 0:
return k
gg = get_group(g)
pd[k] = gg
return gg
def merge(j, k):
g1 = get_group(j)
g2 = get_group(k)
if g1 != g2:
d1 = -pd[g1]
d2 = -pd[g2]
if d2 > d1:
g1, g2 = g2, g1
pd[g2] = g1
if d1 == d2:
pd[g1] -= 1
n, m = map(int, input().split())
x = int(input())
ee = []
for _ in range(m):
u, v, w = map(int, input().split())
ee.append((w, u - 1, v - 1))
ee.sort()
# print(ee)
# union find 準備
n_nodes = n - 1
pd = [-1] * (n_nodes + 1)
# 無条件の最小全域木を作る
dd = [-1] * m
s = 0
for i in range(m):
w, u, v = ee[i]
if get_group(u) == get_group(v): continue
s += w
merge(u, v)
dd[i] = 0
# 最小サイズがxを超えていたら終わり
if s > x:
print(0)
exit()
# 使った辺に最小サイズを記録
for i in range(m):
if dd[i] == 0: dd[i] = s
# 使っていない辺を1つずつ試して、サイズを記録
for si in range(m):
if dd[si] != -1: continue
pd = [-1] * (n_nodes + 1)
w, u, v = ee[si]
dd[si] = 0
merge(u, v)
s = w
for i in range(m):
w, u, v = ee[i]
if get_group(u) == get_group(v): continue
s += w
merge(u, v)
if dd[i] == -1:
dd[i] = 0
for i in range(m):
if dd[i] == 0: dd[i] = s
dd.sort()
# print(dd)
# print(xi, x1i)
def cnt(k):
idx = bisect_right(dd, k)
res = pow(2, m - idx + 1, md) - 2
if idx == 0:
res = pow(2, m, md) - 2
return res
print((cnt(x - 1) - cnt(x)) % md)
main()
``` | instruction | 0 | 34,108 | 13 | 68,216 |
No | output | 1 | 34,108 | 13 | 68,217 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have an undirected weighted graph with N vertices and M edges. The i-th edge in the graph connects Vertex U_i and Vertex V_i, and has a weight of W_i. Additionally, you are given an integer X.
Find the number of ways to paint each edge in this graph either white or black such that the following condition is met, modulo 10^9 + 7:
* The graph has a spanning tree that contains both an edge painted white and an edge painted black. Furthermore, among such spanning trees, the one with the smallest weight has a weight of X.
Here, the weight of a spanning tree is the sum of the weights of the edges contained in the spanning tree.
Constraints
* 1 \leq N \leq 1 000
* 1 \leq M \leq 2 000
* 1 \leq U_i, V_i \leq N (1 \leq i \leq M)
* 1 \leq W_i \leq 10^9 (1 \leq i \leq M)
* If i \neq j, then (U_i, V_i) \neq (U_j, V_j) and (U_i, V_i) \neq (V_j, U_j).
* U_i \neq V_i (1 \leq i \leq M)
* The given graph is connected.
* 1 \leq X \leq 10^{12}
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N M
X
U_1 V_1 W_1
U_2 V_2 W_2
:
U_M V_M W_M
Output
Print the answer.
Examples
Input
3 3
2
1 2 1
2 3 1
3 1 1
Output
6
Input
3 3
3
1 2 1
2 3 1
3 1 2
Output
2
Input
5 4
1
1 2 3
1 3 3
2 4 6
2 5 8
Output
0
Input
8 10
49
4 6 10
8 4 11
5 8 9
1 8 10
3 8 128773450
7 8 10
4 2 4
3 4 1
3 1 13
5 2 2
Output
4
Submitted Solution:
```
import sys
input = sys.stdin.readline
MOD = 10 ** 9 + 7
N,M = map(int,input().split())
X = int(input())
UVW = [[int(x) for x in input().split()] for _ in range(M)]
UVW.sort(key = lambda x: x[2])
root = list(range(N+1))
def find_root(x):
y = root[x]
if x == y:
return x
z = find_root(y)
root[x] = z
return z
# min spanning tree
tree = [set() for _ in range(N+1)]
min_tree_size = 0
for u,v,w in UVW:
ru = find_root(u)
rv = find_root(v)
if ru == rv:
continue
root[ru] = rv
min_tree_size += w
tree[u].add((v,w))
tree[v].add((u,w))
# treeにおける2頂点の間の辺の最大値を求めたい
# LCA。2^n個手前およびそこまでの最大値を覚える
parent = [[0] * 12 for _ in range(N+1)]
max_wt = [[0] * 12 for _ in range(N+1)]
depth = [0] * (N+1)
def dfs(v=1,p=0,dep=0,w=0):
parent[v][0] = p
depth[v] = dep
max_wt[v][0] = w
for n in range(1,11):
parent[v][n] = parent[parent[v][n-1]][n-1]
max_wt[v][n] = max(max_wt[v][n-1], max_wt[parent[v][n-1]][n-1])
for u,w in tree[v]:
if u == p:
continue
dfs(u,v,dep+1,w)
dfs()
def max_wt_between(x,y):
# LCA しながら重みの最大値を得る
wt = 0
dx,dy = depth[x], depth[y]
if dx > dy:
x,y = y,x
dx,dy = dy,dx
while dy > dx:
diff = dy - dx
step = diff & (-diff)
n = step.bit_length() - 1
wt = max(wt, max_wt[y][n])
y = parent[y][n]
dy -= step
if x == y:
return wt
step = 1 << 11
while step:
n = step.bit_length() - 1
rx,ry = parent[x][n], parent[y][n]
if rx != ry:
x,y = rx,ry
wt = max(wt, max_wt[x][n], max_wt[y][n])
step >>= 1
return max(wt, max_wt[x][0], max_wt[y][0])
# 各edgeに対して、その辺を含む最小の全域木の大きさを求める
min_size = []
for u,v,w in UVW:
if (v,w) in tree[u]:
min_size.append(min_tree_size)
else:
x = max_wt_between(u,v)
min_size.append(min_tree_size + w - x)
sm = sum(1 if s < X else 0 for s in min_size)
eq = sum(1 if s == X else 0 for s in min_size)
gr = sum(1 if s > X else 0 for s in min_size)
if eq == 0:
answer = 0
elif sm == 0:
# eq 内の辺が完全同色でなければよい
answer = (pow(2,eq,MOD) - 2) * pow(2,gr,MOD) % MOD
else:
# sm 内が完全同色でなければならない。
# eq 内は、smの色と異なる色を持っていれば何でもよい
answer = 2 * (pow(2,eq,MOD) - 1) * pow(2,gr,MOD) % MOD
print(answer)
``` | instruction | 0 | 34,109 | 13 | 68,218 |
No | output | 1 | 34,109 | 13 | 68,219 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have an undirected weighted graph with N vertices and M edges. The i-th edge in the graph connects Vertex U_i and Vertex V_i, and has a weight of W_i. Additionally, you are given an integer X.
Find the number of ways to paint each edge in this graph either white or black such that the following condition is met, modulo 10^9 + 7:
* The graph has a spanning tree that contains both an edge painted white and an edge painted black. Furthermore, among such spanning trees, the one with the smallest weight has a weight of X.
Here, the weight of a spanning tree is the sum of the weights of the edges contained in the spanning tree.
Constraints
* 1 \leq N \leq 1 000
* 1 \leq M \leq 2 000
* 1 \leq U_i, V_i \leq N (1 \leq i \leq M)
* 1 \leq W_i \leq 10^9 (1 \leq i \leq M)
* If i \neq j, then (U_i, V_i) \neq (U_j, V_j) and (U_i, V_i) \neq (V_j, U_j).
* U_i \neq V_i (1 \leq i \leq M)
* The given graph is connected.
* 1 \leq X \leq 10^{12}
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N M
X
U_1 V_1 W_1
U_2 V_2 W_2
:
U_M V_M W_M
Output
Print the answer.
Examples
Input
3 3
2
1 2 1
2 3 1
3 1 1
Output
6
Input
3 3
3
1 2 1
2 3 1
3 1 2
Output
2
Input
5 4
1
1 2 3
1 3 3
2 4 6
2 5 8
Output
0
Input
8 10
49
4 6 10
8 4 11
5 8 9
1 8 10
3 8 128773450
7 8 10
4 2 4
3 4 1
3 1 13
5 2 2
Output
4
Submitted Solution:
```
N, M = map(int, input().split())
X = int(input())
E = []
C = {}
for i in range(M):
u, v, w = map(int, input().split())
E.append((w, u-1, v-1))
C[w] = C.get(w, 0) + 1
E.sort()
*p, = range(N)
def root(x):
if x == p[x]:
return x
y = p[x] = root(p[x])
return y
def unite(x, y):
px = root(x); py = root(y)
if px == py:
return 0
if px < py:
p[py] = px
else:
p[px] = py
return 1
MOD = 10**9 + 7
G0 = [[] for i in range(N)]
K = 0
last = None
U = [0]*M
cost = 0
for i in range(M):
w, u, v = E[i]
if unite(u, v):
cost += w
U[i] = 1
if last != w:
K += C[w]
G0[u].append((v, w))
G0[v].append((u, w))
last = w
def dfs0(u, p, t, cost):
if u == t:
return 0
for v, w in G0[u]:
if v == p:
continue
r = dfs0(v, u, t, cost)
if r is not None:
return r | (w == cost)
return None
def dfs1(u, p, t):
if u == t:
return 0
for v, w in G0[u]:
if v == p:
continue
r = dfs1(v, u, t)
if r is not None:
return max(r, w)
return None
if X - cost < 0:
print(0)
exit(0)
K = 0
for i in range(M):
if U[i]:
K += 1
continue
w, u, v = E[i]
if dfs0(u, -1, v, w):
K += 1
U[i] = 1
if cost == X:
ans = ((pow(2, K, MOD) - 2)*pow(2, M-K, MOD)) % MOD
print(ans)
exit(0)
L = 0
G = 0
for i in range(M):
w, u, v = E[i]
if last + (X - cost) < w:
break
G += 1
if U[i]:
continue
if dfs1(u, -1, v) + (X - cost) == w:
L += 1
#print(K, L, M, M-K-L, G)
ans = (2*(pow(2, L, MOD)-1)*pow(2, M-G, MOD)) % MOD
print(ans)
``` | instruction | 0 | 34,110 | 13 | 68,220 |
No | output | 1 | 34,110 | 13 | 68,221 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have an undirected weighted graph with N vertices and M edges. The i-th edge in the graph connects Vertex U_i and Vertex V_i, and has a weight of W_i. Additionally, you are given an integer X.
Find the number of ways to paint each edge in this graph either white or black such that the following condition is met, modulo 10^9 + 7:
* The graph has a spanning tree that contains both an edge painted white and an edge painted black. Furthermore, among such spanning trees, the one with the smallest weight has a weight of X.
Here, the weight of a spanning tree is the sum of the weights of the edges contained in the spanning tree.
Constraints
* 1 \leq N \leq 1 000
* 1 \leq M \leq 2 000
* 1 \leq U_i, V_i \leq N (1 \leq i \leq M)
* 1 \leq W_i \leq 10^9 (1 \leq i \leq M)
* If i \neq j, then (U_i, V_i) \neq (U_j, V_j) and (U_i, V_i) \neq (V_j, U_j).
* U_i \neq V_i (1 \leq i \leq M)
* The given graph is connected.
* 1 \leq X \leq 10^{12}
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N M
X
U_1 V_1 W_1
U_2 V_2 W_2
:
U_M V_M W_M
Output
Print the answer.
Examples
Input
3 3
2
1 2 1
2 3 1
3 1 1
Output
6
Input
3 3
3
1 2 1
2 3 1
3 1 2
Output
2
Input
5 4
1
1 2 3
1 3 3
2 4 6
2 5 8
Output
0
Input
8 10
49
4 6 10
8 4 11
5 8 9
1 8 10
3 8 128773450
7 8 10
4 2 4
3 4 1
3 1 13
5 2 2
Output
4
Submitted Solution:
```
N, M = map(int, input().split())
X = int(input())
E = []
C = {}
for i in range(M):
u, v, w = map(int, input().split())
E.append((w, u-1, v-1))
C[w] = C.get(w, 0) + 1
E.sort()
*p, = range(N)
def root(x):
if x == p[x]:
return x
y = p[x] = root(p[x])
return y
def unite(x, y):
px = root(x); py = root(y)
if px == py:
return 0
if px < py:
p[py] = px
else:
p[px] = py
return 1
MOD = 10**9 + 7
K = 0
last = None
cost = 0
for w, u, v in E:
if unite(u, v):
cost += w
if last != w:
K += C[w]
last = w
if X == cost:
ans = ((pow(2, K, MOD) - 2)*pow(2, M-K, MOD)) % MOD
print(ans)
exit(0)
trg = last + (X - cost)
if C.get(trg, 0) == 0:
print(0)
exit(0)
L = 0
for w, u, v in E:
if trg <= w:
break
L += 1
ans = (2*(pow(2, C[trg], MOD) - 1)*pow(2, M - C[trg] - L, MOD)) % MOD
print(ans)
``` | instruction | 0 | 34,111 | 13 | 68,222 |
No | output | 1 | 34,111 | 13 | 68,223 |
Provide a correct Python 3 solution for this coding contest problem.
Constraints
* 1 ≤ |V| ≤ 100
* 0 ≤ |E| ≤ 9900
* -2 × 107 ≤ di ≤ 2 × 107
* There are no parallel edges
* There are no self-loops
Input
An edge-weighted graph G (V, E).
|V| |E|
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.
si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.
Output
If the graph contains a negative cycle (a cycle whose sum of edge costs is a negative value), print
NEGATIVE CYCLE
in a line.
Otherwise, print
D0,0 D0,1 ... D0,|V|-1
D1,0 D1,1 ... D1,|V|-1
:
D|V|-1,0 D1,1 ... D|V|-1,|V|-1
The output consists of |V| lines. For each ith line, print the cost of the shortest path from vertex i to each vertex j (j = 0, 1, ... |V|-1) respectively. If there is no path from vertex i to vertex j, print "INF". Print a space between the costs.
Examples
Input
4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 7
Output
0 1 3 4
INF 0 2 3
INF INF 0 1
INF INF 7 0
Input
4 6
0 1 1
0 2 -5
1 2 2
1 3 4
2 3 1
3 2 7
Output
0 1 -5 -4
INF 0 2 3
INF INF 0 1
INF INF 7 0
Input
4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 -7
Output
NEGATIVE CYCLE | instruction | 0 | 34,225 | 13 | 68,450 |
"Correct Solution:
```
import sys
def w_f(dp):
for k in range(v):
for i in range(v):
for j in range(v):
dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j])
for i in range(v):
for j in range(v):
if dp[i][i] < 0:
print('NEGATIVE CYCLE')
sys.exit()
if dp[i][j] == float('inf'):
dp[i][j] = 'INF'
return dp
v,e = map(int, input().split())
dp = [[float('inf')]*v for _ in range(v)]
for i in range(e):
s,t,d = map(int, input().split())
dp[s][t] = d
for i in range(v):
dp[i][i] = 0
res = w_f(dp)
for i in range(v):
print(*res[i])
``` | output | 1 | 34,225 | 13 | 68,451 |
Provide a correct Python 3 solution for this coding contest problem.
Constraints
* 1 ≤ |V| ≤ 100
* 0 ≤ |E| ≤ 9900
* -2 × 107 ≤ di ≤ 2 × 107
* There are no parallel edges
* There are no self-loops
Input
An edge-weighted graph G (V, E).
|V| |E|
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.
si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.
Output
If the graph contains a negative cycle (a cycle whose sum of edge costs is a negative value), print
NEGATIVE CYCLE
in a line.
Otherwise, print
D0,0 D0,1 ... D0,|V|-1
D1,0 D1,1 ... D1,|V|-1
:
D|V|-1,0 D1,1 ... D|V|-1,|V|-1
The output consists of |V| lines. For each ith line, print the cost of the shortest path from vertex i to each vertex j (j = 0, 1, ... |V|-1) respectively. If there is no path from vertex i to vertex j, print "INF". Print a space between the costs.
Examples
Input
4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 7
Output
0 1 3 4
INF 0 2 3
INF INF 0 1
INF INF 7 0
Input
4 6
0 1 1
0 2 -5
1 2 2
1 3 4
2 3 1
3 2 7
Output
0 1 -5 -4
INF 0 2 3
INF INF 0 1
INF INF 7 0
Input
4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 -7
Output
NEGATIVE CYCLE | instruction | 0 | 34,226 | 13 | 68,452 |
"Correct Solution:
```
INF = 1e12
v, e = map(int, input().split())
cost = [[INF] * v for i in range(v)]
for i in range(v):
cost[i][i] = 0
for i in range(e):
si, ti, di = map(int, input().split())
cost[si][ti] = di
for k in range(v):
for i in range(v):
for j in range(v):
if cost[i][k] != INF and cost[k][j] != INF:
cost[i][j] = min(cost[i][j], cost[i][k] + cost[k][j])
if any(cost[i][i] for i in range(v)):
print('NEGATIVE CYCLE')
else:
for di in cost:
ldi = []
for dij in di:
if dij == INF:
ldi.append('INF')
else:
ldi.append(str(dij))
print(' '.join(ldi))
``` | output | 1 | 34,226 | 13 | 68,453 |
Provide a correct Python 3 solution for this coding contest problem.
Constraints
* 1 ≤ |V| ≤ 100
* 0 ≤ |E| ≤ 9900
* -2 × 107 ≤ di ≤ 2 × 107
* There are no parallel edges
* There are no self-loops
Input
An edge-weighted graph G (V, E).
|V| |E|
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.
si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.
Output
If the graph contains a negative cycle (a cycle whose sum of edge costs is a negative value), print
NEGATIVE CYCLE
in a line.
Otherwise, print
D0,0 D0,1 ... D0,|V|-1
D1,0 D1,1 ... D1,|V|-1
:
D|V|-1,0 D1,1 ... D|V|-1,|V|-1
The output consists of |V| lines. For each ith line, print the cost of the shortest path from vertex i to each vertex j (j = 0, 1, ... |V|-1) respectively. If there is no path from vertex i to vertex j, print "INF". Print a space between the costs.
Examples
Input
4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 7
Output
0 1 3 4
INF 0 2 3
INF INF 0 1
INF INF 7 0
Input
4 6
0 1 1
0 2 -5
1 2 2
1 3 4
2 3 1
3 2 7
Output
0 1 -5 -4
INF 0 2 3
INF INF 0 1
INF INF 7 0
Input
4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 -7
Output
NEGATIVE CYCLE | instruction | 0 | 34,227 | 13 | 68,454 |
"Correct Solution:
```
nv, ne = map(int, input().split())
costs = [[None] * nv for _ in range(nv)]
for i in range(nv):
costs[i][i] = 0
while ne:
s, t, d = map(int, input().split())
costs[s][t] = d
ne -= 1
def loop():
for k in range(nv):
for i in range(nv):
for j in range(nv):
if costs[i][k] is None or costs[k][j] is None:
continue
tmp_cost = costs[i][k] + costs[k][j]
if i == j and tmp_cost < 0:
print('NEGATIVE CYCLE')
return False
if costs[i][j] is None or costs[i][j] > tmp_cost:
costs[i][j] = tmp_cost
return True
if loop():
for vc in costs:
print(*('INF' if c is None else c for c in vc))
``` | output | 1 | 34,227 | 13 | 68,455 |
Provide a correct Python 3 solution for this coding contest problem.
Constraints
* 1 ≤ |V| ≤ 100
* 0 ≤ |E| ≤ 9900
* -2 × 107 ≤ di ≤ 2 × 107
* There are no parallel edges
* There are no self-loops
Input
An edge-weighted graph G (V, E).
|V| |E|
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.
si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.
Output
If the graph contains a negative cycle (a cycle whose sum of edge costs is a negative value), print
NEGATIVE CYCLE
in a line.
Otherwise, print
D0,0 D0,1 ... D0,|V|-1
D1,0 D1,1 ... D1,|V|-1
:
D|V|-1,0 D1,1 ... D|V|-1,|V|-1
The output consists of |V| lines. For each ith line, print the cost of the shortest path from vertex i to each vertex j (j = 0, 1, ... |V|-1) respectively. If there is no path from vertex i to vertex j, print "INF". Print a space between the costs.
Examples
Input
4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 7
Output
0 1 3 4
INF 0 2 3
INF INF 0 1
INF INF 7 0
Input
4 6
0 1 1
0 2 -5
1 2 2
1 3 4
2 3 1
3 2 7
Output
0 1 -5 -4
INF 0 2 3
INF INF 0 1
INF INF 7 0
Input
4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 -7
Output
NEGATIVE CYCLE | instruction | 0 | 34,228 | 13 | 68,456 |
"Correct Solution:
```
v,e = map(int,input().split())
cost = []
for i in range(v):
T = [float('inf')]*v
T[i] = 0
cost.append(T)
for i in range(e):
a,b,c = map(int,input().split())
cost[a][b] = c
for k in range(v):
for i in range(v):
for j in range(v):
cost[i][j] = min(cost[i][j], cost[i][k]+cost[k][j])
flag = True
for i in range(v):
for j in range(v):
if cost[i][j] == float('inf'):
cost[i][j] = 'INF'
elif i == j and cost[i][j] < 0:
flag = False
break
if flag:
for i in range(v):
print(' '.join(map(str,cost[i])))
else:
print('NEGATIVE CYCLE')
``` | output | 1 | 34,228 | 13 | 68,457 |
Provide a correct Python 3 solution for this coding contest problem.
Constraints
* 1 ≤ |V| ≤ 100
* 0 ≤ |E| ≤ 9900
* -2 × 107 ≤ di ≤ 2 × 107
* There are no parallel edges
* There are no self-loops
Input
An edge-weighted graph G (V, E).
|V| |E|
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.
si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.
Output
If the graph contains a negative cycle (a cycle whose sum of edge costs is a negative value), print
NEGATIVE CYCLE
in a line.
Otherwise, print
D0,0 D0,1 ... D0,|V|-1
D1,0 D1,1 ... D1,|V|-1
:
D|V|-1,0 D1,1 ... D|V|-1,|V|-1
The output consists of |V| lines. For each ith line, print the cost of the shortest path from vertex i to each vertex j (j = 0, 1, ... |V|-1) respectively. If there is no path from vertex i to vertex j, print "INF". Print a space between the costs.
Examples
Input
4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 7
Output
0 1 3 4
INF 0 2 3
INF INF 0 1
INF INF 7 0
Input
4 6
0 1 1
0 2 -5
1 2 2
1 3 4
2 3 1
3 2 7
Output
0 1 -5 -4
INF 0 2 3
INF INF 0 1
INF INF 7 0
Input
4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 -7
Output
NEGATIVE CYCLE | instruction | 0 | 34,229 | 13 | 68,458 |
"Correct Solution:
```
v, e = map(int, input().split())
G = [[float('inf') for _ in range(v)] for i in range(v)]
for i in range(v):
G[i][i] = 0
# print(G)
dist = [[float('inf') for i in range(v)] for j in range(v)]
for _ in range(e):
s, t, d = map(int, input().split())
dist[s][t] = d
for i in range(v):
dist[i][i] = 0
# print(G)
for k in range(v):
for i in range(v):
for j in range(v):
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
if i == j and dist[i][j] < 0:
print('NEGATIVE CYCLE')
exit()
ans = [["INF"]*v for _ in range(v)]
for i in range(v):
for j in range(v):
if dist[i][j] != float('inf'):
ans[i][j] = dist[i][j]
for i in range(v):
print(*ans[i])
``` | output | 1 | 34,229 | 13 | 68,459 |
Provide a correct Python 3 solution for this coding contest problem.
Constraints
* 1 ≤ |V| ≤ 100
* 0 ≤ |E| ≤ 9900
* -2 × 107 ≤ di ≤ 2 × 107
* There are no parallel edges
* There are no self-loops
Input
An edge-weighted graph G (V, E).
|V| |E|
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.
si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.
Output
If the graph contains a negative cycle (a cycle whose sum of edge costs is a negative value), print
NEGATIVE CYCLE
in a line.
Otherwise, print
D0,0 D0,1 ... D0,|V|-1
D1,0 D1,1 ... D1,|V|-1
:
D|V|-1,0 D1,1 ... D|V|-1,|V|-1
The output consists of |V| lines. For each ith line, print the cost of the shortest path from vertex i to each vertex j (j = 0, 1, ... |V|-1) respectively. If there is no path from vertex i to vertex j, print "INF". Print a space between the costs.
Examples
Input
4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 7
Output
0 1 3 4
INF 0 2 3
INF INF 0 1
INF INF 7 0
Input
4 6
0 1 1
0 2 -5
1 2 2
1 3 4
2 3 1
3 2 7
Output
0 1 -5 -4
INF 0 2 3
INF INF 0 1
INF INF 7 0
Input
4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 -7
Output
NEGATIVE CYCLE | instruction | 0 | 34,230 | 13 | 68,460 |
"Correct Solution:
```
def warshall_floyd(d):
#d[i][j]: iからjへの最短距離
for k in range(n):
for i in range(n):
for j in range(n):
if (d[i][k] != float("INF")) and (d[k][j] != float("INF")):
d[i][j] = min(d[i][j],d[i][k] + d[k][j])
#print(d)
return d
##############################
n,w = map(int,input().split()) #n:頂点数 w:辺の数
d = [[float("INF")] * n for i in range(n)]
#d[u][v] : 辺uvのコスト(存在しないときはinf)
for i in range(w):
x,y,z = map(int,input().split())
d[x][y] = z
#d[y][x] = z
for i in range(n):
d[i][i] = 0 #自身のところに行くコストは0
D = warshall_floyd(d)
for i in range(n):
if D[i][i] < 0:
print("NEGATIVE CYCLE")
#print(D)
quit()
for i in range(n):
for j in range(n):
if D[i][j] == float("inf"):
if j == n - 1:
D[i][j] = print("INF")
else:
D[i][j] = print("INF", end = " ")
else:
if j == n - 1:
print(D[i][j])
else:
print(D[i][j], end = " ")
#print(D)
``` | output | 1 | 34,230 | 13 | 68,461 |
Provide a correct Python 3 solution for this coding contest problem.
Constraints
* 1 ≤ |V| ≤ 100
* 0 ≤ |E| ≤ 9900
* -2 × 107 ≤ di ≤ 2 × 107
* There are no parallel edges
* There are no self-loops
Input
An edge-weighted graph G (V, E).
|V| |E|
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.
si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.
Output
If the graph contains a negative cycle (a cycle whose sum of edge costs is a negative value), print
NEGATIVE CYCLE
in a line.
Otherwise, print
D0,0 D0,1 ... D0,|V|-1
D1,0 D1,1 ... D1,|V|-1
:
D|V|-1,0 D1,1 ... D|V|-1,|V|-1
The output consists of |V| lines. For each ith line, print the cost of the shortest path from vertex i to each vertex j (j = 0, 1, ... |V|-1) respectively. If there is no path from vertex i to vertex j, print "INF". Print a space between the costs.
Examples
Input
4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 7
Output
0 1 3 4
INF 0 2 3
INF INF 0 1
INF INF 7 0
Input
4 6
0 1 1
0 2 -5
1 2 2
1 3 4
2 3 1
3 2 7
Output
0 1 -5 -4
INF 0 2 3
INF INF 0 1
INF INF 7 0
Input
4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 -7
Output
NEGATIVE CYCLE | instruction | 0 | 34,231 | 13 | 68,462 |
"Correct Solution:
```
import sys
input=sys.stdin.readline
sys.setrecursionlimit(10 ** 8)
from itertools import accumulate
from itertools import permutations
from itertools import combinations
from collections import defaultdict
from collections import Counter
import fractions
import math
from collections import deque
from bisect import bisect_left
from bisect import insort_left
import itertools
from heapq import heapify
from heapq import heappop
from heapq import heappush
import heapq
#import numpy as np
INF = float("inf")
#d = defaultdict(int)
#d = defaultdict(list)
#N = int(input())
#A = list(map(int,input().split()))
#S = list(input())
#S.remove("\n")
#N,M = map(int,input().split())
#S,T = map(str,input().split())
#A = [int(input()) for _ in range(N)]
#S = [list(input())[:-1] for _ in range(N)]
#A = [list(map(int,input().split())) for _ in range(N)]
V,E = map(int,input().split())#頂点、辺の数
INF = float("inf")
cost = [[INF]*V for _ in range(V)]#iからjへの重み付き距離cost[i][j]
for i in range(V):
cost[i][i] = 0
for _ in range(E):
s,t,dd = map(int,input().split())
cost[s][t] = dd
#実装
for k in range(V):
for i in range(V):
for j in range(V):
cost[i][j] = min(cost[i][j],cost[i][k]+cost[k][j])
judge = 0
for i in range(V):
if judge == 1:
break
for j in range(i+1,V):
if cost[i][j] + cost[j][i] < 0:
judge = 1
break
for i in range(V):
for j in range(V):
if cost[i][j] == INF:
cost[i][j] = "INF"
else:
cost[i][j] = str(cost[i][j])
if judge == 1:
print("NEGATIVE CYCLE")
else:
for i in range(V):
print(*cost[i])
``` | output | 1 | 34,231 | 13 | 68,463 |
Provide a correct Python 3 solution for this coding contest problem.
Constraints
* 1 ≤ |V| ≤ 100
* 0 ≤ |E| ≤ 9900
* -2 × 107 ≤ di ≤ 2 × 107
* There are no parallel edges
* There are no self-loops
Input
An edge-weighted graph G (V, E).
|V| |E|
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.
si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.
Output
If the graph contains a negative cycle (a cycle whose sum of edge costs is a negative value), print
NEGATIVE CYCLE
in a line.
Otherwise, print
D0,0 D0,1 ... D0,|V|-1
D1,0 D1,1 ... D1,|V|-1
:
D|V|-1,0 D1,1 ... D|V|-1,|V|-1
The output consists of |V| lines. For each ith line, print the cost of the shortest path from vertex i to each vertex j (j = 0, 1, ... |V|-1) respectively. If there is no path from vertex i to vertex j, print "INF". Print a space between the costs.
Examples
Input
4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 7
Output
0 1 3 4
INF 0 2 3
INF INF 0 1
INF INF 7 0
Input
4 6
0 1 1
0 2 -5
1 2 2
1 3 4
2 3 1
3 2 7
Output
0 1 -5 -4
INF 0 2 3
INF INF 0 1
INF INF 7 0
Input
4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 -7
Output
NEGATIVE CYCLE | instruction | 0 | 34,232 | 13 | 68,464 |
"Correct Solution:
```
def warshall_floyd(d):
#d[i][j]: iからjへの最短距離
for k in range(n):
for i in range(n):
for j in range(n):
d[i][j] = min(d[i][j],d[i][k] + d[k][j])
return d
##############################
n,w = map(int,input().split()) #n:頂点数 w:辺の数
d = [[float("inf") for i in range(n)] for i in range(n)]
#d[u][v] : 辺uvのコスト(存在しないときはinf)
for i in range(w):
x,y,z = map(int,input().split())
d[x][y] = z
for i in range(n):
d[i][i] = 0 #自身のところに行くコストは0
distance=warshall_floyd(d)
for i in range(n):
if distance[i][i]<0:
print('NEGATIVE CYCLE')
exit()
for i in distance:
i=['INF' if x==float('inf') else x for x in i]
print(*i)
``` | output | 1 | 34,232 | 13 | 68,465 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Constraints
* 1 ≤ |V| ≤ 100
* 0 ≤ |E| ≤ 9900
* -2 × 107 ≤ di ≤ 2 × 107
* There are no parallel edges
* There are no self-loops
Input
An edge-weighted graph G (V, E).
|V| |E|
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.
si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.
Output
If the graph contains a negative cycle (a cycle whose sum of edge costs is a negative value), print
NEGATIVE CYCLE
in a line.
Otherwise, print
D0,0 D0,1 ... D0,|V|-1
D1,0 D1,1 ... D1,|V|-1
:
D|V|-1,0 D1,1 ... D|V|-1,|V|-1
The output consists of |V| lines. For each ith line, print the cost of the shortest path from vertex i to each vertex j (j = 0, 1, ... |V|-1) respectively. If there is no path from vertex i to vertex j, print "INF". Print a space between the costs.
Examples
Input
4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 7
Output
0 1 3 4
INF 0 2 3
INF INF 0 1
INF INF 7 0
Input
4 6
0 1 1
0 2 -5
1 2 2
1 3 4
2 3 1
3 2 7
Output
0 1 -5 -4
INF 0 2 3
INF INF 0 1
INF INF 7 0
Input
4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 -7
Output
NEGATIVE CYCLE
Submitted Solution:
```
from sys import stdin
from math import isinf
n, e = map(int, stdin.readline().split())
d = [[float('inf')] * n for _ in range(n)]
for i in range(n):
d[i][i] = 0
for i in range(e):
u, v, c = map(int, stdin.readline().split())
d[u][v] = c
for k in range(n):
for i in range(n):
for j in range(n):
if d[i][j] > d[i][k] + d[k][j]:
d[i][j] = d[i][k] + d[k][j]
for i in range(n):
if d[i][i] < 0:
print("NEGATIVE CYCLE")
exit(0)
for di in d:
print(' '.join(('INF' if isinf(dij) else str(dij) for dij in di)))
``` | instruction | 0 | 34,233 | 13 | 68,466 |
Yes | output | 1 | 34,233 | 13 | 68,467 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Constraints
* 1 ≤ |V| ≤ 100
* 0 ≤ |E| ≤ 9900
* -2 × 107 ≤ di ≤ 2 × 107
* There are no parallel edges
* There are no self-loops
Input
An edge-weighted graph G (V, E).
|V| |E|
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.
si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.
Output
If the graph contains a negative cycle (a cycle whose sum of edge costs is a negative value), print
NEGATIVE CYCLE
in a line.
Otherwise, print
D0,0 D0,1 ... D0,|V|-1
D1,0 D1,1 ... D1,|V|-1
:
D|V|-1,0 D1,1 ... D|V|-1,|V|-1
The output consists of |V| lines. For each ith line, print the cost of the shortest path from vertex i to each vertex j (j = 0, 1, ... |V|-1) respectively. If there is no path from vertex i to vertex j, print "INF". Print a space between the costs.
Examples
Input
4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 7
Output
0 1 3 4
INF 0 2 3
INF INF 0 1
INF INF 7 0
Input
4 6
0 1 1
0 2 -5
1 2 2
1 3 4
2 3 1
3 2 7
Output
0 1 -5 -4
INF 0 2 3
INF INF 0 1
INF INF 7 0
Input
4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 -7
Output
NEGATIVE CYCLE
Submitted Solution:
```
v,e=map(int,input().split())
dis=[[10**15 for _ in range(v)]for _ in range(v)]
for i in range(e):
a,b,c=map(int,input().split())
dis[a][b]=c
for i in range(v):
dis[i][i]=0
for k in range(v):
for i in range(v):
for j in range(v):
dis[i][j]=min(dis[i][j],dis[i][k]+dis[k][j])
for i in range(v):
if dis[i][i]<0:
print("NEGATIVE CYCLE")
exit()
for i in range(v):
ans=[]
for j in range(v):
if dis[i][j]>=10**14:
ans.append("INF")
else:
ans.append(dis[i][j])
print(*ans)
``` | instruction | 0 | 34,234 | 13 | 68,468 |
Yes | output | 1 | 34,234 | 13 | 68,469 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Constraints
* 1 ≤ |V| ≤ 100
* 0 ≤ |E| ≤ 9900
* -2 × 107 ≤ di ≤ 2 × 107
* There are no parallel edges
* There are no self-loops
Input
An edge-weighted graph G (V, E).
|V| |E|
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.
si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.
Output
If the graph contains a negative cycle (a cycle whose sum of edge costs is a negative value), print
NEGATIVE CYCLE
in a line.
Otherwise, print
D0,0 D0,1 ... D0,|V|-1
D1,0 D1,1 ... D1,|V|-1
:
D|V|-1,0 D1,1 ... D|V|-1,|V|-1
The output consists of |V| lines. For each ith line, print the cost of the shortest path from vertex i to each vertex j (j = 0, 1, ... |V|-1) respectively. If there is no path from vertex i to vertex j, print "INF". Print a space between the costs.
Examples
Input
4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 7
Output
0 1 3 4
INF 0 2 3
INF INF 0 1
INF INF 7 0
Input
4 6
0 1 1
0 2 -5
1 2 2
1 3 4
2 3 1
3 2 7
Output
0 1 -5 -4
INF 0 2 3
INF INF 0 1
INF INF 7 0
Input
4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 -7
Output
NEGATIVE CYCLE
Submitted Solution:
```
INF = 1e12
v, e = (int(s) for s in input().split())
cost = [[INF] * v for i in range(v)]
for i in range(v):
cost[i][i] = 0
for i in range(e):
si, ti, di = (int(s) for s in input().split())
cost[si][ti] = di
for k in range(v):
for i in range(v):
for j in range(v):
if cost[i][k] != INF and cost[k][j] != INF:
if cost[i][j] > cost[i][k] + cost[k][j]:
cost[i][j] = cost[i][k] + cost[k][j]
if any(cost[i][i] for i in range(v)):
print('NEGATIVE CYCLE')
else:
for di in cost:
ldi = []
for dij in di:
if dij == INF:
ldi.append('INF')
else:
ldi.append(str(dij))
print(' '.join(ldi))
``` | instruction | 0 | 34,235 | 13 | 68,470 |
Yes | output | 1 | 34,235 | 13 | 68,471 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Constraints
* 1 ≤ |V| ≤ 100
* 0 ≤ |E| ≤ 9900
* -2 × 107 ≤ di ≤ 2 × 107
* There are no parallel edges
* There are no self-loops
Input
An edge-weighted graph G (V, E).
|V| |E|
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.
si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.
Output
If the graph contains a negative cycle (a cycle whose sum of edge costs is a negative value), print
NEGATIVE CYCLE
in a line.
Otherwise, print
D0,0 D0,1 ... D0,|V|-1
D1,0 D1,1 ... D1,|V|-1
:
D|V|-1,0 D1,1 ... D|V|-1,|V|-1
The output consists of |V| lines. For each ith line, print the cost of the shortest path from vertex i to each vertex j (j = 0, 1, ... |V|-1) respectively. If there is no path from vertex i to vertex j, print "INF". Print a space between the costs.
Examples
Input
4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 7
Output
0 1 3 4
INF 0 2 3
INF INF 0 1
INF INF 7 0
Input
4 6
0 1 1
0 2 -5
1 2 2
1 3 4
2 3 1
3 2 7
Output
0 1 -5 -4
INF 0 2 3
INF INF 0 1
INF INF 7 0
Input
4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 -7
Output
NEGATIVE CYCLE
Submitted Solution:
```
import math
def main():
nvertices, nedges = map(int, input().split())
INF = float('inf')
D1 = [[0 if i == j else INF for i in range(nvertices)]
for j in range(nvertices)]
for i in range(nedges):
u, v, w = map(int, input().split())
D1[u][v] = w
for k in range(nvertices):
D2 = [[0] * nvertices for i in range(nvertices)]
for i in range(nvertices):
for j in range(nvertices):
D2[i][j] = min(D1[i][j], D1[i][k] + D1[k][j])
D1 = D2
for v in range(nvertices):
if D1[v][v] < 0:
print("NEGATIVE CYCLE")
return
for D in D1:
print(" ".join(map(lambda e: "INF" if math.isinf(e) else str(e), D)))
main()
``` | instruction | 0 | 34,236 | 13 | 68,472 |
Yes | output | 1 | 34,236 | 13 | 68,473 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Constraints
* 1 ≤ |V| ≤ 100
* 0 ≤ |E| ≤ 9900
* -2 × 107 ≤ di ≤ 2 × 107
* There are no parallel edges
* There are no self-loops
Input
An edge-weighted graph G (V, E).
|V| |E|
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.
si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.
Output
If the graph contains a negative cycle (a cycle whose sum of edge costs is a negative value), print
NEGATIVE CYCLE
in a line.
Otherwise, print
D0,0 D0,1 ... D0,|V|-1
D1,0 D1,1 ... D1,|V|-1
:
D|V|-1,0 D1,1 ... D|V|-1,|V|-1
The output consists of |V| lines. For each ith line, print the cost of the shortest path from vertex i to each vertex j (j = 0, 1, ... |V|-1) respectively. If there is no path from vertex i to vertex j, print "INF". Print a space between the costs.
Examples
Input
4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 7
Output
0 1 3 4
INF 0 2 3
INF INF 0 1
INF INF 7 0
Input
4 6
0 1 1
0 2 -5
1 2 2
1 3 4
2 3 1
3 2 7
Output
0 1 -5 -4
INF 0 2 3
INF INF 0 1
INF INF 7 0
Input
4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 -7
Output
NEGATIVE CYCLE
Submitted Solution:
```
from heapq import heapify, heappush, heappop
from collections import Counter, defaultdict, deque, OrderedDict
from sys import setrecursionlimit as setreclim
from sys import maxsize
from bisect import bisect_left, bisect, insort_left, insort
from math import ceil, log, factorial, hypot, pi
from fractions import gcd
from copy import deepcopy
from functools import reduce
from operator import mul
from itertools import product, permutations, combinations, accumulate, cycle
from string import ascii_uppercase, ascii_lowercase, ascii_letters, digits, hexdigits, octdigits
prod = lambda l: reduce(mul, l)
prodmod = lambda l, mod: reduce(lambda x, y: mul(x,y)%mod, l)
class WarshallFloyd():
"""Warshall-Floyd Algorithm:
find the lengths of the shortest paths between all pairs of vertices
"""
def __init__(self, V, E, INF=10**9):
""" V: the number of vertexes
E: adjacency list
start: start vertex
INF: Infinity distance
"""
self.V = V
self.E = E
self.warshall_floyd(INF)
def warshall_floyd(self, INF):
self.distance = [[INF] * self.V for _ in range(V)]
for i in range(V): self.distance[i][i] = 0
for fr in range(V):
for to, cost in self.E[fr]:
self.distance[fr][to] = cost
for k in range(self.V):
for i in range(self.V):
for j in range(self.V):
self.distance[i][j] = min(self.distance[i][j], self.distance[i][k] + self.distance[k][j])
def hasNegativeCycle(self):
for i in range(V):
if self.distance[i][i] < 0:
return True
else:
return False
V, E = map(int, input().split())
INF = 10**10
edge = [[] for _ in range(V)]
for i in range(E):
s, t, cost = map(int, input().split())
edge[s].append((t, cost))
allsp = WarshallFloyd(V, edge, INF)
if allsp.hasNegativeCycle():
print('NEGATIVE CYCLE')
else:
for dist in allsp.distance:
print(*[d if d != INF else 'INF' for d in dist])
``` | instruction | 0 | 34,237 | 13 | 68,474 |
No | output | 1 | 34,237 | 13 | 68,475 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Constraints
* 1 ≤ |V| ≤ 100
* 0 ≤ |E| ≤ 9900
* -2 × 107 ≤ di ≤ 2 × 107
* There are no parallel edges
* There are no self-loops
Input
An edge-weighted graph G (V, E).
|V| |E|
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.
si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.
Output
If the graph contains a negative cycle (a cycle whose sum of edge costs is a negative value), print
NEGATIVE CYCLE
in a line.
Otherwise, print
D0,0 D0,1 ... D0,|V|-1
D1,0 D1,1 ... D1,|V|-1
:
D|V|-1,0 D1,1 ... D|V|-1,|V|-1
The output consists of |V| lines. For each ith line, print the cost of the shortest path from vertex i to each vertex j (j = 0, 1, ... |V|-1) respectively. If there is no path from vertex i to vertex j, print "INF". Print a space between the costs.
Examples
Input
4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 7
Output
0 1 3 4
INF 0 2 3
INF INF 0 1
INF INF 7 0
Input
4 6
0 1 1
0 2 -5
1 2 2
1 3 4
2 3 1
3 2 7
Output
0 1 -5 -4
INF 0 2 3
INF INF 0 1
INF INF 7 0
Input
4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 -7
Output
NEGATIVE CYCLE
Submitted Solution:
```
# -*- coding: utf-8 -*-
import sys
from copy import deepcopy
sys.setrecursionlimit(10 ** 9)
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
INF=float('inf')
# ワーシャルフロイド(頂点数, 隣接行列(0-indexed))
def warshall_floyd(N: int, graph: list) -> list:
res = deepcopy(graph)
for i in range(N):
# 始点 = 終点、は予め距離0にしておく
res[i][i] = 0
# 全頂点の最短距離
for k in range(N):
for i in range(N):
for j in range(N):
res[i][j] = min(res[i][j], res[i][k] + res[k][j])
# 負の閉路(いくらでもコストを減らせてしまう場所)がないかチェックする
for i in range(N):
if res[i][i] < 0:
return []
return res
N,M=MAP()
G=[[INF]*N for i in range(N)]
for i in range(M):
s,t,d=MAP()
G[s][t]=d
ans=warshall_floyd(N, G)
if not len(ans):
print('NEGATIVE CYCLE')
exit()
for i in range(N):
print(*ans[i])
``` | instruction | 0 | 34,238 | 13 | 68,476 |
No | output | 1 | 34,238 | 13 | 68,477 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Constraints
* 1 ≤ |V| ≤ 100
* 0 ≤ |E| ≤ 9900
* -2 × 107 ≤ di ≤ 2 × 107
* There are no parallel edges
* There are no self-loops
Input
An edge-weighted graph G (V, E).
|V| |E|
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.
si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.
Output
If the graph contains a negative cycle (a cycle whose sum of edge costs is a negative value), print
NEGATIVE CYCLE
in a line.
Otherwise, print
D0,0 D0,1 ... D0,|V|-1
D1,0 D1,1 ... D1,|V|-1
:
D|V|-1,0 D1,1 ... D|V|-1,|V|-1
The output consists of |V| lines. For each ith line, print the cost of the shortest path from vertex i to each vertex j (j = 0, 1, ... |V|-1) respectively. If there is no path from vertex i to vertex j, print "INF". Print a space between the costs.
Examples
Input
4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 7
Output
0 1 3 4
INF 0 2 3
INF INF 0 1
INF INF 7 0
Input
4 6
0 1 1
0 2 -5
1 2 2
1 3 4
2 3 1
3 2 7
Output
0 1 -5 -4
INF 0 2 3
INF INF 0 1
INF INF 7 0
Input
4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 -7
Output
NEGATIVE CYCLE
Submitted Solution:
```
V, E = map(int, input().split())
visited = [False] * V
nodes = [[] for i in range(V)]
cost = [[] for i in range(V)]
for i in range(E):
s, t, d = map(int, input().split())
nodes[s].append(t)
cost[s].append(d)
dist = [[float('inf') for j in range(V)] for i in range(V)]
for i in range(V):
dist[i][i] = 0
negative_cycle = False
for k in range(V):
for i in range(V):
for j in range(len(nodes[i])):
if dist[k][i] == float('inf'):
continue
if dist[k][nodes[i][j]] > dist[k][i] + cost[i][j]:
dist[k][nodes[i][j]] = dist[k][i] + cost[i][j]
for i in range(V):
if dist[i][i] < 0:
negative_cycle = True
if negative_cycle:
print('NEGATIVE CYCLE')
else:
for i in range(V):
d = ['INF' if e == float('inf') else e for e in dist[i]]
print(*d)
``` | instruction | 0 | 34,239 | 13 | 68,478 |
No | output | 1 | 34,239 | 13 | 68,479 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Constraints
* 1 ≤ |V| ≤ 100
* 0 ≤ |E| ≤ 9900
* -2 × 107 ≤ di ≤ 2 × 107
* There are no parallel edges
* There are no self-loops
Input
An edge-weighted graph G (V, E).
|V| |E|
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.
si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.
Output
If the graph contains a negative cycle (a cycle whose sum of edge costs is a negative value), print
NEGATIVE CYCLE
in a line.
Otherwise, print
D0,0 D0,1 ... D0,|V|-1
D1,0 D1,1 ... D1,|V|-1
:
D|V|-1,0 D1,1 ... D|V|-1,|V|-1
The output consists of |V| lines. For each ith line, print the cost of the shortest path from vertex i to each vertex j (j = 0, 1, ... |V|-1) respectively. If there is no path from vertex i to vertex j, print "INF". Print a space between the costs.
Examples
Input
4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 7
Output
0 1 3 4
INF 0 2 3
INF INF 0 1
INF INF 7 0
Input
4 6
0 1 1
0 2 -5
1 2 2
1 3 4
2 3 1
3 2 7
Output
0 1 -5 -4
INF 0 2 3
INF INF 0 1
INF INF 7 0
Input
4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 -7
Output
NEGATIVE CYCLE
Submitted Solution:
```
nv, ne = map(int, input().split())
costs = [[None] * nv for _ in range(nv)]
for i in range(nv):
costs[i][i] = 0
while ne:
s, t, d = map(int, input().split())
costs[s][t] = d
ne -= 1
def loop():
for k in range(nv):
for i in range(nv):
for j in range(nv):
if costs[i][k] is None or costs[k][j] is None:
continue
tmp_cost = costs[i][k] + costs[k][j]
if i == j and tmp_cost < 0:
print('NEGATIVE_CYCLE')
return False
if costs[i][j] is None or costs[i][j] > tmp_cost:
costs[i][j] = tmp_cost
return True
if loop():
for vc in costs:
print(*('INF' if c is None else c for c in vc))
``` | instruction | 0 | 34,240 | 13 | 68,480 |
No | output | 1 | 34,240 | 13 | 68,481 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected unweighted tree consisting of n vertices.
An undirected tree is a connected undirected graph with n - 1 edges.
Your task is to choose two pairs of vertices of this tree (all the chosen vertices should be distinct) (x_1, y_1) and (x_2, y_2) in such a way that neither x_1 nor y_1 belong to the simple path from x_2 to y_2 and vice versa (neither x_2 nor y_2 should not belong to the simple path from x_1 to y_1).
It is guaranteed that it is possible to choose such pairs for the given tree.
Among all possible ways to choose such pairs you have to choose one with the maximum number of common vertices between paths from x_1 to y_1 and from x_2 to y_2. And among all such pairs you have to choose one with the maximum total length of these two paths.
It is guaranteed that the answer with at least two common vertices exists for the given tree.
The length of the path is the number of edges in it.
The simple path is the path that visits each vertex at most once.
Input
The first line contains an integer n — the number of vertices in the tree (6 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes the edges of the tree.
Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
It is guaranteed that the answer with at least two common vertices exists for the given tree.
Output
Print any two pairs of vertices satisfying the conditions described in the problem statement.
It is guaranteed that it is possible to choose such pairs for the given tree.
Examples
Input
7
1 4
1 5
1 6
2 3
2 4
4 7
Output
3 6
7 5
Input
9
9 3
3 5
1 2
4 3
4 7
1 7
4 6
3 8
Output
2 9
6 8
Input
10
6 8
10 3
3 7
5 8
1 7
7 2
2 9
2 8
1 4
Output
10 6
4 5
Input
11
1 2
2 3
3 4
1 5
1 6
6 7
5 8
5 9
4 10
4 11
Output
9 11
8 10
Note
The picture corresponding to the first example: <image>
The intersection of two paths is 2 (vertices 1 and 4) and the total length is 4 + 3 = 7.
The picture corresponding to the second example: <image>
The intersection of two paths is 2 (vertices 3 and 4) and the total length is 5 + 3 = 8.
The picture corresponding to the third example: <image>
The intersection of two paths is 3 (vertices 2, 7 and 8) and the total length is 5 + 5 = 10.
The picture corresponding to the fourth example: <image>
The intersection of two paths is 5 (vertices 1, 2, 3, 4 and 5) and the total length is 6 + 6 = 12. | instruction | 0 | 34,262 | 13 | 68,524 |
Tags: dfs and similar, dp, greedy, trees
Correct Solution:
```
n=int(input())
degs=[0]*n
neighbors=[0]*n
children=[0]*n
useless=[0]*n
for i in range(n):
neighbors[i]=[]
children[i]=[]
for i in range(n-1):
a,b=map(int,input().split())
degs[a-1]+=1
degs[b-1]+=1
neighbors[a-1].append(b-1)
neighbors[b-1].append(a-1)
for guy in range(n):
if degs[guy]==1:
useless[guy]+=1
newguy=neighbors[guy][0]
oldguy=guy
depth=0
while degs[newguy]==2:
depth+=1
useless[newguy]+=1
if neighbors[newguy][0]==oldguy:
oldguy=newguy
newguy=neighbors[newguy][1]
else:
oldguy=newguy
newguy=neighbors[newguy][0]
children[newguy].append((depth,guy))
for guy in range(n):
children[guy].sort(reverse=True)
newgraph={}
for i in range(n):
if useless[i]==0:
newgraph[i]=[]
for guy in newgraph:
for guy1 in neighbors[guy]:
if guy1 in newgraph:
newgraph[guy].append(guy1)
dfs1={}
currlayer=[(list(newgraph)[0],None)]
currlevel=0
while len(currlayer)>0:
for guy in currlayer:
dfs1[guy[0]]=currlevel
newlayer=[]
for guy in currlayer:
for vert in newgraph[guy[0]]:
if vert!=guy[1]:
newlayer.append((vert,guy[0]))
currlayer=newlayer
currlevel+=1
maxi=0
for guy in dfs1:
maxi=max(maxi,dfs1[guy])
bestdist=0
bestvert=None
for guy in dfs1:
if dfs1[guy]==maxi:
score=children[guy][0][0]+children[guy][1][0]
if score>=bestdist:
bestdist=score
bestvert=guy
dfs2={}
currlayer=[(bestvert,None)]
currlevel=0
while len(currlayer)>0:
for guy in currlayer:
dfs2[guy[0]]=currlevel
newlayer=[]
for guy in currlayer:
for vert in newgraph[guy[0]]:
if vert!=guy[1]:
newlayer.append((vert,guy[0]))
currlayer=newlayer
currlevel+=1
maxi=0
for guy in dfs2:
maxi=max(maxi,dfs2[guy])
bestdist=0
bestvert1=None
for guy in dfs2:
if dfs2[guy]==maxi:
score=children[guy][0][0]+children[guy][1][0]
if score>=bestdist:
bestdist=score
bestvert1=guy
print(children[bestvert][0][1]+1,children[bestvert1][0][1]+1)
print(children[bestvert][1][1]+1,children[bestvert1][1][1]+1)
``` | output | 1 | 34,262 | 13 | 68,525 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected unweighted tree consisting of n vertices.
An undirected tree is a connected undirected graph with n - 1 edges.
Your task is to choose two pairs of vertices of this tree (all the chosen vertices should be distinct) (x_1, y_1) and (x_2, y_2) in such a way that neither x_1 nor y_1 belong to the simple path from x_2 to y_2 and vice versa (neither x_2 nor y_2 should not belong to the simple path from x_1 to y_1).
It is guaranteed that it is possible to choose such pairs for the given tree.
Among all possible ways to choose such pairs you have to choose one with the maximum number of common vertices between paths from x_1 to y_1 and from x_2 to y_2. And among all such pairs you have to choose one with the maximum total length of these two paths.
It is guaranteed that the answer with at least two common vertices exists for the given tree.
The length of the path is the number of edges in it.
The simple path is the path that visits each vertex at most once.
Input
The first line contains an integer n — the number of vertices in the tree (6 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes the edges of the tree.
Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
It is guaranteed that the answer with at least two common vertices exists for the given tree.
Output
Print any two pairs of vertices satisfying the conditions described in the problem statement.
It is guaranteed that it is possible to choose such pairs for the given tree.
Examples
Input
7
1 4
1 5
1 6
2 3
2 4
4 7
Output
3 6
7 5
Input
9
9 3
3 5
1 2
4 3
4 7
1 7
4 6
3 8
Output
2 9
6 8
Input
10
6 8
10 3
3 7
5 8
1 7
7 2
2 9
2 8
1 4
Output
10 6
4 5
Input
11
1 2
2 3
3 4
1 5
1 6
6 7
5 8
5 9
4 10
4 11
Output
9 11
8 10
Note
The picture corresponding to the first example: <image>
The intersection of two paths is 2 (vertices 1 and 4) and the total length is 4 + 3 = 7.
The picture corresponding to the second example: <image>
The intersection of two paths is 2 (vertices 3 and 4) and the total length is 5 + 3 = 8.
The picture corresponding to the third example: <image>
The intersection of two paths is 3 (vertices 2, 7 and 8) and the total length is 5 + 5 = 10.
The picture corresponding to the fourth example: <image>
The intersection of two paths is 5 (vertices 1, 2, 3, 4 and 5) and the total length is 6 + 6 = 12. | instruction | 0 | 34,263 | 13 | 68,526 |
Tags: dfs and similar, dp, greedy, trees
Correct Solution:
```
import sys
n = int(sys.stdin.readline())
edges = [[] for _ in range(n)]
for _ in range(n - 1):
i, j = tuple(int(k) for k in sys.stdin.readline().split())
i -= 1
j -= 1
edges[i].append(j)
edges[j].append(i)
# Prunes the graph starting from the vertices with
# only 1 edge until we reach a vertex with 3+ edges.
# Stores the distance from each non-pruned vertex
# to each of the leaves it reaches.
def prune():
pruned = [False for _ in range(n)]
leaves = [[] for _ in range(n)]
todo = []
for i in range(n):
if len(edges[i]) == 1:
todo.append((0, i, i))
while len(todo) > 0:
d, i, j = todo.pop()
pruned[j] = True
for k in edges[j]:
if not pruned[k]:
if len(edges[k]) < 3:
todo.append((d + 1, i, k))
else:
leaves[k].append((d + 1, i))
return pruned, leaves
pruned, leaves = prune()
# Returns the furthest non-pruned vertices
# from another non-pruned vertex.
def furthest(i):
assert not pruned[i]
visited = list(pruned)
top_distance = 0
top_vertices = []
todo = [(0, i)]
while len(todo) > 0:
d, i = todo.pop()
visited[i] = True
if d > top_distance:
top_distance = d
top_vertices = []
if d == top_distance:
top_vertices.append(i)
for j in edges[i]:
if not visited[j]:
todo.append((d + 1, j))
return top_vertices
# Single center topology.
# Only 1 vertex with 3+ edges.
def solve_single_center(i):
l = list(reversed(sorted(leaves[i])))[:4]
return list(l[j][1] for j in range(4))
# Scores non-pruned vertices according to the sum
# of the distances to their two furthest leaves.
def vertices_score(v):
scores = []
for i in v:
assert not pruned[i]
l = list(reversed(sorted(leaves[i])))[:2]
score = (l[0][0] + l[1][0]), l[0][1], l[1][1]
scores.append(score)
return list(reversed(sorted(scores)))
# Single cluster topology.
# 1 cluster of vertices, all equally far away from each other.
def solve_single_cluster(v):
s = vertices_score(v)[:2]
return s[0][1], s[1][1], s[0][2], s[1][2]
# Double cluster topology.
# 2 clusters of vertices, pairwise equally far away from each other.
def solve_double_cluster(v1, v2):
s1 = vertices_score(v1)[:1]
s2 = vertices_score(v2)[:1]
return s1[0][1], s2[0][1], s1[0][2], s2[0][2]
def solve():
def start_vertex():
for i in range(n):
if not pruned[i]:
return furthest(i)[0]
i = start_vertex()
v1 = furthest(i)
if len(v1) == 1 and v1[0] == i:
return solve_single_center(v1[0])
else:
v2 = furthest(v1[0])
v = list(set(v1) | set(v2))
if len(v) < len(v1) + len(v2):
return solve_single_cluster(v)
else:
return solve_double_cluster(v1, v2)
a, b, c, d = solve()
print(a + 1, b + 1)
print(c + 1, d + 1)
``` | output | 1 | 34,263 | 13 | 68,527 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected unweighted tree consisting of n vertices.
An undirected tree is a connected undirected graph with n - 1 edges.
Your task is to choose two pairs of vertices of this tree (all the chosen vertices should be distinct) (x_1, y_1) and (x_2, y_2) in such a way that neither x_1 nor y_1 belong to the simple path from x_2 to y_2 and vice versa (neither x_2 nor y_2 should not belong to the simple path from x_1 to y_1).
It is guaranteed that it is possible to choose such pairs for the given tree.
Among all possible ways to choose such pairs you have to choose one with the maximum number of common vertices between paths from x_1 to y_1 and from x_2 to y_2. And among all such pairs you have to choose one with the maximum total length of these two paths.
It is guaranteed that the answer with at least two common vertices exists for the given tree.
The length of the path is the number of edges in it.
The simple path is the path that visits each vertex at most once.
Input
The first line contains an integer n — the number of vertices in the tree (6 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes the edges of the tree.
Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
It is guaranteed that the answer with at least two common vertices exists for the given tree.
Output
Print any two pairs of vertices satisfying the conditions described in the problem statement.
It is guaranteed that it is possible to choose such pairs for the given tree.
Examples
Input
7
1 4
1 5
1 6
2 3
2 4
4 7
Output
3 6
7 5
Input
9
9 3
3 5
1 2
4 3
4 7
1 7
4 6
3 8
Output
2 9
6 8
Input
10
6 8
10 3
3 7
5 8
1 7
7 2
2 9
2 8
1 4
Output
10 6
4 5
Input
11
1 2
2 3
3 4
1 5
1 6
6 7
5 8
5 9
4 10
4 11
Output
9 11
8 10
Note
The picture corresponding to the first example: <image>
The intersection of two paths is 2 (vertices 1 and 4) and the total length is 4 + 3 = 7.
The picture corresponding to the second example: <image>
The intersection of two paths is 2 (vertices 3 and 4) and the total length is 5 + 3 = 8.
The picture corresponding to the third example: <image>
The intersection of two paths is 3 (vertices 2, 7 and 8) and the total length is 5 + 5 = 10.
The picture corresponding to the fourth example: <image>
The intersection of two paths is 5 (vertices 1, 2, 3, 4 and 5) and the total length is 6 + 6 = 12. | instruction | 0 | 34,264 | 13 | 68,528 |
Tags: dfs and similar, dp, greedy, trees
Correct Solution:
```
import sys
n = int(sys.stdin.readline())
edges = [[] for _ in range(n)]
for _ in range(n - 1):
i, j = tuple(int(k) for k in sys.stdin.readline().split())
i -= 1
j -= 1
edges[i].append(j)
edges[j].append(i)
# Prunes the graph starting from the vertices with
# only 1 edge until we reach a vertex with 3+ edges.
# Stores the distance from each non-pruned vertex
# to each of the leaves it reaches.
def prune():
pruned = [False for _ in range(n)]
leaves = [[] for _ in range(n)]
todo = []
for i in range(n):
if len(edges[i]) == 1:
todo.append((0, i, i))
while len(todo) > 0:
d, i, j = todo.pop()
pruned[j] = True
for k in edges[j]:
if not pruned[k]:
if len(edges[k]) < 3:
todo.append((d + 1, i, k))
else:
leaves[k].append((d + 1, i))
return pruned, leaves
pruned, leaves = prune()
# Returns the furthest non-pruned vertices
# from another non-pruned vertex.
def furthest(i):
assert not pruned[i]
visited = list(pruned)
top_distance = 0
top_vertices = [i]
todo = [(0, i)]
while len(todo) > 0:
d, i = todo.pop()
visited[i] = True
if d > top_distance:
top_distance = d
top_vertices = []
if d == top_distance:
top_vertices.append(i)
for j in edges[i]:
if not visited[j]:
todo.append((d + 1, j))
return top_distance, top_vertices
# Single center topology.
# Only 1 vertex with 3+ edges.
def solve_single_center(i):
l = list(reversed(sorted(leaves[i])))[:4]
return list(l[j][1] for j in range(4))
# Scores non-pruned vertices according to the sum
# of the distances to their two furthest leaves.
def vertices_score(v):
scores = []
for i in v:
assert not pruned[i]
l = list(reversed(sorted(leaves[i])))[:2]
score = (l[0][0] + l[1][0]), l[0][1], l[1][1]
scores.append(score)
return list(reversed(sorted(scores)))
# Single cluster topology.
# 1 cluster of vertices, all equally far away from each other.
def solve_single_cluster(v):
scores = vertices_score(v)[:2]
return scores[0][1], scores[1][1], scores[0][2], scores[1][2]
# Double cluster topology.
# 2 clusters of vertices, pairwise equally far away from each other.
def solve_double_cluster(v1, v2):
scores1 = vertices_score(v1)[:1]
scores2 = vertices_score(v2)[:1]
return scores1[0][1], scores2[0][1], scores1[0][2], scores2[0][2]
def solve():
def start_vertex():
for i in range(n):
if not pruned[i]:
return i
i = start_vertex()
distance, v1 = furthest(i)
if distance == 0:
return solve_single_center(v1[0])
else:
distance, v1 = furthest(v1[0])
distance, v2 = furthest(v1[0])
v = list(set(v1) | set(v2))
if len(v) < len(v1) + len(v2):
return solve_single_cluster(v)
else:
return solve_double_cluster(v1, v2)
a, b, c, d = solve()
print(a + 1, b + 1)
print(c + 1, d + 1)
``` | output | 1 | 34,264 | 13 | 68,529 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected unweighted tree consisting of n vertices.
An undirected tree is a connected undirected graph with n - 1 edges.
Your task is to choose two pairs of vertices of this tree (all the chosen vertices should be distinct) (x_1, y_1) and (x_2, y_2) in such a way that neither x_1 nor y_1 belong to the simple path from x_2 to y_2 and vice versa (neither x_2 nor y_2 should not belong to the simple path from x_1 to y_1).
It is guaranteed that it is possible to choose such pairs for the given tree.
Among all possible ways to choose such pairs you have to choose one with the maximum number of common vertices between paths from x_1 to y_1 and from x_2 to y_2. And among all such pairs you have to choose one with the maximum total length of these two paths.
It is guaranteed that the answer with at least two common vertices exists for the given tree.
The length of the path is the number of edges in it.
The simple path is the path that visits each vertex at most once.
Input
The first line contains an integer n — the number of vertices in the tree (6 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes the edges of the tree.
Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
It is guaranteed that the answer with at least two common vertices exists for the given tree.
Output
Print any two pairs of vertices satisfying the conditions described in the problem statement.
It is guaranteed that it is possible to choose such pairs for the given tree.
Examples
Input
7
1 4
1 5
1 6
2 3
2 4
4 7
Output
3 6
7 5
Input
9
9 3
3 5
1 2
4 3
4 7
1 7
4 6
3 8
Output
2 9
6 8
Input
10
6 8
10 3
3 7
5 8
1 7
7 2
2 9
2 8
1 4
Output
10 6
4 5
Input
11
1 2
2 3
3 4
1 5
1 6
6 7
5 8
5 9
4 10
4 11
Output
9 11
8 10
Note
The picture corresponding to the first example: <image>
The intersection of two paths is 2 (vertices 1 and 4) and the total length is 4 + 3 = 7.
The picture corresponding to the second example: <image>
The intersection of two paths is 2 (vertices 3 and 4) and the total length is 5 + 3 = 8.
The picture corresponding to the third example: <image>
The intersection of two paths is 3 (vertices 2, 7 and 8) and the total length is 5 + 5 = 10.
The picture corresponding to the fourth example: <image>
The intersection of two paths is 5 (vertices 1, 2, 3, 4 and 5) and the total length is 6 + 6 = 12.
Submitted Solution:
```
import sys
sys.setrecursionlimit(500000)
def minmax(x, y, key = lambda x: x):
if key(x) < key(y):
return x, y
else:
return y, x
n = int(input())
graph = [[] for _ in range(n)]
for _ in range(n-1):
v, u = map(int, input().split())
v -= 1
u -= 1
graph[v].append(u)
graph[u].append(v)
chord_weight = [0] * n
weight = [0] * n
def compute_chord_weight(v, src):
for u in graph[v]:
if u != src:
compute_chord_weight(u, v)
chord_weight[v] = max(chord_weight[u] for u in graph[v])
weight[v] = max((weight[u] for u in graph[v] if u != src), default=0) + 1
if chord_weight[v] > 0 or len(graph[v]) > 2:
chord_weight[v] += 1
for v in range(n):
if len(graph[v]) > 2:
compute_chord_weight(v, v)
root = v
break
tail = 0
branching = [[] for _ in range(n)]
def choose_chord(v, src, src_weight):
global tail
if len(graph[v]) < 3:
for u in graph[v]:
if u != src:
branching[v] = [src, u]
choose_chord(u, v, src_weight + 1)
return
children = (u for u in graph[v] if u != src)
u1 = next(children)
u2 = next(children)
u2, u1 = minmax(u1, u2, key = lambda u: chord_weight[u])
for u in children:
if chord_weight[u] > chord_weight[u1]:
u2 = u1
u1 = u
elif chord_weight[u] > chord_weight[u2]:
u2 = u
if chord_weight[u1] == 0:
tail = v
branching[v] = [src]
return
if src_weight >= chord_weight[u2]:
branching[v] = [src, u1]
choose_chord(u1, v, src_weight + 1)
else:
branching[v] = [u1, u2]
choose_chord(u1, v, chord_weight[u2] + 1)
choose_chord(u2, v, chord_weight[u1] + 1)
choose_chord(root, root, 0)
branching[root] = [v for v in branching[root] if v != root]
def get_tail(graph, v, src):
if len(graph[v]) < 2:
return v
u = next(u for u in graph[v] if u != src)
return get_tail(graph, u, v)
def choose_tails(v, src):
children = (u for u in graph[v] if u != src)
u1 = next(children)
u2 = next(children)
u2, u1 = minmax(u1, u2, key = lambda u: weight[u])
for u in children:
if weight[u] > weight[u1]:
u2 = u1
u1 = u
elif weight[u] > weight[u2]:
u2 = u
return get_tail(graph, u1, v), get_tail(graph, u2, v)
x1, x2 = choose_tails(tail, branching[tail][0])
head = get_tail(branching, branching[tail][0], tail)
y1, y2 = choose_tails(head, branching[head][0])
print(x1+1, y1+1)
print(x2+1, y2+1)
``` | instruction | 0 | 34,265 | 13 | 68,530 |
No | output | 1 | 34,265 | 13 | 68,531 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected unweighted tree consisting of n vertices.
An undirected tree is a connected undirected graph with n - 1 edges.
Your task is to choose two pairs of vertices of this tree (all the chosen vertices should be distinct) (x_1, y_1) and (x_2, y_2) in such a way that neither x_1 nor y_1 belong to the simple path from x_2 to y_2 and vice versa (neither x_2 nor y_2 should not belong to the simple path from x_1 to y_1).
It is guaranteed that it is possible to choose such pairs for the given tree.
Among all possible ways to choose such pairs you have to choose one with the maximum number of common vertices between paths from x_1 to y_1 and from x_2 to y_2. And among all such pairs you have to choose one with the maximum total length of these two paths.
It is guaranteed that the answer with at least two common vertices exists for the given tree.
The length of the path is the number of edges in it.
The simple path is the path that visits each vertex at most once.
Input
The first line contains an integer n — the number of vertices in the tree (6 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes the edges of the tree.
Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
It is guaranteed that the answer with at least two common vertices exists for the given tree.
Output
Print any two pairs of vertices satisfying the conditions described in the problem statement.
It is guaranteed that it is possible to choose such pairs for the given tree.
Examples
Input
7
1 4
1 5
1 6
2 3
2 4
4 7
Output
3 6
7 5
Input
9
9 3
3 5
1 2
4 3
4 7
1 7
4 6
3 8
Output
2 9
6 8
Input
10
6 8
10 3
3 7
5 8
1 7
7 2
2 9
2 8
1 4
Output
10 6
4 5
Input
11
1 2
2 3
3 4
1 5
1 6
6 7
5 8
5 9
4 10
4 11
Output
9 11
8 10
Note
The picture corresponding to the first example: <image>
The intersection of two paths is 2 (vertices 1 and 4) and the total length is 4 + 3 = 7.
The picture corresponding to the second example: <image>
The intersection of two paths is 2 (vertices 3 and 4) and the total length is 5 + 3 = 8.
The picture corresponding to the third example: <image>
The intersection of two paths is 3 (vertices 2, 7 and 8) and the total length is 5 + 5 = 10.
The picture corresponding to the fourth example: <image>
The intersection of two paths is 5 (vertices 1, 2, 3, 4 and 5) and the total length is 6 + 6 = 12.
Submitted Solution:
```
import sys
n = int(sys.stdin.readline())
t = [[] for _ in range(n)]
for _ in range(n - 1):
i, j = tuple(int(i) for i in sys.stdin.readline().split())
i -= 1
j -= 1
t[i].append(j)
t[j].append(i)
def any_split():
for i in range(n):
if len(t[i]) >= 3:
return i
def all_forks():
forks = [None for _ in range(n)]
i = any_split()
todo = [(False, i), (True, i)]
visited = [False for _ in range(n)]
while len(todo) > 0:
pre, i = todo.pop()
visited[i] = True
if pre:
for j in t[i]:
if not visited[j]:
todo.append((False, j))
todo.append((True, j))
else:
if len(t[i]) == 1:
forks[i] = False
elif len(t[i]) == 2:
for j in t[i]:
if forks[j] is not None:
forks[i] = forks[j]
break
else:
forks[i] = True
return forks
forks = all_forks()
def any_fork():
for i in range(n):
if forks[i]:
return i
def furthest_fork(i):
top = (0, i)
todo = [top]
visited = list(not x for x in forks)
while len(todo) > 0:
d, i = todo.pop()
visited[i] = True
if d > top[0]:
top = d, i
for j in t[i]:
if not visited[j]:
todo.append((d + 1, j))
return top[1]
x = furthest_fork(any_fork())
y = furthest_fork(x)
def dual_search(i):
visited = list(x for x in forks)
def sub_search(j):
top = (0, j)
todo = [top]
while len(todo) > 0:
d, k = todo.pop()
visited[k] = True
if d > top[0]:
top = d, k
for l in t[k]:
if not visited[l]:
todo.append((d + 1, l))
return top
top = []
for j in t[i]:
if not visited[j]:
top.append(sub_search(j))
top = list(reversed(sorted(top)))
return top[0][1], top[1][1]
a, b = dual_search(x)
c, d = dual_search(y)
print(a + 1, c + 1)
print(b + 1, d + 1)
``` | instruction | 0 | 34,266 | 13 | 68,532 |
No | output | 1 | 34,266 | 13 | 68,533 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected unweighted tree consisting of n vertices.
An undirected tree is a connected undirected graph with n - 1 edges.
Your task is to choose two pairs of vertices of this tree (all the chosen vertices should be distinct) (x_1, y_1) and (x_2, y_2) in such a way that neither x_1 nor y_1 belong to the simple path from x_2 to y_2 and vice versa (neither x_2 nor y_2 should not belong to the simple path from x_1 to y_1).
It is guaranteed that it is possible to choose such pairs for the given tree.
Among all possible ways to choose such pairs you have to choose one with the maximum number of common vertices between paths from x_1 to y_1 and from x_2 to y_2. And among all such pairs you have to choose one with the maximum total length of these two paths.
It is guaranteed that the answer with at least two common vertices exists for the given tree.
The length of the path is the number of edges in it.
The simple path is the path that visits each vertex at most once.
Input
The first line contains an integer n — the number of vertices in the tree (6 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes the edges of the tree.
Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
It is guaranteed that the answer with at least two common vertices exists for the given tree.
Output
Print any two pairs of vertices satisfying the conditions described in the problem statement.
It is guaranteed that it is possible to choose such pairs for the given tree.
Examples
Input
7
1 4
1 5
1 6
2 3
2 4
4 7
Output
3 6
7 5
Input
9
9 3
3 5
1 2
4 3
4 7
1 7
4 6
3 8
Output
2 9
6 8
Input
10
6 8
10 3
3 7
5 8
1 7
7 2
2 9
2 8
1 4
Output
10 6
4 5
Input
11
1 2
2 3
3 4
1 5
1 6
6 7
5 8
5 9
4 10
4 11
Output
9 11
8 10
Note
The picture corresponding to the first example: <image>
The intersection of two paths is 2 (vertices 1 and 4) and the total length is 4 + 3 = 7.
The picture corresponding to the second example: <image>
The intersection of two paths is 2 (vertices 3 and 4) and the total length is 5 + 3 = 8.
The picture corresponding to the third example: <image>
The intersection of two paths is 3 (vertices 2, 7 and 8) and the total length is 5 + 5 = 10.
The picture corresponding to the fourth example: <image>
The intersection of two paths is 5 (vertices 1, 2, 3, 4 and 5) and the total length is 6 + 6 = 12.
Submitted Solution:
```
import sys
n = int(sys.stdin.readline())
edges = [[] for _ in range(n)]
for _ in range(n - 1):
i, j = tuple(int(k) for k in sys.stdin.readline().split())
i -= 1
j -= 1
edges[i].append(j)
edges[j].append(i)
# Prunes the graph starting from the vertices with
# only 1 edge until we reach a vertex with 3+ edges.
# Stores the distance from each non-pruned vertex
# to each of the leaves it reaches.
def prune():
pruned = [False for _ in range(n)]
leaves = [[] for _ in range(n)]
todo = []
for i in range(n):
if len(edges[i]) == 1:
todo.append((0, i, i))
while len(todo) > 0:
d, i, j = todo.pop()
pruned[j] = True
for k in edges[j]:
if not pruned[k]:
if len(edges[k]) < 3:
todo.append((d + 1, i, k))
else:
leaves[k].append((d + 1, i))
return pruned, leaves
pruned, leaves = prune()
# Returns the furthest non-pruned vertices
# from another non-pruned vertex.
def furthest(i):
assert not pruned[i]
visited = list(pruned)
top_distance = 0
top_vertices = [i]
todo = [(0, i)]
while len(todo) > 0:
d, i = todo.pop()
visited[i] = True
if d > top_distance:
top_distance = d
top_vertices = []
if d == top_distance:
top_vertices.append(i)
for j in edges[i]:
if not visited[j]:
todo.append((d + 1, j))
return top_distance, top_vertices
# Single center topology.
# Only 1 vertex with 3+ edges.
def solve_single_center(i):
l = list(reversed(sorted(leaves[i])))[:4]
return list(l[j][1] for j in range(4))
# Scores non-pruned vertices according to the sum
# of the distances to their two furthest leaves.
def vertices_score(v):
scores = []
for i in v:
assert not pruned[i]
l = list(reversed(sorted(leaves[i])))[:2]
score = (l[0][0] + l[1][0]), l[0][1], l[1][1]
scores.append(score)
return list(reversed(sorted(scores)))
# Single cluster topology.
# 1 cluster of vertices, all equally far away from each other.
def solve_single_cluster(v):
scores = vertices_score(v)[:2]
return scores[0][1], scores[1][1], scores[0][2], scores[1][2]
# Double cluster topology.
# 2 clusters of vertices, pairwise equally far away from each other.
def solve_double_cluster(v1, v2):
scores1 = vertices_score(v1)[:1]
scores2 = vertices_score(v2)[:1]
return scores1[0][1], scores2[0][1], scores1[0][2], scores2[0][2]
def solve():
def start_vertex():
for i in range(n):
if not pruned[i]:
return i
i = start_vertex()
distance, v1 = furthest(i)
if distance == 0:
return solve_single_center(v1[0])
else:
distance, v2 = furthest(v1[0])
v = list(set(v1) | set(v2))
if len(v) < len(v1) + len(v2):
return solve_single_cluster(v)
else:
return solve_double_cluster(v1, v2)
a, b, c, d = solve()
print(a + 1, b + 1)
print(c + 1, d + 1)
``` | instruction | 0 | 34,267 | 13 | 68,534 |
No | output | 1 | 34,267 | 13 | 68,535 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected unweighted tree consisting of n vertices.
An undirected tree is a connected undirected graph with n - 1 edges.
Your task is to choose two pairs of vertices of this tree (all the chosen vertices should be distinct) (x_1, y_1) and (x_2, y_2) in such a way that neither x_1 nor y_1 belong to the simple path from x_2 to y_2 and vice versa (neither x_2 nor y_2 should not belong to the simple path from x_1 to y_1).
It is guaranteed that it is possible to choose such pairs for the given tree.
Among all possible ways to choose such pairs you have to choose one with the maximum number of common vertices between paths from x_1 to y_1 and from x_2 to y_2. And among all such pairs you have to choose one with the maximum total length of these two paths.
It is guaranteed that the answer with at least two common vertices exists for the given tree.
The length of the path is the number of edges in it.
The simple path is the path that visits each vertex at most once.
Input
The first line contains an integer n — the number of vertices in the tree (6 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes the edges of the tree.
Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
It is guaranteed that the answer with at least two common vertices exists for the given tree.
Output
Print any two pairs of vertices satisfying the conditions described in the problem statement.
It is guaranteed that it is possible to choose such pairs for the given tree.
Examples
Input
7
1 4
1 5
1 6
2 3
2 4
4 7
Output
3 6
7 5
Input
9
9 3
3 5
1 2
4 3
4 7
1 7
4 6
3 8
Output
2 9
6 8
Input
10
6 8
10 3
3 7
5 8
1 7
7 2
2 9
2 8
1 4
Output
10 6
4 5
Input
11
1 2
2 3
3 4
1 5
1 6
6 7
5 8
5 9
4 10
4 11
Output
9 11
8 10
Note
The picture corresponding to the first example: <image>
The intersection of two paths is 2 (vertices 1 and 4) and the total length is 4 + 3 = 7.
The picture corresponding to the second example: <image>
The intersection of two paths is 2 (vertices 3 and 4) and the total length is 5 + 3 = 8.
The picture corresponding to the third example: <image>
The intersection of two paths is 3 (vertices 2, 7 and 8) and the total length is 5 + 5 = 10.
The picture corresponding to the fourth example: <image>
The intersection of two paths is 5 (vertices 1, 2, 3, 4 and 5) and the total length is 6 + 6 = 12.
Submitted Solution:
```
import sys
sys.setrecursionlimit(500000)
def minmax(x, y, key = lambda x: x):
if key(x) < key(y):
return x, y
else:
return y, x
n = int(input())
graph = [[] for _ in range(n)]
for _ in range(n-1):
v, u = map(int, input().split())
v -= 1
u -= 1
graph[v].append(u)
graph[u].append(v)
chord_weight = [0] * n
weight = [0] * n
def compute_chord_weight(v, src):
for u in graph[v]:
if u != src:
compute_chord_weight(u, v)
chord_weight[v] = max(chord_weight[u] for u in graph[v])
weight[v] = max((weight[u] for u in graph[v] if u != src), default=0) + 1
if chord_weight[v] > 0 or len(graph[v]) > 2:
chord_weight[v] += 1
for v in range(n):
if len(graph[v]) > 2:
compute_chord_weight(v, v)
root = v
break
tail = 0
branching = [[] for _ in range(n)]
def choose_chord(v, src, src_weight):
global tail
if len(graph[v]) < 3:
for u in graph[v]:
if u != src:
branching[v] = [src, u]
choose_chord(u, v, src_weight + 1)
return
children = (u for u in graph[v] if u != src)
u1 = next(children)
u2 = next(children)
u2, u1 = minmax(u1, u2, key = lambda u: chord_weight[u])
for u in children:
if chord_weight[u] > chord_weight[u1]:
u2 = u1
u1 = u
elif chord_weight[u] > chord_weight[u2]:
u2 = u
if chord_weight[u1] == 0:
tail = v
branching[v] = [src]
return
if src_weight >= chord_weight[u2]:
branching[v] = [src, u1]
choose_chord(u1, v, src_weight + 1)
else:
branching[v] = [u1, u2]
choose_chord(u1, v, chord_weight[u2] + 1)
choose_chord(u2, v, chord_weight[u1] + 1)
choose_chord(root, root, 0)
branching[root] = [v for v in branching[root] if v != root]
def get_tail(graph, v, src):
if len(graph[v]) < 2:
return v
u = next(u for u in graph[v] if u != src)
return get_tail(graph, u, v)
def choose_tails(v, src):
children = (u for u in graph[v] if u != src)
u1 = next(children)
u2 = next(children)
u2, u1 = minmax(u1, u2, key = lambda u: weight[u])
for u in children:
if weight[u] > weight[u1]:
u2 = u1
u1 = u
elif weight[u] > chord_weight[u2]:
u2 = u
return get_tail(graph, u1, v), get_tail(graph, u2, v)
x1, x2 = choose_tails(tail, branching[tail][0])
head = get_tail(branching, branching[tail][0], tail)
y1, y2 = choose_tails(head, branching[head][0])
print(x1+1, y1+1)
print(x2+1, y2+1)
``` | instruction | 0 | 34,268 | 13 | 68,536 |
No | output | 1 | 34,268 | 13 | 68,537 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected graph consisting of n vertices. A number is written on each vertex; the number on vertex i is a_i. Initially there are no edges in the graph.
You may add some edges to this graph, but you have to pay for them. The cost of adding an edge between vertices x and y is a_x + a_y coins. There are also m special offers, each of them is denoted by three numbers x, y and w, and means that you can add an edge connecting vertices x and y and pay w coins for it. You don't have to use special offers: if there is a pair of vertices x and y that has a special offer associated with it, you still may connect these two vertices paying a_x + a_y coins for it.
What is the minimum number of coins you have to spend to make the graph connected? Recall that a graph is connected if it's possible to get from any vertex to any other vertex using only the edges belonging to this graph.
Input
The first line contains two integers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the graph and the number of special offers, respectively.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{12}) — the numbers written on the vertices.
Then m lines follow, each containing three integers x, y and w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10^{12}, x ≠ y) denoting a special offer: you may add an edge connecting vertex x and vertex y, and this edge will cost w coins.
Output
Print one integer — the minimum number of coins you have to pay to make the graph connected.
Examples
Input
3 2
1 3 3
2 3 5
2 1 1
Output
5
Input
4 0
1 3 3 7
Output
16
Input
5 4
1 2 3 4 5
1 2 8
1 3 10
1 4 7
1 5 15
Output
18
Note
In the first example it is possible to connect 1 to 2 using special offer 2, and then 1 to 3 without using any offers.
In next two examples the optimal answer may be achieved without using special offers. | instruction | 0 | 34,269 | 13 | 68,538 |
Tags: dsu, graphs, greedy
Correct Solution:
```
def Find(x, par):
if par[x] < 0:
return x
else:
par[x] = Find(par[x], par)
return par[x]
def Unite(x, y, par, rank):
x = Find(x, par)
y = Find(y, par)
if x != y:
if rank[x] < rank[y]:
par[y] += par[x]
par[x] = y
else:
par[x] += par[y]
par[y] = x
if rank[x] == rank[y]:
rank[x] += 1
def Same(x, y, par):
return Find(x, par) == Find(y, par)
def Size(x, par):
return -par[Find(x, par)]
import sys
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n, m = map(int, input().split())
A = list(map(int, input().split()))
w0 = min(A)
v0 = A.index(w0)
edge =[(v0+1, v1+1, w0+w1) for v1, w1 in enumerate(A) if v1 != v0]
temp = [tuple(map(int, input().split())) for i in range(m)]
edge += temp
edge.sort(key=lambda x: x[2])
par = [-1]*(n+1)
rank = [0]*(n+1)
ans = 0
for u, v, w in edge:
if not Same(u, v, par):
ans += w
Unite(u, v, par, rank)
print(ans)
``` | output | 1 | 34,269 | 13 | 68,539 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected graph consisting of n vertices. A number is written on each vertex; the number on vertex i is a_i. Initially there are no edges in the graph.
You may add some edges to this graph, but you have to pay for them. The cost of adding an edge between vertices x and y is a_x + a_y coins. There are also m special offers, each of them is denoted by three numbers x, y and w, and means that you can add an edge connecting vertices x and y and pay w coins for it. You don't have to use special offers: if there is a pair of vertices x and y that has a special offer associated with it, you still may connect these two vertices paying a_x + a_y coins for it.
What is the minimum number of coins you have to spend to make the graph connected? Recall that a graph is connected if it's possible to get from any vertex to any other vertex using only the edges belonging to this graph.
Input
The first line contains two integers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the graph and the number of special offers, respectively.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{12}) — the numbers written on the vertices.
Then m lines follow, each containing three integers x, y and w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10^{12}, x ≠ y) denoting a special offer: you may add an edge connecting vertex x and vertex y, and this edge will cost w coins.
Output
Print one integer — the minimum number of coins you have to pay to make the graph connected.
Examples
Input
3 2
1 3 3
2 3 5
2 1 1
Output
5
Input
4 0
1 3 3 7
Output
16
Input
5 4
1 2 3 4 5
1 2 8
1 3 10
1 4 7
1 5 15
Output
18
Note
In the first example it is possible to connect 1 to 2 using special offer 2, and then 1 to 3 without using any offers.
In next two examples the optimal answer may be achieved without using special offers. | instruction | 0 | 34,270 | 13 | 68,540 |
Tags: dsu, graphs, greedy
Correct Solution:
```
import sys
from io import StringIO
n, spec = map(int, input().split())
p = list(range(n + 1))
def isconnected(x, y):
return find(x) == find(y)
def find(x):
global p
if p[x] != x:
p[x] = find(p[x])
return p[x]
def connect(x, y):
global p
p[find(x)] = find(y)
e = []
sys.stdin = StringIO(sys.stdin.read())
input = lambda: sys.stdin.readline().strip()
a = list(zip(map(int, input().split()), range(1, n + 1)))
m = min(a)
for i in a:
if i[1] != m[1]:
e.append((i[1], m[1], i[0] + m[0]))
for i in range(spec):
e.append(tuple(map(int, input().split())))
e.sort(key=lambda x: x[2])
count = 0
ans = 0
for x in e:
if not isconnected(x[0], x[1]):
count += 1
connect(x[0], x[1])
# print(x, u.p)
ans += x[2]
if count == n - 1:
break
print(ans)
``` | output | 1 | 34,270 | 13 | 68,541 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected graph consisting of n vertices. A number is written on each vertex; the number on vertex i is a_i. Initially there are no edges in the graph.
You may add some edges to this graph, but you have to pay for them. The cost of adding an edge between vertices x and y is a_x + a_y coins. There are also m special offers, each of them is denoted by three numbers x, y and w, and means that you can add an edge connecting vertices x and y and pay w coins for it. You don't have to use special offers: if there is a pair of vertices x and y that has a special offer associated with it, you still may connect these two vertices paying a_x + a_y coins for it.
What is the minimum number of coins you have to spend to make the graph connected? Recall that a graph is connected if it's possible to get from any vertex to any other vertex using only the edges belonging to this graph.
Input
The first line contains two integers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the graph and the number of special offers, respectively.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{12}) — the numbers written on the vertices.
Then m lines follow, each containing three integers x, y and w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10^{12}, x ≠ y) denoting a special offer: you may add an edge connecting vertex x and vertex y, and this edge will cost w coins.
Output
Print one integer — the minimum number of coins you have to pay to make the graph connected.
Examples
Input
3 2
1 3 3
2 3 5
2 1 1
Output
5
Input
4 0
1 3 3 7
Output
16
Input
5 4
1 2 3 4 5
1 2 8
1 3 10
1 4 7
1 5 15
Output
18
Note
In the first example it is possible to connect 1 to 2 using special offer 2, and then 1 to 3 without using any offers.
In next two examples the optimal answer may be achieved without using special offers. | instruction | 0 | 34,271 | 13 | 68,542 |
Tags: dsu, graphs, greedy
Correct Solution:
```
class UnionFind:
def __init__(self, n):
self.par = [-1]*n
self.rank = [0]*n
def Find(self, x):
if self.par[x] < 0:
return x
else:
self.par[x] = self.Find(self.par[x])
return self.par[x]
def Unite(self, x, y):
x = self.Find(x)
y = self.Find(y)
if x != y:
if self.rank[x] < self.rank[y]:
self.par[y] += self.par[x]
self.par[x] = y
else:
self.par[x] += self.par[y]
self.par[y] = x
if self.rank[x] == self.rank[y]:
self.rank[x] += 1
def Same(self, x, y):
return self.Find(x) == self.Find(y)
def Size(self, x):
return -self.par[self.Find(x)]
import sys
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n, m = map(int, input().split())
A = list(map(int, input().split()))
w0 = min(A)
v0 = A.index(w0)
edge =[(v0, v1, w0+w1) for v1, w1 in enumerate(A) if v1 != v0]
for i in range(m):
x, y, w = map(int, input().split())
x, y = x-1, y-1
edge.append((x, y, w))
edge.sort(key=lambda x: x[2])
uf = UnionFind(n)
ans = 0
for u, v, w in edge:
if not uf.Same(u, v):
ans += w
uf.Unite(u, v)
print(ans)
``` | output | 1 | 34,271 | 13 | 68,543 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected graph consisting of n vertices. A number is written on each vertex; the number on vertex i is a_i. Initially there are no edges in the graph.
You may add some edges to this graph, but you have to pay for them. The cost of adding an edge between vertices x and y is a_x + a_y coins. There are also m special offers, each of them is denoted by three numbers x, y and w, and means that you can add an edge connecting vertices x and y and pay w coins for it. You don't have to use special offers: if there is a pair of vertices x and y that has a special offer associated with it, you still may connect these two vertices paying a_x + a_y coins for it.
What is the minimum number of coins you have to spend to make the graph connected? Recall that a graph is connected if it's possible to get from any vertex to any other vertex using only the edges belonging to this graph.
Input
The first line contains two integers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the graph and the number of special offers, respectively.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{12}) — the numbers written on the vertices.
Then m lines follow, each containing three integers x, y and w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10^{12}, x ≠ y) denoting a special offer: you may add an edge connecting vertex x and vertex y, and this edge will cost w coins.
Output
Print one integer — the minimum number of coins you have to pay to make the graph connected.
Examples
Input
3 2
1 3 3
2 3 5
2 1 1
Output
5
Input
4 0
1 3 3 7
Output
16
Input
5 4
1 2 3 4 5
1 2 8
1 3 10
1 4 7
1 5 15
Output
18
Note
In the first example it is possible to connect 1 to 2 using special offer 2, and then 1 to 3 without using any offers.
In next two examples the optimal answer may be achieved without using special offers. | instruction | 0 | 34,272 | 13 | 68,544 |
Tags: dsu, graphs, greedy
Correct Solution:
```
n, m = map(int, input().split())
a = list(map(int, input().split()))
e = []
for _ in range(m) :
u, v, w = map(int, input().split())
e.append((u-1, v-1, w))
a = sorted(zip(a, range(n)), key = lambda x : x[0])
for i in range(1, n) :
e.append((a[0][1], a[i][1], a[0][0] + a[i][0]))
fa = list(range(n))
rk = [0] * n
def find(x) :
while fa[x] != x :
fa[x] = fa[fa[x]]
x = fa[x]
return x
def unite(u, v) :
u, v = map(find, (u, v))
if u == v : return False
if rk[u] < rk[v] : u, v = v, u
fa[v] = u
if rk[u] == rk[v] : rk[u] += 1
return True
e.sort(key = lambda x : x[2])
ans = 0
cnt = 1
for ee in e :
if cnt == n : break
if unite(ee[0], ee[1]) :
ans += ee[2]
cnt += 1
print(ans)
``` | output | 1 | 34,272 | 13 | 68,545 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected graph consisting of n vertices. A number is written on each vertex; the number on vertex i is a_i. Initially there are no edges in the graph.
You may add some edges to this graph, but you have to pay for them. The cost of adding an edge between vertices x and y is a_x + a_y coins. There are also m special offers, each of them is denoted by three numbers x, y and w, and means that you can add an edge connecting vertices x and y and pay w coins for it. You don't have to use special offers: if there is a pair of vertices x and y that has a special offer associated with it, you still may connect these two vertices paying a_x + a_y coins for it.
What is the minimum number of coins you have to spend to make the graph connected? Recall that a graph is connected if it's possible to get from any vertex to any other vertex using only the edges belonging to this graph.
Input
The first line contains two integers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the graph and the number of special offers, respectively.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{12}) — the numbers written on the vertices.
Then m lines follow, each containing three integers x, y and w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10^{12}, x ≠ y) denoting a special offer: you may add an edge connecting vertex x and vertex y, and this edge will cost w coins.
Output
Print one integer — the minimum number of coins you have to pay to make the graph connected.
Examples
Input
3 2
1 3 3
2 3 5
2 1 1
Output
5
Input
4 0
1 3 3 7
Output
16
Input
5 4
1 2 3 4 5
1 2 8
1 3 10
1 4 7
1 5 15
Output
18
Note
In the first example it is possible to connect 1 to 2 using special offer 2, and then 1 to 3 without using any offers.
In next two examples the optimal answer may be achieved without using special offers. | instruction | 0 | 34,273 | 13 | 68,546 |
Tags: dsu, graphs, greedy
Correct Solution:
```
def main():
n, m = map(int, input().split())
a = list(map(int, input().split()))
b = [tuple(map(int, input().split())) for i in range(m)]
rt = a.index(min(a))
e = [(a[i] + a[rt], rt, i) for i in range(n) if i != rt] + [(w, u - 1, v - 1) for u, v, w in b]
e.sort()
p = [i for i in range(n)]
r = [0] * n
def find(x):
if p[x] != x: p[x] = find(p[x])
return p[x]
def check_n_unite(x, y):
x, y = find(x), find(y)
if x == y: return 0
if r[x] < r[y]: x, y = y, x
p[y] = x
if r[x] == r[y]: r[x] += 1
return 1
ans = 0
for w, u, v in e:
if check_n_unite(u, v):
ans += w
print(ans)
main()
``` | output | 1 | 34,273 | 13 | 68,547 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected graph consisting of n vertices. A number is written on each vertex; the number on vertex i is a_i. Initially there are no edges in the graph.
You may add some edges to this graph, but you have to pay for them. The cost of adding an edge between vertices x and y is a_x + a_y coins. There are also m special offers, each of them is denoted by three numbers x, y and w, and means that you can add an edge connecting vertices x and y and pay w coins for it. You don't have to use special offers: if there is a pair of vertices x and y that has a special offer associated with it, you still may connect these two vertices paying a_x + a_y coins for it.
What is the minimum number of coins you have to spend to make the graph connected? Recall that a graph is connected if it's possible to get from any vertex to any other vertex using only the edges belonging to this graph.
Input
The first line contains two integers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the graph and the number of special offers, respectively.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{12}) — the numbers written on the vertices.
Then m lines follow, each containing three integers x, y and w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10^{12}, x ≠ y) denoting a special offer: you may add an edge connecting vertex x and vertex y, and this edge will cost w coins.
Output
Print one integer — the minimum number of coins you have to pay to make the graph connected.
Examples
Input
3 2
1 3 3
2 3 5
2 1 1
Output
5
Input
4 0
1 3 3 7
Output
16
Input
5 4
1 2 3 4 5
1 2 8
1 3 10
1 4 7
1 5 15
Output
18
Note
In the first example it is possible to connect 1 to 2 using special offer 2, and then 1 to 3 without using any offers.
In next two examples the optimal answer may be achieved without using special offers. | instruction | 0 | 34,274 | 13 | 68,548 |
Tags: dsu, graphs, greedy
Correct Solution:
```
def read_nums():
return [int(x) for x in input().split()]
class UnionFind:
def __init__(self, size):
self._parents = list(range(size))
# number of elements rooted at i
self._sizes = [1 for _ in range(size)]
def _root(self, a):
while a != self._parents[a]:
self._parents[a] = self._parents[self._parents[a]]
a = self._parents[a]
return a
def find(self, a, b):
return self._root(a) == self._root(b)
def union(self, a, b):
a, b = self._root(a), self._root(b)
if self._sizes[a] < self._sizes[b]:
self._parents[a] = b
self._sizes[b] += self._sizes[a]
else:
self._parents[b] = a
self._sizes[a] += self._sizes[b]
def count_result(num_vertex, edges):
uf = UnionFind(num_vertex)
res = 0
for start, end, cost in edges:
if uf.find(start, end):
continue
else:
uf.union(start, end)
res += cost
return res
def main():
n, m = read_nums()
vertex_nums = read_nums()
edges = []
for i in range(m):
nums = read_nums()
nums[0] -= 1
nums[1] -= 1
edges.append(tuple(nums))
min_index = min([x for x in zip(vertex_nums, range(n))], key=lambda x: x[0])[1]
for i in range(n):
if i != min_index:
edges.append((min_index, i, vertex_nums[min_index] + vertex_nums[i]))
edges = sorted(edges, key=lambda x: x[2])
print(count_result(n, edges))
if __name__ == '__main__':
main()
``` | output | 1 | 34,274 | 13 | 68,549 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected graph consisting of n vertices. A number is written on each vertex; the number on vertex i is a_i. Initially there are no edges in the graph.
You may add some edges to this graph, but you have to pay for them. The cost of adding an edge between vertices x and y is a_x + a_y coins. There are also m special offers, each of them is denoted by three numbers x, y and w, and means that you can add an edge connecting vertices x and y and pay w coins for it. You don't have to use special offers: if there is a pair of vertices x and y that has a special offer associated with it, you still may connect these two vertices paying a_x + a_y coins for it.
What is the minimum number of coins you have to spend to make the graph connected? Recall that a graph is connected if it's possible to get from any vertex to any other vertex using only the edges belonging to this graph.
Input
The first line contains two integers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the graph and the number of special offers, respectively.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{12}) — the numbers written on the vertices.
Then m lines follow, each containing three integers x, y and w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10^{12}, x ≠ y) denoting a special offer: you may add an edge connecting vertex x and vertex y, and this edge will cost w coins.
Output
Print one integer — the minimum number of coins you have to pay to make the graph connected.
Examples
Input
3 2
1 3 3
2 3 5
2 1 1
Output
5
Input
4 0
1 3 3 7
Output
16
Input
5 4
1 2 3 4 5
1 2 8
1 3 10
1 4 7
1 5 15
Output
18
Note
In the first example it is possible to connect 1 to 2 using special offer 2, and then 1 to 3 without using any offers.
In next two examples the optimal answer may be achieved without using special offers. | instruction | 0 | 34,275 | 13 | 68,550 |
Tags: dsu, graphs, greedy
Correct Solution:
```
class UnionFind:
def __init__(self, n):
self.par = [-1]*n
self.rank = [0]*n
def Find(self, x):
if self.par[x] < 0:
return x
else:
self.par[x] = self.Find(self.par[x])
return self.par[x]
def Unite(self, x, y):
x = self.Find(x)
y = self.Find(y)
if x != y:
if self.rank[x] < self.rank[y]:
self.par[y] += self.par[x]
self.par[x] = y
else:
self.par[x] += self.par[y]
self.par[y] = x
if self.rank[x] == self.rank[y]:
self.rank[x] += 1
def Same(self, x, y):
return self.Find(x) == self.Find(y)
def Size(self, x):
return -self.par[self.Find(x)]
import sys
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n, m = map(int, input().split())
A = list(map(int, input().split()))
w0 = min(A)
v0 = A.index(w0)
edge =[(v0+1, v1+1, w0+w1) for v1, w1 in enumerate(A) if v1 != v0]
for i in range(m):
x, y, w = map(int, input().split())
edge.append((x, y, w))
edge.sort(key=lambda x: x[2])
uf = UnionFind(n+1)
ans = 0
for u, v, w in edge:
if not uf.Same(u, v):
ans += w
uf.Unite(u, v)
print(ans)
``` | output | 1 | 34,275 | 13 | 68,551 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected graph consisting of n vertices. A number is written on each vertex; the number on vertex i is a_i. Initially there are no edges in the graph.
You may add some edges to this graph, but you have to pay for them. The cost of adding an edge between vertices x and y is a_x + a_y coins. There are also m special offers, each of them is denoted by three numbers x, y and w, and means that you can add an edge connecting vertices x and y and pay w coins for it. You don't have to use special offers: if there is a pair of vertices x and y that has a special offer associated with it, you still may connect these two vertices paying a_x + a_y coins for it.
What is the minimum number of coins you have to spend to make the graph connected? Recall that a graph is connected if it's possible to get from any vertex to any other vertex using only the edges belonging to this graph.
Input
The first line contains two integers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the graph and the number of special offers, respectively.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{12}) — the numbers written on the vertices.
Then m lines follow, each containing three integers x, y and w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10^{12}, x ≠ y) denoting a special offer: you may add an edge connecting vertex x and vertex y, and this edge will cost w coins.
Output
Print one integer — the minimum number of coins you have to pay to make the graph connected.
Examples
Input
3 2
1 3 3
2 3 5
2 1 1
Output
5
Input
4 0
1 3 3 7
Output
16
Input
5 4
1 2 3 4 5
1 2 8
1 3 10
1 4 7
1 5 15
Output
18
Note
In the first example it is possible to connect 1 to 2 using special offer 2, and then 1 to 3 without using any offers.
In next two examples the optimal answer may be achieved without using special offers. | instruction | 0 | 34,276 | 13 | 68,552 |
Tags: dsu, graphs, greedy
Correct Solution:
```
import sys
from io import StringIO
def main():
def find_set(v):
tmp = []
while v != parent[v]:
tmp.append(v)
v = parent[v]
for i in tmp:
parent[i] = v
return v
sys.stdin = StringIO(sys.stdin.read())
input = lambda: sys.stdin.readline().rstrip('\r\n')
n, m = map(int, input().split(' '))
a = list(map(int, input().split(' ')))
edges = []
for _ in range(m):
x, y, w = map(int, input().split(' '))
edges.append((x - 1, y - 1, w))
min_val = min(a)
min_ind = a.index(min_val)
for i in range(n):
edges.append((min_ind, i, min_val + a[i]))
parent, rank = list(range(n)), [0] * n
cost = 0
for edge in sorted(edges, key=lambda edge: edge[2]):
find_u, find_v = find_set(edge[0]), find_set(edge[1])
if find_u != find_v:
cost += edge[2]
if rank[find_u] < rank[find_v]:
find_v, find_u = find_u, find_v
elif rank[find_u] == rank[find_v]:
rank[find_u] += 1
parent[find_v] = find_u
print(cost)
main()
``` | output | 1 | 34,276 | 13 | 68,553 |
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 consisting of n vertices. A number is written on each vertex; the number on vertex i is a_i. Initially there are no edges in the graph.
You may add some edges to this graph, but you have to pay for them. The cost of adding an edge between vertices x and y is a_x + a_y coins. There are also m special offers, each of them is denoted by three numbers x, y and w, and means that you can add an edge connecting vertices x and y and pay w coins for it. You don't have to use special offers: if there is a pair of vertices x and y that has a special offer associated with it, you still may connect these two vertices paying a_x + a_y coins for it.
What is the minimum number of coins you have to spend to make the graph connected? Recall that a graph is connected if it's possible to get from any vertex to any other vertex using only the edges belonging to this graph.
Input
The first line contains two integers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the graph and the number of special offers, respectively.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{12}) — the numbers written on the vertices.
Then m lines follow, each containing three integers x, y and w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10^{12}, x ≠ y) denoting a special offer: you may add an edge connecting vertex x and vertex y, and this edge will cost w coins.
Output
Print one integer — the minimum number of coins you have to pay to make the graph connected.
Examples
Input
3 2
1 3 3
2 3 5
2 1 1
Output
5
Input
4 0
1 3 3 7
Output
16
Input
5 4
1 2 3 4 5
1 2 8
1 3 10
1 4 7
1 5 15
Output
18
Note
In the first example it is possible to connect 1 to 2 using special offer 2, and then 1 to 3 without using any offers.
In next two examples the optimal answer may be achieved without using special offers.
Submitted Solution:
```
from sys import stdin, stdout
input = stdin.readline
import gc, os
from os import _exit
gc.disable()
def put():
return map(int, input().split())
def find(i):
if i==p[i]:
return i
p[i]=find(p[i])
return p[i]
def union(i,j):
if rank[i]>rank[j]:
i,j = j,i
p[i]=j
if rank[i]==rank[j]:
rank[j]+=1
n,m = put()
l = list(put())
edge = []
minw = min(l)
mini = l.index(minw)
for _ in range(m):
x,y,w = put()
x,y = x-1,y-1
edge.append((w,x,y))
for i in range(n):
if i!=mini:
w = l[i]+minw
edge.append((w,mini,i))
edge.sort()
p = [i for i in range(n)]
rank = [0]*n
ans = 0
for w,x,y in edge:
x = find(x)
y = find(y)
if x!=y:
union(x,y)
ans+=w
stdout.write(str(ans))
stdout.flush()
_exit(0)
``` | instruction | 0 | 34,277 | 13 | 68,554 |
Yes | output | 1 | 34,277 | 13 | 68,555 |
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 consisting of n vertices. A number is written on each vertex; the number on vertex i is a_i. Initially there are no edges in the graph.
You may add some edges to this graph, but you have to pay for them. The cost of adding an edge between vertices x and y is a_x + a_y coins. There are also m special offers, each of them is denoted by three numbers x, y and w, and means that you can add an edge connecting vertices x and y and pay w coins for it. You don't have to use special offers: if there is a pair of vertices x and y that has a special offer associated with it, you still may connect these two vertices paying a_x + a_y coins for it.
What is the minimum number of coins you have to spend to make the graph connected? Recall that a graph is connected if it's possible to get from any vertex to any other vertex using only the edges belonging to this graph.
Input
The first line contains two integers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the graph and the number of special offers, respectively.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{12}) — the numbers written on the vertices.
Then m lines follow, each containing three integers x, y and w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10^{12}, x ≠ y) denoting a special offer: you may add an edge connecting vertex x and vertex y, and this edge will cost w coins.
Output
Print one integer — the minimum number of coins you have to pay to make the graph connected.
Examples
Input
3 2
1 3 3
2 3 5
2 1 1
Output
5
Input
4 0
1 3 3 7
Output
16
Input
5 4
1 2 3 4 5
1 2 8
1 3 10
1 4 7
1 5 15
Output
18
Note
In the first example it is possible to connect 1 to 2 using special offer 2, and then 1 to 3 without using any offers.
In next two examples the optimal answer may be achieved without using special offers.
Submitted Solution:
```
import sys
input = sys.stdin.readline
n,m=map(int,input().split())
A=list(map(int,input().split()))
SP=[list(map(int,input().split())) for i in range(m)]
MIN=min(A)
x=A.index(MIN)
EDGE_x=[[x+1,i+1,A[x]+A[i]] for i in range(n) if x!=i]
EDGE=EDGE_x+SP
EDGE.sort(key=lambda x:x[2])
#UnionFind
Group=[i for i in range(n+1)]
def find(x):
while Group[x] != x:
x=Group[x]
return x
def Union(x,y):
if find(x) != find(y):
Group[find(y)]=Group[find(x)]=min(find(y),find(x))
ANS=0
for i,j,x in EDGE:
if find(i)!=find(j):
ANS+=x
Union(i,j)
print(ANS)
``` | instruction | 0 | 34,278 | 13 | 68,556 |
Yes | output | 1 | 34,278 | 13 | 68,557 |
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 consisting of n vertices. A number is written on each vertex; the number on vertex i is a_i. Initially there are no edges in the graph.
You may add some edges to this graph, but you have to pay for them. The cost of adding an edge between vertices x and y is a_x + a_y coins. There are also m special offers, each of them is denoted by three numbers x, y and w, and means that you can add an edge connecting vertices x and y and pay w coins for it. You don't have to use special offers: if there is a pair of vertices x and y that has a special offer associated with it, you still may connect these two vertices paying a_x + a_y coins for it.
What is the minimum number of coins you have to spend to make the graph connected? Recall that a graph is connected if it's possible to get from any vertex to any other vertex using only the edges belonging to this graph.
Input
The first line contains two integers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the graph and the number of special offers, respectively.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{12}) — the numbers written on the vertices.
Then m lines follow, each containing three integers x, y and w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10^{12}, x ≠ y) denoting a special offer: you may add an edge connecting vertex x and vertex y, and this edge will cost w coins.
Output
Print one integer — the minimum number of coins you have to pay to make the graph connected.
Examples
Input
3 2
1 3 3
2 3 5
2 1 1
Output
5
Input
4 0
1 3 3 7
Output
16
Input
5 4
1 2 3 4 5
1 2 8
1 3 10
1 4 7
1 5 15
Output
18
Note
In the first example it is possible to connect 1 to 2 using special offer 2, and then 1 to 3 without using any offers.
In next two examples the optimal answer may be achieved without using special offers.
Submitted Solution:
```
import sys
from io import StringIO
def find_set(v):
tmp = []
while v != parent[v]:
tmp.append(v)
v = parent[v]
for i in tmp:
parent[i] = v
return v
sys.stdin = StringIO(sys.stdin.read())
input = lambda: sys.stdin.readline().rstrip('\r\n')
n, m = map(int, input().split(' '))
a = list(map(int, input().split(' ')))
edges = []
for _ in range(m):
x, y, w = map(int, input().split(' '))
edges.append((x - 1, y - 1, w))
min_val = min(a)
min_ind = a.index(min_val)
for i in range(n):
edges.append((min_ind, i, min_val + a[i]))
parent, rank = list(range(n)), [0] * n
cost = 0
for edge in sorted(edges, key=lambda edge: edge[2]):
find_u, find_v = find_set(edge[0]), find_set(edge[1])
if find_u != find_v:
cost += edge[2]
if rank[find_u] < rank[find_v]:
find_v, find_u = find_u, find_v
elif rank[find_u] == rank[find_v]:
rank[find_u] += 1
parent[find_v] = find_u
print(cost)
``` | instruction | 0 | 34,279 | 13 | 68,558 |
Yes | output | 1 | 34,279 | 13 | 68,559 |
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 consisting of n vertices. A number is written on each vertex; the number on vertex i is a_i. Initially there are no edges in the graph.
You may add some edges to this graph, but you have to pay for them. The cost of adding an edge between vertices x and y is a_x + a_y coins. There are also m special offers, each of them is denoted by three numbers x, y and w, and means that you can add an edge connecting vertices x and y and pay w coins for it. You don't have to use special offers: if there is a pair of vertices x and y that has a special offer associated with it, you still may connect these two vertices paying a_x + a_y coins for it.
What is the minimum number of coins you have to spend to make the graph connected? Recall that a graph is connected if it's possible to get from any vertex to any other vertex using only the edges belonging to this graph.
Input
The first line contains two integers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the graph and the number of special offers, respectively.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{12}) — the numbers written on the vertices.
Then m lines follow, each containing three integers x, y and w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10^{12}, x ≠ y) denoting a special offer: you may add an edge connecting vertex x and vertex y, and this edge will cost w coins.
Output
Print one integer — the minimum number of coins you have to pay to make the graph connected.
Examples
Input
3 2
1 3 3
2 3 5
2 1 1
Output
5
Input
4 0
1 3 3 7
Output
16
Input
5 4
1 2 3 4 5
1 2 8
1 3 10
1 4 7
1 5 15
Output
18
Note
In the first example it is possible to connect 1 to 2 using special offer 2, and then 1 to 3 without using any offers.
In next two examples the optimal answer may be achieved without using special offers.
Submitted Solution:
```
import sys, os
# import numpy as np
from math import sqrt, gcd, ceil, log, floor
from math import factorial as fact
from bisect import bisect, bisect_left
from collections import defaultdict, Counter, deque
from heapq import heapify, heappush, heappop
from itertools import permutations
input = sys.stdin.readline
read = lambda: list(map(int, input().strip().split()))
# read_f = lambda file: list(map(int, file.readline().strip().split()))
# from time import time
# sys.setrecursionlimit(5*10**6)
MOD = 10**9 + 7
def main():
# file1 = open("C:\\Users\\shank\\Desktop\\Comp_Code\\input.txt", "r")
# n = int(file1.readline().strip());
# arr = list(map(int, file1.read().strip().split(" ")))
# file1.close()
# ans_ = []
# for _ in range(int(input())):
def find(x):
while par[x] != x:
par[x] = par[par[x]]
x = par[x]
return(x)
n, m = read(); cost = [10**12+1]+read()
mn = 10**12 * 2; mnind = 0
for i in range(1, n+1):
if mn > cost[i]:
mn = cost[i]
mnind = i
# arr = []
# for i in range(1,n+1):
# if i != mnind:
# arr.append([cost[i]+mn, mnind, i])
arr = [[mnind, i, cost[i]+mn] for i in range(1, n+1) if i != mnind]
a = [read() for i in range(m)]
# for i in range(m):
# a, b, c = read()
# arr.append([c, a, b])
# print(arr)
arr += a
# print(arr)
arr.sort(key = lambda x: x[2])
# print(arr)
par = [i for i in range(n + 1)]
ans = 0
for a, b, cost in arr:
f_a = find(a); f_b = find(b)
if f_a != f_b:
par[f_a] = f_b
ans += cost
# print(a, b, par)
print(ans)
# for i in ans_:
# print(i)
# print(("\n").join(ans_))
# file = open("output.txt", "w")
# file.write(ans+"\n")
# file.close()
if __name__ == "__main__":
main()
"""
"""
``` | instruction | 0 | 34,280 | 13 | 68,560 |
Yes | output | 1 | 34,280 | 13 | 68,561 |
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 consisting of n vertices. A number is written on each vertex; the number on vertex i is a_i. Initially there are no edges in the graph.
You may add some edges to this graph, but you have to pay for them. The cost of adding an edge between vertices x and y is a_x + a_y coins. There are also m special offers, each of them is denoted by three numbers x, y and w, and means that you can add an edge connecting vertices x and y and pay w coins for it. You don't have to use special offers: if there is a pair of vertices x and y that has a special offer associated with it, you still may connect these two vertices paying a_x + a_y coins for it.
What is the minimum number of coins you have to spend to make the graph connected? Recall that a graph is connected if it's possible to get from any vertex to any other vertex using only the edges belonging to this graph.
Input
The first line contains two integers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the graph and the number of special offers, respectively.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{12}) — the numbers written on the vertices.
Then m lines follow, each containing three integers x, y and w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10^{12}, x ≠ y) denoting a special offer: you may add an edge connecting vertex x and vertex y, and this edge will cost w coins.
Output
Print one integer — the minimum number of coins you have to pay to make the graph connected.
Examples
Input
3 2
1 3 3
2 3 5
2 1 1
Output
5
Input
4 0
1 3 3 7
Output
16
Input
5 4
1 2 3 4 5
1 2 8
1 3 10
1 4 7
1 5 15
Output
18
Note
In the first example it is possible to connect 1 to 2 using special offer 2, and then 1 to 3 without using any offers.
In next two examples the optimal answer may be achieved without using special offers.
Submitted Solution:
```
import sys
def v_min(l) :
res = l[0]
for v in l :
if (v[1] < res[1]) :
res = v
return res
def min_offers(g_i, g_w, v, offers, cost) :
c = cost
vi = v[0]
for o in offers :
if (o[0] == vi and o[1] in g_i) or (o[1] == vi and o[0] in g_i) :
if (o[2] < c) :
c = o[2]
offers.remove(o)
return c
ch = input().split()
n, m = int(ch[0]), int(ch[1])
vx, offers = [], []
count = 0
ch = input().split()
for i in range(len(ch)) :
vx += [(i,int(ch[i]))]
for i in range(m) :
ch = input().split()
offers += [(int(ch[0])-1,int(ch[1])-1,int(ch[2]))]
tot_cost = 0
v = v_min(vx)
g_i = [v[0]]
g_w = [v[1]]
vx.remove(v)
while (len(g_i) < n) :
vbis = v_min(vx)
g_i += [vbis[0]]
g_w += [vbis[1]]
vx.remove(vbis)
cmin= v[1] + vbis[1]
tot_cost += min_offers(g_i, g_w, vbis, offers, cmin)
print(tot_cost)
``` | instruction | 0 | 34,281 | 13 | 68,562 |
No | output | 1 | 34,281 | 13 | 68,563 |
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 consisting of n vertices. A number is written on each vertex; the number on vertex i is a_i. Initially there are no edges in the graph.
You may add some edges to this graph, but you have to pay for them. The cost of adding an edge between vertices x and y is a_x + a_y coins. There are also m special offers, each of them is denoted by three numbers x, y and w, and means that you can add an edge connecting vertices x and y and pay w coins for it. You don't have to use special offers: if there is a pair of vertices x and y that has a special offer associated with it, you still may connect these two vertices paying a_x + a_y coins for it.
What is the minimum number of coins you have to spend to make the graph connected? Recall that a graph is connected if it's possible to get from any vertex to any other vertex using only the edges belonging to this graph.
Input
The first line contains two integers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the graph and the number of special offers, respectively.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{12}) — the numbers written on the vertices.
Then m lines follow, each containing three integers x, y and w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10^{12}, x ≠ y) denoting a special offer: you may add an edge connecting vertex x and vertex y, and this edge will cost w coins.
Output
Print one integer — the minimum number of coins you have to pay to make the graph connected.
Examples
Input
3 2
1 3 3
2 3 5
2 1 1
Output
5
Input
4 0
1 3 3 7
Output
16
Input
5 4
1 2 3 4 5
1 2 8
1 3 10
1 4 7
1 5 15
Output
18
Note
In the first example it is possible to connect 1 to 2 using special offer 2, and then 1 to 3 without using any offers.
In next two examples the optimal answer may be achieved without using special offers.
Submitted Solution:
```
#!/usr/bin/env python3
# Le problème revient à trouver un arbre couvrant minimal
# dans le graphe constitué de tous les arcs possibles
def edges(nodes,offers):
edges = dict(offers)
for i in range(1,len(nodes)+1):
for j in range(i+1,len(nodes)+1):
cost = nodes[i] + nodes[j]
if cost not in edges:
edges[cost] = []
if not((i,j) in edges[cost] or (j,i) in edges[cost]):
edges[cost] += [(i,j)]
return edges
def connect(nodes,edges):
if (list(nodes.keys()) == [1,2,3,4,5,6,7,8,9,10]):
return 67
# on utilise l'algo de Kruskal
cost = 0
connected_nodes = []
for key in edges:
for (x,y) in edges[key]:
x_con = x in connected_nodes
y_con = y in connected_nodes
if not (x_con and y_con):
cost += key
if not x_con:
connected_nodes += [x]
if not y_con:
connected_nodes += [y]
return cost
def getline():
return [int(i) for i in input().split(' ')]
if __name__ == '__main__':
line = getline()
n, m = line[0], line[1]
line = getline()
nodes = {node:line[node-1] for node in range(1,n+1)}
offers = {}
for i in range(m):
line = getline()
x,y,w = line[0],line[1],line[2]
if w not in offers:
offers[w] = []
if not((x,y) in offers or (y,x) in offers):
offers[w] += [(x,y)]
edges = edges(nodes,offers)
sorted_edges = {key:edges[key] for key in sorted(edges.keys())}
print(connect(nodes,sorted_edges))
``` | instruction | 0 | 34,282 | 13 | 68,564 |
No | output | 1 | 34,282 | 13 | 68,565 |
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 consisting of n vertices. A number is written on each vertex; the number on vertex i is a_i. Initially there are no edges in the graph.
You may add some edges to this graph, but you have to pay for them. The cost of adding an edge between vertices x and y is a_x + a_y coins. There are also m special offers, each of them is denoted by three numbers x, y and w, and means that you can add an edge connecting vertices x and y and pay w coins for it. You don't have to use special offers: if there is a pair of vertices x and y that has a special offer associated with it, you still may connect these two vertices paying a_x + a_y coins for it.
What is the minimum number of coins you have to spend to make the graph connected? Recall that a graph is connected if it's possible to get from any vertex to any other vertex using only the edges belonging to this graph.
Input
The first line contains two integers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the graph and the number of special offers, respectively.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{12}) — the numbers written on the vertices.
Then m lines follow, each containing three integers x, y and w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10^{12}, x ≠ y) denoting a special offer: you may add an edge connecting vertex x and vertex y, and this edge will cost w coins.
Output
Print one integer — the minimum number of coins you have to pay to make the graph connected.
Examples
Input
3 2
1 3 3
2 3 5
2 1 1
Output
5
Input
4 0
1 3 3 7
Output
16
Input
5 4
1 2 3 4 5
1 2 8
1 3 10
1 4 7
1 5 15
Output
18
Note
In the first example it is possible to connect 1 to 2 using special offer 2, and then 1 to 3 without using any offers.
In next two examples the optimal answer may be achieved without using special offers.
Submitted Solution:
```
#!/usr/bin/env python3
import sys
import array
def _offer(offers, x, y):
"""
Returns the offer if there is one.
Returns +infinity otherwise
"""
if (x,y) in offers:
return offers[(x,y)]
if (y,x) in offers:
return offers[(y,x)]
return float('inf')
def _extract_min(queue, prices, idx_in_queue):
res = queue[1]
queue[1] = queue[queue[0]] # Le dernier elt du tas est mis à
# la place de l'elt le plus petit
idx_in_queue[queue[1]] = 1
queue[0] -= 1
_reheapify_from(queue, prices, idx_in_queue, 1) # Remet le tas en l'état
return res
def _reheapify_from(queue, prices, idx_in_queue, idx):
"""
Fait 'descendre' l'élément à l'indice [idx] de la file
de priorité [queue] tant que possible. [queue] est un tas-min
"""
l = 2*idx
r = 2*idx + 1
win = idx
if l <= queue[0] and prices[queue[l]] < prices[queue[win]]: win = l
if r <= queue[0] and prices[queue[r]] < prices[queue[win]]: win = r
if win != idx:
queue[win], queue[idx] = queue[idx], queue[win]
idx_in_queue[queue[win]] = win
idx_in_queue[queue[idx]] = idx
_reheapify_from(queue, prices, idx_in_queue, win)
def update_pqueue(queue, prices, idx_in_queue, x):
"""
Ici, on suppose que le [cout] nécéssaire pour joindre le sommet
[x] est inférieur à sont cout précédant. On met donc à jour
la file de priorité pour prendre en compte cette modification
"""
i = idx_in_queue[x]
while i//2 >= 1 and prices[queue[i//2]] > prices[queue[i]]:
queue[i//2], queue[i] = queue[i], queue[i//2]
idx_in_queue[queue[i]] = i
idx_in_queue[queue[i//2]] = i//2
i = i // 2
def add_edge(edges, vertices, u, v, offers):
price = min(vertices[v] + vertices[u], _offer(offers,v,u))
if u not in edges:
edges[u] = [(v, price)]
else:
edges[u].append((v, price))
if v not in edges:
edges[v] = [(u, price)]
else:
edges[v].append((u, price))
if __name__ == "__main__":
lines = sys.stdin.readlines()
nb_vertices, nb_offers = [int(x) for x in lines[0].split()]
vertices = array.array('l', [int(x) for x in lines[1].split()])
_min = vertices[0]
_idx_min = 0
for idx,val in enumerate(vertices):
if val < _min:
_min = val
_idx_min = idx
# L'ensemble des sommets à joindre
#vertices_to_check = {x for x in range(nb_vertices)}
offers = {}
for line in lines[2: 2 + nb_offers]:
x, y, cost = [int(x) for x in line.split()]
offers[(x-1, y-1)] = cost # Le 'x-1', 'y-1' est pour 'convertir'
# les sommets en leur indice dans
# le tableau [vertices]
edges = {}
for i in range(nb_vertices):
if i != _idx_min:
add_edge(edges, vertices, _idx_min, i, offers)
for (u,v),offer in offers.items(): # TODO: FIX
if vertices[u] + vertices[v] > offer:
edges[u].append((v,offer))
edges[v].append((u,offer))
## Implémentation de l'algorithme de Prim
total_price = 0
prices = array.array('f', [float('inf') for _ in range(nb_vertices)])
prices[0] = 0 # Le cout pour joindre le premier sommet est nul
queue = array.array('i', [idx-1 for idx in range(nb_vertices + 1)])
queue[0] = nb_vertices # On stocke en queue[0] le nombre d'éléments
# de la file de priorité
# Un tableau qui donne l'indice d'un sommet dans
# la file de priorité
idx_in_queue = array.array('i', [idx + 1 for idx in range(nb_vertices)])
while queue[0] > 0:
s = _extract_min(queue, prices, idx_in_queue)
total_price += prices[s]
# On retire le sommet extrait de l'ensemble des sommets à
# joindre
#vertices_to_check -= set([s])
for (v,price) in edges[s]: #vertices_to_check:
# Le 'poids' d'une arete est défini comme
# la somme de la valeur des sommets ou d'une
# offre existante pour ces deux sommets
#weight = min(vertices[v] + vertices[s], _offer(offers,v,s))
if prices[v] > price:
prices[v] = price
update_pqueue(queue, prices, idx_in_queue, v)
print(int(total_price))
``` | instruction | 0 | 34,283 | 13 | 68,566 |
No | output | 1 | 34,283 | 13 | 68,567 |
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 consisting of n vertices. A number is written on each vertex; the number on vertex i is a_i. Initially there are no edges in the graph.
You may add some edges to this graph, but you have to pay for them. The cost of adding an edge between vertices x and y is a_x + a_y coins. There are also m special offers, each of them is denoted by three numbers x, y and w, and means that you can add an edge connecting vertices x and y and pay w coins for it. You don't have to use special offers: if there is a pair of vertices x and y that has a special offer associated with it, you still may connect these two vertices paying a_x + a_y coins for it.
What is the minimum number of coins you have to spend to make the graph connected? Recall that a graph is connected if it's possible to get from any vertex to any other vertex using only the edges belonging to this graph.
Input
The first line contains two integers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the graph and the number of special offers, respectively.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{12}) — the numbers written on the vertices.
Then m lines follow, each containing three integers x, y and w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10^{12}, x ≠ y) denoting a special offer: you may add an edge connecting vertex x and vertex y, and this edge will cost w coins.
Output
Print one integer — the minimum number of coins you have to pay to make the graph connected.
Examples
Input
3 2
1 3 3
2 3 5
2 1 1
Output
5
Input
4 0
1 3 3 7
Output
16
Input
5 4
1 2 3 4 5
1 2 8
1 3 10
1 4 7
1 5 15
Output
18
Note
In the first example it is possible to connect 1 to 2 using special offer 2, and then 1 to 3 without using any offers.
In next two examples the optimal answer may be achieved without using special offers.
Submitted Solution:
```
def ii():
return int(input())
def mi():
return map(int, input().split())
def li():
return list(mi())
n, m = mi()
a = li()
b = [li() for i in range(m)]
b = sorted((w, u - 1, v - 1) for u, v, w in b)
rt = a.index(min(a))
p = [rt for i in range(n)]
c = [a[i] + a[rt] for i in range(n)]
for w, u, v in b:
if c[u] > c[v]:
u, v = v, u
if w < c[v]:
p[v] = u
c[v] = w
ans = sum(c[i] for i in range(n) if i != rt)
print(ans)
``` | instruction | 0 | 34,284 | 13 | 68,568 |
No | output | 1 | 34,284 | 13 | 68,569 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rooted tree with vertices numerated from 1 to n. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.
Ancestors of the vertex i are all vertices on the path from the root to the vertex i, except the vertex i itself. The parent of the vertex i is the nearest to the vertex i ancestor of i. Each vertex is a child of its parent. In the given tree the parent of the vertex i is the vertex p_i. For the root, the value p_i is -1.
<image> An example of a tree with n=8, the root is vertex 5. The parent of the vertex 2 is vertex 3, the parent of the vertex 1 is vertex 5. The ancestors of the vertex 6 are vertices 4 and 5, the ancestors of the vertex 7 are vertices 8, 3 and 5
You noticed that some vertices do not respect others. In particular, if c_i = 1, then the vertex i does not respect any of its ancestors, and if c_i = 0, it respects all of them.
You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex v, all children of v become connected with the parent of v.
<image> An example of deletion of the vertex 7.
Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of vertices in the tree.
The next n lines describe the tree: the i-th line contains two integers p_i and c_i (1 ≤ p_i ≤ n, 0 ≤ c_i ≤ 1), where p_i is the parent of the vertex i, and c_i = 0, if the vertex i respects its parents, and c_i = 1, if the vertex i does not respect any of its parents. The root of the tree has -1 instead of the parent index, also, c_i=0 for the root. It is guaranteed that the values p_i define a rooted tree with n vertices.
Output
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer -1.
Examples
Input
5
3 1
1 1
-1 0
2 1
3 0
Output
1 2 4
Input
5
-1 0
1 1
1 1
2 0
3 0
Output
-1
Input
8
2 1
-1 0
1 0
1 1
1 1
4 0
5 1
7 0
Output
5
Note
The deletion process in the first example is as follows (see the picture below, the vertices with c_i=1 are in yellow):
* first you will delete the vertex 1, because it does not respect ancestors and all its children (the vertex 2) do not respect it, and 1 is the smallest index among such vertices;
* the vertex 2 will be connected with the vertex 3 after deletion;
* then you will delete the vertex 2, because it does not respect ancestors and all its children (the only vertex 4) do not respect it;
* the vertex 4 will be connected with the vertex 3;
* then you will delete the vertex 4, because it does not respect ancestors and all its children (there are none) do not respect it ([vacuous truth](https://en.wikipedia.org/wiki/Vacuous_truth));
* you will just delete the vertex 4;
* there are no more vertices to delete.
<image>
In the second example you don't need to delete any vertex:
* vertices 2 and 3 have children that respect them;
* vertices 4 and 5 respect ancestors.
<image>
In the third example the tree will change this way:
<image> | instruction | 0 | 34,301 | 13 | 68,602 |
Tags: dfs and similar, trees
Correct Solution:
```
def main():
n = int(input())
par = {}
chi = {i: 0 for i in range(1, n + 1)}
fl = 0
uvaj = {}
for i in range(n):
p, c = map(int, input().split())
if p != -1:
par[i + 1] = p
chi[p] += 1 - c
uvaj[i + 1] = 1 - c
for i in range(1, n + 1):
g = chi[i]
if g == 0 and uvaj[i] == 0:
print(i, end=' ')
fl = 1
if fl == 0:
print(-1)
main()
``` | output | 1 | 34,301 | 13 | 68,603 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rooted tree with vertices numerated from 1 to n. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.
Ancestors of the vertex i are all vertices on the path from the root to the vertex i, except the vertex i itself. The parent of the vertex i is the nearest to the vertex i ancestor of i. Each vertex is a child of its parent. In the given tree the parent of the vertex i is the vertex p_i. For the root, the value p_i is -1.
<image> An example of a tree with n=8, the root is vertex 5. The parent of the vertex 2 is vertex 3, the parent of the vertex 1 is vertex 5. The ancestors of the vertex 6 are vertices 4 and 5, the ancestors of the vertex 7 are vertices 8, 3 and 5
You noticed that some vertices do not respect others. In particular, if c_i = 1, then the vertex i does not respect any of its ancestors, and if c_i = 0, it respects all of them.
You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex v, all children of v become connected with the parent of v.
<image> An example of deletion of the vertex 7.
Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of vertices in the tree.
The next n lines describe the tree: the i-th line contains two integers p_i and c_i (1 ≤ p_i ≤ n, 0 ≤ c_i ≤ 1), where p_i is the parent of the vertex i, and c_i = 0, if the vertex i respects its parents, and c_i = 1, if the vertex i does not respect any of its parents. The root of the tree has -1 instead of the parent index, also, c_i=0 for the root. It is guaranteed that the values p_i define a rooted tree with n vertices.
Output
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer -1.
Examples
Input
5
3 1
1 1
-1 0
2 1
3 0
Output
1 2 4
Input
5
-1 0
1 1
1 1
2 0
3 0
Output
-1
Input
8
2 1
-1 0
1 0
1 1
1 1
4 0
5 1
7 0
Output
5
Note
The deletion process in the first example is as follows (see the picture below, the vertices with c_i=1 are in yellow):
* first you will delete the vertex 1, because it does not respect ancestors and all its children (the vertex 2) do not respect it, and 1 is the smallest index among such vertices;
* the vertex 2 will be connected with the vertex 3 after deletion;
* then you will delete the vertex 2, because it does not respect ancestors and all its children (the only vertex 4) do not respect it;
* the vertex 4 will be connected with the vertex 3;
* then you will delete the vertex 4, because it does not respect ancestors and all its children (there are none) do not respect it ([vacuous truth](https://en.wikipedia.org/wiki/Vacuous_truth));
* you will just delete the vertex 4;
* there are no more vertices to delete.
<image>
In the second example you don't need to delete any vertex:
* vertices 2 and 3 have children that respect them;
* vertices 4 and 5 respect ancestors.
<image>
In the third example the tree will change this way:
<image> | instruction | 0 | 34,302 | 13 | 68,604 |
Tags: dfs and similar, trees
Correct Solution:
```
def chk(node):
global g,p,c
temp=0
g[node].remove(p[node])
for i in g[node]:
temp+=c[i]
if temp==len(g[node]):
g[node].append(p[node])
return 1
g[node].append(p[node])
return 0
def del_node(node):
global g,c,p
g[node].remove(p[node])
for i in g[node]:
g[i].remove(node)
g[i].append(p[node])
p[i]=p[node]
g[p[node]].remove(node)
g[p[node]].extend(g[node])
v=int(input())
c={}
p={}
g={}
ans=[]
for i in range(1,v+1):
g[i]=[]
for i in range(1,v+1):
x,y=map(int,input().split())
p[i]=x
c[i]=y
if x!=-1:
g[i].append(x)
g[x].append(i)
for i in range(1,v+1):
if p[i]!=-1 and c[i] and chk(i):
ans.append(i)
if len(ans)==0:
print(-1)
else:
for i in ans:
print(i,end=" ")
``` | output | 1 | 34,302 | 13 | 68,605 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rooted tree with vertices numerated from 1 to n. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.
Ancestors of the vertex i are all vertices on the path from the root to the vertex i, except the vertex i itself. The parent of the vertex i is the nearest to the vertex i ancestor of i. Each vertex is a child of its parent. In the given tree the parent of the vertex i is the vertex p_i. For the root, the value p_i is -1.
<image> An example of a tree with n=8, the root is vertex 5. The parent of the vertex 2 is vertex 3, the parent of the vertex 1 is vertex 5. The ancestors of the vertex 6 are vertices 4 and 5, the ancestors of the vertex 7 are vertices 8, 3 and 5
You noticed that some vertices do not respect others. In particular, if c_i = 1, then the vertex i does not respect any of its ancestors, and if c_i = 0, it respects all of them.
You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex v, all children of v become connected with the parent of v.
<image> An example of deletion of the vertex 7.
Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of vertices in the tree.
The next n lines describe the tree: the i-th line contains two integers p_i and c_i (1 ≤ p_i ≤ n, 0 ≤ c_i ≤ 1), where p_i is the parent of the vertex i, and c_i = 0, if the vertex i respects its parents, and c_i = 1, if the vertex i does not respect any of its parents. The root of the tree has -1 instead of the parent index, also, c_i=0 for the root. It is guaranteed that the values p_i define a rooted tree with n vertices.
Output
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer -1.
Examples
Input
5
3 1
1 1
-1 0
2 1
3 0
Output
1 2 4
Input
5
-1 0
1 1
1 1
2 0
3 0
Output
-1
Input
8
2 1
-1 0
1 0
1 1
1 1
4 0
5 1
7 0
Output
5
Note
The deletion process in the first example is as follows (see the picture below, the vertices with c_i=1 are in yellow):
* first you will delete the vertex 1, because it does not respect ancestors and all its children (the vertex 2) do not respect it, and 1 is the smallest index among such vertices;
* the vertex 2 will be connected with the vertex 3 after deletion;
* then you will delete the vertex 2, because it does not respect ancestors and all its children (the only vertex 4) do not respect it;
* the vertex 4 will be connected with the vertex 3;
* then you will delete the vertex 4, because it does not respect ancestors and all its children (there are none) do not respect it ([vacuous truth](https://en.wikipedia.org/wiki/Vacuous_truth));
* you will just delete the vertex 4;
* there are no more vertices to delete.
<image>
In the second example you don't need to delete any vertex:
* vertices 2 and 3 have children that respect them;
* vertices 4 and 5 respect ancestors.
<image>
In the third example the tree will change this way:
<image> | instruction | 0 | 34,303 | 13 | 68,606 |
Tags: dfs and similar, trees
Correct Solution:
```
import os
from io import BytesIO, StringIO
input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
n = int(input())
dels = []
cof = [0] * n
G = [list() for _ in range(n)]
for v in range(n):
p, c = map(int, input().split())
if p == -1:
root = v
else:
p = p-1
G[p].append(v)
cof[v] = c
stack = [root]
while stack:
u = stack.pop()
d = False
if cof[u] == 1:
d = True
for v in G[u]:
if cof[v] == 0:
d = False
stack.append(v)
if d:
dels.append(u+1)
if dels:
print(*sorted(dels))
else:
print(-1)
``` | output | 1 | 34,303 | 13 | 68,607 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rooted tree with vertices numerated from 1 to n. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.
Ancestors of the vertex i are all vertices on the path from the root to the vertex i, except the vertex i itself. The parent of the vertex i is the nearest to the vertex i ancestor of i. Each vertex is a child of its parent. In the given tree the parent of the vertex i is the vertex p_i. For the root, the value p_i is -1.
<image> An example of a tree with n=8, the root is vertex 5. The parent of the vertex 2 is vertex 3, the parent of the vertex 1 is vertex 5. The ancestors of the vertex 6 are vertices 4 and 5, the ancestors of the vertex 7 are vertices 8, 3 and 5
You noticed that some vertices do not respect others. In particular, if c_i = 1, then the vertex i does not respect any of its ancestors, and if c_i = 0, it respects all of them.
You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex v, all children of v become connected with the parent of v.
<image> An example of deletion of the vertex 7.
Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of vertices in the tree.
The next n lines describe the tree: the i-th line contains two integers p_i and c_i (1 ≤ p_i ≤ n, 0 ≤ c_i ≤ 1), where p_i is the parent of the vertex i, and c_i = 0, if the vertex i respects its parents, and c_i = 1, if the vertex i does not respect any of its parents. The root of the tree has -1 instead of the parent index, also, c_i=0 for the root. It is guaranteed that the values p_i define a rooted tree with n vertices.
Output
In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer -1.
Examples
Input
5
3 1
1 1
-1 0
2 1
3 0
Output
1 2 4
Input
5
-1 0
1 1
1 1
2 0
3 0
Output
-1
Input
8
2 1
-1 0
1 0
1 1
1 1
4 0
5 1
7 0
Output
5
Note
The deletion process in the first example is as follows (see the picture below, the vertices with c_i=1 are in yellow):
* first you will delete the vertex 1, because it does not respect ancestors and all its children (the vertex 2) do not respect it, and 1 is the smallest index among such vertices;
* the vertex 2 will be connected with the vertex 3 after deletion;
* then you will delete the vertex 2, because it does not respect ancestors and all its children (the only vertex 4) do not respect it;
* the vertex 4 will be connected with the vertex 3;
* then you will delete the vertex 4, because it does not respect ancestors and all its children (there are none) do not respect it ([vacuous truth](https://en.wikipedia.org/wiki/Vacuous_truth));
* you will just delete the vertex 4;
* there are no more vertices to delete.
<image>
In the second example you don't need to delete any vertex:
* vertices 2 and 3 have children that respect them;
* vertices 4 and 5 respect ancestors.
<image>
In the third example the tree will change this way:
<image> | instruction | 0 | 34,304 | 13 | 68,608 |
Tags: dfs and similar, trees
Correct Solution:
```
from sys import stdin,stdout
from math import gcd,sqrt
from collections import deque
input=stdin.readline
R=lambda:map(int,input().split())
I=lambda:int(input())
S=lambda:input().rstrip('\n')
P=lambda x:stdout.write(x)
hg=lambda x,y:((y+x-1)//x)*x
pw=lambda x:1 if x==1 else 1+pw(x//2)
chk=lambda x:chk(x//2) if not x%2 else True if x==1 else False
def ok():print('OK')
N=10**9+7
n=I()
val=[0]*n
ans=[]
a=[[] for i in range(n)]
for i in range(n):
p,c=R()
if p!=-1:
a[p-1]+=i,
val[i]=c
for i in range(n):
if val[i]:
flg=True
for el in a[i]:
if not val[el]:flg=False;break
if flg:ans+=i+1,
print(*ans if ans else [-1])
``` | output | 1 | 34,304 | 13 | 68,609 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.