message stringlengths 2 49.9k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 446 108k | cluster float64 13 13 | __index_level_0__ int64 892 217k |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given N-1 subsets of \\{1,2,...,N\\}. Let the i-th set be E_i.
Let us choose two distinct elements u_i and v_i from each set E_i, and consider a graph T with N vertices and N-1 edges, whose vertex set is \\{1,2,..,N\\} and whose edge set is (u_1,v_1),(u_2,v_2),...,(u_{N-1},v_{N-1}). Determine if T can be a tree by properly deciding u_i and v_i. If it can, additionally find one instance of (u_1,v_1),(u_2,v_2),...,(u_{N-1},v_{N-1}) such that T is actually a tree.
Constraints
* 2 \leq N \leq 10^5
* E_i is a subset of \\{1,2,..,N\\}.
* |E_i| \geq 2
* The sum of |E_i| is at most 2 \times 10^5.
Input
Input is given from Standard Input in the following format:
N
c_1 w_{1,1} w_{1,2} ... w_{1,c_1}
:
c_{N-1} w_{N-1,1} w_{N-1,2} ... w_{N-1,c_{N-1}}
Here, c_i stands for the number of elements in E_i, and w_{i,1},...,w_{i,c_i} are the c_i elements in c_i. Here, 2 \leq c_i \leq N, 1 \leq w_{i,j} \leq N, and w_{i,j} \neq w_{i,k} (1 \leq j < k \leq c_i) hold.
Output
If T cannot be a tree, print `-1`; otherwise, print the choices of (u_i,v_i) that satisfy the condition, in the following format:
u_1 v_1
:
u_{N-1} v_{N-1}
Output
If T cannot be a tree, print `-1`; otherwise, print the choices of (u_i,v_i) that satisfy the condition, in the following format:
u_1 v_1
:
u_{N-1} v_{N-1}
Examples
Input
5
2 1 2
3 1 2 3
3 3 4 5
2 4 5
Output
1 2
1 3
3 4
4 5
Input
6
3 1 2 3
3 2 3 4
3 1 3 4
3 1 2 4
3 4 5 6
Output
-1
Input
10
5 1 2 3 4 5
5 2 3 4 5 6
5 3 4 5 6 7
5 4 5 6 7 8
5 5 6 7 8 9
5 6 7 8 9 10
5 7 8 9 10 1
5 8 9 10 1 2
5 9 10 1 2 3
Output
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
Submitted Solution:
```
"""
https://atcoder.jp/contests/agc029/tasks/agc029_f
方針:頂点1とすべてつなげたい
→1が入ってる場合、1 & ナニカを選べばいい
→そうでない場合、既に選択済み & 新規点を選べばよい
小さい集合から選択するべき論はそうかも
→むしろ登場回数が少ない頂点から選択するべき?
→登場回数が2回の頂点2つがある
→互いの選択で影響しあうのは重なってる場合
各集合で取るより1から遠い点は残りの集合の中での登場回数がすくない点から貪欲に?
→おkそう
あとはこれでループが生まれないことを証明
→おk
まずいのは、選択によって不可能集合を作ってしまうこと
=====再挑戦=====
方針は、1が入ってるやつは 1&ナニカを選ぶ
それ以外は新規を選ぶ
→マッチング
→dinicなら高速に行ける
"""
from sys import stdin
from collections import defaultdict
from collections import deque
import sys
sys.setrecursionlimit(200000)
def Dinic_DFS(v,g,maxflow,lines,cost,level,cap):
if v == g:
return maxflow
realflow = 0
tmp = [i for i in lines[v]]
for nex in tmp:
if level[nex] > level[v] and (nex not in cap[v]):
plusflow = Dinic_DFS(nex,g,min(maxflow , cost[v][nex]),lines,cost,level,cap)
if plusflow == 0:
cap[v].add(nex)
continue
cost[v][nex] -= plusflow
if cost[v][nex] == 0:
lines[v].remove(nex)
if cost[nex][v] == 0:
lines[nex].add(v)
cost[nex][v] += plusflow
realflow += plusflow
return realflow
return realflow
def Dinic(s,g,lines,cost):
N = len(cost)
ans = 0
while True:
#bfs
q = deque([s])
level = [float("inf")] * N
level[s] = 0
while q:
now = q.popleft()
#print (now)
for nex in lines[now]:
if level[nex] > level[now] + 1:
level[nex] = level[now] + 1
q.append(nex)
if level[g] == float("inf"):
return ans
#dfs
cap = [set() for i in range(N)]
delta_flow = Dinic_DFS(s,g,float("inf"),lines,cost,level,cap)
while delta_flow > 0:
ans += delta_flow
delta_flow = Dinic_DFS(s,g,float("inf"),lines,cost,level,cap)
N = int(stdin.readline())
w = []
vtoc = [ [] for i in range(N)] #頂点から属す集合を逆引き
for loop in range(N-1):
cw = list(map(int,input().split()))
for i in range(1,cw[0]+1):
cw[i] -= 1
vtoc[cw[i]].append(loop)
w.append(cw[1:])
#二部マッチングを求める 集合N-1個と数字N-1個をマッチング
#フロー始点を0,終点をNにしよう
lines = defaultdict(set)
cost = [ defaultdict(int) for i in range(2*N) ]
for i in range(1,N):
lines[0].add(i)
cost[0][i] = 1
for i in range(N+1,2*N):
lines[i].add(N)
cost[i][N] = 1
for i in range(N-1):
for j in w[i]:
if j != 0:
lines[i+1].add(N + j)
cost[i+1][N + j] = 1
flow = Dinic(0,N,lines,cost)
if flow != N-1:
print (-1)
sys.exit()
newv = [None] * (N-1)
for i in range(N-1):
for j in w[i]:
if j != 0 and cost[i+1][N + j] == 0:
newv[i] = j
break
end = [False] * N
q = deque([0])
ans = [None] * (N-1)
while len(q) > 0:
nv = q.popleft()
for c in vtoc[nv]:
if not end[newv[c]]:
ans[c] = (nv+1,newv[c]+1)
end[newv[c]] = True
q.append(newv[c])
if None not in ans:
for i in ans:
print (*i)
else:
print (-1)
"""
#一転更新区間取得のセグ木とRMQである(最大取得したいなら負で突っ込めばおk?)
#query区間左,右は実際に求めたい区間(半開区間なので右は+1しておくこと)
#注目ノード番号は0でOK
#担当範囲左,担当範囲右 は、それぞれ 0 , (len(セグ木)+1)//2 にしておくこと
def make_ST(n,first): #firstで初期化された、葉がn要素を超えるように2のべき乗個用意されたリストを返す
i = 0
ret = []
while 2 ** (i-1) < n:
for j in range(2 ** i):
ret.append(first)
i += 1
return ret
def RMQ_update_point(num,point,tree): #葉のindex(0-origin)がpointの要素をnumにする/treeはセグ木
i = (len(tree) - 1) // 2 + point
tree[i] = num
while i > 0:
i = (i - 1) // 2
tree[i] = min(tree[i * 2 + 2] , tree[i * 2 + 1])
return
def RMQ_query(a,b,k,l,r,tree): #query区間左,右,注目ノード番号,担当範囲左,担当範囲右,木
if r <= a or b <= l: #区間が完全にかぶらない場合inf
return ( float("inf") , float("inf") )
if a <= l and r <= b: #区間が完全に含まれる場合自分
return tree[k]
c1 = RMQ_query(a,b,2*k+1,l,(l+r)//2,tree)
c2 = RMQ_query(a,b,2*k+2,(l+r)//2,r,tree)
return min(c1,c2)
import sys
from collections import deque
N = int(input())
w = []
app = [0] * N
vtoc = [ [] for i in range(N)]
for loop in range(N-1):
cw = list(map(int,input().split()))
for i in range(1,cw[0]+1):
cw[i] -= 1
app[cw[i]] += 1
vtoc[cw[i]].append(loop)
w.append(cw[1:])
newv = [None] * (N-1)
tree = make_ST(N,(float("inf"),float("inf")))
for i in range(1,N):
RMQ_update_point((app[i],i),i,tree)
for i in range(N-1):
nmin,minind = RMQ_query(0,N,0,0,(len(tree)+1)//2,tree)
for c in vtoc[minind]:
if newv[c] == None:
newv[c] = minind
for tmpv in w[c]:
if tmpv != 0:
tmpmin,minind2 = tree[(len(tree) - 1) // 2 + tmpv]
RMQ_update_point((tmpmin-1,minind2),minind2,tree)
RMQ_update_point((float("inf"),minind),minind,tree)
break
else:
#print (newv)
print (-1)
sys.exit()
#ansにそれぞれの集合からどれを取るかを入れればいい
#print (newv)
end = [False] * N
q = deque([0])
ans = [None] * (N-1)
while len(q) > 0:
nv = q.popleft()
for c in vtoc[nv]:
if not end[newv[c]]:
ans[c] = (nv+1,newv[c]+1)
end[newv[c]] = True
q.append(newv[c])
if None not in ans:
for i in ans:
print (*i)
else:
print (-1)
"""
``` | instruction | 0 | 90,774 | 13 | 181,548 |
No | output | 1 | 90,774 | 13 | 181,549 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given N-1 subsets of \\{1,2,...,N\\}. Let the i-th set be E_i.
Let us choose two distinct elements u_i and v_i from each set E_i, and consider a graph T with N vertices and N-1 edges, whose vertex set is \\{1,2,..,N\\} and whose edge set is (u_1,v_1),(u_2,v_2),...,(u_{N-1},v_{N-1}). Determine if T can be a tree by properly deciding u_i and v_i. If it can, additionally find one instance of (u_1,v_1),(u_2,v_2),...,(u_{N-1},v_{N-1}) such that T is actually a tree.
Constraints
* 2 \leq N \leq 10^5
* E_i is a subset of \\{1,2,..,N\\}.
* |E_i| \geq 2
* The sum of |E_i| is at most 2 \times 10^5.
Input
Input is given from Standard Input in the following format:
N
c_1 w_{1,1} w_{1,2} ... w_{1,c_1}
:
c_{N-1} w_{N-1,1} w_{N-1,2} ... w_{N-1,c_{N-1}}
Here, c_i stands for the number of elements in E_i, and w_{i,1},...,w_{i,c_i} are the c_i elements in c_i. Here, 2 \leq c_i \leq N, 1 \leq w_{i,j} \leq N, and w_{i,j} \neq w_{i,k} (1 \leq j < k \leq c_i) hold.
Output
If T cannot be a tree, print `-1`; otherwise, print the choices of (u_i,v_i) that satisfy the condition, in the following format:
u_1 v_1
:
u_{N-1} v_{N-1}
Output
If T cannot be a tree, print `-1`; otherwise, print the choices of (u_i,v_i) that satisfy the condition, in the following format:
u_1 v_1
:
u_{N-1} v_{N-1}
Examples
Input
5
2 1 2
3 1 2 3
3 3 4 5
2 4 5
Output
1 2
1 3
3 4
4 5
Input
6
3 1 2 3
3 2 3 4
3 1 3 4
3 1 2 4
3 4 5 6
Output
-1
Input
10
5 1 2 3 4 5
5 2 3 4 5 6
5 3 4 5 6 7
5 4 5 6 7 8
5 5 6 7 8 9
5 6 7 8 9 10
5 7 8 9 10 1
5 8 9 10 1 2
5 9 10 1 2 3
Output
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
Submitted Solution:
```
"""
https://atcoder.jp/contests/agc029/tasks/agc029_f
方針:頂点1とすべてつなげたい
→1が入ってる場合、1 & ナニカを選べばいい
→そうでない場合、既に選択済み & 新規点を選べばよい
小さい集合から選択するべき論はそうかも
→むしろ登場回数が少ない頂点から選択するべき?
→登場回数が2回の頂点2つがある
→互いの選択で影響しあうのは重なってる場合
各集合で取るより1から遠い点は残りの集合の中での登場回数がすくない点から貪欲に?
→おkそう
あとはこれでループが生まれないことを証明
→おk
"""
#一転更新区間取得のセグ木とRMQである(最大取得したいなら負で突っ込めばおk?)
#query区間左,右は実際に求めたい区間(半開区間なので右は+1しておくこと)
#注目ノード番号は0でOK
#担当範囲左,担当範囲右 は、それぞれ 0 , (len(セグ木)+1)//2 にしておくこと
def make_ST(n,first): #firstで初期化された、葉がn要素を超えるように2のべき乗個用意されたリストを返す
i = 0
ret = []
while 2 ** (i-1) < n:
for j in range(2 ** i):
ret.append(first)
i += 1
return ret
def RMQ_update_point(num,point,tree): #葉のindex(0-origin)がpointの要素をnumにする/treeはセグ木
i = (len(tree) - 1) // 2 + point
tree[i] = num
while i > 0:
i = (i - 1) // 2
tree[i] = min(tree[i * 2 + 2] , tree[i * 2 + 1])
return
def RMQ_query(a,b,k,l,r,tree): #query区間左,右,注目ノード番号,担当範囲左,担当範囲右,木
if r <= a or b <= l: #区間が完全にかぶらない場合inf
return ( float("inf") , float("inf") )
if a <= l and r <= b: #区間が完全に含まれる場合自分
return tree[k]
c1 = RMQ_query(a,b,2*k+1,l,(l+r)//2,tree)
c2 = RMQ_query(a,b,2*k+2,(l+r)//2,r,tree)
return min(c1,c2)
import sys
from collections import deque
N = int(input())
w = []
app = [0] * N
vtoc = [ [] for i in range(N)]
for loop in range(N-1):
cw = list(map(int,input().split()))
for i in range(1,cw[0]+1):
cw[i] -= 1
app[cw[i]] += 1
vtoc[cw[i]].append(loop)
w.append(cw[1:])
newv = [None] * (N-1)
tree = make_ST(N,(float("inf"),float("inf")))
for i in range(1,N):
RMQ_update_point((app[i],i),i,tree)
for i in range(N-1):
nmin,minind = RMQ_query(0,N,0,0,(len(tree)+1)//2,tree)
for c in vtoc[minind]:
if newv[c] == None:
newv[c] = minind
for tmpv in w[c]:
if tmpv != 0:
tmpmin,minind2 = tree[(len(tree) - 1) // 2 + tmpv]
RMQ_update_point((tmpmin-1,minind2),minind2,tree)
RMQ_update_point((float("inf"),minind),minind,tree)
break
else:
#print (newv)
print (-1)
sys.exit()
#print (newv)
end = [False] * N
q = deque([0])
ans = [None] * (N-1)
while len(q) > 0:
nv = q.popleft()
for c in vtoc[nv]:
if not end[newv[c]]:
ans[c] = (nv+1,newv[c]+1)
end[newv[c]] = True
q.append(newv[c])
if None not in ans:
for i in ans:
print (*i)
else:
print (-1)
``` | instruction | 0 | 90,775 | 13 | 181,550 |
No | output | 1 | 90,775 | 13 | 181,551 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given N-1 subsets of \\{1,2,...,N\\}. Let the i-th set be E_i.
Let us choose two distinct elements u_i and v_i from each set E_i, and consider a graph T with N vertices and N-1 edges, whose vertex set is \\{1,2,..,N\\} and whose edge set is (u_1,v_1),(u_2,v_2),...,(u_{N-1},v_{N-1}). Determine if T can be a tree by properly deciding u_i and v_i. If it can, additionally find one instance of (u_1,v_1),(u_2,v_2),...,(u_{N-1},v_{N-1}) such that T is actually a tree.
Constraints
* 2 \leq N \leq 10^5
* E_i is a subset of \\{1,2,..,N\\}.
* |E_i| \geq 2
* The sum of |E_i| is at most 2 \times 10^5.
Input
Input is given from Standard Input in the following format:
N
c_1 w_{1,1} w_{1,2} ... w_{1,c_1}
:
c_{N-1} w_{N-1,1} w_{N-1,2} ... w_{N-1,c_{N-1}}
Here, c_i stands for the number of elements in E_i, and w_{i,1},...,w_{i,c_i} are the c_i elements in c_i. Here, 2 \leq c_i \leq N, 1 \leq w_{i,j} \leq N, and w_{i,j} \neq w_{i,k} (1 \leq j < k \leq c_i) hold.
Output
If T cannot be a tree, print `-1`; otherwise, print the choices of (u_i,v_i) that satisfy the condition, in the following format:
u_1 v_1
:
u_{N-1} v_{N-1}
Output
If T cannot be a tree, print `-1`; otherwise, print the choices of (u_i,v_i) that satisfy the condition, in the following format:
u_1 v_1
:
u_{N-1} v_{N-1}
Examples
Input
5
2 1 2
3 1 2 3
3 3 4 5
2 4 5
Output
1 2
1 3
3 4
4 5
Input
6
3 1 2 3
3 2 3 4
3 1 3 4
3 1 2 4
3 4 5 6
Output
-1
Input
10
5 1 2 3 4 5
5 2 3 4 5 6
5 3 4 5 6 7
5 4 5 6 7 8
5 5 6 7 8 9
5 6 7 8 9 10
5 7 8 9 10 1
5 8 9 10 1 2
5 9 10 1 2 3
Output
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
Submitted Solution:
```
"""
https://atcoder.jp/contests/agc029/tasks/agc029_f
方針:頂点1とすべてつなげたい
→1が入ってる場合、1 & ナニカを選べばいい
→そうでない場合、既に選択済み & 新規点を選べばよい
小さい集合から選択するべき論はそうかも
→むしろ登場回数が少ない頂点から選択するべき?
→登場回数が2回の頂点2つがある
→互いの選択で影響しあうのは重なってる場合
各集合で取るより1から遠い点は残りの集合の中での登場回数がすくない点から貪欲に?
→おkそう
あとはこれでループが生まれないことを証明
→おk
まずいのは、選択によって不可能集合を作ってしまうこと
=====再挑戦=====
方針は、1が入ってるやつは 1&ナニカを選ぶ
それ以外は新規を選ぶ
→マッチング
→dinicなら高速に行ける
"""
from collections import defaultdict
from collections import deque
def Dinic_DFS(v,g,maxflow,lines,cost,level):
if v == g:
return maxflow
realflow = 0
tmp = [i for i in lines[v]]
for nex in tmp:
if level[nex] > level[v]:
plusflow = Dinic_DFS(nex,g,min(maxflow , cost[v][nex]),lines,cost,level)
cost[v][nex] -= plusflow
if cost[v][nex] == 0:
lines[v].remove(nex)
if cost[nex][v] == 0:
lines[nex].add(v)
cost[nex][v] += plusflow
realflow += plusflow
maxflow -= plusflow
if maxflow <= 0:
return realflow
return realflow
def Dinic(s,g,lines,cost):
N = len(cost)
ans = 0
while True:
#bfs
q = deque([s])
level = [float("inf")] * N
level[s] = 0
while q:
now = q.popleft()
#print (now)
for nex in lines[now]:
if level[nex] > level[now] + 1:
level[nex] = level[now] + 1
q.append(nex)
if level[g] == float("inf"):
return ans
#dfs
delta_flow = Dinic_DFS(s,g,float("inf"),lines,cost,level)
while delta_flow > 0:
ans += delta_flow
delta_flow = Dinic_DFS(s,g,float("inf"),lines,cost,level)
import sys
from sys import stdin
N = int(stdin.readline())
w = []
vtoc = [ [] for i in range(N)] #頂点から属す集合を逆引き
for loop in range(N-1):
cw = list(map(int,input().split()))
for i in range(1,cw[0]+1):
cw[i] -= 1
vtoc[cw[i]].append(loop)
w.append(cw[1:])
#二部マッチングを求める 集合N-1個と数字N-1個をマッチング
#フロー始点を0,終点をNにしよう
lines = defaultdict(set)
cost = [ defaultdict(int) for i in range(2*N) ]
for i in range(1,N):
lines[0].add(i)
cost[0][i] = 1
for i in range(N+1,2*N):
lines[i].add(N)
cost[i][N] = 1
for i in range(N-1):
for j in w[i]:
if j != 0:
lines[i+1].add(N + j)
cost[i+1][N + j] = 1
flow = Dinic(0,N,lines,cost)
if flow != N-1:
print (-1)
sys.exit()
newv = [None] * (N-1)
for i in range(N-1):
for j in w[i]:
if j != 0 and cost[i+1][N + j] == 0:
newv[i] = j
break
end = [False] * N
q = deque([0])
ans = [None] * (N-1)
while len(q) > 0:
nv = q.popleft()
for c in vtoc[nv]:
if not end[newv[c]]:
ans[c] = (nv+1,newv[c]+1)
end[newv[c]] = True
q.append(newv[c])
if None not in ans:
for i in ans:
print (*i)
else:
print (-1)
"""
#一転更新区間取得のセグ木とRMQである(最大取得したいなら負で突っ込めばおk?)
#query区間左,右は実際に求めたい区間(半開区間なので右は+1しておくこと)
#注目ノード番号は0でOK
#担当範囲左,担当範囲右 は、それぞれ 0 , (len(セグ木)+1)//2 にしておくこと
def make_ST(n,first): #firstで初期化された、葉がn要素を超えるように2のべき乗個用意されたリストを返す
i = 0
ret = []
while 2 ** (i-1) < n:
for j in range(2 ** i):
ret.append(first)
i += 1
return ret
def RMQ_update_point(num,point,tree): #葉のindex(0-origin)がpointの要素をnumにする/treeはセグ木
i = (len(tree) - 1) // 2 + point
tree[i] = num
while i > 0:
i = (i - 1) // 2
tree[i] = min(tree[i * 2 + 2] , tree[i * 2 + 1])
return
def RMQ_query(a,b,k,l,r,tree): #query区間左,右,注目ノード番号,担当範囲左,担当範囲右,木
if r <= a or b <= l: #区間が完全にかぶらない場合inf
return ( float("inf") , float("inf") )
if a <= l and r <= b: #区間が完全に含まれる場合自分
return tree[k]
c1 = RMQ_query(a,b,2*k+1,l,(l+r)//2,tree)
c2 = RMQ_query(a,b,2*k+2,(l+r)//2,r,tree)
return min(c1,c2)
import sys
from collections import deque
N = int(input())
w = []
app = [0] * N
vtoc = [ [] for i in range(N)]
for loop in range(N-1):
cw = list(map(int,input().split()))
for i in range(1,cw[0]+1):
cw[i] -= 1
app[cw[i]] += 1
vtoc[cw[i]].append(loop)
w.append(cw[1:])
newv = [None] * (N-1)
tree = make_ST(N,(float("inf"),float("inf")))
for i in range(1,N):
RMQ_update_point((app[i],i),i,tree)
for i in range(N-1):
nmin,minind = RMQ_query(0,N,0,0,(len(tree)+1)//2,tree)
for c in vtoc[minind]:
if newv[c] == None:
newv[c] = minind
for tmpv in w[c]:
if tmpv != 0:
tmpmin,minind2 = tree[(len(tree) - 1) // 2 + tmpv]
RMQ_update_point((tmpmin-1,minind2),minind2,tree)
RMQ_update_point((float("inf"),minind),minind,tree)
break
else:
#print (newv)
print (-1)
sys.exit()
#ansにそれぞれの集合からどれを取るかを入れればいい
#print (newv)
end = [False] * N
q = deque([0])
ans = [None] * (N-1)
while len(q) > 0:
nv = q.popleft()
for c in vtoc[nv]:
if not end[newv[c]]:
ans[c] = (nv+1,newv[c]+1)
end[newv[c]] = True
q.append(newv[c])
if None not in ans:
for i in ans:
print (*i)
else:
print (-1)
"""
``` | instruction | 0 | 90,776 | 13 | 181,552 |
No | output | 1 | 90,776 | 13 | 181,553 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given N-1 subsets of \\{1,2,...,N\\}. Let the i-th set be E_i.
Let us choose two distinct elements u_i and v_i from each set E_i, and consider a graph T with N vertices and N-1 edges, whose vertex set is \\{1,2,..,N\\} and whose edge set is (u_1,v_1),(u_2,v_2),...,(u_{N-1},v_{N-1}). Determine if T can be a tree by properly deciding u_i and v_i. If it can, additionally find one instance of (u_1,v_1),(u_2,v_2),...,(u_{N-1},v_{N-1}) such that T is actually a tree.
Constraints
* 2 \leq N \leq 10^5
* E_i is a subset of \\{1,2,..,N\\}.
* |E_i| \geq 2
* The sum of |E_i| is at most 2 \times 10^5.
Input
Input is given from Standard Input in the following format:
N
c_1 w_{1,1} w_{1,2} ... w_{1,c_1}
:
c_{N-1} w_{N-1,1} w_{N-1,2} ... w_{N-1,c_{N-1}}
Here, c_i stands for the number of elements in E_i, and w_{i,1},...,w_{i,c_i} are the c_i elements in c_i. Here, 2 \leq c_i \leq N, 1 \leq w_{i,j} \leq N, and w_{i,j} \neq w_{i,k} (1 \leq j < k \leq c_i) hold.
Output
If T cannot be a tree, print `-1`; otherwise, print the choices of (u_i,v_i) that satisfy the condition, in the following format:
u_1 v_1
:
u_{N-1} v_{N-1}
Output
If T cannot be a tree, print `-1`; otherwise, print the choices of (u_i,v_i) that satisfy the condition, in the following format:
u_1 v_1
:
u_{N-1} v_{N-1}
Examples
Input
5
2 1 2
3 1 2 3
3 3 4 5
2 4 5
Output
1 2
1 3
3 4
4 5
Input
6
3 1 2 3
3 2 3 4
3 1 3 4
3 1 2 4
3 4 5 6
Output
-1
Input
10
5 1 2 3 4 5
5 2 3 4 5 6
5 3 4 5 6 7
5 4 5 6 7 8
5 5 6 7 8 9
5 6 7 8 9 10
5 7 8 9 10 1
5 8 9 10 1 2
5 9 10 1 2 3
Output
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
Submitted Solution:
```
"""
https://atcoder.jp/contests/agc029/tasks/agc029_f
方針:頂点1とすべてつなげたい
→1が入ってる場合、1 & ナニカを選べばいい
→そうでない場合、既に選択済み & 新規点を選べばよい
小さい集合から選択するべき論はそうかも
→むしろ登場回数が少ない頂点から選択するべき?
→登場回数が2回の頂点2つがある
→互いの選択で影響しあうのは重なってる場合
各集合で取るより1から遠い点は残りの集合の中での登場回数がすくない点から貪欲に?
→おkそう
あとはこれでループが生まれないことを証明
→おk
まずいのは、選択によって不可能集合を作ってしまうこと
=====再挑戦=====
方針は、1が入ってるやつは 1&ナニカを選ぶ
それ以外は新規を選ぶ
→マッチング
→dinicなら高速に行ける
"""
from collections import defaultdict
from collections import deque
def Ford_Fulkerson_Func(s,g,lines,cost):
N = len(cost)
ans = 0
queue = deque([ [s,float("inf")] ])
ed = [True] * N
ed[s] = False
route = [0] * N
route[s] = -1
while queue:
now,flow = queue.pop()
for nex in lines[now]:
if ed[nex]:
flow = min(cost[now][nex],flow)
route[nex] = now
queue.append([nex,flow])
ed[nex] = False
if nex == g:
ans += flow
break
else:
continue
break
else:
return False,ans
t = g
s = route[t]
while s != -1:
cost[s][t] -= flow
if cost[s][t] == 0:
lines[s].remove(t)
if cost[t][s] == 0:
lines[t].add(s)
cost[t][s] += flow
t = s
s = route[t]
return True,ans
def Ford_Fulkerson(s,g,lines,cost):
ans = 0
while True:
fl,nans = Ford_Fulkerson_Func(s,g,lines,cost)
if fl:
ans += nans
continue
else:
break
return ans
import sys
from sys import stdin
N = int(stdin.readline())
w = []
vtoc = [ [] for i in range(N)] #頂点から属す集合を逆引き
for loop in range(N-1):
cw = list(map(int,input().split()))
for i in range(1,cw[0]+1):
cw[i] -= 1
vtoc[cw[i]].append(loop)
w.append(cw[1:])
#二部マッチングを求める 集合N-1個と数字N-1個をマッチング
#フロー始点を0,終点をNにしよう
lines = defaultdict(set)
cost = [ defaultdict(int) for i in range(2*N) ]
for i in range(1,N):
lines[0].add(i)
cost[0][i] = 1
for i in range(N+1,2*N):
lines[i].add(N)
cost[i][N] = 1
for i in range(N-1):
for j in w[i]:
if j != 0:
lines[i+1].add(N + j)
cost[i+1][N + j] = 1
flow = Ford_Fulkerson(0,N,lines,cost)
if flow != N-1:
print (-1)
sys.exit()
newv = [None] * (N-1)
for i in range(N-1):
for j in w[i]:
if j != 0 and cost[i+1][N + j] == 0:
newv[i] = j
break
end = [False] * N
q = deque([0])
ans = [None] * (N-1)
while len(q) > 0:
nv = q.popleft()
for c in vtoc[nv]:
if not end[newv[c]]:
ans[c] = (nv+1,newv[c]+1)
end[newv[c]] = True
q.append(newv[c])
if None not in ans:
for i in ans:
print (*i)
else:
print (-1)
"""
#一転更新区間取得のセグ木とRMQである(最大取得したいなら負で突っ込めばおk?)
#query区間左,右は実際に求めたい区間(半開区間なので右は+1しておくこと)
#注目ノード番号は0でOK
#担当範囲左,担当範囲右 は、それぞれ 0 , (len(セグ木)+1)//2 にしておくこと
def make_ST(n,first): #firstで初期化された、葉がn要素を超えるように2のべき乗個用意されたリストを返す
i = 0
ret = []
while 2 ** (i-1) < n:
for j in range(2 ** i):
ret.append(first)
i += 1
return ret
def RMQ_update_point(num,point,tree): #葉のindex(0-origin)がpointの要素をnumにする/treeはセグ木
i = (len(tree) - 1) // 2 + point
tree[i] = num
while i > 0:
i = (i - 1) // 2
tree[i] = min(tree[i * 2 + 2] , tree[i * 2 + 1])
return
def RMQ_query(a,b,k,l,r,tree): #query区間左,右,注目ノード番号,担当範囲左,担当範囲右,木
if r <= a or b <= l: #区間が完全にかぶらない場合inf
return ( float("inf") , float("inf") )
if a <= l and r <= b: #区間が完全に含まれる場合自分
return tree[k]
c1 = RMQ_query(a,b,2*k+1,l,(l+r)//2,tree)
c2 = RMQ_query(a,b,2*k+2,(l+r)//2,r,tree)
return min(c1,c2)
import sys
from collections import deque
N = int(input())
w = []
app = [0] * N
vtoc = [ [] for i in range(N)]
for loop in range(N-1):
cw = list(map(int,input().split()))
for i in range(1,cw[0]+1):
cw[i] -= 1
app[cw[i]] += 1
vtoc[cw[i]].append(loop)
w.append(cw[1:])
newv = [None] * (N-1)
tree = make_ST(N,(float("inf"),float("inf")))
for i in range(1,N):
RMQ_update_point((app[i],i),i,tree)
for i in range(N-1):
nmin,minind = RMQ_query(0,N,0,0,(len(tree)+1)//2,tree)
for c in vtoc[minind]:
if newv[c] == None:
newv[c] = minind
for tmpv in w[c]:
if tmpv != 0:
tmpmin,minind2 = tree[(len(tree) - 1) // 2 + tmpv]
RMQ_update_point((tmpmin-1,minind2),minind2,tree)
RMQ_update_point((float("inf"),minind),minind,tree)
break
else:
#print (newv)
print (-1)
sys.exit()
#ansにそれぞれの集合からどれを取るかを入れればいい
#print (newv)
end = [False] * N
q = deque([0])
ans = [None] * (N-1)
while len(q) > 0:
nv = q.popleft()
for c in vtoc[nv]:
if not end[newv[c]]:
ans[c] = (nv+1,newv[c]+1)
end[newv[c]] = True
q.append(newv[c])
if None not in ans:
for i in ans:
print (*i)
else:
print (-1)
"""
``` | instruction | 0 | 90,777 | 13 | 181,554 |
No | output | 1 | 90,777 | 13 | 181,555 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Once, during a lesson, Sasha got bored and decided to talk with his friends. Suddenly, he saw Kefa. Since we can talk endlessly about Kefa, we won't even start doing that. The conversation turned to graphs. Kefa promised Sasha to tell him about one interesting fact from graph theory if Sasha helps Kefa to count the number of beautiful trees.
In this task, a tree is a weighted connected graph, consisting of n vertices and n-1 edges, and weights of edges are integers from 1 to m. Kefa determines the beauty of a tree as follows: he finds in the tree his two favorite vertices — vertices with numbers a and b, and counts the distance between them. The distance between two vertices x and y is the sum of weights of edges on the simple path from x to y. If the distance between two vertices a and b is equal to m, then the tree is beautiful.
Sasha likes graph theory, and even more, Sasha likes interesting facts, that's why he agreed to help Kefa. Luckily, Sasha is familiar with you the best programmer in Byteland. Help Sasha to count the number of beautiful trees for Kefa. Two trees are considered to be distinct if there is an edge that occurs in one of them and doesn't occur in the other one. Edge's weight matters.
Kefa warned Sasha, that there can be too many beautiful trees, so it will be enough to count the number modulo 10^9 + 7.
Input
The first line contains four integers n, m, a, b (2 ≤ n ≤ 10^6, 1 ≤ m ≤ 10^6, 1 ≤ a, b ≤ n, a ≠ b) — the number of vertices in the tree, the maximum weight of an edge and two Kefa's favorite vertices.
Output
Print one integer — the number of beautiful trees modulo 10^9+7.
Examples
Input
3 2 1 3
Output
5
Input
3 1 1 2
Output
2
Input
5 15 1 5
Output
345444
Note
There are 5 beautiful trees in the first example:
<image>
In the second example the following trees are beautiful:
<image>
Submitted Solution:
```
from itertools import accumulate
MOD = int(1e9 + 7)
def invmod(x):
return pow(x, MOD - 2, MOD)
def main():
n, m, *_ = map(int, input().split())
mulmod = lambda x, y: x * y % MOD
factorials = [1] + list(accumulate(range(1, max(n, m) + 1), mulmod))
def lower_factorial(a, b):
return factorials[a] * invmod(factorials[a - b]) % MOD
def nCk(n, k):
return lower_factorial(n, k) * invmod(factorials[k]) % MOD
def F(x, y):
return y * (pow(x, x - y - 1)) % MOD if x - y - 1 >= 0 else 1
result = 0
for d in range(1, min(m + 1, n)):
result += (lower_factorial(n - 2, d - 1) * nCk(m - 1, d - 1)
* pow(m, n - d - 1, MOD) * F(n, d + 1)) % MOD
print(result)
if __name__ == "__main__":
main()
``` | instruction | 0 | 90,967 | 13 | 181,934 |
No | output | 1 | 90,967 | 13 | 181,935 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob are playing a fun game of tree tag.
The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.
Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.
If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.
Determine the winner if both players play optimally.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively.
The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, output a single line containing the winner of the game: "Alice" or "Bob".
Example
Input
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
Output
Alice
Bob
Alice
Alice
Note
In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move.
<image>
In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice.
<image> | instruction | 0 | 91,114 | 13 | 182,228 |
Tags: dfs and similar, dp, games, trees
Correct Solution:
```
import os,io
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def distance(graph,u,v):
visited = {i: True for i in graph}
stack = [(u,0)]
rp = 0
while stack:
node,p = stack.pop()
if node == v:
rp = p
break
if visited[node]:
visited[node]=False
for i in graph[node]:
if visited[i]:
stack.append((i,p+1))
return rp
def diameter(graph,root):
visited = {i:True for i in graph}
def inner(visited,root):
diam = 0
hl = []
if visited[root]:
visited[root] = False
for i in graph[root]:
if visited[i]:
h,diam1 = inner(visited,i)
hl.append(h)
diam = max(diam,diam1)
hl.extend([0,0])
h1,h2 = sorted(hl,reverse=True)[:2]
return max(h1,h2)+1,max(diam,h1+h2+1)
_,diam = inner(visited,root)
return diam
cases = int(input())
for t in range(cases):
n,a,b,da,db = list(map(int,input().split()))
if db <= 2*da:
for i in range(n-1):
_ = input()
print("Alice")
else:
graph = {i+1:[] for i in range(n)}
for i in range(n-1):
u,v = list(map(int,input().split()))
graph[u].append(v)
graph[v].append(u)
ab = distance(graph,a,b)
if ab <= da:
print("Alice")
else:
diam = diameter(graph,1)
if da >= diam//2:
print("Alice")
else:
print("Bob")
``` | output | 1 | 91,114 | 13 | 182,229 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob are playing a fun game of tree tag.
The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.
Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.
If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.
Determine the winner if both players play optimally.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively.
The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, output a single line containing the winner of the game: "Alice" or "Bob".
Example
Input
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
Output
Alice
Bob
Alice
Alice
Note
In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move.
<image>
In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice.
<image> | instruction | 0 | 91,115 | 13 | 182,230 |
Tags: dfs and similar, dp, games, trees
Correct Solution:
```
from sys import stdin
for _ in range(int(input())):
n,a,b,da,db=map(int,input().split())
a-=1
b-=1
go=[[] for _ in range(n)]
for _ in range(n-1):
x,y=map(int,stdin.readline().split())
x-=1
y-=1
go[x].append(y)
go[y].append(x)
MAX=0
re=[[] for _ in range(n)]
q=[(a,0,-1)]
go[a].append(-1)
while q!=[]:
node,level,pre=q[-1]
if node==b:
dis=level
if len(re[node])==len(go[node])-1:
re[node].extend([0,0])
re[node].sort()
MAX=max(MAX,re[node][-1]+re[node][-2])
re[pre].append(re[node][-1]+1)
q.pop()
continue
for x in go[node]:
if x!=pre:
q.append([x,level+1,node])
if dis<=da or da*2>=db or da*2>=MAX:
print('Alice')
else:
print('Bob')
``` | output | 1 | 91,115 | 13 | 182,231 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob are playing a fun game of tree tag.
The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.
Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.
If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.
Determine the winner if both players play optimally.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively.
The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, output a single line containing the winner of the game: "Alice" or "Bob".
Example
Input
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
Output
Alice
Bob
Alice
Alice
Note
In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move.
<image>
In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice.
<image> | instruction | 0 | 91,116 | 13 | 182,232 |
Tags: dfs and similar, dp, games, trees
Correct Solution:
```
# -*- coding: utf-8 -*-
# import bisect
# import heapq
# import math
# import random
# from collections import Counter, defaultdict, deque
# from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
# from fractions import Fraction
# from functools import lru_cache, reduce
# from itertools import combinations, combinations_with_replacement, product, permutations, accumulate
# from operator import add, mul, sub, itemgetter, attrgetter
import sys
# sys.setrecursionlimit(10**6)
# readline = sys.stdin.buffer.readline
readline = sys.stdin.readline
INF = 2**62-1
def read_int():
return int(readline())
def read_int_n():
return list(map(int, readline().split()))
def read_float():
return float(readline())
def read_float_n():
return list(map(float, readline().split()))
def read_str():
return readline().strip()
def read_str_n():
return readline().strip().split()
def error_print(*args):
print(*args, file=sys.stderr)
def mt(f):
import time
def wrap(*args, **kwargs):
s = time.perf_counter()
ret = f(*args, **kwargs)
e = time.perf_counter()
error_print(e - s, 'sec')
return ret
return wrap
from collections import defaultdict
from functools import reduce
@mt
def slv(N, A, B, DA, DB, UV):
if 2*DA >= DB:
return 'Alice'
g = defaultdict(list)
for u, v in UV:
g[u].append(v)
g[v].append(u)
def dfs(u):
d = {u: 0}
s = [u]
while s:
u = s.pop()
for v in g[u]:
if v in d:
continue
d[v] = d[u] + 1
s.append(v)
return d
d = dfs(A)
if d[B] <= DA:
return 'Alice'
mv = reduce(lambda m, i: max(m, (d[i], i)), range(1, N+1), (-INF, -1))
# print(mv)
d = dfs(mv[1])
diam = max(d.values())
# print(diam)
if 2*DA >= diam:
return 'Alice'
return 'Bob'
def main():
for _ in range(read_int()):
N, A, B, DA, DB = read_int_n()
UV = [read_int_n() for _ in range(N-1)]
print(slv(N, A, B, DA, DB, UV))
if __name__ == '__main__':
main()
``` | output | 1 | 91,116 | 13 | 182,233 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob are playing a fun game of tree tag.
The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.
Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.
If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.
Determine the winner if both players play optimally.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively.
The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, output a single line containing the winner of the game: "Alice" or "Bob".
Example
Input
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
Output
Alice
Bob
Alice
Alice
Note
In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move.
<image>
In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice.
<image> | instruction | 0 | 91,117 | 13 | 182,234 |
Tags: dfs and similar, dp, games, trees
Correct Solution:
```
import os, sys
from io import IOBase, BytesIO
py2 = round(0.5)
if py2:
from future_builtins import ascii, filter, hex, map, oct, zip
range = xrange
BUFSIZE = 8192
class FastIO(BytesIO):
newlines = 0
def __init__(self, file):
self._file = file
self._fd = file.fileno()
self.writable = "x" in file.mode or "w" in file.mode
self.write = super(FastIO, self).write if self.writable else None
def _fill(self):
s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0])
return s
def read(self):
while self._fill(): pass
return super(FastIO,self).read()
def readline(self):
while self.newlines == 0:
s = self._fill(); self.newlines = s.count(b"\n") + (not s)
self.newlines -= 1
return super(FastIO, self).readline()
def flush(self):
if self.writable:
os.write(self._fd, self.getvalue())
self.truncate(0), self.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
if py2:
self.write = self.buffer.write
self.read = self.buffer.read
self.readline = self.buffer.readline
else:
self.write = lambda s:self.buffer.write(s.encode('ascii'))
self.read = lambda:self.buffer.read().decode('ascii')
self.readline = lambda:self.buffer.readline().decode('ascii')
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')
# Cout implemented in Python
import sys
class ostream:
def __lshift__(self,a):
sys.stdout.write(str(a))
return self
cout = ostream()
endl = '\n'
def dfs(i):
q=[i]
pa=[-1 for i in range(n)]
de=[0 for i in range(n)]
while q:
x=q.pop()
for y in tr[x]:
if y==pa[x]:continue
pa[y]=x
de[y]=de[x]+1
q.append(y)
return(de)
for _ in range(int(input())):
n,a,b,da,db=map(int,input().split())
a-=1;b-=1
tr=[[] for i in range(n)]
for i in range(n-1):
u,v=map(int,input().split())
u-=1;v-=1
tr[u].append(v)
tr[v].append(u)
bbb=dfs(a);dist=bbb[b]
ci=bbb.index(max(bbb))
dimr=max(dfs(ci))
if dist<=da:
print("Alice")
elif 2*da>=dimr:
print("Alice")
elif db<=2*da:
print("Alice")
else:
print("Bob")
``` | output | 1 | 91,117 | 13 | 182,235 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob are playing a fun game of tree tag.
The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.
Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.
If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.
Determine the winner if both players play optimally.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively.
The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, output a single line containing the winner of the game: "Alice" or "Bob".
Example
Input
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
Output
Alice
Bob
Alice
Alice
Note
In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move.
<image>
In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice.
<image> | instruction | 0 | 91,118 | 13 | 182,236 |
Tags: dfs and similar, dp, games, trees
Correct Solution:
```
import sys
input = sys.stdin.readline
t = int(input())
for i in range(t):
n, a, b, da, db = map(int,input().split())
C = [list(map(int,input().split())) for j in range(n-1)]
for j in range(n-1):
for k in range(2):
C[j][k] -= 1
a -= 1
b -= 1
M = [[] for j in range(n)]
for j in range(n-1):
M[C[j][0]].append(C[j][1])
M[C[j][1]].append(C[j][0])
V = [-1] * n
V[a] = 0
Q = [[a, 0]]
s = 0
while len(Q) > s:
V[Q[s][0]] = Q[s][1]
for x in M[Q[s][0]]:
if V[x] == -1:
Q.append([x, Q[s][1]+1])
s += 1
mi = V.index(max(V))
# print(V,a,b)
if V[b] <= da:
print("Alice")
continue
V = [-1] * n
V[mi] = 0
Q = [[mi, 0]]
s = 0
while len(Q) > s:
V[Q[s][0]] = Q[s][1]
for x in M[Q[s][0]]:
if V[x] == -1:
Q.append([x, Q[s][1]+1])
s += 1
mi = V.index(max(V))
# print(V)
if db >= da*2 + 1 and max(V) >= da*2 + 1:
print("Bob")
else:
print("Alice")
``` | output | 1 | 91,118 | 13 | 182,237 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob are playing a fun game of tree tag.
The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.
Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.
If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.
Determine the winner if both players play optimally.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively.
The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, output a single line containing the winner of the game: "Alice" or "Bob".
Example
Input
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
Output
Alice
Bob
Alice
Alice
Note
In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move.
<image>
In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice.
<image> | instruction | 0 | 91,119 | 13 | 182,238 |
Tags: dfs and similar, dp, games, trees
Correct Solution:
```
from sys import stdin
def inp():
return stdin.buffer.readline().rstrip().decode('utf8')
def itg():
return int(stdin.buffer.readline())
def mpint():
return map(int, stdin.buffer.readline().split())
# ############################## import
from copy import deepcopy
def to_tree(graph, root=0):
"""
graph: undirected graph (adjacency list)
:return directed graph that parent -> children
"""
graph[:] = map(set, graph)
stack = [[root]]
while stack:
if not stack[-1]:
del stack[-1]
continue
vertex = stack[-1].pop()
for e in graph[vertex]:
graph[e].remove(vertex)
stack.append(list(graph[vertex]))
graph[:] = map(list, graph)
def to_graph(tree, root=0):
"""
:return undirected graph (adjacency list)
"""
tree[:] = map(set, tree)
for node1, node_set in enumerate(deepcopy(tree)):
for node2 in node_set:
tree[node2].add(node1)
tree[:] = map(list, tree)
def tree_distance(tree, u, v):
# bfs
if u == v:
return 0
graph = deepcopy(tree)
to_graph(graph)
graph[:] = map(set, graph)
curr = {u}
step = 1
while True:
nxt = set()
for node in curr:
if v in graph[node]:
return step
nxt |= graph[node]
curr = nxt
step += 1
def tree_bfs(tree, start=0, flat=False):
stack = [start]
result = []
while stack:
new_stack = []
if flat:
result.extend(stack)
else:
result.append(stack)
for node in stack:
new_stack.extend(tree[node])
stack = new_stack
return result
def tree_farthest(tree):
"""
:returns u, v, n
that u, v is the both ends of one of the longest chain
and the longest chain has n nodes
"""
# 2 times bfs
node1 = tree_bfs(tree, flat=True)[-1]
to_graph(tree)
to_tree(tree, node1)
bfs_data = tree_bfs(tree, node1)
node2 = bfs_data[-1][-1]
return node1, node2, len(bfs_data)
# ############################## main
def solve():
n, a, b, da, db = mpint()
a -= 1
b -= 1
tree = [[] for _ in range(n)]
for _ in range(n - 1):
u, v = mpint()
u -= 1
v -= 1
tree[u].append(v)
tree[v].append(u)
if db - da < 2:
return True
to_tree(tree)
if tree_distance(tree, a, b) <= da:
return True
longest = tree_farthest(tree)[2]
dis = longest >> 1
return dis <= da or db < da * 2 + 1
for __ in range(itg()):
print("Alice" if solve() else "Bob")
# Please check!
``` | output | 1 | 91,119 | 13 | 182,239 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob are playing a fun game of tree tag.
The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.
Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.
If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.
Determine the winner if both players play optimally.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively.
The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, output a single line containing the winner of the game: "Alice" or "Bob".
Example
Input
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
Output
Alice
Bob
Alice
Alice
Note
In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move.
<image>
In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice.
<image> | instruction | 0 | 91,120 | 13 | 182,240 |
Tags: dfs and similar, dp, games, trees
Correct Solution:
```
from sys import stdin
def input():
return stdin.readline().strip()
tests = int(input())
for t in range(tests):
n, a, b, da, db = list(map(int, input().split()))
edge_ls = [[] for _ in range(n+1)]
for _ in range(n-1):
e1, e2 = list(map(int, input().split()))
edge_ls[e1].append(e2)
edge_ls[e2].append(e1)
if da*2<db:
stack = [[a,0]]
visited = [False for _ in range(n+1)]
visited[a] = True
found = None
furthest_edge = None
furthest_dist = -1
# find distance between a and b start points
while stack:
curr, curr_step = stack.pop(-1)
if curr_step > furthest_dist:
furthest_dist = curr_step
furthest_edge = curr
for item in edge_ls[curr]:
if not visited[item]:
stack.append([item, curr_step+1])
visited[item] = True
if item == b:
found = curr_step+1
# find longest sinmple path length
stack = [[furthest_edge,1]]
visited = [False for _ in range(n+1)]
visited[furthest_edge] = True
furthest_dist = -1
while stack:
curr, curr_step = stack.pop(-1)
if curr_step > furthest_dist:
furthest_dist = curr_step
for item in edge_ls[curr]:
if not visited[item]:
stack.append([item, curr_step+1])
visited[item] = True
if found > da and furthest_dist >= (da*2)+2:
print('Bob')
else:
print('Alice')
else:
print('Alice')
``` | output | 1 | 91,120 | 13 | 182,241 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob are playing a fun game of tree tag.
The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.
Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.
If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.
Determine the winner if both players play optimally.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively.
The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, output a single line containing the winner of the game: "Alice" or "Bob".
Example
Input
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
Output
Alice
Bob
Alice
Alice
Note
In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move.
<image>
In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice.
<image> | instruction | 0 | 91,121 | 13 | 182,242 |
Tags: dfs and similar, dp, games, trees
Correct Solution:
```
# if da > db then Alice wins
# if dist(a, b) <= da then Alice wins
# if da+da >= db then Alice wins because Bob can't jump over Alice
# and go to some other branch of tree
# otherwise is there always an element at more than 2*da away?
# Optimizations if sync_with_stdio False
# from https://github.com/Cheran-Senthil/PyRival
import atexit
from io import StringIO
import sys
input = iter(sys.stdin.read().splitlines()).__next__
sys.stdout = StringIO()
atexit.register(lambda: sys.__stdout__.write(sys.stdout.getvalue()))
def furthest(graph, source):
S = [(source, 0)]
furthest_node = source
furthest_dist = 0
discovered = [False]*len(graph)
while S:
u, dist = S.pop()
if dist > furthest_dist:
furthest_node = u
furthest_dist = dist
if discovered[u]:
continue
discovered[u] = True
for v in graph[u]:
S.append((v, dist+1))
return furthest_node, furthest_dist
def distance(graph, source, dest):
S = [(source, 0)]
discovered = set()
while S:
u, dist = S.pop()
if u == dest:
return dist
if u in discovered:
continue
discovered.add(u)
for v in graph[u]:
S.append((v, dist+1))
t = int(input())
for _ in range(t):
n, a, b, da, db = map(int, input().split())
if da+da >= db:
for edge in range(n-1):
input()
print('Alice')
continue
graph = [[] for node in range(n)]
for edge in range(n-1):
u, v = [int(i)-1 for i in input().split()]
graph[u].append(v)
graph[v].append(u)
if distance(graph, a-1, b-1) <= da:
print('Alice')
continue
diameter = furthest(graph, furthest(graph, 0)[0])[1]
if da+da >= diameter:
print('Alice')
else:
print('Bob')
``` | output | 1 | 91,121 | 13 | 182,243 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are playing a fun game of tree tag.
The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.
Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.
If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.
Determine the winner if both players play optimally.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively.
The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, output a single line containing the winner of the game: "Alice" or "Bob".
Example
Input
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
Output
Alice
Bob
Alice
Alice
Note
In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move.
<image>
In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice.
<image>
Submitted Solution:
```
import sys
input = sys.stdin.readline
t = int(input())
for rrr in range(t):
n,a,b,da,db = list(map(int,input().split()))
a -= 1
b -= 1
if da>=db:
for _ in range(n-1):
x,y = list(map(int,input().split()))
print('Alice')
else:
N = [[] for _ in range(n)]
V = [0 for _ in range(n)]
D = [0 for _ in range(n)]
for _ in range(n-1):
x,y = list(map(int,input().split()))
x -= 1
y -= 1
N[x].append(y)
N[y].append(x)
Q = [a]
V[a] = 1
depth = 0
done = 0
while Q:
depth += 1
new_Q = []
for node in Q:
for child in N[node]:
if V[child]==0:
new_Q.append(child)
V[child]=1
if child==b:
if depth<=da:
print('Alice')
done = 1
Q = new_Q
if done==0:
V = [0 for _ in range(n)]
Q = [0]
OR = [0]
V[0] = 1
depth = 0
while Q:
new_Q = []
for node in Q:
for child in N[node]:
if V[child]==0:
new_Q.append(child)
V[child]=1
OR.append(child)
Q = new_Q
depth += 1
Q = [OR[-1]]
V = [0 for _ in range(n)]
V[OR[-1]] = 1
depth = 0
while Q:
new_Q = []
for node in Q:
for child in N[node]:
if V[child]==0:
new_Q.append(child)
V[child]=1
OR.append(child)
Q = new_Q
depth += 1
depth -= 1
if depth > 2*da and db>2*da:
print('Bob')
else:
print('Alice')
``` | instruction | 0 | 91,122 | 13 | 182,244 |
Yes | output | 1 | 91,122 | 13 | 182,245 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are playing a fun game of tree tag.
The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.
Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.
If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.
Determine the winner if both players play optimally.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively.
The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, output a single line containing the winner of the game: "Alice" or "Bob".
Example
Input
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
Output
Alice
Bob
Alice
Alice
Note
In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move.
<image>
In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice.
<image>
Submitted Solution:
```
gans = []
for _ in range(int(input())):
n, a, b, da, db = map(int, input().split())
a -= 1
b -= 1
u = []
for i in range(n):
u.append([])
for i in range(n - 1):
v1, v2 = map(lambda x: int(x) - 1, input().split())
u[v1].append(v2)
u[v2].append(v1)
ind = a
q = [ind]
q0 = 0
INF = 100000000
d = [INF] * n
d[ind] = 0
while len(q) > q0:
v = q[q0]
q0 += 1
for i in u[v]:
if d[i] > d[v] + 1:
d[i] = d[v] + 1
q.append(i)
if d[b] <= da:
gans.append('Alice')
continue
ind = -1
mx = max(d)
for i in range(n):
if d[i] == mx:
ind = i
break
q = [ind]
q0 = 0
d = [INF] * n
d[ind] = 0
while len(q) > q0:
v = q[q0]
q0 += 1
for i in u[v]:
if d[i] > d[v] + 1:
d[i] = d[v] + 1
q.append(i)
D = max(d)
#print(*d)
if db > 2 * da and 2 * da < D:
gans.append('Bob')
else:
gans.append('Alice')
print('\n'.join(gans))
``` | instruction | 0 | 91,123 | 13 | 182,246 |
Yes | output | 1 | 91,123 | 13 | 182,247 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are playing a fun game of tree tag.
The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.
Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.
If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.
Determine the winner if both players play optimally.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively.
The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, output a single line containing the winner of the game: "Alice" or "Bob".
Example
Input
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
Output
Alice
Bob
Alice
Alice
Note
In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move.
<image>
In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice.
<image>
Submitted Solution:
```
from sys import stdin, stdout
get_string = lambda: stdin.readline().strip('\n')
get_intmap = lambda: map( int, get_string().split(' ') )
def testcase():
n, a, b, da, db = get_intmap()
adj = [[] for i in range(n+1)]
for i in range(n-1):
u, v = get_intmap()
adj[u].append(v)
adj[v].append(u)
used = [ 0 ] * (n + 1)
frontier, nxt, used[a], distance = [ a ], [], 1, 0
while len(frontier):
distance += 1
for u in frontier:
for v in adj[u]:
if used[v]: continue
if v == b: distance_ab = distance
used[v] = 1
nxt.append(v)
if nxt == []: #bfs is about to end
leaf_node = frontier.pop()
frontier, nxt = nxt, []
if distance_ab <= da: print("Alice"); return
used = [ 0 ] * (n + 1)
frontier, nxt, used[leaf_node], distance = [ leaf_node ], [], 1, 0
while len(frontier):
distance += 1
for u in frontier:
for v in adj[u]:
if used[v]: continue
used[v] = 1
nxt.append(v)
if nxt == []: #bfs is about to end
tree_diameter = distance - 1
frontier, nxt = nxt, []
#print(a, leaf_node, tree_diameter,da,db)
if tree_diameter <= 2 * da: print("Alice"); return
if db <= 2 * da: print("Alice")
else: print("Bob")
#testcase();quit()
for t in range(int(input())):
testcase()
``` | instruction | 0 | 91,124 | 13 | 182,248 |
Yes | output | 1 | 91,124 | 13 | 182,249 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are playing a fun game of tree tag.
The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.
Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.
If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.
Determine the winner if both players play optimally.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively.
The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, output a single line containing the winner of the game: "Alice" or "Bob".
Example
Input
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
Output
Alice
Bob
Alice
Alice
Note
In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move.
<image>
In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice.
<image>
Submitted Solution:
```
def dfs(x,p):
l = 0
for i in graph[x]:
if i!=p:
depth[i]=depth[x]+1
cur = 1+dfs(i,x)
diam[0] = max(diam[0],cur+l)
l = max(l,cur)
return l
for _ in range (int(input())):
n,a,b,da,db = [int(i) for i in input().split()]
graph = [[] for i in range (n)]
for i in range (n-1):
uu,vv = [int(i)-1 for i in input().split()]
graph[uu].append(vv)
graph[vv].append(uu)
depth=[0]*n
diam = [0]
temp = dfs(a-1,-1)
if 2*da >= min(diam[0],db) or depth[b-1]<=da:
print('Alice')
else:
print('Bob')
``` | instruction | 0 | 91,125 | 13 | 182,250 |
Yes | output | 1 | 91,125 | 13 | 182,251 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are playing a fun game of tree tag.
The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.
Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.
If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.
Determine the winner if both players play optimally.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively.
The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, output a single line containing the winner of the game: "Alice" or "Bob".
Example
Input
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
Output
Alice
Bob
Alice
Alice
Note
In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move.
<image>
In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice.
<image>
Submitted Solution:
```
tests = int(input())
for t in range(tests):
n, a, b, da, db = list(map(int, input().split()))
edge_ls = [[] for _ in range(n+1)]
for _ in range(n-1):
e1, e2 = list(map(int, input().split()))
edge_ls[e1].append(e2)
edge_ls[e2].append(e1)
if da*2<db:
stack = [[a,0]]
visited = [False for _ in range(n+1)]
visited[a] = True
found = None
while stack and found is None:
curr, curr_step = stack.pop(-1)
for item in edge_ls[curr]:
if not visited[item]:
stack.append([item, curr_step+1])
visited[item] = True
if item == b:
found = curr_step+1
break
if found > da:
print('Bob')
else:
print('Alice')
else:
print('Alice')
``` | instruction | 0 | 91,126 | 13 | 182,252 |
No | output | 1 | 91,126 | 13 | 182,253 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are playing a fun game of tree tag.
The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.
Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.
If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.
Determine the winner if both players play optimally.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively.
The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, output a single line containing the winner of the game: "Alice" or "Bob".
Example
Input
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
Output
Alice
Bob
Alice
Alice
Note
In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move.
<image>
In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice.
<image>
Submitted Solution:
```
import sys
ii = lambda: sys.stdin.readline().strip()
idata = lambda: [int(x) for x in ii().split()]
def dfs_2(graph, ver):
visited = set()
visited.add(ver)
depth = [0] * (len(graph) + 1)
queue = [ver]
while queue:
vertex = queue.pop(0)
for i in graph[vertex]:
if i not in visited:
visited.add(i)
depth[i] = depth[vertex] + 1
queue += [i]
return depth
def solve():
n, a, b, da, db = idata()
graph = {}
for i in range(n - 1):
v, u = idata()
if not v in graph:
graph[v] = [u]
else:
graph[v] += [u]
if not u in graph:
graph[u] = [v]
else:
graph[u] += [v]
global t
if t != 105 and t > 3:
return
print(n, a, b, da, db)
q = dfs_2(graph, a)
if q[b] <= da:
print('Alice')
return
q.sort()
y = q[-1]
for i in range(len(q) - 1, 0, -1):
if q[i] == q[i - 1]:
y += q[i]
break
if y <= 2 * da:
print('Alice')
return
if db <= 2 * da:
print('Alice')
return
print('Bob')
return
for t in range(int(ii())):
solve()
``` | instruction | 0 | 91,127 | 13 | 182,254 |
No | output | 1 | 91,127 | 13 | 182,255 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are playing a fun game of tree tag.
The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.
Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.
If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.
Determine the winner if both players play optimally.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively.
The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, output a single line containing the winner of the game: "Alice" or "Bob".
Example
Input
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
Output
Alice
Bob
Alice
Alice
Note
In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move.
<image>
In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice.
<image>
Submitted Solution:
```
import sys
from collections import deque
input = sys.stdin.buffer.readline
T = int(input())
for _ in range(T):
n, a, b, da, db = map(int, input().split())
e = [[] for _ in range(n+1)]
for _ in range(n-1):
u, v = map(int, input().split())
e[u].append(v)
e[v].append(u)
par = [0]*(n+1)
q, dis, leaf = deque([a]), [0]*(n+1), []
while q:
u = q.popleft()
is_leaf = 1
for v in e[u]:
if v == par[u]: continue
q.append(v)
par[v], dis[v] = u, dis[u]+1
is_leaf = 0
if is_leaf: leaf.append(dis[u])
leaf.sort(reverse=True)
dis_ab = dis[b]
dis_mx = 0
if len(leaf) == 1: dis_mx = leaf[0]
elif len(leaf) > 1: dis_mx = leaf[0] + leaf[1]
if dis_ab <= da or min(dis_mx, db) <= 2*da:
print('Alice')
else:
print('Bob')
``` | instruction | 0 | 91,128 | 13 | 182,256 |
No | output | 1 | 91,128 | 13 | 182,257 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are playing a fun game of tree tag.
The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.
Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.
If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.
Determine the winner if both players play optimally.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively.
The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, output a single line containing the winner of the game: "Alice" or "Bob".
Example
Input
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
Output
Alice
Bob
Alice
Alice
Note
In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move.
<image>
In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice.
<image>
Submitted Solution:
```
import sys
ii = lambda: sys.stdin.readline().strip()
idata = lambda: [int(x) for x in ii().split()]
def dfs_2(graph, ver):
visited = set()
depth = [0] * (len(graph) + 1)
queue = [ver]
while queue:
vertex = queue.pop(0)
for i in graph[vertex]:
if i not in visited:
visited.add(i)
depth[i] = depth[vertex] + 1
queue += [i]
return depth
def solve():
n, a, b, da, db = idata()
graph = {}
for i in range(n - 1):
v, u = idata()
if not v in graph:
graph[v] = [u]
else:
graph[v] += [u]
if not u in graph:
graph[u] = [v]
else:
graph[u] += [v]
q = dfs_2(graph, a)
if q[b] <= da:
print('Alice')
return
q.sort()
y = q[-1]
for i in range(len(q) - 1, 0, -1):
if q[i] == q[i - 1]:
y += q[i]
break
if y <= 2 * da:
print('Alice')
return
if db <= 2 * da:
print('Alice')
return
print('Bob')
return
for t in range(int(ii())):
solve()
``` | instruction | 0 | 91,129 | 13 | 182,258 |
No | output | 1 | 91,129 | 13 | 182,259 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a weighted undirected connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Let's define the weight of the path consisting of k edges with indices e_1, e_2, ..., e_k as ∑_{i=1}^{k}{w_{e_i}} - max_{i=1}^{k}{w_{e_i}} + min_{i=1}^{k}{w_{e_i}}, where w_i — weight of the i-th edge in the graph.
Your task is to find the minimum weight of the path from the 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Input
The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices and the number of edges in the graph.
Following m lines contains three integers v_i, u_i, w_i (1 ≤ v_i, u_i ≤ n; 1 ≤ w_i ≤ 10^9; v_i ≠ u_i) — endpoints of the i-th edge and its weight respectively.
Output
Print n-1 integers — the minimum weight of the path from 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Examples
Input
5 4
5 3 4
2 1 1
3 2 2
2 4 2
Output
1 2 2 4
Input
6 8
3 1 1
3 6 2
5 4 2
4 2 2
6 1 1
5 2 1
3 2 3
1 5 4
Output
2 1 4 3 1
Input
7 10
7 5 5
2 3 3
4 7 1
5 3 6
2 7 6
6 2 6
3 7 6
4 2 1
3 1 4
1 7 4
Output
3 4 2 7 7 3 | instruction | 0 | 91,146 | 13 | 182,292 |
Tags: graphs, shortest paths
Correct Solution:
```
import io
import os
# import __pypy__
def dijkstra(*args):
return dijkstraHeap(*args)
# return dijkstraHeapComparatorWrong(*args)
# return dijkstraHeapComparator(*args)
# return dijkstraSegTree(*args)
# return dijkstraSortedList(*args)
def dijkstraHeap(source, N, getAdj):
# Heap of (dist, node)
# Use float for dist because max dist for this problem doesn't fit in 32-bit
# Then node has to be a float too, because `(float, int)` will use `W_SpecialisedTupleObject_oo` but we want `W_SpecialisedTupleObject_ff`
from heapq import heappop, heappush
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
queue = [(0.0, float(source))]
# print(__pypy__.internal_repr(queue[0])) # W_SpecialisedTupleObject_ff
# print(__pypy__.strategy(dist)) # FloatListStrategy
while queue:
d, u = heappop(queue)
u = int(u)
if dist[u] == d:
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
heappush(queue, (cost, float(v)))
return dist
def dijkstraHeapComparatorWrong(source, N, getAdj):
# Heap of nodes, sorted with a comparator
# This implementation is actually incorrect but kept for reference since it performs well when using a SPFA-like heuristic
# Note: normal SPFA will TLE since there's a uphack for it in testcase #62
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
inQueue = [0] * N
inQueue[source] = 1
queue = [source]
# print(__pypy__.strategy(queue)) # IntegerListStrategy
def cmp_lt(u, v):
return dist[u] < dist[v]
heappush, heappop, _ = import_heapq(cmp_lt)
while queue:
u = heappop(queue)
d = dist[u]
inQueue[u] = 0
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
if not inQueue[v]:
heappush(queue, v)
inQueue[v] = 1
else:
# If v is already in the queue, we were suppose to bubble it to fix heap invariant
pass
return dist
def dijkstraHeapComparator(source, N, getAdj):
# Same above, except correctly re-bubbling the key after updates
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
def cmp_lt(u, v):
return dist[u] < dist[v]
heappush, heappop, _siftdown = import_heapq(cmp_lt)
class ListWrapper:
# Exactly like a regular list except with fast .index(x) meant to be used with heapq
# Not general purpose and relies on the exact heapq implementation for correctness (swaps only, added via append, deleted via pop)
def __init__(self, maxN):
self.arr = []
self.loc = [-1] * maxN
def append(self, x):
arr = self.arr
arr.append(x)
self.loc[x] = len(arr) - 1
def pop(self):
ret = self.arr.pop()
self.loc[ret] = -1
return ret
def index(self, x):
return self.loc[x]
def __setitem__(self, i, x):
self.arr[i] = x
self.loc[x] = i
def __getitem__(self, i):
return self.arr[i]
def __len__(self):
return len(self.arr)
queue = ListWrapper(N)
queue.append(source)
# print(__pypy__.strategy(queue.arr)) # IntegerListStrategy
while queue:
u = heappop(queue)
d = dist[u]
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
heapIndex = queue.index(v)
if heapIndex == -1:
heappush(queue, v)
else:
_siftdown(queue, 0, heapIndex)
return dist
def dijkstraSegTree(start, n, getAdj):
# From pajenegod: https://github.com/cheran-senthil/PyRival/pull/55
# Modifications:
# Use floats instead of ints for inf/_min
# Fix typo: m -> self.m
# Fix python 3 compatibility: __getitem__
# Cache self.data
# Remove parent pointers
if False:
inf = -1
def _min(a, b):
return a if b == inf or inf != a < b else b
else:
inf = float("inf")
_min = min
class DistanceKeeper:
def __init__(self, n):
m = 1
while m < n:
m *= 2
self.m = m
self.data = 2 * m * [inf]
self.dist = n * [inf]
def __getitem__(self, x):
return self.dist[x]
def __setitem__(self, ind, x):
data = self.data
self.dist[ind] = x
ind += self.m
data[ind] = x
ind >>= 1
while ind:
data[ind] = _min(data[2 * ind], data[2 * ind + 1])
ind >>= 1
def trav(self):
m = self.m
data = self.data
dist = self.dist
while data[1] != inf:
x = data[1]
ind = 1
while ind < m:
ind = 2 * ind + (data[2 * ind] != x)
ind -= m
self[ind] = inf
dist[ind] = x
yield ind
# P = [-1] * n
D = DistanceKeeper(n)
D[start] = 0.0
for node in D.trav():
for nei, weight in getAdj(node):
new_dist = D[node] + weight
if D[nei] == inf or new_dist < D[nei]:
D[nei] = new_dist
# P[nei] = node
# print(__pypy__.strategy(D.dist))
# print(__pypy__.strategy(D.data))
return D.dist
def dijkstraSortedList(source, N, getAdj):
# Just for completeness
# COPY AND PASTE from https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [
values[i : i + _load] for i in range(0, _len, _load)
]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError("{0!r} not in list".format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (
value for _list in reversed(self._lists) for value in reversed(_list)
)
def __repr__(self):
"""Return string representation of sorted list."""
return "SortedList({0})".format(list(self))
# END COPY AND PASTE #####################################
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
queue = SortedList([(0.0, float(source))])
while queue:
negD, u = queue.pop(-1)
d = -negD
u = int(u)
for v, w in getAdj(u):
prevCost = dist[v]
cost = d + w
if cost < prevCost:
if prevCost != inf:
queue.discard((-prevCost, float(v)))
dist[v] = cost
queue.add((-cost, float(v)))
return dist
def import_heapq(cmp_lt):
# Python 2 has a heapq.cmp_lt but python 3 removed it
# Add it back for pypy3 submissions
import sys
if sys.version_info < (3,):
# Python 2
import heapq
from heapq import heappush, heappop, _siftdown
heapq.cmp_lt = cmp_lt
else:
# Python 3
# COPY AND PASTE python 2.7 heapq from https://github.com/python/cpython/blob/2.7/Lib/heapq.py
def heappush(heap, item):
"""Push item onto heap, maintaining the heap invariant."""
heap.append(item)
_siftdown(heap, 0, len(heap) - 1)
def heappop(heap):
"""Pop the smallest item off the heap, maintaining the heap invariant."""
lastelt = heap.pop() # raises appropriate IndexError if heap is empty
if heap:
returnitem = heap[0]
heap[0] = lastelt
_siftup(heap, 0)
return returnitem
return lastelt
def _siftdown(heap, startpos, pos):
newitem = heap[pos]
# Follow the path to the root, moving parents down until finding a place
# newitem fits.
while pos > startpos:
parentpos = (pos - 1) >> 1
parent = heap[parentpos]
if cmp_lt(newitem, parent):
heap[pos] = parent
pos = parentpos
continue
break
heap[pos] = newitem
def _siftup(heap, pos):
endpos = len(heap)
startpos = pos
newitem = heap[pos]
# Bubble up the smaller child until hitting a leaf.
childpos = 2 * pos + 1 # leftmost child position
while childpos < endpos:
# Set childpos to index of smaller child.
rightpos = childpos + 1
if rightpos < endpos and not cmp_lt(heap[childpos], heap[rightpos]):
childpos = rightpos
# Move the smaller child up.
heap[pos] = heap[childpos]
pos = childpos
childpos = 2 * pos + 1
# The leaf at pos is empty now. Put newitem there, and bubble it up
# to its final resting place (by sifting its parents down).
heap[pos] = newitem
_siftdown(heap, startpos, pos)
# END COPY AND PASTE ###############################
return heappush, heappop, _siftdown
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, M = [int(x) for x in input().split()]
graph = [[] for i in range(N)]
for i in range(M):
u, v, w = [int(x) for x in input().split()]
u -= 1
v -= 1
graph[u].append((v, w))
graph[v].append((u, w))
# Want shortest path except one edge is worth 0 and one edge is worth 2x
# Track this with 2 bits of extra state
def getAdj(node):
u = node >> 2
state = node & 3
for v, w in graph[u]:
vBase = v << 2
# Regular edge
yield vBase | state, w
if not state & 1:
# Take max edge, worth 0
yield vBase | state | 1, 0
if not state & 2:
# Take min edge, worth double
yield vBase | state | 2, 2 * w
if not state & 3:
# Take both min and max edge, worth normal
yield vBase | state | 3, w
dist = dijkstra(0, 4 * N, getAdj)
print(" ".join(str(int(dist[(u << 2) | 3])) for u in range(1, N)))
``` | output | 1 | 91,146 | 13 | 182,293 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a weighted undirected connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Let's define the weight of the path consisting of k edges with indices e_1, e_2, ..., e_k as ∑_{i=1}^{k}{w_{e_i}} - max_{i=1}^{k}{w_{e_i}} + min_{i=1}^{k}{w_{e_i}}, where w_i — weight of the i-th edge in the graph.
Your task is to find the minimum weight of the path from the 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Input
The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices and the number of edges in the graph.
Following m lines contains three integers v_i, u_i, w_i (1 ≤ v_i, u_i ≤ n; 1 ≤ w_i ≤ 10^9; v_i ≠ u_i) — endpoints of the i-th edge and its weight respectively.
Output
Print n-1 integers — the minimum weight of the path from 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Examples
Input
5 4
5 3 4
2 1 1
3 2 2
2 4 2
Output
1 2 2 4
Input
6 8
3 1 1
3 6 2
5 4 2
4 2 2
6 1 1
5 2 1
3 2 3
1 5 4
Output
2 1 4 3 1
Input
7 10
7 5 5
2 3 3
4 7 1
5 3 6
2 7 6
6 2 6
3 7 6
4 2 1
3 1 4
1 7 4
Output
3 4 2 7 7 3 | instruction | 0 | 91,147 | 13 | 182,294 |
Tags: graphs, shortest paths
Correct Solution:
```
import io
import os
# import __pypy__
def dijkstra(*args):
# return dijkstraHeap(*args)
# return dijkstraHeapComparatorWrong(*args)
# return dijkstraHeapComparator(*args)
return dijkstraSegTree(*args)
# return dijkstraSortedList(*args)
def dijkstraHeap(source, N, getAdj):
# Heap of (dist, node)
# Use float for dist because max dist for this problem doesn't fit in 32-bit
# Then node has to be a float too, because `(float, int)` will use `W_SpecialisedTupleObject_oo` but we want `W_SpecialisedTupleObject_ff`
from heapq import heappop, heappush
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
queue = [(0.0, float(source))]
# print(__pypy__.internal_repr(queue[0])) # W_SpecialisedTupleObject_ff
# print(__pypy__.strategy(dist)) # FloatListStrategy
while queue:
d, u = heappop(queue)
u = int(u)
if dist[u] == d:
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
heappush(queue, (cost, float(v)))
return dist
def dijkstraHeapComparatorWrong(source, N, getAdj):
# Heap of nodes, sorted with a comparator
# This implementation is actually incorrect but kept for reference since it performs well when using a SPFA-like heuristic
# Note: normal SPFA will TLE since there's a uphack for it in testcase #62
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
inQueue = [0] * N
inQueue[source] = 1
queue = [source]
# print(__pypy__.strategy(queue)) # IntegerListStrategy
def cmp_lt(u, v):
return dist[u] < dist[v]
heappush, heappop, _ = import_heapq(cmp_lt)
while queue:
u = heappop(queue)
d = dist[u]
inQueue[u] = 0
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
if not inQueue[v]:
heappush(queue, v)
inQueue[v] = 1
else:
# If v is already in the queue, we were suppose to bubble it to fix heap invariant
pass
return dist
def dijkstraHeapComparator(source, N, getAdj):
# Same above, except correctly re-bubbling the key after updates
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
def cmp_lt(u, v):
return dist[u] < dist[v]
heappush, heappop, _siftdown = import_heapq(cmp_lt)
class ListWrapper:
# Exactly like a regular list except with fast .index(x) meant to be used with heapq
# Not general purpose and relies on the exact heapq implementation for correctness (swaps only, added via append, deleted via pop)
def __init__(self, maxN):
self.arr = []
self.loc = [-1] * maxN
def append(self, x):
arr = self.arr
arr.append(x)
self.loc[x] = len(arr) - 1
def pop(self):
ret = self.arr.pop()
self.loc[ret] = -1
return ret
def index(self, x):
return self.loc[x]
def __setitem__(self, i, x):
self.arr[i] = x
self.loc[x] = i
def __getitem__(self, i):
return self.arr[i]
def __len__(self):
return len(self.arr)
queue = ListWrapper(N)
queue.append(source)
# print(__pypy__.strategy(queue.arr)) # IntegerListStrategy
while queue:
u = heappop(queue)
d = dist[u]
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
heapIndex = queue.index(v)
if heapIndex == -1:
heappush(queue, v)
else:
_siftdown(queue, 0, heapIndex)
return dist
def dijkstraSegTree(start, n, getAdj):
# From pajenegod: https://github.com/cheran-senthil/PyRival/pull/55
# Modifications:
# Use floats instead of ints for inf/_min
# Fix typo: m -> self.m
# Fix python 3 compatibility: __getitem__
# Cache self.data
# Remove parent pointers
if False:
inf = -1
def _min(a, b):
return a if b == inf or inf != a < b else b
else:
inf = float("inf")
_min = min
class DistanceKeeper:
def __init__(self, n):
m = 1
while m < n:
m *= 2
self.m = m
self.data = 2 * m * [inf]
self.dist = n * [inf]
def __getitem__(self, x):
return self.dist[x]
def __setitem__(self, ind, x):
data = self.data
self.dist[ind] = x
ind += self.m
data[ind] = x
ind >>= 1
while ind:
data[ind] = _min(data[2 * ind], data[2 * ind + 1])
ind >>= 1
def trav(self):
m = self.m
data = self.data
dist = self.dist
while data[1] != inf:
x = data[1]
ind = 1
while ind < m:
ind = 2 * ind + (data[2 * ind] != x)
ind -= m
self[ind] = inf
dist[ind] = x
yield ind
# P = [-1] * n
D = DistanceKeeper(n)
D[start] = 0.0
for node in D.trav():
for nei, weight in getAdj(node):
new_dist = D[node] + weight
if D[nei] == inf or new_dist < D[nei]:
D[nei] = new_dist
# P[nei] = node
# print(__pypy__.strategy(D.dist))
# print(__pypy__.strategy(D.data))
return D.dist
def dijkstraSortedList(source, N, getAdj):
# Just for completeness
# COPY AND PASTE from https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [
values[i : i + _load] for i in range(0, _len, _load)
]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError("{0!r} not in list".format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (
value for _list in reversed(self._lists) for value in reversed(_list)
)
def __repr__(self):
"""Return string representation of sorted list."""
return "SortedList({0})".format(list(self))
# END COPY AND PASTE #####################################
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
queue = SortedList([(0.0, float(source))])
while queue:
negD, u = queue.pop(-1)
d = -negD
u = int(u)
for v, w in getAdj(u):
prevCost = dist[v]
cost = d + w
if cost < prevCost:
if prevCost != inf:
queue.discard((-prevCost, float(v)))
dist[v] = cost
queue.add((-cost, float(v)))
return dist
def import_heapq(cmp_lt):
# Python 2 has a heapq.cmp_lt but python 3 removed it
# Add it back for pypy3 submissions
import sys
if sys.version_info < (3,):
# Python 2
import heapq
from heapq import heappush, heappop, _siftdown
heapq.cmp_lt = cmp_lt
else:
# Python 3
# COPY AND PASTE python 2.7 heapq from https://github.com/python/cpython/blob/2.7/Lib/heapq.py
def heappush(heap, item):
"""Push item onto heap, maintaining the heap invariant."""
heap.append(item)
_siftdown(heap, 0, len(heap) - 1)
def heappop(heap):
"""Pop the smallest item off the heap, maintaining the heap invariant."""
lastelt = heap.pop() # raises appropriate IndexError if heap is empty
if heap:
returnitem = heap[0]
heap[0] = lastelt
_siftup(heap, 0)
return returnitem
return lastelt
def _siftdown(heap, startpos, pos):
newitem = heap[pos]
# Follow the path to the root, moving parents down until finding a place
# newitem fits.
while pos > startpos:
parentpos = (pos - 1) >> 1
parent = heap[parentpos]
if cmp_lt(newitem, parent):
heap[pos] = parent
pos = parentpos
continue
break
heap[pos] = newitem
def _siftup(heap, pos):
endpos = len(heap)
startpos = pos
newitem = heap[pos]
# Bubble up the smaller child until hitting a leaf.
childpos = 2 * pos + 1 # leftmost child position
while childpos < endpos:
# Set childpos to index of smaller child.
rightpos = childpos + 1
if rightpos < endpos and not cmp_lt(heap[childpos], heap[rightpos]):
childpos = rightpos
# Move the smaller child up.
heap[pos] = heap[childpos]
pos = childpos
childpos = 2 * pos + 1
# The leaf at pos is empty now. Put newitem there, and bubble it up
# to its final resting place (by sifting its parents down).
heap[pos] = newitem
_siftdown(heap, startpos, pos)
# END COPY AND PASTE ###############################
return heappush, heappop, _siftdown
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, M = [int(x) for x in input().split()]
graph = [[] for i in range(N)]
for i in range(M):
u, v, w = [int(x) for x in input().split()]
u -= 1
v -= 1
graph[u].append((v, w))
graph[v].append((u, w))
# Want shortest path except one edge is worth 0 and one edge is worth 2x
# Track this with 2 bits of extra state
def getAdj(node):
u = node >> 2
state = node & 3
for v, w in graph[u]:
vBase = v << 2
# Regular edge
yield vBase | state, w
if not state & 1:
# Take max edge, worth 0
yield vBase | state | 1, 0
if not state & 2:
# Take min edge, worth double
yield vBase | state | 2, 2 * w
if not state & 3:
# Take both min and max edge, worth normal
yield vBase | state | 3, w
dist = dijkstra(0, 4 * N, getAdj)
print(" ".join(str(int(dist[(u << 2) | 3])) for u in range(1, N)))
``` | output | 1 | 91,147 | 13 | 182,295 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a weighted undirected connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Let's define the weight of the path consisting of k edges with indices e_1, e_2, ..., e_k as ∑_{i=1}^{k}{w_{e_i}} - max_{i=1}^{k}{w_{e_i}} + min_{i=1}^{k}{w_{e_i}}, where w_i — weight of the i-th edge in the graph.
Your task is to find the minimum weight of the path from the 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Input
The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices and the number of edges in the graph.
Following m lines contains three integers v_i, u_i, w_i (1 ≤ v_i, u_i ≤ n; 1 ≤ w_i ≤ 10^9; v_i ≠ u_i) — endpoints of the i-th edge and its weight respectively.
Output
Print n-1 integers — the minimum weight of the path from 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Examples
Input
5 4
5 3 4
2 1 1
3 2 2
2 4 2
Output
1 2 2 4
Input
6 8
3 1 1
3 6 2
5 4 2
4 2 2
6 1 1
5 2 1
3 2 3
1 5 4
Output
2 1 4 3 1
Input
7 10
7 5 5
2 3 3
4 7 1
5 3 6
2 7 6
6 2 6
3 7 6
4 2 1
3 1 4
1 7 4
Output
3 4 2 7 7 3 | instruction | 0 | 91,148 | 13 | 182,296 |
Tags: graphs, shortest paths
Correct Solution:
```
import io
import os
# import __pypy__
def dijkstra(*args):
# return dijkstraHeap(*args)
# return dijkstraHeapComparatorWrong(*args)
return dijkstraHeapComparator(*args)
# return dijkstraSegTree(*args)
# return dijkstraSortedList(*args)
def dijkstraHeap(source, N, getAdj):
# Heap of (dist, node)
# Use float for dist because max dist for this problem doesn't fit in 32-bit
# Then node has to be a float too, because `(float, int)` will use `W_SpecialisedTupleObject_oo` but we want `W_SpecialisedTupleObject_ff`
from heapq import heappop, heappush
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
queue = [(0.0, float(source))]
# print(__pypy__.internal_repr(queue[0])) # W_SpecialisedTupleObject_ff
# print(__pypy__.strategy(dist)) # FloatListStrategy
while queue:
d, u = heappop(queue)
u = int(u)
if dist[u] == d:
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
heappush(queue, (cost, float(v)))
return dist
def dijkstraHeapComparatorWrong(source, N, getAdj):
# Heap of nodes, sorted with a comparator
# This implementation is actually incorrect but kept for reference since it performs well when using a SPFA-like heuristic
# Note: normal SPFA will TLE since there's a uphack for it in testcase #62
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
inQueue = [0] * N
inQueue[source] = 1
queue = [source]
# print(__pypy__.strategy(queue)) # IntegerListStrategy
def cmp_lt(u, v):
return dist[u] < dist[v]
heappush, heappop, _ = import_heapq(cmp_lt)
while queue:
u = heappop(queue)
d = dist[u]
inQueue[u] = 0
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
if not inQueue[v]:
heappush(queue, v)
inQueue[v] = 1
else:
# If v is already in the queue, we were suppose to bubble it to fix heap invariant
pass
return dist
def dijkstraHeapComparator(source, N, getAdj):
# Same above, except correctly re-bubbling the key after updates
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
def cmp_lt(u, v):
return dist[u] < dist[v]
heappush, heappop, _siftdown = import_heapq(cmp_lt)
class ListWrapper:
# Exactly like a regular list except with fast .index(x) meant to be used with heapq
# Not general purpose and relies on the exact heapq implementation for correctness (swaps only, added via append, deleted via pop)
def __init__(self, maxN):
self.arr = []
self.loc = [-1] * maxN
def append(self, x):
arr = self.arr
arr.append(x)
self.loc[x] = len(arr) - 1
def pop(self):
ret = self.arr.pop()
self.loc[ret] = -1
return ret
def index(self, x):
return self.loc[x]
def __setitem__(self, i, x):
self.arr[i] = x
self.loc[x] = i
def __getitem__(self, i):
return self.arr[i]
def __len__(self):
return len(self.arr)
queue = ListWrapper(N)
queue.append(source)
# print(__pypy__.strategy(queue.arr)) # IntegerListStrategy
while queue:
u = heappop(queue)
d = dist[u]
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
heapIndex = queue.index(v)
if heapIndex == -1:
heappush(queue, v)
else:
_siftdown(queue, 0, heapIndex)
return dist
def dijkstraSegTree(start, n, getAdj):
# From pajenegod: https://github.com/cheran-senthil/PyRival/pull/55
# Modifications:
# Use floats instead of ints for inf/_min
# Fix typo: m -> self.m
# Fix python 3 compatibility: __getitem__
# Cache self.data
# Remove parent pointers
if False:
inf = -1
def _min(a, b):
return a if b == inf or inf != a < b else b
else:
inf = float("inf")
_min = min
class DistanceKeeper:
def __init__(self, n):
m = 1
while m < n:
m *= 2
self.m = m
self.data = 2 * m * [inf]
self.dist = n * [inf]
def __getitem__(self, x):
return self.dist[x]
def __setitem__(self, ind, x):
data = self.data
self.dist[ind] = x
ind += self.m
data[ind] = x
ind >>= 1
while ind:
data[ind] = _min(data[2 * ind], data[2 * ind + 1])
ind >>= 1
def trav(self):
m = self.m
data = self.data
dist = self.dist
while data[1] != inf:
x = data[1]
ind = 1
while ind < m:
ind = 2 * ind + (data[2 * ind] != x)
ind -= m
self[ind] = inf
dist[ind] = x
yield ind
# P = [-1] * n
D = DistanceKeeper(n)
D[start] = 0.0
for node in D.trav():
for nei, weight in getAdj(node):
new_dist = D[node] + weight
if D[nei] == inf or new_dist < D[nei]:
D[nei] = new_dist
# P[nei] = node
# print(__pypy__.strategy(D.dist))
# print(__pypy__.strategy(D.data))
return D.dist
def dijkstraSortedList(source, N, getAdj):
# Just for completeness
# COPY AND PASTE from https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [
values[i : i + _load] for i in range(0, _len, _load)
]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError("{0!r} not in list".format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (
value for _list in reversed(self._lists) for value in reversed(_list)
)
def __repr__(self):
"""Return string representation of sorted list."""
return "SortedList({0})".format(list(self))
# END COPY AND PASTE #####################################
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
queue = SortedList([(0.0, float(source))])
while queue:
negD, u = queue.pop(-1)
d = -negD
u = int(u)
for v, w in getAdj(u):
prevCost = dist[v]
cost = d + w
if cost < prevCost:
if prevCost != inf:
queue.discard((-prevCost, float(v)))
dist[v] = cost
queue.add((-cost, float(v)))
return dist
def import_heapq(cmp_lt):
# Python 2 has a heapq.cmp_lt but python 3 removed it
# Add it back for pypy3 submissions
import sys
if sys.version_info < (3,):
# Python 2
import heapq
from heapq import heappush, heappop, _siftdown
heapq.cmp_lt = cmp_lt
else:
# Python 3
# COPY AND PASTE python 2.7 heapq from https://github.com/python/cpython/blob/2.7/Lib/heapq.py
def heappush(heap, item):
"""Push item onto heap, maintaining the heap invariant."""
heap.append(item)
_siftdown(heap, 0, len(heap) - 1)
def heappop(heap):
"""Pop the smallest item off the heap, maintaining the heap invariant."""
lastelt = heap.pop() # raises appropriate IndexError if heap is empty
if heap:
returnitem = heap[0]
heap[0] = lastelt
_siftup(heap, 0)
return returnitem
return lastelt
def _siftdown(heap, startpos, pos):
newitem = heap[pos]
# Follow the path to the root, moving parents down until finding a place
# newitem fits.
while pos > startpos:
parentpos = (pos - 1) >> 1
parent = heap[parentpos]
if cmp_lt(newitem, parent):
heap[pos] = parent
pos = parentpos
continue
break
heap[pos] = newitem
def _siftup(heap, pos):
endpos = len(heap)
startpos = pos
newitem = heap[pos]
# Bubble up the smaller child until hitting a leaf.
childpos = 2 * pos + 1 # leftmost child position
while childpos < endpos:
# Set childpos to index of smaller child.
rightpos = childpos + 1
if rightpos < endpos and not cmp_lt(heap[childpos], heap[rightpos]):
childpos = rightpos
# Move the smaller child up.
heap[pos] = heap[childpos]
pos = childpos
childpos = 2 * pos + 1
# The leaf at pos is empty now. Put newitem there, and bubble it up
# to its final resting place (by sifting its parents down).
heap[pos] = newitem
_siftdown(heap, startpos, pos)
# END COPY AND PASTE ###############################
return heappush, heappop, _siftdown
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, M = [int(x) for x in input().split()]
graph = [[] for i in range(N)]
for i in range(M):
u, v, w = [int(x) for x in input().split()]
u -= 1
v -= 1
graph[u].append((v, w))
graph[v].append((u, w))
# Want shortest path except one edge is worth 0 and one edge is worth 2x
# Track this with 2 bits of extra state
def getAdj(node):
u = node >> 2
state = node & 3
for v, w in graph[u]:
vBase = v << 2
# Regular edge
yield vBase | state, w
if not state & 1:
# Take max edge, worth 0
yield vBase | state | 1, 0
if not state & 2:
# Take min edge, worth double
yield vBase | state | 2, 2 * w
if not state & 3:
# Take both min and max edge, worth normal
yield vBase | state | 3, w
dist = dijkstra(0, 4 * N, getAdj)
print(" ".join(str(int(dist[(u << 2) | 3])) for u in range(1, N)))
``` | output | 1 | 91,148 | 13 | 182,297 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a weighted undirected connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Let's define the weight of the path consisting of k edges with indices e_1, e_2, ..., e_k as ∑_{i=1}^{k}{w_{e_i}} - max_{i=1}^{k}{w_{e_i}} + min_{i=1}^{k}{w_{e_i}}, where w_i — weight of the i-th edge in the graph.
Your task is to find the minimum weight of the path from the 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Input
The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices and the number of edges in the graph.
Following m lines contains three integers v_i, u_i, w_i (1 ≤ v_i, u_i ≤ n; 1 ≤ w_i ≤ 10^9; v_i ≠ u_i) — endpoints of the i-th edge and its weight respectively.
Output
Print n-1 integers — the minimum weight of the path from 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Examples
Input
5 4
5 3 4
2 1 1
3 2 2
2 4 2
Output
1 2 2 4
Input
6 8
3 1 1
3 6 2
5 4 2
4 2 2
6 1 1
5 2 1
3 2 3
1 5 4
Output
2 1 4 3 1
Input
7 10
7 5 5
2 3 3
4 7 1
5 3 6
2 7 6
6 2 6
3 7 6
4 2 1
3 1 4
1 7 4
Output
3 4 2 7 7 3 | instruction | 0 | 91,149 | 13 | 182,298 |
Tags: graphs, shortest paths
Correct Solution:
```
import io
import os
# import __pypy__
def dijkstra(*args):
# return dijkstraHeap(*args)
return dijkstraHeapComparatorWrong(*args)
# return dijkstraHeapComparator(*args)
# return dijkstraSegTree(*args)
# return dijkstraSortedList(*args)
def dijkstraHeap(source, N, getAdj):
# Heap of (dist, node)
# Use float for dist because max dist for this problem doesn't fit in 32-bit
# Then node has to be a float too, because `(float, int)` will use `W_SpecialisedTupleObject_oo` but we want `W_SpecialisedTupleObject_ff`
from heapq import heappop, heappush
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
queue = [(0.0, float(source))]
# print(__pypy__.internal_repr(queue[0])) # W_SpecialisedTupleObject_ff
# print(__pypy__.strategy(dist)) # FloatListStrategy
while queue:
d, u = heappop(queue)
u = int(u)
if dist[u] == d:
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
heappush(queue, (cost, float(v)))
return dist
def dijkstraHeapComparatorWrong(source, N, getAdj):
# Heap of nodes, sorted with a comparator
# This implementation is actually incorrect but kept for reference since it performs well when using a SPFA-like heuristic
# Note: normal SPFA will TLE since there's a uphack for it in testcase #62
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
inQueue = [0] * N
inQueue[source] = 1
queue = [source]
# print(__pypy__.strategy(queue)) # IntegerListStrategy
def cmp_lt(u, v):
return dist[u] < dist[v]
heappush, heappop, _ = import_heapq(cmp_lt)
while queue:
u = heappop(queue)
d = dist[u]
inQueue[u] = 0
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
if not inQueue[v]:
heappush(queue, v)
inQueue[v] = 1
else:
# If v is already in the queue, we were suppose to bubble it to fix heap invariant
pass
return dist
def dijkstraHeapComparator(source, N, getAdj):
# Same above, except correctly re-bubbling the key after updates
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
def cmp_lt(u, v):
return dist[u] < dist[v]
heappush, heappop, _siftdown = import_heapq(cmp_lt)
class ListWrapper:
# Exactly like a regular list except with fast .index(x) meant to be used with heapq
# Not general purpose and relies on the exact heapq implementation for correctness (swaps only, added via append, deleted via pop)
def __init__(self, maxN):
self.arr = []
self.loc = [-1] * maxN
def append(self, x):
arr = self.arr
arr.append(x)
self.loc[x] = len(arr) - 1
def pop(self):
ret = self.arr.pop()
self.loc[ret] = -1
return ret
def index(self, x):
return self.loc[x]
def __setitem__(self, i, x):
self.arr[i] = x
self.loc[x] = i
def __getitem__(self, i):
return self.arr[i]
def __len__(self):
return len(self.arr)
queue = ListWrapper(N)
queue.append(source)
# print(__pypy__.strategy(queue.arr)) # IntegerListStrategy
while queue:
u = heappop(queue)
d = dist[u]
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
heapIndex = queue.index(v)
if heapIndex == -1:
heappush(queue, v)
else:
_siftdown(queue, 0, heapIndex)
return dist
def dijkstraSegTree(start, n, getAdj):
# From pajenegod: https://github.com/cheran-senthil/PyRival/pull/55
# Modifications:
# Use floats instead of ints for inf/_min
# Fix typo: m -> self.m
# Fix python 3 compatibility: __getitem__
# Cache self.data
# Remove parent pointers
if False:
inf = -1
def _min(a, b):
return a if b == inf or inf != a < b else b
else:
inf = float("inf")
_min = min
class DistanceKeeper:
def __init__(self, n):
m = 1
while m < n:
m *= 2
self.m = m
self.data = 2 * m * [inf]
self.dist = n * [inf]
def __getitem__(self, x):
return self.dist[x]
def __setitem__(self, ind, x):
data = self.data
self.dist[ind] = x
ind += self.m
data[ind] = x
ind >>= 1
while ind:
data[ind] = _min(data[2 * ind], data[2 * ind + 1])
ind >>= 1
def trav(self):
m = self.m
data = self.data
dist = self.dist
while data[1] != inf:
x = data[1]
ind = 1
while ind < m:
ind = 2 * ind + (data[2 * ind] != x)
ind -= m
self[ind] = inf
dist[ind] = x
yield ind
# P = [-1] * n
D = DistanceKeeper(n)
D[start] = 0.0
for node in D.trav():
for nei, weight in getAdj(node):
new_dist = D[node] + weight
if D[nei] == inf or new_dist < D[nei]:
D[nei] = new_dist
# P[nei] = node
# print(__pypy__.strategy(D.dist))
# print(__pypy__.strategy(D.data))
return D.dist
def dijkstraSortedList(source, N, getAdj):
# Just for completeness
# COPY AND PASTE from https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [
values[i : i + _load] for i in range(0, _len, _load)
]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError("{0!r} not in list".format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (
value for _list in reversed(self._lists) for value in reversed(_list)
)
def __repr__(self):
"""Return string representation of sorted list."""
return "SortedList({0})".format(list(self))
# END COPY AND PASTE #####################################
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
queue = SortedList([(0.0, float(source))])
while queue:
negD, u = queue.pop(-1)
d = -negD
u = int(u)
for v, w in getAdj(u):
prevCost = dist[v]
cost = d + w
if cost < prevCost:
if prevCost != inf:
queue.discard((-prevCost, float(v)))
dist[v] = cost
queue.add((-cost, float(v)))
return dist
def import_heapq(cmp_lt):
# Python 2 has a heapq.cmp_lt but python 3 removed it
# Add it back for pypy3 submissions
import sys
if sys.version_info < (3,):
# Python 2
import heapq
from heapq import heappush, heappop, _siftdown
heapq.cmp_lt = cmp_lt
else:
# Python 3
# COPY AND PASTE python 2.7 heapq from https://github.com/python/cpython/blob/2.7/Lib/heapq.py
def heappush(heap, item):
"""Push item onto heap, maintaining the heap invariant."""
heap.append(item)
_siftdown(heap, 0, len(heap) - 1)
def heappop(heap):
"""Pop the smallest item off the heap, maintaining the heap invariant."""
lastelt = heap.pop() # raises appropriate IndexError if heap is empty
if heap:
returnitem = heap[0]
heap[0] = lastelt
_siftup(heap, 0)
return returnitem
return lastelt
def _siftdown(heap, startpos, pos):
newitem = heap[pos]
# Follow the path to the root, moving parents down until finding a place
# newitem fits.
while pos > startpos:
parentpos = (pos - 1) >> 1
parent = heap[parentpos]
if cmp_lt(newitem, parent):
heap[pos] = parent
pos = parentpos
continue
break
heap[pos] = newitem
def _siftup(heap, pos):
endpos = len(heap)
startpos = pos
newitem = heap[pos]
# Bubble up the smaller child until hitting a leaf.
childpos = 2 * pos + 1 # leftmost child position
while childpos < endpos:
# Set childpos to index of smaller child.
rightpos = childpos + 1
if rightpos < endpos and not cmp_lt(heap[childpos], heap[rightpos]):
childpos = rightpos
# Move the smaller child up.
heap[pos] = heap[childpos]
pos = childpos
childpos = 2 * pos + 1
# The leaf at pos is empty now. Put newitem there, and bubble it up
# to its final resting place (by sifting its parents down).
heap[pos] = newitem
_siftdown(heap, startpos, pos)
# END COPY AND PASTE ###############################
return heappush, heappop, _siftdown
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, M = [int(x) for x in input().split()]
graph = [[] for i in range(N)]
for i in range(M):
u, v, w = [int(x) for x in input().split()]
u -= 1
v -= 1
graph[u].append((v, w))
graph[v].append((u, w))
# Want shortest path except one edge is worth 0 and one edge is worth 2x
# Track this with 2 bits of extra state
def getAdj(node):
u = node >> 2
state = node & 3
for v, w in graph[u]:
vBase = v << 2
# Regular edge
yield vBase | state, w
if not state & 1:
# Take max edge, worth 0
yield vBase | state | 1, 0
if not state & 2:
# Take min edge, worth double
yield vBase | state | 2, 2 * w
if not state & 3:
# Take both min and max edge, worth normal
yield vBase | state | 3, w
dist = dijkstra(0, 4 * N, getAdj)
print(" ".join(str(int(dist[(u << 2) | 3])) for u in range(1, N)))
``` | output | 1 | 91,149 | 13 | 182,299 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a weighted undirected connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Let's define the weight of the path consisting of k edges with indices e_1, e_2, ..., e_k as ∑_{i=1}^{k}{w_{e_i}} - max_{i=1}^{k}{w_{e_i}} + min_{i=1}^{k}{w_{e_i}}, where w_i — weight of the i-th edge in the graph.
Your task is to find the minimum weight of the path from the 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Input
The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices and the number of edges in the graph.
Following m lines contains three integers v_i, u_i, w_i (1 ≤ v_i, u_i ≤ n; 1 ≤ w_i ≤ 10^9; v_i ≠ u_i) — endpoints of the i-th edge and its weight respectively.
Output
Print n-1 integers — the minimum weight of the path from 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Examples
Input
5 4
5 3 4
2 1 1
3 2 2
2 4 2
Output
1 2 2 4
Input
6 8
3 1 1
3 6 2
5 4 2
4 2 2
6 1 1
5 2 1
3 2 3
1 5 4
Output
2 1 4 3 1
Input
7 10
7 5 5
2 3 3
4 7 1
5 3 6
2 7 6
6 2 6
3 7 6
4 2 1
3 1 4
1 7 4
Output
3 4 2 7 7 3 | instruction | 0 | 91,150 | 13 | 182,300 |
Tags: graphs, shortest paths
Correct Solution:
```
import io
import os
# import __pypy__
def dijkstra(*args):
# return dijkstraHeap(*args) # 2979 ms
return dijkstraHeapComparatorWrong(*args) # 2823 ms
# return dijkstraHeapComparator(*args) # 2370 ms
# return dijkstraSegTree(*args) # 2417 ms with inf=float('inf), 2995 ms with inf=-1
# return dijkstraSortedList(*args) # 2995 ms
def dijkstraHeap(source, N, getAdj):
# Heap of (dist, node)
# Use float for dist because max dist for this problem doesn't fit in 32-bit
# Then node has to be a float too, because `(float, int)` will use `W_SpecialisedTupleObject_oo` but we want `W_SpecialisedTupleObject_ff`
from heapq import heappop, heappush
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
queue = [(0.0, float(source))]
# print(__pypy__.internal_repr(queue[0])) # W_SpecialisedTupleObject_ff
# print(__pypy__.strategy(dist)) # FloatListStrategy
while queue:
d, u = heappop(queue)
u = int(u)
if dist[u] == d:
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
heappush(queue, (cost, float(v)))
return dist
def dijkstraHeapComparatorWrong(source, N, getAdj):
# Heap of nodes, sorted with a comparator
# This implementation is actually incorrect but kept for reference since it performs well when using a SPFA-like heuristic
# Note: normal SPFA will TLE since there's a uphack for it in testcase #62
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
inQueue = [0] * N
inQueue[source] = 1
queue = [source]
# print(__pypy__.strategy(queue)) # IntegerListStrategy
def cmp_lt(u, v):
return dist[u] < dist[v]
heappush, heappop, _ = import_heapq(cmp_lt)
while queue:
u = heappop(queue)
d = dist[u]
inQueue[u] = 0
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
if not inQueue[v]:
heappush(queue, v)
inQueue[v] = 1
# If v is already in the queue, we were suppose to bubble it to fix heap invariant
return dist
def dijkstraHeapComparator(source, N, getAdj):
# Same above, except correctly re-bubbling the key after updates
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
def cmp_lt(u, v):
return dist[u] < dist[v]
heappush, heappop, _siftdown = import_heapq(cmp_lt)
class ListWrapper:
# Exactly like a regular list except with fast .index(x) meant to be used with heapq
# Not general purpose and relies on the exact heapq implementation for correctness (swaps only, added via append, deleted via pop)
def __init__(self, maxN):
self.arr = []
self.loc = [-1] * maxN
def append(self, x):
arr = self.arr
arr.append(x)
self.loc[x] = len(arr) - 1
def pop(self):
ret = self.arr.pop()
self.loc[ret] = -1
return ret
def index(self, x):
return self.loc[x]
def __setitem__(self, i, x):
self.arr[i] = x
self.loc[x] = i
def __getitem__(self, i):
return self.arr[i]
def __len__(self):
return len(self.arr)
queue = ListWrapper(N)
queue.append(source)
# print(__pypy__.strategy(queue.arr)) # IntegerListStrategy
while queue:
u = heappop(queue)
d = dist[u]
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
heapIndex = queue.index(v)
if heapIndex == -1:
heappush(queue, v)
else:
_siftdown(queue, 0, heapIndex)
return dist
def dijkstraSegTree(start, n, getAdj):
# From pajenegod: https://github.com/cheran-senthil/PyRival/pull/55
# Modifications:
# Use floats instead of ints for inf/_min
# Fix typo: m -> self.m
# Fix python 3 compatibility: __getitem__
# Cache self.data
# Remove parent pointers
if False:
inf = -1
def _min(a, b):
return a if b == inf or inf != a < b else b
else:
inf = float("inf")
_min = min
class DistanceKeeper:
def __init__(self, n):
m = 1
while m < n:
m *= 2
self.m = m
self.data = 2 * m * [inf]
self.dist = n * [inf]
def __getitem__(self, x):
return self.dist[x]
def __setitem__(self, ind, x):
data = self.data
self.dist[ind] = x
ind += self.m
data[ind] = x
ind >>= 1
while ind:
data[ind] = _min(data[2 * ind], data[2 * ind + 1])
ind >>= 1
def trav(self):
m = self.m
data = self.data
dist = self.dist
while data[1] != inf:
x = data[1]
ind = 1
while ind < m:
ind = 2 * ind + (data[2 * ind] != x)
ind -= m
self[ind] = inf
dist[ind] = x
yield ind
# P = [-1] * n
D = DistanceKeeper(n)
D[start] = 0.0
for node in D.trav():
for nei, weight in getAdj(node):
new_dist = D[node] + weight
if D[nei] == inf or new_dist < D[nei]:
D[nei] = new_dist
# P[nei] = node
# print(__pypy__.strategy(D.dist))
# print(__pypy__.strategy(D.data))
return D.dist
def dijkstraSortedList(source, N, getAdj):
# Just for completeness
# COPY AND PASTE from https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [
values[i : i + _load] for i in range(0, _len, _load)
]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError("{0!r} not in list".format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (
value for _list in reversed(self._lists) for value in reversed(_list)
)
def __repr__(self):
"""Return string representation of sorted list."""
return "SortedList({0})".format(list(self))
# END COPY AND PASTE #####################################
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
queue = SortedList([(0.0, float(source))])
while queue:
negD, u = queue.pop(-1)
d = -negD
u = int(u)
for v, w in getAdj(u):
prevCost = dist[v]
cost = d + w
if cost < prevCost:
if prevCost != inf:
queue.discard((-prevCost, float(v)))
dist[v] = cost
queue.add((-cost, float(v)))
return dist
def import_heapq(cmp_lt):
# Python 2 has a heapq.cmp_lt but python 3 removed it
# Add it back for pypy3 submissions
import sys
if sys.version_info < (3,):
# Python 2
import heapq
from heapq import heappush, heappop, _siftdown
heapq.cmp_lt = cmp_lt
else:
# Python 3
# COPY AND PASTE python 2.7 heapq from https://github.com/python/cpython/blob/2.7/Lib/heapq.py
def heappush(heap, item):
"""Push item onto heap, maintaining the heap invariant."""
heap.append(item)
_siftdown(heap, 0, len(heap) - 1)
def heappop(heap):
"""Pop the smallest item off the heap, maintaining the heap invariant."""
lastelt = heap.pop() # raises appropriate IndexError if heap is empty
if heap:
returnitem = heap[0]
heap[0] = lastelt
_siftup(heap, 0)
return returnitem
return lastelt
def _siftdown(heap, startpos, pos):
newitem = heap[pos]
# Follow the path to the root, moving parents down until finding a place
# newitem fits.
while pos > startpos:
parentpos = (pos - 1) >> 1
parent = heap[parentpos]
if cmp_lt(newitem, parent):
heap[pos] = parent
pos = parentpos
continue
break
heap[pos] = newitem
def _siftup(heap, pos):
endpos = len(heap)
startpos = pos
newitem = heap[pos]
# Bubble up the smaller child until hitting a leaf.
childpos = 2 * pos + 1 # leftmost child position
while childpos < endpos:
# Set childpos to index of smaller child.
rightpos = childpos + 1
if rightpos < endpos and not cmp_lt(heap[childpos], heap[rightpos]):
childpos = rightpos
# Move the smaller child up.
heap[pos] = heap[childpos]
pos = childpos
childpos = 2 * pos + 1
# The leaf at pos is empty now. Put newitem there, and bubble it up
# to its final resting place (by sifting its parents down).
heap[pos] = newitem
_siftdown(heap, startpos, pos)
# END COPY AND PASTE ###############################
return heappush, heappop, _siftdown
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, M = [int(x) for x in input().split()]
graph = [[] for i in range(N)]
for i in range(M):
u, v, w = [int(x) for x in input().split()]
u -= 1
v -= 1
graph[u].append((v, w))
graph[v].append((u, w))
# Want shortest path except one edge is worth 0 and one edge is worth 2x
# Track this with 2 bits of extra state
def getAdj(node):
u = node >> 2
state = node & 3
for v, w in graph[u]:
vBase = v << 2
# Regular edge
yield vBase | state, w
if not state & 1:
# Take max edge, worth 0
yield vBase | state | 1, 0
if not state & 2:
# Take min edge, worth double
yield vBase | state | 2, 2 * w
if not state & 3:
# Take both min and max edge, worth normal
yield vBase | state | 3, w
dist = dijkstra(0, 4 * N, getAdj)
print(" ".join(str(int(dist[(u << 2) | 3])) for u in range(1, N)))
``` | output | 1 | 91,150 | 13 | 182,301 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a weighted undirected connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Let's define the weight of the path consisting of k edges with indices e_1, e_2, ..., e_k as ∑_{i=1}^{k}{w_{e_i}} - max_{i=1}^{k}{w_{e_i}} + min_{i=1}^{k}{w_{e_i}}, where w_i — weight of the i-th edge in the graph.
Your task is to find the minimum weight of the path from the 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Input
The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices and the number of edges in the graph.
Following m lines contains three integers v_i, u_i, w_i (1 ≤ v_i, u_i ≤ n; 1 ≤ w_i ≤ 10^9; v_i ≠ u_i) — endpoints of the i-th edge and its weight respectively.
Output
Print n-1 integers — the minimum weight of the path from 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Examples
Input
5 4
5 3 4
2 1 1
3 2 2
2 4 2
Output
1 2 2 4
Input
6 8
3 1 1
3 6 2
5 4 2
4 2 2
6 1 1
5 2 1
3 2 3
1 5 4
Output
2 1 4 3 1
Input
7 10
7 5 5
2 3 3
4 7 1
5 3 6
2 7 6
6 2 6
3 7 6
4 2 1
3 1 4
1 7 4
Output
3 4 2 7 7 3 | instruction | 0 | 91,151 | 13 | 182,302 |
Tags: graphs, shortest paths
Correct Solution:
```
import io
import os
# import __pypy__
def dijkstra(*args):
# return dijkstraHeap(*args)
# return dijkstraHeapComparatorWrong(*args)
# return dijkstraHeapComparator(*args)
return dijkstraSegTree(*args) # with inf = -1
# return dijkstraSortedList(*args)
def dijkstraHeap(source, N, getAdj):
# Heap of (dist, node)
# Use float for dist because max dist for this problem doesn't fit in 32-bit
# Then node has to be a float too, because `(float, int)` will use `W_SpecialisedTupleObject_oo` but we want `W_SpecialisedTupleObject_ff`
from heapq import heappop, heappush
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
queue = [(0.0, float(source))]
# print(__pypy__.internal_repr(queue[0])) # W_SpecialisedTupleObject_ff
# print(__pypy__.strategy(dist)) # FloatListStrategy
while queue:
d, u = heappop(queue)
u = int(u)
if dist[u] == d:
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
heappush(queue, (cost, float(v)))
return dist
def dijkstraHeapComparatorWrong(source, N, getAdj):
# Heap of nodes, sorted with a comparator
# This implementation is actually incorrect but kept for reference since it performs well when using a SPFA-like heuristic
# Note: normal SPFA will TLE since there's a uphack for it in testcase #62
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
inQueue = [0] * N
inQueue[source] = 1
queue = [source]
# print(__pypy__.strategy(queue)) # IntegerListStrategy
def cmp_lt(u, v):
return dist[u] < dist[v]
heappush, heappop, _ = import_heapq(cmp_lt)
while queue:
u = heappop(queue)
d = dist[u]
inQueue[u] = 0
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
if not inQueue[v]:
heappush(queue, v)
inQueue[v] = 1
else:
# If v is already in the queue, we were suppose to bubble it to fix heap invariant
pass
return dist
def dijkstraHeapComparator(source, N, getAdj):
# Same above, except correctly re-bubbling the key after updates
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
def cmp_lt(u, v):
return dist[u] < dist[v]
heappush, heappop, _siftdown = import_heapq(cmp_lt)
class ListWrapper:
# Exactly like a regular list except with fast .index(x) meant to be used with heapq
# Not general purpose and relies on the exact heapq implementation for correctness (swaps only, added via append, deleted via pop)
def __init__(self, maxN):
self.arr = []
self.loc = [-1] * maxN
def append(self, x):
arr = self.arr
arr.append(x)
self.loc[x] = len(arr) - 1
def pop(self):
ret = self.arr.pop()
self.loc[ret] = -1
return ret
def index(self, x):
return self.loc[x]
def __setitem__(self, i, x):
self.arr[i] = x
self.loc[x] = i
def __getitem__(self, i):
return self.arr[i]
def __len__(self):
return len(self.arr)
queue = ListWrapper(N)
queue.append(source)
# print(__pypy__.strategy(queue.arr)) # IntegerListStrategy
while queue:
u = heappop(queue)
d = dist[u]
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
heapIndex = queue.index(v)
if heapIndex == -1:
heappush(queue, v)
else:
_siftdown(queue, 0, heapIndex)
return dist
def dijkstraSegTree(start, n, getAdj):
# From pajenegod: https://github.com/cheran-senthil/PyRival/pull/55
# Modifications:
# Use floats instead of ints for inf/_min
# Fix typo: m -> self.m
# Fix python 3 compatibility: __getitem__
# Cache self.data
# Remove parent pointers
if True:
inf = -1
def _min(a, b):
return a if b == inf or inf != a < b else b
else:
inf = float("inf")
_min = min
class DistanceKeeper:
def __init__(self, n):
m = 1
while m < n:
m *= 2
self.m = m
self.data = 2 * m * [inf]
self.dist = n * [inf]
def __getitem__(self, x):
return self.dist[x]
def __setitem__(self, ind, x):
data = self.data
self.dist[ind] = x
ind += self.m
data[ind] = x
ind >>= 1
while ind:
data[ind] = _min(data[2 * ind], data[2 * ind + 1])
ind >>= 1
def trav(self):
m = self.m
data = self.data
dist = self.dist
while data[1] != inf:
x = data[1]
ind = 1
while ind < m:
ind = 2 * ind + (data[2 * ind] != x)
ind -= m
self[ind] = inf
dist[ind] = x
yield ind
# P = [-1] * n
D = DistanceKeeper(n)
D[start] = 0.0
for node in D.trav():
for nei, weight in getAdj(node):
new_dist = D[node] + weight
if D[nei] == inf or new_dist < D[nei]:
D[nei] = new_dist
# P[nei] = node
# print(__pypy__.strategy(D.dist))
# print(__pypy__.strategy(D.data))
return D.dist
def dijkstraSortedList(source, N, getAdj):
# Just for completeness
# COPY AND PASTE from https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [
values[i : i + _load] for i in range(0, _len, _load)
]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError("{0!r} not in list".format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (
value for _list in reversed(self._lists) for value in reversed(_list)
)
def __repr__(self):
"""Return string representation of sorted list."""
return "SortedList({0})".format(list(self))
# END COPY AND PASTE #####################################
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
queue = SortedList([(0.0, float(source))])
while queue:
negD, u = queue.pop(-1)
d = -negD
u = int(u)
for v, w in getAdj(u):
prevCost = dist[v]
cost = d + w
if cost < prevCost:
if prevCost != inf:
queue.discard((-prevCost, float(v)))
dist[v] = cost
queue.add((-cost, float(v)))
return dist
def import_heapq(cmp_lt):
# Python 2 has a heapq.cmp_lt but python 3 removed it
# Add it back for pypy3 submissions
import sys
if sys.version_info < (3,):
# Python 2
import heapq
from heapq import heappush, heappop, _siftdown
heapq.cmp_lt = cmp_lt
else:
# Python 3
# COPY AND PASTE python 2.7 heapq from https://github.com/python/cpython/blob/2.7/Lib/heapq.py
def heappush(heap, item):
"""Push item onto heap, maintaining the heap invariant."""
heap.append(item)
_siftdown(heap, 0, len(heap) - 1)
def heappop(heap):
"""Pop the smallest item off the heap, maintaining the heap invariant."""
lastelt = heap.pop() # raises appropriate IndexError if heap is empty
if heap:
returnitem = heap[0]
heap[0] = lastelt
_siftup(heap, 0)
return returnitem
return lastelt
def _siftdown(heap, startpos, pos):
newitem = heap[pos]
# Follow the path to the root, moving parents down until finding a place
# newitem fits.
while pos > startpos:
parentpos = (pos - 1) >> 1
parent = heap[parentpos]
if cmp_lt(newitem, parent):
heap[pos] = parent
pos = parentpos
continue
break
heap[pos] = newitem
def _siftup(heap, pos):
endpos = len(heap)
startpos = pos
newitem = heap[pos]
# Bubble up the smaller child until hitting a leaf.
childpos = 2 * pos + 1 # leftmost child position
while childpos < endpos:
# Set childpos to index of smaller child.
rightpos = childpos + 1
if rightpos < endpos and not cmp_lt(heap[childpos], heap[rightpos]):
childpos = rightpos
# Move the smaller child up.
heap[pos] = heap[childpos]
pos = childpos
childpos = 2 * pos + 1
# The leaf at pos is empty now. Put newitem there, and bubble it up
# to its final resting place (by sifting its parents down).
heap[pos] = newitem
_siftdown(heap, startpos, pos)
# END COPY AND PASTE ###############################
return heappush, heappop, _siftdown
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, M = [int(x) for x in input().split()]
graph = [[] for i in range(N)]
for i in range(M):
u, v, w = [int(x) for x in input().split()]
u -= 1
v -= 1
graph[u].append((v, w))
graph[v].append((u, w))
# Want shortest path except one edge is worth 0 and one edge is worth 2x
# Track this with 2 bits of extra state
def getAdj(node):
u = node >> 2
state = node & 3
for v, w in graph[u]:
vBase = v << 2
# Regular edge
yield vBase | state, w
if not state & 1:
# Take max edge, worth 0
yield vBase | state | 1, 0
if not state & 2:
# Take min edge, worth double
yield vBase | state | 2, 2 * w
if not state & 3:
# Take both min and max edge, worth normal
yield vBase | state | 3, w
dist = dijkstra(0, 4 * N, getAdj)
print(" ".join(str(int(dist[(u << 2) | 3])) for u in range(1, N)))
``` | output | 1 | 91,151 | 13 | 182,303 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a weighted undirected connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Let's define the weight of the path consisting of k edges with indices e_1, e_2, ..., e_k as ∑_{i=1}^{k}{w_{e_i}} - max_{i=1}^{k}{w_{e_i}} + min_{i=1}^{k}{w_{e_i}}, where w_i — weight of the i-th edge in the graph.
Your task is to find the minimum weight of the path from the 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Input
The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices and the number of edges in the graph.
Following m lines contains three integers v_i, u_i, w_i (1 ≤ v_i, u_i ≤ n; 1 ≤ w_i ≤ 10^9; v_i ≠ u_i) — endpoints of the i-th edge and its weight respectively.
Output
Print n-1 integers — the minimum weight of the path from 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Examples
Input
5 4
5 3 4
2 1 1
3 2 2
2 4 2
Output
1 2 2 4
Input
6 8
3 1 1
3 6 2
5 4 2
4 2 2
6 1 1
5 2 1
3 2 3
1 5 4
Output
2 1 4 3 1
Input
7 10
7 5 5
2 3 3
4 7 1
5 3 6
2 7 6
6 2 6
3 7 6
4 2 1
3 1 4
1 7 4
Output
3 4 2 7 7 3 | instruction | 0 | 91,152 | 13 | 182,304 |
Tags: graphs, shortest paths
Correct Solution:
```
import io
import os
# import __pypy__
def dijkstra(*args):
# return dijkstraHeap(*args)
# return dijkstraHeapComparatorWrong(*args)
# return dijkstraHeapComparator(*args)
# return dijkstraSegTree(*args)
return dijkstraSortedList(*args)
def dijkstraHeap(source, N, getAdj):
# Heap of (dist, node)
# Use float for dist because max dist for this problem doesn't fit in 32-bit
# Then node has to be a float too, because `(float, int)` will use `W_SpecialisedTupleObject_oo` but we want `W_SpecialisedTupleObject_ff`
from heapq import heappop, heappush
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
queue = [(0.0, float(source))]
# print(__pypy__.internal_repr(queue[0])) # W_SpecialisedTupleObject_ff
# print(__pypy__.strategy(dist)) # FloatListStrategy
while queue:
d, u = heappop(queue)
u = int(u)
if dist[u] == d:
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
heappush(queue, (cost, float(v)))
return dist
def dijkstraHeapComparatorWrong(source, N, getAdj):
# Heap of nodes, sorted with a comparator
# This implementation is actually incorrect but kept for reference since it performs well when using a SPFA-like heuristic
# Note: normal SPFA will TLE since there's a uphack for it in testcase #62
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
inQueue = [0] * N
inQueue[source] = 1
queue = [source]
# print(__pypy__.strategy(queue)) # IntegerListStrategy
def cmp_lt(u, v):
return dist[u] < dist[v]
heappush, heappop, _ = import_heapq(cmp_lt)
while queue:
u = heappop(queue)
d = dist[u]
inQueue[u] = 0
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
if not inQueue[v]:
heappush(queue, v)
inQueue[v] = 1
else:
# If v is already in the queue, we were suppose to bubble it to fix heap invariant
pass
return dist
def dijkstraHeapComparator(source, N, getAdj):
# Same above, except correctly re-bubbling the key after updates
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
def cmp_lt(u, v):
return dist[u] < dist[v]
heappush, heappop, _siftdown = import_heapq(cmp_lt)
class ListWrapper:
# Exactly like a regular list except with fast .index(x) meant to be used with heapq
# Not general purpose and relies on the exact heapq implementation for correctness (swaps only, added via append, deleted via pop)
def __init__(self, maxN):
self.arr = []
self.loc = [-1] * maxN
def append(self, x):
arr = self.arr
arr.append(x)
self.loc[x] = len(arr) - 1
def pop(self):
ret = self.arr.pop()
self.loc[ret] = -1
return ret
def index(self, x):
return self.loc[x]
def __setitem__(self, i, x):
self.arr[i] = x
self.loc[x] = i
def __getitem__(self, i):
return self.arr[i]
def __len__(self):
return len(self.arr)
queue = ListWrapper(N)
queue.append(source)
# print(__pypy__.strategy(queue.arr)) # IntegerListStrategy
while queue:
u = heappop(queue)
d = dist[u]
for v, w in getAdj(u):
cost = d + w
if cost < dist[v]:
dist[v] = cost
heapIndex = queue.index(v)
if heapIndex == -1:
heappush(queue, v)
else:
_siftdown(queue, 0, heapIndex)
return dist
def dijkstraSegTree(start, n, getAdj):
# From pajenegod: https://github.com/cheran-senthil/PyRival/pull/55
# Modifications:
# Use floats instead of ints for inf/_min
# Fix typo: m -> self.m
# Fix python 3 compatibility: __getitem__
# Cache self.data
# Remove parent pointers
if False:
inf = -1
def _min(a, b):
return a if b == inf or inf != a < b else b
else:
inf = float("inf")
_min = min
class DistanceKeeper:
def __init__(self, n):
m = 1
while m < n:
m *= 2
self.m = m
self.data = 2 * m * [inf]
self.dist = n * [inf]
def __getitem__(self, x):
return self.dist[x]
def __setitem__(self, ind, x):
data = self.data
self.dist[ind] = x
ind += self.m
data[ind] = x
ind >>= 1
while ind:
data[ind] = _min(data[2 * ind], data[2 * ind + 1])
ind >>= 1
def trav(self):
m = self.m
data = self.data
dist = self.dist
while data[1] != inf:
x = data[1]
ind = 1
while ind < m:
ind = 2 * ind + (data[2 * ind] != x)
ind -= m
self[ind] = inf
dist[ind] = x
yield ind
# P = [-1] * n
D = DistanceKeeper(n)
D[start] = 0.0
for node in D.trav():
for nei, weight in getAdj(node):
new_dist = D[node] + weight
if D[nei] == inf or new_dist < D[nei]:
D[nei] = new_dist
# P[nei] = node
# print(__pypy__.strategy(D.dist))
# print(__pypy__.strategy(D.data))
return D.dist
def dijkstraSortedList(source, N, getAdj):
# Just for completeness
# COPY AND PASTE from https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [
values[i : i + _load] for i in range(0, _len, _load)
]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError("{0!r} not in list".format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (
value for _list in reversed(self._lists) for value in reversed(_list)
)
def __repr__(self):
"""Return string representation of sorted list."""
return "SortedList({0})".format(list(self))
# END COPY AND PASTE #####################################
inf = float("inf")
dist = [inf] * N
dist[source] = 0.0
queue = SortedList([(0.0, float(source))])
while queue:
negD, u = queue.pop(-1)
d = -negD
u = int(u)
for v, w in getAdj(u):
prevCost = dist[v]
cost = d + w
if cost < prevCost:
if prevCost != inf:
queue.discard((-prevCost, float(v)))
dist[v] = cost
queue.add((-cost, float(v)))
return dist
def import_heapq(cmp_lt):
# Python 2 has a heapq.cmp_lt but python 3 removed it
# Add it back for pypy3 submissions
import sys
if sys.version_info < (3,):
# Python 2
import heapq
from heapq import heappush, heappop, _siftdown
heapq.cmp_lt = cmp_lt
else:
# Python 3
# COPY AND PASTE python 2.7 heapq from https://github.com/python/cpython/blob/2.7/Lib/heapq.py
def heappush(heap, item):
"""Push item onto heap, maintaining the heap invariant."""
heap.append(item)
_siftdown(heap, 0, len(heap) - 1)
def heappop(heap):
"""Pop the smallest item off the heap, maintaining the heap invariant."""
lastelt = heap.pop() # raises appropriate IndexError if heap is empty
if heap:
returnitem = heap[0]
heap[0] = lastelt
_siftup(heap, 0)
return returnitem
return lastelt
def _siftdown(heap, startpos, pos):
newitem = heap[pos]
# Follow the path to the root, moving parents down until finding a place
# newitem fits.
while pos > startpos:
parentpos = (pos - 1) >> 1
parent = heap[parentpos]
if cmp_lt(newitem, parent):
heap[pos] = parent
pos = parentpos
continue
break
heap[pos] = newitem
def _siftup(heap, pos):
endpos = len(heap)
startpos = pos
newitem = heap[pos]
# Bubble up the smaller child until hitting a leaf.
childpos = 2 * pos + 1 # leftmost child position
while childpos < endpos:
# Set childpos to index of smaller child.
rightpos = childpos + 1
if rightpos < endpos and not cmp_lt(heap[childpos], heap[rightpos]):
childpos = rightpos
# Move the smaller child up.
heap[pos] = heap[childpos]
pos = childpos
childpos = 2 * pos + 1
# The leaf at pos is empty now. Put newitem there, and bubble it up
# to its final resting place (by sifting its parents down).
heap[pos] = newitem
_siftdown(heap, startpos, pos)
# END COPY AND PASTE ###############################
return heappush, heappop, _siftdown
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, M = [int(x) for x in input().split()]
graph = [[] for i in range(N)]
for i in range(M):
u, v, w = [int(x) for x in input().split()]
u -= 1
v -= 1
graph[u].append((v, w))
graph[v].append((u, w))
# Want shortest path except one edge is worth 0 and one edge is worth 2x
# Track this with 2 bits of extra state
def getAdj(node):
u = node >> 2
state = node & 3
for v, w in graph[u]:
vBase = v << 2
# Regular edge
yield vBase | state, w
if not state & 1:
# Take max edge, worth 0
yield vBase | state | 1, 0
if not state & 2:
# Take min edge, worth double
yield vBase | state | 2, 2 * w
if not state & 3:
# Take both min and max edge, worth normal
yield vBase | state | 3, w
dist = dijkstra(0, 4 * N, getAdj)
print(" ".join(str(int(dist[(u << 2) | 3])) for u in range(1, N)))
``` | output | 1 | 91,152 | 13 | 182,305 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a weighted undirected connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Let's define the weight of the path consisting of k edges with indices e_1, e_2, ..., e_k as ∑_{i=1}^{k}{w_{e_i}} - max_{i=1}^{k}{w_{e_i}} + min_{i=1}^{k}{w_{e_i}}, where w_i — weight of the i-th edge in the graph.
Your task is to find the minimum weight of the path from the 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Input
The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices and the number of edges in the graph.
Following m lines contains three integers v_i, u_i, w_i (1 ≤ v_i, u_i ≤ n; 1 ≤ w_i ≤ 10^9; v_i ≠ u_i) — endpoints of the i-th edge and its weight respectively.
Output
Print n-1 integers — the minimum weight of the path from 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Examples
Input
5 4
5 3 4
2 1 1
3 2 2
2 4 2
Output
1 2 2 4
Input
6 8
3 1 1
3 6 2
5 4 2
4 2 2
6 1 1
5 2 1
3 2 3
1 5 4
Output
2 1 4 3 1
Input
7 10
7 5 5
2 3 3
4 7 1
5 3 6
2 7 6
6 2 6
3 7 6
4 2 1
3 1 4
1 7 4
Output
3 4 2 7 7 3
Submitted Solution:
```
from collections import defaultdict
import heapq
def calculate_distances(graph, starting_vertex, n):
ans = [float('inf') for i in range(n+1)]
ans[1] = 0
pq = [((0, float('inf'), float('-inf')), starting_vertex)]
while len(pq) > 0:
cur_lst, current_vertex = heapq.heappop(pq)
cur_dist, cur_min, cur_max = cur_lst
# if cur_dist > ans[current_vertex][0]:
# continue
if cur_max == float('-inf'):
cur_weight_sum = cur_dist
else:
cur_weight_sum = cur_dist + cur_max - cur_min
for neighbor, weight in graph[current_vertex].items():
distance = cur_weight_sum + weight - max(weight, cur_max) + min(weight, cur_min)
if distance < ans[neighbor] or weight < cur_min:
ans[neighbor] = min(ans[neighbor], distance)
push_val = [distance, min(weight, cur_min), max(weight, cur_max)]
heapq.heappush(pq, (push_val, neighbor))
return ans[2:]
def main():
n, m = map(int, input().split(' '))
graph = defaultdict(dict)
for _ in range(m):
x,y,w = map(int, input().split(' '))
graph[x][y] = w
graph[y][x] = w
ans = calculate_distances(graph, 1, n)
print(" ".join(list(map(str, ans))))
# region fastio
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
``` | instruction | 0 | 91,153 | 13 | 182,306 |
No | output | 1 | 91,153 | 13 | 182,307 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a weighted undirected connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Let's define the weight of the path consisting of k edges with indices e_1, e_2, ..., e_k as ∑_{i=1}^{k}{w_{e_i}} - max_{i=1}^{k}{w_{e_i}} + min_{i=1}^{k}{w_{e_i}}, where w_i — weight of the i-th edge in the graph.
Your task is to find the minimum weight of the path from the 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Input
The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices and the number of edges in the graph.
Following m lines contains three integers v_i, u_i, w_i (1 ≤ v_i, u_i ≤ n; 1 ≤ w_i ≤ 10^9; v_i ≠ u_i) — endpoints of the i-th edge and its weight respectively.
Output
Print n-1 integers — the minimum weight of the path from 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Examples
Input
5 4
5 3 4
2 1 1
3 2 2
2 4 2
Output
1 2 2 4
Input
6 8
3 1 1
3 6 2
5 4 2
4 2 2
6 1 1
5 2 1
3 2 3
1 5 4
Output
2 1 4 3 1
Input
7 10
7 5 5
2 3 3
4 7 1
5 3 6
2 7 6
6 2 6
3 7 6
4 2 1
3 1 4
1 7 4
Output
3 4 2 7 7 3
Submitted Solution:
```
a=1
``` | instruction | 0 | 91,154 | 13 | 182,308 |
No | output | 1 | 91,154 | 13 | 182,309 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a weighted undirected connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Let's define the weight of the path consisting of k edges with indices e_1, e_2, ..., e_k as ∑_{i=1}^{k}{w_{e_i}} - max_{i=1}^{k}{w_{e_i}} + min_{i=1}^{k}{w_{e_i}}, where w_i — weight of the i-th edge in the graph.
Your task is to find the minimum weight of the path from the 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Input
The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices and the number of edges in the graph.
Following m lines contains three integers v_i, u_i, w_i (1 ≤ v_i, u_i ≤ n; 1 ≤ w_i ≤ 10^9; v_i ≠ u_i) — endpoints of the i-th edge and its weight respectively.
Output
Print n-1 integers — the minimum weight of the path from 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Examples
Input
5 4
5 3 4
2 1 1
3 2 2
2 4 2
Output
1 2 2 4
Input
6 8
3 1 1
3 6 2
5 4 2
4 2 2
6 1 1
5 2 1
3 2 3
1 5 4
Output
2 1 4 3 1
Input
7 10
7 5 5
2 3 3
4 7 1
5 3 6
2 7 6
6 2 6
3 7 6
4 2 1
3 1 4
1 7 4
Output
3 4 2 7 7 3
Submitted Solution:
```
from collections import defaultdict
import heapq
def calculate_distances(graph, starting_vertex, n):
ans = [float('inf') for i in range(n+1)]
ans[1] = 0
pq = [((0, float('inf'), float('-inf')), starting_vertex)]
while len(pq) > 0:
cur_lst, current_vertex = heapq.heappop(pq)
cur_dist, cur_min, cur_max = cur_lst
# if cur_dist > ans[current_vertex][0]:
# continue
if cur_max == float('-inf'):
cur_weight_sum = cur_dist
else:
cur_weight_sum = cur_dist + cur_max - cur_min
for neighbor, weight in graph[current_vertex].items():
distance = cur_weight_sum + weight - max(weight, cur_max) + min(weight, cur_min)
if distance < ans[neighbor] or weight < cur_min or weight > cur_max:
ans[neighbor] = min(ans[neighbor], distance)
push_val = [distance, min(weight, cur_min), max(weight, cur_max)]
heapq.heappush(pq, (push_val, neighbor))
return ans[2:]
def main():
n, m = map(int, input().split(' '))
graph = defaultdict(dict)
for _ in range(m):
x,y,w = map(int, input().split(' '))
graph[x][y] = w
graph[y][x] = w
ans = calculate_distances(graph, 1, n)
print(" ".join(list(map(str, ans))))
# region fastio
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
``` | instruction | 0 | 91,155 | 13 | 182,310 |
No | output | 1 | 91,155 | 13 | 182,311 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a weighted undirected connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Let's define the weight of the path consisting of k edges with indices e_1, e_2, ..., e_k as ∑_{i=1}^{k}{w_{e_i}} - max_{i=1}^{k}{w_{e_i}} + min_{i=1}^{k}{w_{e_i}}, where w_i — weight of the i-th edge in the graph.
Your task is to find the minimum weight of the path from the 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Input
The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices and the number of edges in the graph.
Following m lines contains three integers v_i, u_i, w_i (1 ≤ v_i, u_i ≤ n; 1 ≤ w_i ≤ 10^9; v_i ≠ u_i) — endpoints of the i-th edge and its weight respectively.
Output
Print n-1 integers — the minimum weight of the path from 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).
Examples
Input
5 4
5 3 4
2 1 1
3 2 2
2 4 2
Output
1 2 2 4
Input
6 8
3 1 1
3 6 2
5 4 2
4 2 2
6 1 1
5 2 1
3 2 3
1 5 4
Output
2 1 4 3 1
Input
7 10
7 5 5
2 3 3
4 7 1
5 3 6
2 7 6
6 2 6
3 7 6
4 2 1
3 1 4
1 7 4
Output
3 4 2 7 7 3
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
def __init__(self, file):
self.newlines = 0
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline()
# --------------------------------------------------------------------
def RL(): return map(int, sys.stdin.readline().split())
def RLL(): return list(map(int, sys.stdin.readline().split()))
def N(): return int(input())
def S(): return input().strip()
def print_list(l): print(' '.join(map(str, l)))
# sys.setrecursionlimit(200000)
# import random
# from functools import reduce
# from functools import lru_cache
from heapq import *
# from collections import deque as dq
# import math
# import bisect as bs
# from collections import Counter
# from collections import defaultdict as dc
def judge(d, ma, mi, u, dist):
return (d <= dist[u][0]) or (d - ma <= dist[u][0] - dist[u][1]) or (d + mi <= dist[u][0] + dist[u][2])
def Dijkstra(s, n, adj):
# 注意,当边权固定时,直接使用BFS更快
# s起点,n节点个数,adj带权邻接表
dist = [(float('inf'), 0, float('inf'))] * (n + 1)
dist[s] = (0, 0, float('inf'))
heap = [(0, 0, float('inf'), s)]
while heap:
d, ma, mi, u = heappop(heap)
if not judge(d, ma, mi, u, dist): continue
for v, w in adj[u]:
nd = d + w
nmi = min(mi, w)
nma = max(ma, w)
if not judge(nd, nma, nmi, v, dist): continue
heappush(heap, (nd, nma, nmi, v))
if nd - nma + nmi < dist[v][0] - dist[v][1] + dist[v][2]:
dist[v] = (nd, nma, nmi)
return dist
n, m = RL()
adj = [[] for _ in range(n + 1)]
for _ in range(m):
u, v, w = RL()
adj[u].append((v, w))
adj[v].append((u, w))
ans = Dijkstra(1, n, adj)
print(ans)
print_list([ans[v][0] - ans[v][1] + ans[v][2] for v in range(2, n + 1)])
``` | instruction | 0 | 91,156 | 13 | 182,312 |
No | output | 1 | 91,156 | 13 | 182,313 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a bipartite graph consisting of n_1 vertices in the first part, n_2 vertices in the second part, and m edges, numbered from 1 to m. You have to color each edge into one of two colors, red and blue. You have to minimize the following value: ∑ _{v ∈ V} |r(v) - b(v)|, where V is the set of vertices of the graph, r(v) is the number of red edges incident to v, and b(v) is the number of blue edges incident to v.
Sounds classical and easy, right? Well, you have to process q queries of the following format:
* 1 v_1 v_2 — add a new edge connecting the vertex v_1 of the first part with the vertex v_2 of the second part. This edge gets a new index as follows: the first added edge gets the index m + 1, the second — m + 2, and so on. After adding the edge, you have to print the hash of the current optimal coloring (if there are multiple optimal colorings, print the hash of any of them). Actually, this hash won't be verified, you may print any number as the answer to this query, but you may be asked to produce the coloring having this hash;
* 2 — print the optimal coloring of the graph with the same hash you printed while processing the previous query. The query of this type will only be asked after a query of type 1, and there will be at most 10 queries of this type. If there are multiple optimal colorings corresponding to this hash, print any of them.
Note that if an edge was red or blue in some coloring, it may change its color in next colorings.
The hash of the coloring is calculated as follows: let R be the set of indices of red edges, then the hash is (∑ _{i ∈ R} 2^i) mod 998244353.
Note that you should solve the problem in online mode. It means that you can't read the whole input at once. You can read each query only after writing the answer for the last query. Use functions fflush in C++ and BufferedWriter.flush in Java languages after each writing in your program.
Input
The first line contains three integers n_1, n_2 and m (1 ≤ n_1, n_2, m ≤ 2 ⋅ 10^5).
Then m lines follow, the i-th of them contains two integers x_i and y_i (1 ≤ x_i ≤ n_1; 1 ≤ y_i ≤ n_2) meaning that the i-th edge connects the vertex x_i from the first part and the vertex y_i from the second part.
The next line contains one integer q (1 ≤ q ≤ 2 ⋅ 10^5) — the number of queries you have to process.
The next q lines contain the queries in the format introduced in the statement.
Additional constraints on the input:
* at any moment, the graph won't contain any multiple edges;
* the queries of type 2 are only asked if the previous query had type 1;
* there are at most 10 queries of type 2.
Output
To answer a query of type 1, print one integer — the hash of the optimal coloring.
To answer a query of type 2, print one line. It should begin with the integer k — the number of red edges. Then, k distinct integer should follow — the indices of red edges in your coloring, in any order. Each index should correspond to an existing edge, and the hash of the coloring you produce should be equal to the hash you printed as the answer to the previous query.
If there are multiple answers to a query, you may print any of them.
Example
Input
3 4 2
1 2
3 4
10
1 1 3
1 2 3
2
1 3 3
2
1 2 4
2
1 2 1
1 1 1
2
Output
8
8
1 3
40
2 3 5
104
3 5 6 3
104
360
4 5 6 3 8
Submitted Solution:
```
print(8)
print(8)
print(1, 3)
print(40)
print(2, 3, 5)
print(104)
print(3, 5, 6, 3)
print(104)
print(360)
print(4, 5, 6, 3, 8)
``` | instruction | 0 | 91,157 | 13 | 182,314 |
No | output | 1 | 91,157 | 13 | 182,315 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree T with n vertices (numbered 1 through n) and a letter in each vertex. The tree is rooted at vertex 1.
Let's look at the subtree Tv of some vertex v. It is possible to read a string along each simple path starting at v and ending at some vertex in Tv (possibly v itself). Let's denote the number of distinct strings which can be read this way as <image>.
Also, there's a number cv assigned to each vertex v. We are interested in vertices with the maximum value of <image>.
You should compute two statistics: the maximum value of <image> and the number of vertices v with the maximum <image>.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 300 000) — the number of vertices of the tree.
The second line contains n space-separated integers ci (0 ≤ ci ≤ 109).
The third line contains a string s consisting of n lowercase English letters — the i-th character of this string is the letter in vertex i.
The following n - 1 lines describe the tree T. Each of them contains two space-separated integers u and v (1 ≤ u, v ≤ n) indicating an edge between vertices u and v.
It's guaranteed that the input will describe a tree.
Output
Print two lines.
On the first line, print <image> over all 1 ≤ i ≤ n.
On the second line, print the number of vertices v for which <image>.
Examples
Input
10
1 2 7 20 20 30 40 50 50 50
cacabbcddd
1 2
6 8
7 2
6 2
5 4
5 9
3 10
2 5
2 3
Output
51
3
Input
6
0 2 4 1 1 1
raaaba
1 2
2 3
2 4
2 5
3 6
Output
6
2
Note
In the first sample, the tree looks like this:
<image>
The sets of strings that can be read from individual vertices are:
<image>
Finally, the values of <image> are:
<image>
In the second sample, the values of <image> are (5, 4, 2, 1, 1, 1). The distinct strings read in T2 are <image>; note that <image> can be read down to vertices 3 or 4.
Submitted Solution:
```
class Node:
def __init__(self):
self.l = [None]*30
self.ind = []
def d(i, n, p=-1):
if i in vis: return
if i != 1:
if n.l[ord(st[i-1])-ord('a')]: n = n.l[ord(st[i-1])-ord('a')]
else:
n.l[ord(st[i-1])-ord('a')] = Node()
n.l[ord(st[i-1])-ord('a')].l[p] = n
n = n.l[ord(st[i-1])-ord('a')]
vis[i] = 1
n.ind.append(i)
for j in g[i]:
d(j, n, ord(st[i-1])-ord('a'))
vis2 = {}
def c(n):
if n in vis2: return 0
vis2[n] = 1
cnt = 1
for j in range(27):
if n.l[j]:
cnt += c(n.l[j])
for j in n.ind:
if cnt+num[j-1] in a2:
a2[cnt+num[j-1]][j] = 1
else:
a2[cnt+num[j-1]] = {j: 1}
return cnt
g = []
for i in range(int(3e5+5)):
g.append([])
n = int(input())
num = list(map(int,input().split()))
st = input()
for i in range(n-1):
a,b = map(int,input().split())
g[a].append(b)
g[b].append(a)
root = Node()
vis = {}
d(1, root)
vis = {}
a2 = {}
c(root)
m = -1e9
for i in a2:
m = max(m, i)
print(m)
print(len(a2[m]))
``` | instruction | 0 | 91,308 | 13 | 182,616 |
No | output | 1 | 91,308 | 13 | 182,617 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree T with n vertices (numbered 1 through n) and a letter in each vertex. The tree is rooted at vertex 1.
Let's look at the subtree Tv of some vertex v. It is possible to read a string along each simple path starting at v and ending at some vertex in Tv (possibly v itself). Let's denote the number of distinct strings which can be read this way as <image>.
Also, there's a number cv assigned to each vertex v. We are interested in vertices with the maximum value of <image>.
You should compute two statistics: the maximum value of <image> and the number of vertices v with the maximum <image>.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 300 000) — the number of vertices of the tree.
The second line contains n space-separated integers ci (0 ≤ ci ≤ 109).
The third line contains a string s consisting of n lowercase English letters — the i-th character of this string is the letter in vertex i.
The following n - 1 lines describe the tree T. Each of them contains two space-separated integers u and v (1 ≤ u, v ≤ n) indicating an edge between vertices u and v.
It's guaranteed that the input will describe a tree.
Output
Print two lines.
On the first line, print <image> over all 1 ≤ i ≤ n.
On the second line, print the number of vertices v for which <image>.
Examples
Input
10
1 2 7 20 20 30 40 50 50 50
cacabbcddd
1 2
6 8
7 2
6 2
5 4
5 9
3 10
2 5
2 3
Output
51
3
Input
6
0 2 4 1 1 1
raaaba
1 2
2 3
2 4
2 5
3 6
Output
6
2
Note
In the first sample, the tree looks like this:
<image>
The sets of strings that can be read from individual vertices are:
<image>
Finally, the values of <image> are:
<image>
In the second sample, the values of <image> are (5, 4, 2, 1, 1, 1). The distinct strings read in T2 are <image>; note that <image> can be read down to vertices 3 or 4.
Submitted Solution:
```
class Node:
def __init__(self):
self.l = [None]*26
self.ind = []
def set(self, i, n):
self.l[i]=n
return self.l[i]
def get(self, i):
return self.l[i]
def d(i, n):
if i in vis: return
if i != 1:
if n.get(ord(st[i-1])-ord('a')): n = n.get(ord(st[i-1])-ord('a'))
else: n = n.set(ord(st[i-1])-ord('a'), Node())
vis[i] = 1
n.ind.append(i)
for j in g[i]:
d(j, n)
def c(n):
cnt = 1
for j in range(26):
if n.get(j):
cnt += c(n.get(j))
for j in n.ind:
if cnt+num[j-1] in a2:
a2[cnt+num[j-1]].append(j)
else:
a2[cnt+num[j-1]] = [j]
return cnt
g = []
for i in range(int(3e5+5)):
g.append([])
n = int(input())
num = list(map(int,input().split()))
st = input()
for i in range(n-1):
a,b = map(int,input().split())
g[a].append(b)
g[b].append(a)
root = Node()
vis = {}
d(1, root)
vis = {}
a2 = {}
c(root)
m = max(i for i in a2)
print(m)
print(len(a2[m]))
``` | instruction | 0 | 91,309 | 13 | 182,618 |
No | output | 1 | 91,309 | 13 | 182,619 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree T with n vertices (numbered 1 through n) and a letter in each vertex. The tree is rooted at vertex 1.
Let's look at the subtree Tv of some vertex v. It is possible to read a string along each simple path starting at v and ending at some vertex in Tv (possibly v itself). Let's denote the number of distinct strings which can be read this way as <image>.
Also, there's a number cv assigned to each vertex v. We are interested in vertices with the maximum value of <image>.
You should compute two statistics: the maximum value of <image> and the number of vertices v with the maximum <image>.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 300 000) — the number of vertices of the tree.
The second line contains n space-separated integers ci (0 ≤ ci ≤ 109).
The third line contains a string s consisting of n lowercase English letters — the i-th character of this string is the letter in vertex i.
The following n - 1 lines describe the tree T. Each of them contains two space-separated integers u and v (1 ≤ u, v ≤ n) indicating an edge between vertices u and v.
It's guaranteed that the input will describe a tree.
Output
Print two lines.
On the first line, print <image> over all 1 ≤ i ≤ n.
On the second line, print the number of vertices v for which <image>.
Examples
Input
10
1 2 7 20 20 30 40 50 50 50
cacabbcddd
1 2
6 8
7 2
6 2
5 4
5 9
3 10
2 5
2 3
Output
51
3
Input
6
0 2 4 1 1 1
raaaba
1 2
2 3
2 4
2 5
3 6
Output
6
2
Note
In the first sample, the tree looks like this:
<image>
The sets of strings that can be read from individual vertices are:
<image>
Finally, the values of <image> are:
<image>
In the second sample, the values of <image> are (5, 4, 2, 1, 1, 1). The distinct strings read in T2 are <image>; note that <image> can be read down to vertices 3 or 4.
Submitted Solution:
```
class Node:
def __init__(self):
self.l = [None]*30
self.ind = []
def d(i, n):
if i in vis: return
if i != 1:
if n.l[ord(st[i-1])-ord('a')]: n = n.l[ord(st[i-1])-ord('a')]
else:
n.l[ord(st[i-1])-ord('a')] = Node()
n = n.l[ord(st[i-1])-ord('a')]
vis[i] = 1
n.ind.append(i)
for j in g[i]:
d(j, n)
def c(n):
cnt = 1
for j in range(27):
if n.l[j]:
cnt += c(n.l[j])
for j in n.ind:
if cnt+num[j-1] in a2:
a2[cnt+num[j-1]][j] = 1
else:
a2[cnt+num[j-1]] = {j: 1}
return cnt
g = []
for i in range(int(3e5+5)):
g.append([])
n = int(input())
num = list(map(int,input().split()))
st = input()
for i in range(n-1):
a,b = map(int,input().split())
g[a].append(b)
g[b].append(a)
root = Node()
vis = {}
d(1, root)
vis = {}
a2 = {}
c(root)
m = -1e9
for i in a2:
m = max(m, i)
print(m)
print(len(a2[m]))
``` | instruction | 0 | 91,310 | 13 | 182,620 |
No | output | 1 | 91,310 | 13 | 182,621 |
Provide a correct Python 3 solution for this coding contest problem.
Ringo has an undirected graph G with N vertices numbered 1,2,...,N and M edges numbered 1,2,...,M. Edge i connects Vertex a_{i} and b_{i} and has a length of w_i.
Now, he is in the middle of painting these N vertices in K colors numbered 1,2,...,K. Vertex i is already painted in Color c_i, except when c_i = 0, in which case Vertex i is not yet painted.
After he paints each vertex that is not yet painted in one of the K colors, he will give G to Snuke.
Based on G, Snuke will make another undirected graph G' with K vertices numbered 1,2,...,K and M edges. Initially, there is no edge in G'. The i-th edge will be added as follows:
* Let x and y be the colors of the two vertices connected by Edge i in G.
* Add an edge of length w_i connecting Vertex x and y in G'.
What is the minimum possible sum of the lengths of the edges in the minimum spanning tree of G'? If G' will not be connected regardless of how Ringo paints the vertices, print -1.
Constraints
* 1 \leq N,M \leq 10^{5}
* 1 \leq K \leq N
* 0 \leq c_i \leq K
* 1 \leq a_i,b_i \leq N
* 1 \leq w_i \leq 10^{9}
* The given graph may NOT be simple or connected.
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N M K
c_1 c_2 ... c_{N}
a_1 b_1 w_1
:
a_M b_M w_M
Output
Print the answer.
Examples
Input
4 3 3
1 0 1 2
1 2 10
2 3 20
2 4 50
Output
60
Input
5 2 4
0 0 0 0 0
1 2 10
2 3 10
Output
-1
Input
9 12 9
1 2 3 4 5 6 7 8 9
6 9 9
8 9 6
6 7 85
9 5 545631016
2 1 321545
1 6 33562944
7 3 84946329
9 7 15926167
4 7 53386480
5 8 70476
4 6 4549
4 8 8
Output
118901402
Input
18 37 12
5 0 4 10 8 7 2 10 6 0 9 12 12 11 11 11 0 1
17 1 1
11 16 7575
11 15 9
10 10 289938980
5 10 17376
18 4 1866625
8 11 959154208
18 13 200
16 13 2
2 7 982223
12 12 9331
13 12 8861390
14 13 743
2 10 162440
2 4 981849
7 9 1
14 17 2800
2 7 7225452
3 7 85
5 17 4
2 13 1
10 3 45
1 15 973
14 7 56553306
16 17 70476
7 18 9
9 13 27911
18 14 7788322
11 11 8925
9 13 654295
2 10 9
10 1 545631016
3 4 5
17 12 1929
2 11 57
1 5 4
1 17 7807368
Output
171 | instruction | 0 | 91,558 | 13 | 183,116 |
"Correct Solution:
```
class Unionfindtree:
def __init__(self, number):
self.par = [i for i in range(number)]
self.rank = [0] * (number)
def find(self, x): # 親を探す
if self.par[x] == x:
return x
else:
self.par[x] = self.find(self.par[x])
return self.par[x]
def union(self, x, y): # x,yを繋げる
px = self.find(x)
py = self.find(y)
if px == py:
return
if self.rank[px] < self.rank[py]:
self.par[px] = py
else:
self.par[py] = px
if self.rank[px] == self.rank[py]:
self.rank[px] += 1
def connect(self, x, y): # 親が同じかみる
return self.find(x) == self.find(y)
N, M, K = map(int, input().split())
C = [int(i) for i in input().split()]
table = []
t = K
for i in range(N):
if C[i]==0:
t+=1
C[i]=t
for i in range(M):
s, u, c = map(int, input().split())
a, b = C[s - 1], C[u - 1]
table.append((c, a, b))
tree = Unionfindtree(t+1)
table.sort()
ct = K - 1
ans = 0
for c, a, b in table:
if not tree.connect(a, b) and ct > 0:
tree.union(a, b)
ans += c
ct -= 1
if ct > 0:
print(-1)
else:
print(ans)
``` | output | 1 | 91,558 | 13 | 183,117 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ringo has an undirected graph G with N vertices numbered 1,2,...,N and M edges numbered 1,2,...,M. Edge i connects Vertex a_{i} and b_{i} and has a length of w_i.
Now, he is in the middle of painting these N vertices in K colors numbered 1,2,...,K. Vertex i is already painted in Color c_i, except when c_i = 0, in which case Vertex i is not yet painted.
After he paints each vertex that is not yet painted in one of the K colors, he will give G to Snuke.
Based on G, Snuke will make another undirected graph G' with K vertices numbered 1,2,...,K and M edges. Initially, there is no edge in G'. The i-th edge will be added as follows:
* Let x and y be the colors of the two vertices connected by Edge i in G.
* Add an edge of length w_i connecting Vertex x and y in G'.
What is the minimum possible sum of the lengths of the edges in the minimum spanning tree of G'? If G' will not be connected regardless of how Ringo paints the vertices, print -1.
Constraints
* 1 \leq N,M \leq 10^{5}
* 1 \leq K \leq N
* 0 \leq c_i \leq K
* 1 \leq a_i,b_i \leq N
* 1 \leq w_i \leq 10^{9}
* The given graph may NOT be simple or connected.
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N M K
c_1 c_2 ... c_{N}
a_1 b_1 w_1
:
a_M b_M w_M
Output
Print the answer.
Examples
Input
4 3 3
1 0 1 2
1 2 10
2 3 20
2 4 50
Output
60
Input
5 2 4
0 0 0 0 0
1 2 10
2 3 10
Output
-1
Input
9 12 9
1 2 3 4 5 6 7 8 9
6 9 9
8 9 6
6 7 85
9 5 545631016
2 1 321545
1 6 33562944
7 3 84946329
9 7 15926167
4 7 53386480
5 8 70476
4 6 4549
4 8 8
Output
118901402
Input
18 37 12
5 0 4 10 8 7 2 10 6 0 9 12 12 11 11 11 0 1
17 1 1
11 16 7575
11 15 9
10 10 289938980
5 10 17376
18 4 1866625
8 11 959154208
18 13 200
16 13 2
2 7 982223
12 12 9331
13 12 8861390
14 13 743
2 10 162440
2 4 981849
7 9 1
14 17 2800
2 7 7225452
3 7 85
5 17 4
2 13 1
10 3 45
1 15 973
14 7 56553306
16 17 70476
7 18 9
9 13 27911
18 14 7788322
11 11 8925
9 13 654295
2 10 9
10 1 545631016
3 4 5
17 12 1929
2 11 57
1 5 4
1 17 7807368
Output
171
Submitted Solution:
```
#include <bits/stdc++.h>
using namespace std;
const long long INF =
sizeof(long long) == sizeof(long long) ? 0x3f3f3f3f3f3f3f3fLL : 0x3f3f3f3f;
const long long MOD = (long long)(1e9) + 7;
const double PI = acos(-1);
const double EPS = 1e-9;
using pii = pair<long long, long long>;
template <typename T, typename S>
istream &operator>>(istream &is, pair<T, S> &p) {
is >> p.first >> p.second;
return is;
}
template <typename T, typename S>
ostream &operator<<(ostream &os, pair<T, S> &p) {
os << p.first << " " << p.second;
return os;
}
template <typename T>
void printvv(const vector<vector<T>> &v) {
cerr << endl;
for (long long i = (0); i < (v.size()); i++)
for (long long j = (0); j < (v[i].size()); j++) {
if (typeid(v[i][j]).name() == typeid(INF).name() and v[i][j] == INF) {
cerr << "INF";
} else
cerr << v[i][j];
cerr << (j == v[i].size() - 1 ? '\n' : ' ');
}
cerr << endl;
}
void YES(bool f) { cout << (f ? "YES" : "NO") << endl; }
void Yes(bool f) { cout << (f ? "Yes" : "No") << endl; }
template <class T>
bool chmax(T &a, const T &b) {
if (a < b) {
a = b;
return true;
}
return false;
}
template <class T>
bool chmin(T &a, const T &b) {
if (a > b) {
a = b;
return true;
}
return false;
}
using Weight = long long;
using Flow = long long;
struct Edge {
long long s, d;
Weight w;
Flow c;
Edge(){};
Edge(long long s, long long d, Weight w = 1) : s(s), d(d), w(w), c(w){};
};
bool operator<(const Edge &e1, const Edge &e2) { return e1.w < e2.w; }
bool operator>(const Edge &e1, const Edge &e2) { return e2 < e1; }
inline ostream &operator<<(ostream &os, const Edge &e) {
return (os << '(' << e.s << ", " << e.d << ", " << e.w << ')');
}
using Edges = vector<Edge>;
using Graph = vector<Edges>;
using Array = vector<Weight>;
using Matrix = vector<Array>;
void addArc(Graph &g, long long s, long long d, Weight w = 1) {
g[s].emplace_back(s, d, w);
}
void addEdge(Graph &g, long long a, long long b, Weight w = 1) {
addArc(g, a, b, w);
addArc(g, b, a, w);
}
struct DisjointSet {
vector<long long> rank, p, S;
DisjointSet() {}
DisjointSet(long long size) {
S.resize(size, 1);
rank.resize(size, 0);
p.resize(size, 0);
for (long long i = (0); i < (size); i++) makeSet(i);
}
void makeSet(long long x) {
p[x] = x;
rank[x] = 0;
}
bool same(long long x, long long y) { return findSet(x) == findSet(y); }
void unite(long long x, long long y) {
if (same(x, y)) return;
link(findSet(x), findSet(y));
}
void link(long long x, long long y) {
if (rank[x] > rank[y]) {
p[y] = x;
} else {
p[x] = y;
if (rank[x] == rank[y]) {
rank[y]++;
}
}
S[x] = S[y] = S[x] + S[y];
}
long long findSet(long long x) {
if (x != p[x]) {
p[x] = findSet(p[x]);
}
return p[x];
}
long long connectedComponentSize(long long x) { return S[findSet(x)]; }
};
long long kruskal(long long N, long long K, vector<Edge> &edges) {
long long totalCost = 0;
sort(begin(edges), end(edges));
DisjointSet dset(N);
long long k = 0;
for (long long i = (0); i < (edges.size()); i++) {
Edge e = edges[i];
if (!dset.same(e.s, e.d)) {
totalCost += e.w;
dset.unite(e.s, e.d);
k++;
if (k == K - 1) break;
}
}
if (k != K - 1) totalCost = -1;
return totalCost;
}
signed main(signed argc, char *argv[]) {
cin.tie(0);
ios::sync_with_stdio(false);
cout << fixed << setprecision(12);
long long N, M;
cin >> N >> M;
long long K;
cin >> K;
vector<long long> c(N);
long long x = K;
for (long long i = (0); i < (N); i++) {
cin >> c[i];
c[i]--;
if (c[i] == -1) c[i] = x++;
}
Edges es;
for (long long loop = ((0)); loop < ((M)); loop++) {
long long a, b, w;
cin >> a >> b >> w;
a--, b--;
es.emplace_back(c[a], c[b], w);
}
cout << kruskal(x, K, es) << endl;
return 0;
}
``` | instruction | 0 | 91,559 | 13 | 183,118 |
No | output | 1 | 91,559 | 13 | 183,119 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ringo has an undirected graph G with N vertices numbered 1,2,...,N and M edges numbered 1,2,...,M. Edge i connects Vertex a_{i} and b_{i} and has a length of w_i.
Now, he is in the middle of painting these N vertices in K colors numbered 1,2,...,K. Vertex i is already painted in Color c_i, except when c_i = 0, in which case Vertex i is not yet painted.
After he paints each vertex that is not yet painted in one of the K colors, he will give G to Snuke.
Based on G, Snuke will make another undirected graph G' with K vertices numbered 1,2,...,K and M edges. Initially, there is no edge in G'. The i-th edge will be added as follows:
* Let x and y be the colors of the two vertices connected by Edge i in G.
* Add an edge of length w_i connecting Vertex x and y in G'.
What is the minimum possible sum of the lengths of the edges in the minimum spanning tree of G'? If G' will not be connected regardless of how Ringo paints the vertices, print -1.
Constraints
* 1 \leq N,M \leq 10^{5}
* 1 \leq K \leq N
* 0 \leq c_i \leq K
* 1 \leq a_i,b_i \leq N
* 1 \leq w_i \leq 10^{9}
* The given graph may NOT be simple or connected.
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N M K
c_1 c_2 ... c_{N}
a_1 b_1 w_1
:
a_M b_M w_M
Output
Print the answer.
Examples
Input
4 3 3
1 0 1 2
1 2 10
2 3 20
2 4 50
Output
60
Input
5 2 4
0 0 0 0 0
1 2 10
2 3 10
Output
-1
Input
9 12 9
1 2 3 4 5 6 7 8 9
6 9 9
8 9 6
6 7 85
9 5 545631016
2 1 321545
1 6 33562944
7 3 84946329
9 7 15926167
4 7 53386480
5 8 70476
4 6 4549
4 8 8
Output
118901402
Input
18 37 12
5 0 4 10 8 7 2 10 6 0 9 12 12 11 11 11 0 1
17 1 1
11 16 7575
11 15 9
10 10 289938980
5 10 17376
18 4 1866625
8 11 959154208
18 13 200
16 13 2
2 7 982223
12 12 9331
13 12 8861390
14 13 743
2 10 162440
2 4 981849
7 9 1
14 17 2800
2 7 7225452
3 7 85
5 17 4
2 13 1
10 3 45
1 15 973
14 7 56553306
16 17 70476
7 18 9
9 13 27911
18 14 7788322
11 11 8925
9 13 654295
2 10 9
10 1 545631016
3 4 5
17 12 1929
2 11 57
1 5 4
1 17 7807368
Output
171
Submitted Solution:
```
N, M, K = map(int, input().split())
*C, = map(int, input().split())
G = [[] for i in range(N)]
E = []
for i in range(M):
a, b, w = map(int, input().split())
G[a-1].append((b-1, w))
G[b-1].append((a-1, w))
E.append((w, a-1, b-1))
def root(parent, x):
if x == parent[x]:
return x
parent[x] = y = root(parent, parent[x])
return y
def unite(parent, x, y):
px = root(parent, x); py = root(parent, y)
if px < py:
parent[py] = px
else:
parent[px] = py
E.sort()
*p, = range(N)
res = 0
for w, a, b in E:
if root(p, a) != root(p, b):
unite(p, a, b)
res += w
if N == K and all(C[i] == i+1 for i in range(N)):
if not all(root(p, i) == 0 for i in range(N)):
print(-1)
exit(0)
print(res)
else:
if all(C[i] == 0 for i in range(N)):
#if not all(root(p, i) == 0 for i in range(N)):
# print(-1)
# exit(0)
print(0)
if all(C[i] != 0 for i in range(N)):
*p, = range(K)
res = 0
for w, a, b in E:
ga = C[a]-1; gb = C[b]-1
if root(p, ga) != root(p, gb):
unite(p, ga, gb)
res += w
if not all(root(p, i) == 0 for i in range(K)):
print(-1)
else:
print(res)
``` | instruction | 0 | 91,560 | 13 | 183,120 |
No | output | 1 | 91,560 | 13 | 183,121 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ringo has an undirected graph G with N vertices numbered 1,2,...,N and M edges numbered 1,2,...,M. Edge i connects Vertex a_{i} and b_{i} and has a length of w_i.
Now, he is in the middle of painting these N vertices in K colors numbered 1,2,...,K. Vertex i is already painted in Color c_i, except when c_i = 0, in which case Vertex i is not yet painted.
After he paints each vertex that is not yet painted in one of the K colors, he will give G to Snuke.
Based on G, Snuke will make another undirected graph G' with K vertices numbered 1,2,...,K and M edges. Initially, there is no edge in G'. The i-th edge will be added as follows:
* Let x and y be the colors of the two vertices connected by Edge i in G.
* Add an edge of length w_i connecting Vertex x and y in G'.
What is the minimum possible sum of the lengths of the edges in the minimum spanning tree of G'? If G' will not be connected regardless of how Ringo paints the vertices, print -1.
Constraints
* 1 \leq N,M \leq 10^{5}
* 1 \leq K \leq N
* 0 \leq c_i \leq K
* 1 \leq a_i,b_i \leq N
* 1 \leq w_i \leq 10^{9}
* The given graph may NOT be simple or connected.
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N M K
c_1 c_2 ... c_{N}
a_1 b_1 w_1
:
a_M b_M w_M
Output
Print the answer.
Examples
Input
4 3 3
1 0 1 2
1 2 10
2 3 20
2 4 50
Output
60
Input
5 2 4
0 0 0 0 0
1 2 10
2 3 10
Output
-1
Input
9 12 9
1 2 3 4 5 6 7 8 9
6 9 9
8 9 6
6 7 85
9 5 545631016
2 1 321545
1 6 33562944
7 3 84946329
9 7 15926167
4 7 53386480
5 8 70476
4 6 4549
4 8 8
Output
118901402
Input
18 37 12
5 0 4 10 8 7 2 10 6 0 9 12 12 11 11 11 0 1
17 1 1
11 16 7575
11 15 9
10 10 289938980
5 10 17376
18 4 1866625
8 11 959154208
18 13 200
16 13 2
2 7 982223
12 12 9331
13 12 8861390
14 13 743
2 10 162440
2 4 981849
7 9 1
14 17 2800
2 7 7225452
3 7 85
5 17 4
2 13 1
10 3 45
1 15 973
14 7 56553306
16 17 70476
7 18 9
9 13 27911
18 14 7788322
11 11 8925
9 13 654295
2 10 9
10 1 545631016
3 4 5
17 12 1929
2 11 57
1 5 4
1 17 7807368
Output
171
Submitted Solution:
```
N, M, K = map(int, input().split())
*C, = map(int, input().split())
G = [[] for i in range(N)]
E = []
for i in range(M):
a, b, w = map(int, input().split())
G[a-1].append((b-1, w))
G[b-1].append((a-1, w))
E.append((w, a-1, b-1))
def root(parent, x):
if x == parent[x]:
return x
parent[x] = y = root(parent, parent[x])
return y
def unite(parent, x, y):
px = root(parent, x); py = root(parent, y)
if px < py:
parent[py] = px
else:
parent[px] = py
E.sort()
*p, = range(N)
res = 0
for w, a, b in E:
if root(p, a) != root(p, b):
unite(p, a, b)
res += w
if N == K and all(C[i] == i+1 for i in range(N)):
if not all(root(p, i) == 0 for i in range(N)):
print(-1)
exit(0)
print(res)
else:
if all(C[i] == 0 for i in range(N)):
count = 0
*p, = range(N)
res = 0
for w, a, b in E:
if root(p, a) != root(p, b) and count < K:
unite(p, a, b)
res += w
count += 1
if count == K:
print(res)
else:
print(-1)
elif all(C[i] != 0 for i in range(N)):
*p, = range(K)
res = 0
for w, a, b in E:
ga = C[a]-1; gb = C[b]-1
if root(p, ga) != root(p, gb):
unite(p, ga, gb)
res += w
if not all(root(p, i) == 0 for i in range(K)):
print(-1)
else:
print(res)
else:
exit(1)
``` | instruction | 0 | 91,561 | 13 | 183,122 |
No | output | 1 | 91,561 | 13 | 183,123 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ringo has an undirected graph G with N vertices numbered 1,2,...,N and M edges numbered 1,2,...,M. Edge i connects Vertex a_{i} and b_{i} and has a length of w_i.
Now, he is in the middle of painting these N vertices in K colors numbered 1,2,...,K. Vertex i is already painted in Color c_i, except when c_i = 0, in which case Vertex i is not yet painted.
After he paints each vertex that is not yet painted in one of the K colors, he will give G to Snuke.
Based on G, Snuke will make another undirected graph G' with K vertices numbered 1,2,...,K and M edges. Initially, there is no edge in G'. The i-th edge will be added as follows:
* Let x and y be the colors of the two vertices connected by Edge i in G.
* Add an edge of length w_i connecting Vertex x and y in G'.
What is the minimum possible sum of the lengths of the edges in the minimum spanning tree of G'? If G' will not be connected regardless of how Ringo paints the vertices, print -1.
Constraints
* 1 \leq N,M \leq 10^{5}
* 1 \leq K \leq N
* 0 \leq c_i \leq K
* 1 \leq a_i,b_i \leq N
* 1 \leq w_i \leq 10^{9}
* The given graph may NOT be simple or connected.
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N M K
c_1 c_2 ... c_{N}
a_1 b_1 w_1
:
a_M b_M w_M
Output
Print the answer.
Examples
Input
4 3 3
1 0 1 2
1 2 10
2 3 20
2 4 50
Output
60
Input
5 2 4
0 0 0 0 0
1 2 10
2 3 10
Output
-1
Input
9 12 9
1 2 3 4 5 6 7 8 9
6 9 9
8 9 6
6 7 85
9 5 545631016
2 1 321545
1 6 33562944
7 3 84946329
9 7 15926167
4 7 53386480
5 8 70476
4 6 4549
4 8 8
Output
118901402
Input
18 37 12
5 0 4 10 8 7 2 10 6 0 9 12 12 11 11 11 0 1
17 1 1
11 16 7575
11 15 9
10 10 289938980
5 10 17376
18 4 1866625
8 11 959154208
18 13 200
16 13 2
2 7 982223
12 12 9331
13 12 8861390
14 13 743
2 10 162440
2 4 981849
7 9 1
14 17 2800
2 7 7225452
3 7 85
5 17 4
2 13 1
10 3 45
1 15 973
14 7 56553306
16 17 70476
7 18 9
9 13 27911
18 14 7788322
11 11 8925
9 13 654295
2 10 9
10 1 545631016
3 4 5
17 12 1929
2 11 57
1 5 4
1 17 7807368
Output
171
Submitted Solution:
```
class Unionfindtree:
def __init__(self, number):
self.par = [i for i in range(number)]
self.rank = [0] * (number)
def find(self, x): # 親を探す
if self.par[x] == x:
return x
else:
self.par[x] = self.find(self.par[x])
return self.par[x]
def union(self, x, y): # x,yを繋げる
px = self.find(x)
py = self.find(y)
if px == py:
return
if self.rank[px] < self.rank[py]:
self.par[px] = py
else:
self.par[py] = px
if self.rank[px] == self.rank[py]:
self.rank[px] += 1
def connect(self, x, y): # 親が同じかみる
return self.find(x) == self.find(y)
N, M, K = map(int, input().split())
C = [int(i) for i in input().split()]
table = []
t = K
dd = {}
for i in range(M):
s, u, c = map(int, input().split())
a, b = C[s - 1], C[u - 1]
if a == 0:
a = dd.get(s, -1)
if a == -1:
t += 1
dd[s] = t
a = t
elif b == 0:
b = dd.get(u, -1)
if b == -1:
t += 1
dd[u] = t
b = t
table.append((c, a, b))
tree = Unionfindtree(t+1)
table.sort()
ct = K - 1
ans = 0
for c, a, b in table:
if not tree.connect(a, b) and ct > 0:
tree.union(a, b)
ans += c
ct -= 1
if ct > 0:
print(-1)
else:
print(ans)
``` | instruction | 0 | 91,562 | 13 | 183,124 |
No | output | 1 | 91,562 | 13 | 183,125 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a simple and connected undirected graph consisting of n nodes and m edges.
Consider any way to pair some subset of these n nodes such that no node is present in more than one pair.
This pairing is valid if for every pair of pairs, the induced subgraph containing all 4 nodes, two from each pair, has at most 2 edges (out of the 6 possible edges). More formally, for any two pairs, (a,b) and (c,d), the induced subgraph with nodes \\{a,b,c,d\} should have at most 2 edges.
Please note that the subgraph induced by a set of nodes contains nodes only from this set and edges which have both of its end points in this set.
Now, do one of the following:
* Find a simple path consisting of at least ⌈ n/2 ⌉ nodes. Here, a path is called simple if it does not visit any node multiple times.
* Find a valid pairing in which at least ⌈ n/2 ⌉ nodes are paired.
It can be shown that it is possible to find at least one of the two in every graph satisfying constraints from the statement.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^5). Description of the test cases follows.
The first line of each test case contains 2 integers n, m (2 ≤ n ≤ 5⋅ 10^5, 1 ≤ m ≤ 10^6), denoting the number of nodes and edges, respectively.
The next m lines each contain 2 integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting that there is an undirected edge between nodes u and v in the given graph.
It is guaranteed that the given graph is connected, and simple — it does not contain multiple edges between the same pair of nodes, nor does it have any self-loops.
It is guaranteed that the sum of n over all test cases does not exceed 5⋅ 10^5.
It is guaranteed that the sum of m over all test cases does not exceed 10^6.
Output
For each test case, the output format is as follows.
If you have found a pairing, in the first line output "PAIRING" (without quotes).
* Then, output k (⌈ n/2 ⌉ ≤ 2⋅ k ≤ n), the number of pairs in your pairing.
* Then, in each of the next k lines, output 2 integers a and b — denoting that a and b are paired with each other. Note that the graph does not have to have an edge between a and b!
* This pairing has to be valid, and every node has to be a part of at most 1 pair.
Otherwise, in the first line output "PATH" (without quotes).
* Then, output k (⌈ n/2 ⌉ ≤ k ≤ n), the number of nodes in your path.
* Then, in the second line, output k integers, v_1, v_2, …, v_k, in the order in which they appear on the path. Formally, v_i and v_{i+1} should have an edge between them for every i (1 ≤ i < k).
* This path has to be simple, meaning no node should appear more than once.
Example
Input
4
6 5
1 4
2 5
3 6
1 5
3 5
6 5
1 4
2 5
3 6
1 5
3 5
12 14
1 2
2 3
3 4
4 1
1 5
1 12
2 6
2 7
3 8
3 9
4 10
4 11
2 4
1 3
12 14
1 2
2 3
3 4
4 1
1 5
1 12
2 6
2 7
3 8
3 9
4 10
4 11
2 4
1 3
Output
PATH
4
1 5 3 6
PAIRING
2
1 6
2 4
PAIRING
3
1 8
2 5
4 10
PAIRING
4
1 7
2 9
3 11
4 5
Note
The path outputted in the first case is the following.
<image>
The pairing outputted in the second case is the following.
<image>
Here is an invalid pairing for the same graph — the subgraph \{1,3,4,5\} has 3 edges.
<image>
Here is the pairing outputted in the third case.
<image>
It's valid because —
* The subgraph \{1,8,2,5\} has edges (1,2) and (1,5).
* The subgraph \{1,8,4,10\} has edges (1,4) and (4,10).
* The subgraph \{4,10,2,5\} has edges (2,4) and (4,10).
Here is the pairing outputted in the fourth case.
<image> | instruction | 0 | 91,902 | 13 | 183,804 |
Tags: constructive algorithms, dfs and similar, graphs, greedy, trees
Correct Solution:
```
# Fast IO (only use in integer input)
import os,io
input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
t = int(input())
for _ in range(t):
n,m = map(int,input().split())
connectionList = []
for _ in range(n):
connectionList.append([])
for _ in range(m):
u,v = map(int,input().split())
connectionList[u-1].append(v-1)
connectionList[v-1].append(u-1)
DFSLevel = [-1] * n
DFSParent = [-1] * n
vertexStack = []
vertexStack.append((0,1,-1)) # vertex depth and parent
while vertexStack:
vertex,depth,parent = vertexStack.pop()
if DFSLevel[vertex] != -1:
continue
DFSLevel[vertex] = depth
DFSParent[vertex] = parent
for nextV in connectionList[vertex]:
if DFSLevel[nextV] == -1:
vertexStack.append((nextV,depth + 1,vertex))
if max(DFSLevel) >= n//2 + n % 2:
for i in range(n):
if DFSLevel[i] >= (n//2 + n%2):
break
longPath = [str(i + 1)]
while DFSParent[i] != -1:
longPath.append(str(DFSParent[i] + 1))
i = DFSParent[i]
print("PATH")
print(len(longPath))
print(" ".join(longPath))
else:
levelWithVertex = list(enumerate(DFSLevel))
levelWithVertex.sort(key = lambda x: x[1])
i = 0
pair = []
while i < len(levelWithVertex) - 1:
if levelWithVertex[i][1] == levelWithVertex[i + 1][1]:
pair.append([levelWithVertex[i][0],levelWithVertex[i + 1][0]])
i += 2
else:
i += 1
print("PAIRING")
print(len(pair))
for elem in pair:
print(str(elem[0] + 1)+" "+str(elem[1] + 1))
``` | output | 1 | 91,902 | 13 | 183,805 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a simple and connected undirected graph consisting of n nodes and m edges.
Consider any way to pair some subset of these n nodes such that no node is present in more than one pair.
This pairing is valid if for every pair of pairs, the induced subgraph containing all 4 nodes, two from each pair, has at most 2 edges (out of the 6 possible edges). More formally, for any two pairs, (a,b) and (c,d), the induced subgraph with nodes \\{a,b,c,d\} should have at most 2 edges.
Please note that the subgraph induced by a set of nodes contains nodes only from this set and edges which have both of its end points in this set.
Now, do one of the following:
* Find a simple path consisting of at least ⌈ n/2 ⌉ nodes. Here, a path is called simple if it does not visit any node multiple times.
* Find a valid pairing in which at least ⌈ n/2 ⌉ nodes are paired.
It can be shown that it is possible to find at least one of the two in every graph satisfying constraints from the statement.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^5). Description of the test cases follows.
The first line of each test case contains 2 integers n, m (2 ≤ n ≤ 5⋅ 10^5, 1 ≤ m ≤ 10^6), denoting the number of nodes and edges, respectively.
The next m lines each contain 2 integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting that there is an undirected edge between nodes u and v in the given graph.
It is guaranteed that the given graph is connected, and simple — it does not contain multiple edges between the same pair of nodes, nor does it have any self-loops.
It is guaranteed that the sum of n over all test cases does not exceed 5⋅ 10^5.
It is guaranteed that the sum of m over all test cases does not exceed 10^6.
Output
For each test case, the output format is as follows.
If you have found a pairing, in the first line output "PAIRING" (without quotes).
* Then, output k (⌈ n/2 ⌉ ≤ 2⋅ k ≤ n), the number of pairs in your pairing.
* Then, in each of the next k lines, output 2 integers a and b — denoting that a and b are paired with each other. Note that the graph does not have to have an edge between a and b!
* This pairing has to be valid, and every node has to be a part of at most 1 pair.
Otherwise, in the first line output "PATH" (without quotes).
* Then, output k (⌈ n/2 ⌉ ≤ k ≤ n), the number of nodes in your path.
* Then, in the second line, output k integers, v_1, v_2, …, v_k, in the order in which they appear on the path. Formally, v_i and v_{i+1} should have an edge between them for every i (1 ≤ i < k).
* This path has to be simple, meaning no node should appear more than once.
Example
Input
4
6 5
1 4
2 5
3 6
1 5
3 5
6 5
1 4
2 5
3 6
1 5
3 5
12 14
1 2
2 3
3 4
4 1
1 5
1 12
2 6
2 7
3 8
3 9
4 10
4 11
2 4
1 3
12 14
1 2
2 3
3 4
4 1
1 5
1 12
2 6
2 7
3 8
3 9
4 10
4 11
2 4
1 3
Output
PATH
4
1 5 3 6
PAIRING
2
1 6
2 4
PAIRING
3
1 8
2 5
4 10
PAIRING
4
1 7
2 9
3 11
4 5
Note
The path outputted in the first case is the following.
<image>
The pairing outputted in the second case is the following.
<image>
Here is an invalid pairing for the same graph — the subgraph \{1,3,4,5\} has 3 edges.
<image>
Here is the pairing outputted in the third case.
<image>
It's valid because —
* The subgraph \{1,8,2,5\} has edges (1,2) and (1,5).
* The subgraph \{1,8,4,10\} has edges (1,4) and (4,10).
* The subgraph \{4,10,2,5\} has edges (2,4) and (4,10).
Here is the pairing outputted in the fourth case.
<image>
Submitted Solution:
```
# Fast IO (only use in integer input)
# import os,io
# input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
t = int(input())
for _ in range(t):
n,m = map(int,input().split())
connectionList = []
for _ in range(n):
connectionList.append([])
for _ in range(m):
u,v = map(int,input().split())
connectionList[u-1].append(v-1)
connectionList[v-1].append(u-1)
DFSLevel = [-1] * n
DFSParent = [-1] * n
vertexStack = []
vertexStack.append((0,1,-1)) # vertex depth and parent
while vertexStack:
vertex,depth,parent = vertexStack.pop()
if DFSLevel[vertex] != -1:
continue
DFSLevel[vertex] = depth
DFSParent[vertex] = parent
for nextV in connectionList[vertex]:
if DFSLevel[nextV] == -1:
vertexStack.append((nextV,depth + 1,vertex))
if max(DFSLevel) >= n//2 + n % 2:
for i in range(n):
if DFSLevel[i] >= (n//2 + n%2):
break
longPath = [str(i + 1)]
while DFSParent[i] != -1:
longPath.append(str(DFSParent[i] + 1))
i = DFSParent[i]
print("PATH")
print(len(longPath))
print(" ".join(longPath))
else:
levelWithVertex = list(enumerate(DFSLevel))
levelWithVertex.sort(key = lambda x: x[1])
i = 0
pair = []
while i < len(levelWithVertex) - 1:
if levelWithVertex[i][1] == levelWithVertex[i + 1][1]:
pair.append([levelWithVertex[i][0],levelWithVertex[i + 1][0]])
i += 2
else:
i += 1
print("PAIRING")
print(len(pair))
for elem in pair:
print(str(elem[0])+" "+str(elem[1]))
``` | instruction | 0 | 91,903 | 13 | 183,806 |
No | output | 1 | 91,903 | 13 | 183,807 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a simple and connected undirected graph consisting of n nodes and m edges.
Consider any way to pair some subset of these n nodes such that no node is present in more than one pair.
This pairing is valid if for every pair of pairs, the induced subgraph containing all 4 nodes, two from each pair, has at most 2 edges (out of the 6 possible edges). More formally, for any two pairs, (a,b) and (c,d), the induced subgraph with nodes \\{a,b,c,d\} should have at most 2 edges.
Please note that the subgraph induced by a set of nodes contains nodes only from this set and edges which have both of its end points in this set.
Now, do one of the following:
* Find a simple path consisting of at least ⌈ n/2 ⌉ nodes. Here, a path is called simple if it does not visit any node multiple times.
* Find a valid pairing in which at least ⌈ n/2 ⌉ nodes are paired.
It can be shown that it is possible to find at least one of the two in every graph satisfying constraints from the statement.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^5). Description of the test cases follows.
The first line of each test case contains 2 integers n, m (2 ≤ n ≤ 5⋅ 10^5, 1 ≤ m ≤ 10^6), denoting the number of nodes and edges, respectively.
The next m lines each contain 2 integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting that there is an undirected edge between nodes u and v in the given graph.
It is guaranteed that the given graph is connected, and simple — it does not contain multiple edges between the same pair of nodes, nor does it have any self-loops.
It is guaranteed that the sum of n over all test cases does not exceed 5⋅ 10^5.
It is guaranteed that the sum of m over all test cases does not exceed 10^6.
Output
For each test case, the output format is as follows.
If you have found a pairing, in the first line output "PAIRING" (without quotes).
* Then, output k (⌈ n/2 ⌉ ≤ 2⋅ k ≤ n), the number of pairs in your pairing.
* Then, in each of the next k lines, output 2 integers a and b — denoting that a and b are paired with each other. Note that the graph does not have to have an edge between a and b!
* This pairing has to be valid, and every node has to be a part of at most 1 pair.
Otherwise, in the first line output "PATH" (without quotes).
* Then, output k (⌈ n/2 ⌉ ≤ k ≤ n), the number of nodes in your path.
* Then, in the second line, output k integers, v_1, v_2, …, v_k, in the order in which they appear on the path. Formally, v_i and v_{i+1} should have an edge between them for every i (1 ≤ i < k).
* This path has to be simple, meaning no node should appear more than once.
Example
Input
4
6 5
1 4
2 5
3 6
1 5
3 5
6 5
1 4
2 5
3 6
1 5
3 5
12 14
1 2
2 3
3 4
4 1
1 5
1 12
2 6
2 7
3 8
3 9
4 10
4 11
2 4
1 3
12 14
1 2
2 3
3 4
4 1
1 5
1 12
2 6
2 7
3 8
3 9
4 10
4 11
2 4
1 3
Output
PATH
4
1 5 3 6
PAIRING
2
1 6
2 4
PAIRING
3
1 8
2 5
4 10
PAIRING
4
1 7
2 9
3 11
4 5
Note
The path outputted in the first case is the following.
<image>
The pairing outputted in the second case is the following.
<image>
Here is an invalid pairing for the same graph — the subgraph \{1,3,4,5\} has 3 edges.
<image>
Here is the pairing outputted in the third case.
<image>
It's valid because —
* The subgraph \{1,8,2,5\} has edges (1,2) and (1,5).
* The subgraph \{1,8,4,10\} has edges (1,4) and (4,10).
* The subgraph \{4,10,2,5\} has edges (2,4) and (4,10).
Here is the pairing outputted in the fourth case.
<image>
Submitted Solution:
```
import sys
sys.setrecursionlimit(10 ** 5)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def MI1(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]
for _ in range(II()):
n,m=MI()
to=[[] for _ in range(n+1)]
for _ in range(m):
u,v=MI()
to[u].append(v)
to[v].append(u)
pp=[-1]*(n+1)
dtou=[[]]
stack=[(1,0,1)]
while stack:
u,pu,d=stack.pop()
pp[u]=pu
if len(dtou)<d+1:dtou.append([])
dtou[d].append(u)
for v in to[u]:
if pp[v]!=-1:continue
stack.append((v,u,d+1))
#print(pp)
#print(dtou)
if len(dtou)-1>=(n+1)//2:
print("PATH")
ans=[dtou[-1][0]]
while ans[-1]!=1:
ans.append(pp[ans[-1]])
print(len(ans))
print(*ans)
else:
print("PAIRING")
ans=[]
for uu in dtou:
for u1,u2 in zip(uu[::2],uu[1::2]):
ans.append((u1,u2))
print(len(ans))
for u,v in ans:print(u,v)
``` | instruction | 0 | 91,904 | 13 | 183,808 |
No | output | 1 | 91,904 | 13 | 183,809 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a simple and connected undirected graph consisting of n nodes and m edges.
Consider any way to pair some subset of these n nodes such that no node is present in more than one pair.
This pairing is valid if for every pair of pairs, the induced subgraph containing all 4 nodes, two from each pair, has at most 2 edges (out of the 6 possible edges). More formally, for any two pairs, (a,b) and (c,d), the induced subgraph with nodes \\{a,b,c,d\} should have at most 2 edges.
Please note that the subgraph induced by a set of nodes contains nodes only from this set and edges which have both of its end points in this set.
Now, do one of the following:
* Find a simple path consisting of at least ⌈ n/2 ⌉ nodes. Here, a path is called simple if it does not visit any node multiple times.
* Find a valid pairing in which at least ⌈ n/2 ⌉ nodes are paired.
It can be shown that it is possible to find at least one of the two in every graph satisfying constraints from the statement.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^5). Description of the test cases follows.
The first line of each test case contains 2 integers n, m (2 ≤ n ≤ 5⋅ 10^5, 1 ≤ m ≤ 10^6), denoting the number of nodes and edges, respectively.
The next m lines each contain 2 integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting that there is an undirected edge between nodes u and v in the given graph.
It is guaranteed that the given graph is connected, and simple — it does not contain multiple edges between the same pair of nodes, nor does it have any self-loops.
It is guaranteed that the sum of n over all test cases does not exceed 5⋅ 10^5.
It is guaranteed that the sum of m over all test cases does not exceed 10^6.
Output
For each test case, the output format is as follows.
If you have found a pairing, in the first line output "PAIRING" (without quotes).
* Then, output k (⌈ n/2 ⌉ ≤ 2⋅ k ≤ n), the number of pairs in your pairing.
* Then, in each of the next k lines, output 2 integers a and b — denoting that a and b are paired with each other. Note that the graph does not have to have an edge between a and b!
* This pairing has to be valid, and every node has to be a part of at most 1 pair.
Otherwise, in the first line output "PATH" (without quotes).
* Then, output k (⌈ n/2 ⌉ ≤ k ≤ n), the number of nodes in your path.
* Then, in the second line, output k integers, v_1, v_2, …, v_k, in the order in which they appear on the path. Formally, v_i and v_{i+1} should have an edge between them for every i (1 ≤ i < k).
* This path has to be simple, meaning no node should appear more than once.
Example
Input
4
6 5
1 4
2 5
3 6
1 5
3 5
6 5
1 4
2 5
3 6
1 5
3 5
12 14
1 2
2 3
3 4
4 1
1 5
1 12
2 6
2 7
3 8
3 9
4 10
4 11
2 4
1 3
12 14
1 2
2 3
3 4
4 1
1 5
1 12
2 6
2 7
3 8
3 9
4 10
4 11
2 4
1 3
Output
PATH
4
1 5 3 6
PAIRING
2
1 6
2 4
PAIRING
3
1 8
2 5
4 10
PAIRING
4
1 7
2 9
3 11
4 5
Note
The path outputted in the first case is the following.
<image>
The pairing outputted in the second case is the following.
<image>
Here is an invalid pairing for the same graph — the subgraph \{1,3,4,5\} has 3 edges.
<image>
Here is the pairing outputted in the third case.
<image>
It's valid because —
* The subgraph \{1,8,2,5\} has edges (1,2) and (1,5).
* The subgraph \{1,8,4,10\} has edges (1,4) and (4,10).
* The subgraph \{4,10,2,5\} has edges (2,4) and (4,10).
Here is the pairing outputted in the fourth case.
<image>
Submitted Solution:
```
import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
n, m = map(int,input().split())
adj = [[] for i in range(n)]
check = set()
for edj in range(m):
a, b = map(int, input().split())
a -= 1
b -= 1
adj[a].append(b)
adj[b].append(a)
check.add((a,b))
check.add((b,a))
todo = list(range(n))
pair = [-1] * n
stack = []
while todo:
i = todo.pop()
if len(stack) == 0:
stack.append(i)
continue
top = stack[-1]
if (top, i) in check:
stack.append(i)
continue
for test in adj[i]:
if pair[i] == -1:
continue
if (test, top) in check:
stack.append(test)
stack.append(i)
todo.append(pair[test])
pair[pair[test]] = -1
pair[test] = -1
else:
stack.pop()
pair[top] = i
pair[i] = top
if len(stack) >= n - len(stack):
print('PATH')
print(len(stack))
print(''.join(lambda x: str(x + 1), stack))
else:
print('PAIRING')
print((n - len(stack))//2)
out = []
for i in range(n):
if pair[i] > i:
out.append(str(pair[i] + 1)+' '+str(i + 1))
print('\n'.join(out))
``` | instruction | 0 | 91,905 | 13 | 183,810 |
No | output | 1 | 91,905 | 13 | 183,811 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a simple and connected undirected graph consisting of n nodes and m edges.
Consider any way to pair some subset of these n nodes such that no node is present in more than one pair.
This pairing is valid if for every pair of pairs, the induced subgraph containing all 4 nodes, two from each pair, has at most 2 edges (out of the 6 possible edges). More formally, for any two pairs, (a,b) and (c,d), the induced subgraph with nodes \\{a,b,c,d\} should have at most 2 edges.
Please note that the subgraph induced by a set of nodes contains nodes only from this set and edges which have both of its end points in this set.
Now, do one of the following:
* Find a simple path consisting of at least ⌈ n/2 ⌉ nodes. Here, a path is called simple if it does not visit any node multiple times.
* Find a valid pairing in which at least ⌈ n/2 ⌉ nodes are paired.
It can be shown that it is possible to find at least one of the two in every graph satisfying constraints from the statement.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^5). Description of the test cases follows.
The first line of each test case contains 2 integers n, m (2 ≤ n ≤ 5⋅ 10^5, 1 ≤ m ≤ 10^6), denoting the number of nodes and edges, respectively.
The next m lines each contain 2 integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting that there is an undirected edge between nodes u and v in the given graph.
It is guaranteed that the given graph is connected, and simple — it does not contain multiple edges between the same pair of nodes, nor does it have any self-loops.
It is guaranteed that the sum of n over all test cases does not exceed 5⋅ 10^5.
It is guaranteed that the sum of m over all test cases does not exceed 10^6.
Output
For each test case, the output format is as follows.
If you have found a pairing, in the first line output "PAIRING" (without quotes).
* Then, output k (⌈ n/2 ⌉ ≤ 2⋅ k ≤ n), the number of pairs in your pairing.
* Then, in each of the next k lines, output 2 integers a and b — denoting that a and b are paired with each other. Note that the graph does not have to have an edge between a and b!
* This pairing has to be valid, and every node has to be a part of at most 1 pair.
Otherwise, in the first line output "PATH" (without quotes).
* Then, output k (⌈ n/2 ⌉ ≤ k ≤ n), the number of nodes in your path.
* Then, in the second line, output k integers, v_1, v_2, …, v_k, in the order in which they appear on the path. Formally, v_i and v_{i+1} should have an edge between them for every i (1 ≤ i < k).
* This path has to be simple, meaning no node should appear more than once.
Example
Input
4
6 5
1 4
2 5
3 6
1 5
3 5
6 5
1 4
2 5
3 6
1 5
3 5
12 14
1 2
2 3
3 4
4 1
1 5
1 12
2 6
2 7
3 8
3 9
4 10
4 11
2 4
1 3
12 14
1 2
2 3
3 4
4 1
1 5
1 12
2 6
2 7
3 8
3 9
4 10
4 11
2 4
1 3
Output
PATH
4
1 5 3 6
PAIRING
2
1 6
2 4
PAIRING
3
1 8
2 5
4 10
PAIRING
4
1 7
2 9
3 11
4 5
Note
The path outputted in the first case is the following.
<image>
The pairing outputted in the second case is the following.
<image>
Here is an invalid pairing for the same graph — the subgraph \{1,3,4,5\} has 3 edges.
<image>
Here is the pairing outputted in the third case.
<image>
It's valid because —
* The subgraph \{1,8,2,5\} has edges (1,2) and (1,5).
* The subgraph \{1,8,4,10\} has edges (1,4) and (4,10).
* The subgraph \{4,10,2,5\} has edges (2,4) and (4,10).
Here is the pairing outputted in the fourth case.
<image>
Submitted Solution:
```
import sys
import threading
from sys import stdin, stdout
sys.setrecursionlimit(10**4)
threading.stack_size(32*1024)
def dfs(node, depth, n, visited, dic, plist, dep_a):
if node in visited:
return
visited.add(node)
plist.append(node)
if depth > 0:
dep_a[depth].append(node)
if len(plist) > n//2:
return plist
for ch in dic[node]:
res = dfs(ch, depth + 1, n, visited, dic, plist, dep_a)
if res:
return res
plist.pop()
return []
def pairs_of_pairs(n, m, dic):
dep_a = [[] for i in range(n//2 + 1)]
ans = dfs(1, 0, n, set(), dic, [], dep_a)
if ans:
return [1, ans]
else:
ans2 = []
for dep in dep_a:
while len(dep) > 1:
ans2.append([dep.pop(), dep.pop()])
return [2, ans2]
def solve():
t = int(stdin.readline())
for _ in range(t):
dic = {}
n, m = map(int, stdin.readline().split())
for _ in range(m):
u, v = map(int, stdin.readline().split())
if u not in dic:
dic[u] = []
if v not in dic:
dic[v] = []
dic[u].append(v)
dic[v].append(u)
ans = pairs_of_pairs(n, m, dic)
if ans[0] == 1:
stdout.write('PATH\n')
stdout.write(str(len(ans[1])) + '\n')
stdout.write(' '.join(map(str, ans[1])) + '\n')
else:
stdout.write('PAIRING\n')
stdout.write(str(len(ans[1])) + '\n')
for p in ans[1]:
stdout.write(' '.join(map(str, p)) + '\n')
threading.Thread(target=solve).start()
#solve()
``` | instruction | 0 | 91,906 | 13 | 183,812 |
No | output | 1 | 91,906 | 13 | 183,813 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is a connected graph that doesn't contain any cycles.
The distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices.
You are given a tree with n vertices and a positive number k. Find the number of distinct pairs of the vertices which have a distance of exactly k between them. Note that pairs (v, u) and (u, v) are considered to be the same pair.
Input
The first line contains two integers n and k (1 ≤ n ≤ 50000, 1 ≤ k ≤ 500) — the number of vertices and the required distance between the vertices.
Next n - 1 lines describe the edges as "ai bi" (without the quotes) (1 ≤ ai, bi ≤ n, ai ≠ bi), where ai and bi are the vertices connected by the i-th edge. All given edges are different.
Output
Print a single integer — the number of distinct pairs of the tree's vertices which have a distance of exactly k between them.
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
5 2
1 2
2 3
3 4
2 5
Output
4
Input
5 3
1 2
2 3
3 4
4 5
Output
2
Note
In the first sample the pairs of vertexes at distance 2 from each other are (1, 3), (1, 5), (3, 5) and (2, 4). | instruction | 0 | 91,991 | 13 | 183,982 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
import sys
from array import array # noqa: F401
import typing as Tp # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
def output(*args):
sys.stdout.buffer.write(
('\n'.join(map(str, args)) + '\n').encode('utf-8')
)
def main():
n, k = map(int, input().split())
adj = [[] for _ in range(n)]
for u, v in (map(int, input().split()) for _ in range(n - 1)):
adj[u - 1].append(v - 1)
adj[v - 1].append(u - 1)
route = []
parent = [-1] * n
stack = [0]
while stack:
v = stack.pop()
route.append(v)
for dest in adj[v]:
if dest == parent[v]:
continue
parent[dest] = v
stack.append(dest)
ans = 0
dp = [[1] + [0] * k for _ in range(n)]
for v in reversed(route):
ans += dp[v][k] * 2
for child in adj[v]:
if child == parent[v]:
continue
for i in range(1, k):
ans += dp[child][i - 1] * (dp[v][k - i] - dp[child][k - i - 1])
if v != 0:
for i in range(k):
dp[parent[v]][i + 1] += dp[v][i]
print(ans >> 1)
if __name__ == '__main__':
main()
``` | output | 1 | 91,991 | 13 | 183,983 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is a connected graph that doesn't contain any cycles.
The distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices.
You are given a tree with n vertices and a positive number k. Find the number of distinct pairs of the vertices which have a distance of exactly k between them. Note that pairs (v, u) and (u, v) are considered to be the same pair.
Input
The first line contains two integers n and k (1 ≤ n ≤ 50000, 1 ≤ k ≤ 500) — the number of vertices and the required distance between the vertices.
Next n - 1 lines describe the edges as "ai bi" (without the quotes) (1 ≤ ai, bi ≤ n, ai ≠ bi), where ai and bi are the vertices connected by the i-th edge. All given edges are different.
Output
Print a single integer — the number of distinct pairs of the tree's vertices which have a distance of exactly k between them.
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
5 2
1 2
2 3
3 4
2 5
Output
4
Input
5 3
1 2
2 3
3 4
4 5
Output
2
Note
In the first sample the pairs of vertexes at distance 2 from each other are (1, 3), (1, 5), (3, 5) and (2, 4). | instruction | 0 | 91,992 | 13 | 183,984 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
"""
#If FastIO not needed, used this and don't forget to strip
#import sys, math
#input = sys.stdin.readline
"""
import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
from types import GeneratorType
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
self.os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
import collections as col
import math, string
def getInts():
return [int(s) for s in input().split()]
def getInt():
return int(input())
def getStrs():
return [s for s in input().split()]
def getStr():
return input()
def listStr():
return list(input())
MOD = 10**9+7
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
"""
Pick a root
Within each subtree, count: the number of nodes at levels 1 to K in that subtree
dp = [0]*500
So, dp[node][level] = number of nodes at level K
dp[node][0] = 1 for every node
"""
def solve():
N, K = getInts()
graph = col.defaultdict(set)
dp = [[0 for k in range(K+1)] for n in range(N)]
for n in range(N-1):
U, V = getInts()
U -= 1
V -= 1
graph[U].add(V)
graph[V].add(U)
visited = set()
@bootstrap
def dfs(node):
dp[node][0] = 1
visited.add(node)
for neighbour in graph[node]:
if neighbour not in visited:
yield dfs(neighbour)
for k in range(K):
dp[node][k+1] += dp[neighbour][k]
yield
dfs(0)
ans = 0
#print(dp)
visited = set()
for n in range(N):
visited.add(n)
ans += dp[n][K]
tmp = 0
for neighbour in graph[n]:
if neighbour not in visited:
for k in range(1,K):
tmp += dp[neighbour][k-1]*(dp[n][K-k] - dp[neighbour][K-k-1])
tmp //= 2
ans += tmp
#print(n+1,dp[n][K],ans,tmp)
return ans
#for _ in range(getInt()):
print(solve())
``` | output | 1 | 91,992 | 13 | 183,985 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is a connected graph that doesn't contain any cycles.
The distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices.
You are given a tree with n vertices and a positive number k. Find the number of distinct pairs of the vertices which have a distance of exactly k between them. Note that pairs (v, u) and (u, v) are considered to be the same pair.
Input
The first line contains two integers n and k (1 ≤ n ≤ 50000, 1 ≤ k ≤ 500) — the number of vertices and the required distance between the vertices.
Next n - 1 lines describe the edges as "ai bi" (without the quotes) (1 ≤ ai, bi ≤ n, ai ≠ bi), where ai and bi are the vertices connected by the i-th edge. All given edges are different.
Output
Print a single integer — the number of distinct pairs of the tree's vertices which have a distance of exactly k between them.
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
5 2
1 2
2 3
3 4
2 5
Output
4
Input
5 3
1 2
2 3
3 4
4 5
Output
2
Note
In the first sample the pairs of vertexes at distance 2 from each other are (1, 3), (1, 5), (3, 5) and (2, 4). | instruction | 0 | 91,993 | 13 | 183,986 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
# Author : nitish420 --------------------------------------------------------------------
import os
import sys
from io import BytesIO, IOBase
def main():
n,k=map(int,input().split())
tree=[[] for _ in range(n+1)]
# 1 indexed
for _ in range(n-1):
a,b=map(int,input().split())
tree[a].append(b)
tree[b].append(a)
dp=[[0 for _ in range(k+1)] for _ in range(n+1)]
idx=[0]*(n+1)
stack=[(1,0)]
ans=0
dp[1][0]=1
while stack:
x,p=stack[-1]
y=idx[x]
if y==len(tree[x]):
if x==1:
break
for i in range(k,0,-1):
dp[x][i]=dp[x][i-1]
dp[x][0]=0
for i in range(k+1):
ans+=dp[p][i]*dp[x][k-i]
dp[p][i]+=dp[x][i]
stack.pop()
else:
z=tree[x][y]
if z!=p:
dp[z][0]=1
stack.append((z,x))
idx[x]+=1
print(ans)
#----------------------------------------------------------------------------------------
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = 'x' in file.mode or 'r' not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b'\n') + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode('ascii'))
self.read = lambda: self.buffer.read().decode('ascii')
self.readline = lambda: self.buffer.readline().decode('ascii')
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')
# endregion
if __name__ == '__main__':
main()
``` | output | 1 | 91,993 | 13 | 183,987 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is a connected graph that doesn't contain any cycles.
The distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices.
You are given a tree with n vertices and a positive number k. Find the number of distinct pairs of the vertices which have a distance of exactly k between them. Note that pairs (v, u) and (u, v) are considered to be the same pair.
Input
The first line contains two integers n and k (1 ≤ n ≤ 50000, 1 ≤ k ≤ 500) — the number of vertices and the required distance between the vertices.
Next n - 1 lines describe the edges as "ai bi" (without the quotes) (1 ≤ ai, bi ≤ n, ai ≠ bi), where ai and bi are the vertices connected by the i-th edge. All given edges are different.
Output
Print a single integer — the number of distinct pairs of the tree's vertices which have a distance of exactly k between them.
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
5 2
1 2
2 3
3 4
2 5
Output
4
Input
5 3
1 2
2 3
3 4
4 5
Output
2
Note
In the first sample the pairs of vertexes at distance 2 from each other are (1, 3), (1, 5), (3, 5) and (2, 4). | instruction | 0 | 91,994 | 13 | 183,988 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
n, k = map(int, input().split())
t, q = [[] for i in range(n + 1)], [1]
for j in range(n - 1):
a, b = map(int, input().split())
t[a].append(b)
t[b].append(a)
for x in q:
for y in t[x]: t[y].remove(x)
q.extend(t[x])
q.reverse()
a, luismore = {}, 0
for x in q:
a[x] = [1]
u = len(a[x])
for y in t[x]:
v = len(a[y])
for d in range(max(0, k - u), v): luismore += a[y][d] * a[x][k - d - 1]
if v >= u:
for d in range(u - 1): a[x][d + 1] += a[y][d]
a[x] += a[y][u - 1: ]
u = v + 1
else:
for d in range(0, v): a[x][d + 1] += a[y][d]
if u > k: a[x].pop()
print(luismore)
#<3
``` | output | 1 | 91,994 | 13 | 183,989 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.