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 a tree T with N vertices and an undirected graph G with N vertices and M edges. The vertices of each graph are numbered 1 to N. The i-th of the N-1 edges in T connects Vertex a_i and Vertex b_i, and the j-th of the M edges in G connects Vertex c_j and Vertex d_j.
Consider adding edges to G by repeatedly performing the following operation:
* Choose three integers a, b and c such that G has an edge connecting Vertex a and b and an edge connecting Vertex b and c but not an edge connecting Vertex a and c. If there is a simple path in T that contains all three of Vertex a, b and c in some order, add an edge in G connecting Vertex a and c.
Print the number of edges in G when no more edge can be added. It can be shown that this number does not depend on the choices made in the operation.
Constraints
* 2 \leq N \leq 2000
* 1 \leq M \leq 2000
* 1 \leq a_i, b_i \leq N
* a_i \neq b_i
* 1 \leq c_j, d_j \leq N
* c_j \neq d_j
* G does not contain multiple edges.
* T is a tree.
Input
Input is given from Standard Input in the following format:
N M
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 d_1
:
c_M d_M
Output
Print the final number of edges in G.
Examples
Input
5 3
1 2
1 3
3 4
1 5
5 4
2 5
1 5
Output
6
Input
7 5
1 5
1 4
1 7
1 2
2 6
6 3
2 5
1 3
1 6
4 6
4 7
Output
11
Input
13 11
6 13
1 2
5 1
8 4
9 7
12 2
10 11
1 9
13 7
13 11
8 10
3 8
4 13
8 12
4 7
2 3
5 11
1 4
2 11
8 10
3 5
6 9
4 10
Output
27
Submitted Solution:
```
# no sub撤退をしないという覚悟
print('nan')
``` | instruction | 0 | 13,159 | 13 | 26,318 |
No | output | 1 | 13,159 | 13 | 26,319 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.
One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.
Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.
Input
The first line contains two space-separated integers n and k (1 ≤ k < n ≤ 105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph.
The second line contains space-separated integers d[1], d[2], ..., d[n] (0 ≤ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.
Output
If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 ≤ m ≤ 106) — the number of edges in the found graph.
In each of the next m lines print two space-separated integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.
Examples
Input
3 2
0 1 1
Output
3
1 2
1 3
3 2
Input
4 2
2 0 1 3
Output
3
1 3
1 4
2 3
Input
3 1
0 0 0
Output
-1 | instruction | 0 | 13,625 | 13 | 27,250 |
Tags: dfs and similar, graphs, sortings
Correct Solution:
```
import sys
import itertools as it
import math as mt
import collections as cc
import bisect as bi
input=sys.stdin.readline
I=lambda:list(map(int,input().split()))
n,k=I()
l=I()
ar=[]
f=cc.defaultdict(list)
ch=cc.defaultdict(int)
for i in range(n):
ar.append([l[i],i])
f[l[i]].append(i)
ar.sort(key=lambda x:x[0])
if l.count(0)>1:
print(-1)
elif 0 not in l:
print(-1)
else:
d=max(l)
ed=[]
now=0;
prev=[l.index(0)]
tf=1
while now+1<=d:
cur=set()
if len(f[now+1])==0:
tf=0
break
ii=0
ll=len(prev)
if ll*k<len(f[now+1]):
tf=0
break
else:
for j in f[now+1]:
if ch[prev[ii]]<k:
#print(1,ch,prev[ii])
ch[prev[ii]]+=1
ch[j]+=1
cur.add(j)
ed.append([prev[ii]+1,j+1])
ii+=1
ii%=ll
else:
tf=0
break
#print(2,ch)
prev=list(cur)
now+=1
if not tf:
print(-1)
else:
print(len(ed))
for i in ed:
print(*i)
``` | output | 1 | 13,625 | 13 | 27,251 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.
One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.
Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.
Input
The first line contains two space-separated integers n and k (1 ≤ k < n ≤ 105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph.
The second line contains space-separated integers d[1], d[2], ..., d[n] (0 ≤ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.
Output
If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 ≤ m ≤ 106) — the number of edges in the found graph.
In each of the next m lines print two space-separated integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.
Examples
Input
3 2
0 1 1
Output
3
1 2
1 3
3 2
Input
4 2
2 0 1 3
Output
3
1 3
1 4
2 3
Input
3 1
0 0 0
Output
-1 | instruction | 0 | 13,626 | 13 | 27,252 |
Tags: dfs and similar, graphs, sortings
Correct Solution:
```
n, k = map(int, input().split())
d = zip(list(map(int, input().split())), range(1, n + 1))
d = sorted(d)
if d[0][0] != 0:
print(-1)
else:
u = 0
m = 0
check = True
graph = []
deg = [0]*(n + 1)
for v in range(1, n):
while u < v and (d[v][0] != d[u][0] + 1 or deg[d[u][1]] == k):
u += 1
if u == v:
print(-1)
check = False
break
graph.append([d[u][1], d[v][1]])
deg[d[u][1]] += 1
deg[d[v][1]] += 1
m += 1
if check:
print(m)
for i in range(0, m):
print(graph[i][0], graph[i][1])
``` | output | 1 | 13,626 | 13 | 27,253 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.
One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.
Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.
Input
The first line contains two space-separated integers n and k (1 ≤ k < n ≤ 105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph.
The second line contains space-separated integers d[1], d[2], ..., d[n] (0 ≤ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.
Output
If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 ≤ m ≤ 106) — the number of edges in the found graph.
In each of the next m lines print two space-separated integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.
Examples
Input
3 2
0 1 1
Output
3
1 2
1 3
3 2
Input
4 2
2 0 1 3
Output
3
1 3
1 4
2 3
Input
3 1
0 0 0
Output
-1 | instruction | 0 | 13,627 | 13 | 27,254 |
Tags: dfs and similar, graphs, sortings
Correct Solution:
```
class RestoreGraph():
def __init__(self,n, k, dis_values):
self.dis_values = dis_values
self.n = n
self.k = k
def generate_graph(self):
dis_pairs = [(self.dis_values[i],i) for i in range(len(self.dis_values))]
dis_pairs = sorted(dis_pairs)
if dis_pairs[0][0] != 0:
print(-1)
return
count = [0]*self.n
parent = [-1]*self.n
ind = 0
for i in range(1, self.n):
if dis_pairs[ind][0] != dis_pairs[i][0]-1 or count[ind] == self.k:
ind = ind+1
while(ind < i and (dis_pairs[ind][0] < dis_pairs[i][0]-1 or count[ind] == self.k)):
ind += 1
if dis_pairs[ind][0] != dis_pairs[i][0]-1 or count[ind] == self.k:
print(-1)
return
parent[i] = ind
count[i] += 1
count[ind] += 1
print(self.n-1)
for i in range(1,n):
print(dis_pairs[i][1]+1, dis_pairs[parent[i]][1]+1)
n, k = list(map(int,input().strip(' ').split(' ')))
arr = list(map(int,input().strip(' ').split(' ')))
graph = RestoreGraph(n,k,arr)
graph.generate_graph()
``` | output | 1 | 13,627 | 13 | 27,255 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.
One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.
Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.
Input
The first line contains two space-separated integers n and k (1 ≤ k < n ≤ 105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph.
The second line contains space-separated integers d[1], d[2], ..., d[n] (0 ≤ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.
Output
If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 ≤ m ≤ 106) — the number of edges in the found graph.
In each of the next m lines print two space-separated integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.
Examples
Input
3 2
0 1 1
Output
3
1 2
1 3
3 2
Input
4 2
2 0 1 3
Output
3
1 3
1 4
2 3
Input
3 1
0 0 0
Output
-1 | instruction | 0 | 13,628 | 13 | 27,256 |
Tags: dfs and similar, graphs, sortings
Correct Solution:
```
n, k = map(int, input().split())
d = zip(list(map(int, input().split())), range(1, n + 1))
d = sorted(d)
if d[0][0] != 0:
print(-1)
else:
u = 0
check = True
graph = []
deg = [0]*(n + 1)
for v in range(1, n):
if deg[d[u][1]] >= k:
u += 1
while u < v and d[v][0] != d[u][0] + 1:
u += 1
if u == v or deg[d[u][1]] >= k or deg[d[v][1]] >= k:
print(-1)
check = False
break
graph.append([d[u][1], d[v][1]])
deg[d[u][1]] += 1
deg[d[v][1]] += 1
if check:
m = len(graph)
print(m)
for i in range(0, m):
print(graph[i][0], graph[i][1])
``` | output | 1 | 13,628 | 13 | 27,257 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.
One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.
Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.
Input
The first line contains two space-separated integers n and k (1 ≤ k < n ≤ 105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph.
The second line contains space-separated integers d[1], d[2], ..., d[n] (0 ≤ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.
Output
If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 ≤ m ≤ 106) — the number of edges in the found graph.
In each of the next m lines print two space-separated integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.
Examples
Input
3 2
0 1 1
Output
3
1 2
1 3
3 2
Input
4 2
2 0 1 3
Output
3
1 3
1 4
2 3
Input
3 1
0 0 0
Output
-1 | instruction | 0 | 13,629 | 13 | 27,258 |
Tags: dfs and similar, graphs, sortings
Correct Solution:
```
n, k = map(int, input().split())
t = list(map(int, input().split()))
s, p = [], [[] for i in range(max(t) + 1)]
for i, j in enumerate(t, 1): p[j].append(str(i))
if len(p[0]) - 1: print('-1')
else:
for i in range(1, len(p)):
if k * len(p[i - 1]) < len(p[i]):
print('-1')
exit(0)
j, u, v = 0, len(p[i]) // k, len(p[i]) % k
for x in range(u):
s += [p[i - 1][x] + ' ' + p[i][y] for y in range(j, j + k)]
j += k
s += [p[i - 1][u] + ' ' + p[i][y] for y in range(j, j + v)]
if i == 1: k -= 1
print(len(s))
print('\n'.join(s))
``` | output | 1 | 13,629 | 13 | 27,259 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.
One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.
Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.
Input
The first line contains two space-separated integers n and k (1 ≤ k < n ≤ 105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph.
The second line contains space-separated integers d[1], d[2], ..., d[n] (0 ≤ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.
Output
If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 ≤ m ≤ 106) — the number of edges in the found graph.
In each of the next m lines print two space-separated integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.
Examples
Input
3 2
0 1 1
Output
3
1 2
1 3
3 2
Input
4 2
2 0 1 3
Output
3
1 3
1 4
2 3
Input
3 1
0 0 0
Output
-1 | instruction | 0 | 13,630 | 13 | 27,260 |
Tags: dfs and similar, graphs, sortings
Correct Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
def main():
n,k = map(int,input().split())
d = list(map(int,input().split()))
cou = [[] for _ in range(n)]
for i in range(n):
cou[d[i]].append(i+1)
if len(cou[0]) != 1:
print(-1)
return
ans = []
for i in range(max(d)):
if len(cou[i])*(k-1)+(i==0) < len(cou[i+1]):
print(-1)
return
x,y = 0,0
for j in cou[i+1]:
if x == k-1+(i==0):
x,y = 0,y+1
x += 1
ans.append((cou[i][y],j))
print(len(ans))
for i in ans:
print(*i)
# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
``` | output | 1 | 13,630 | 13 | 27,261 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.
One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.
Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.
Input
The first line contains two space-separated integers n and k (1 ≤ k < n ≤ 105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph.
The second line contains space-separated integers d[1], d[2], ..., d[n] (0 ≤ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.
Output
If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 ≤ m ≤ 106) — the number of edges in the found graph.
In each of the next m lines print two space-separated integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.
Examples
Input
3 2
0 1 1
Output
3
1 2
1 3
3 2
Input
4 2
2 0 1 3
Output
3
1 3
1 4
2 3
Input
3 1
0 0 0
Output
-1 | instruction | 0 | 13,631 | 13 | 27,262 |
Tags: dfs and similar, graphs, sortings
Correct Solution:
```
import sys
n, k = map(int, input().split())
a = [int(i) for i in input().split()]
g = [k] * n
maxi = max(a)
ans = []
if a.count(0) != 1:
print(-1)
sys.exit()
i = 1
f = a.index(0)
pref_t = [f]
x = [[] for y in range(maxi + 1)]
for v in range(n):
x[a[v]].append(v)
while i <= maxi:
t = x[i]
w = len(t)
z = 0
for o in pref_t:
z += g[o]
if z < w:
print(-1)
sys.exit()
u = 0
for l in pref_t:
while w > 0 and g[l] > 0:
g[l] -= 1
g[t[u]] -= 1
w -= 1
ans.append([l, t[u]])
u += 1
pref_t = t
i += 1
print(len(ans))
for row in ans:
print(row[0] + 1, row[1] + 1)
``` | output | 1 | 13,631 | 13 | 27,263 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.
One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.
Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.
Input
The first line contains two space-separated integers n and k (1 ≤ k < n ≤ 105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph.
The second line contains space-separated integers d[1], d[2], ..., d[n] (0 ≤ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.
Output
If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 ≤ m ≤ 106) — the number of edges in the found graph.
In each of the next m lines print two space-separated integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.
Examples
Input
3 2
0 1 1
Output
3
1 2
1 3
3 2
Input
4 2
2 0 1 3
Output
3
1 3
1 4
2 3
Input
3 1
0 0 0
Output
-1 | instruction | 0 | 13,632 | 13 | 27,264 |
Tags: dfs and similar, graphs, sortings
Correct Solution:
```
from math import ceil
def mkgr(n, srs, k):
res = [str(n-1)]
for d in srs[1]:
res.append("%i %i" % (srs[0][0]+1, d+1))
for i in range(2, len(srs)):
h, hs= 0, 0
for j in range(len(srs[i])):
res.append("%i %i" % (srs[i][j]+1, srs[i-1][h]+1))
hs += 1
if hs == k-1:
h += 1
hs = 0
return res
def test(n,k,dists):
m = max(dists)
srs = [[] for i in range(m+1)]
for i in range(n):
srs[dists[i]].append(i)
if [] in srs:
return ["-1"]
if len(srs[0]) != 1:
return ["-1"]
if len(srs[1]) > k:
return ["-1"]
for i in range(1, m):
if ceil(len(srs[i+1])/len(srs[i])) + 1 > k:
return ["-1"]
return mkgr(n, srs, k)
n, k = map(int, input().split())
dists = list(map(int, input().split()))
res = test(n,k,dists)
print("\n".join(res))
``` | output | 1 | 13,632 | 13 | 27,265 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.
One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.
Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.
Input
The first line contains two space-separated integers n and k (1 ≤ k < n ≤ 105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph.
The second line contains space-separated integers d[1], d[2], ..., d[n] (0 ≤ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.
Output
If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 ≤ m ≤ 106) — the number of edges in the found graph.
In each of the next m lines print two space-separated integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.
Examples
Input
3 2
0 1 1
Output
3
1 2
1 3
3 2
Input
4 2
2 0 1 3
Output
3
1 3
1 4
2 3
Input
3 1
0 0 0
Output
-1
Submitted Solution:
```
from sys import exit
n, k = map(int, input().split())
nodes = [[] for _ in range(n+1)]
edges = []
for node, dist in enumerate(map(int, input().split())):
nodes[dist].append(node)
if len(nodes[0]) != 1 or len(nodes[1]) > k:
print(-1)
else:
for i in range(1, n):
if len(nodes[i])*(k-1) < len(nodes[i+1]):
print(-1)
exit(0)
for i in range(n):
next = 0
if len(nodes[i+1]) > 0:
for j, node in enumerate(nodes[i]):
current = 0
while current < (k if i == 0 else k-1) and next < len(nodes[i+1]):
edges.append((node+1, nodes[i+1][next]+1))
next += 1
current += 1
print(len(edges))
print('\n'.join(map(lambda x: ' '.join([str(x[0]), str(x[1])]), edges)))
``` | instruction | 0 | 13,633 | 13 | 27,266 |
Yes | output | 1 | 13,633 | 13 | 27,267 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.
One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.
Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.
Input
The first line contains two space-separated integers n and k (1 ≤ k < n ≤ 105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph.
The second line contains space-separated integers d[1], d[2], ..., d[n] (0 ≤ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.
Output
If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 ≤ m ≤ 106) — the number of edges in the found graph.
In each of the next m lines print two space-separated integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.
Examples
Input
3 2
0 1 1
Output
3
1 2
1 3
3 2
Input
4 2
2 0 1 3
Output
3
1 3
1 4
2 3
Input
3 1
0 0 0
Output
-1
Submitted Solution:
```
n, k = map(int, input().split())
d = list(map(int, input().split()))
dmax = max(d)
nv = [[] for i in range(dmax+1)]
v = [0] * (dmax+1)
for i, dist in enumerate(d):
nv[dist].append(i)
v[dist] += 1
flag = True
if v[0] != 1 or v[1] > k:
flag = False
else:
for i in range(2, dmax+1):
if v[i] > (k-1) * v[i-1] or v[i] == 0:
flag = False
break
if flag:
print(n-1)
for vrtx in nv[1]:
print(nv[0][0] + 1, vrtx + 1)
for i, vs in enumerate(nv[1:-1]):
for j, vrtx in enumerate(vs):
m = 0
while m < (k-1):
if (j*(k-1) + m) < len(nv[i+2]):
print(vrtx + 1, nv[i+2][j*(k-1) + m] + 1)
m += 1
else:
break
else:
print(-1)
``` | instruction | 0 | 13,634 | 13 | 27,268 |
Yes | output | 1 | 13,634 | 13 | 27,269 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.
One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.
Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.
Input
The first line contains two space-separated integers n and k (1 ≤ k < n ≤ 105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph.
The second line contains space-separated integers d[1], d[2], ..., d[n] (0 ≤ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.
Output
If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 ≤ m ≤ 106) — the number of edges in the found graph.
In each of the next m lines print two space-separated integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.
Examples
Input
3 2
0 1 1
Output
3
1 2
1 3
3 2
Input
4 2
2 0 1 3
Output
3
1 3
1 4
2 3
Input
3 1
0 0 0
Output
-1
Submitted Solution:
```
import sys
input=sys.stdin.readline
n,k=map(int,input().split())
d=list(map(int,input().split()))
r=[[d[i],i] for i in range(n)]
r.sort()
if r[0][0]!=0 or r[1][0]==0:
print(-1)
exit()
v=[[] for i in range(n+1)]
cnt=[0]*n
v[0].append(r[0][1])
edges=[]
for rank,ver in r[1:]:
if len(v[rank-1])==0:
print(-1)
exit()
edges.append([v[rank-1][-1]+1,ver+1])
v[rank].append(ver)
cnt[v[rank-1][-1]]+=1
cnt[ver]+=1
if cnt[v[rank-1][-1]]==k:
v[rank-1].pop()
if cnt[ver]==k:
v[rank].pop()
print(len(edges))
for x in edges:
print(*x)
``` | instruction | 0 | 13,635 | 13 | 27,270 |
Yes | output | 1 | 13,635 | 13 | 27,271 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.
One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.
Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.
Input
The first line contains two space-separated integers n and k (1 ≤ k < n ≤ 105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph.
The second line contains space-separated integers d[1], d[2], ..., d[n] (0 ≤ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.
Output
If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 ≤ m ≤ 106) — the number of edges in the found graph.
In each of the next m lines print two space-separated integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.
Examples
Input
3 2
0 1 1
Output
3
1 2
1 3
3 2
Input
4 2
2 0 1 3
Output
3
1 3
1 4
2 3
Input
3 1
0 0 0
Output
-1
Submitted Solution:
```
import sys
n, k = map(int, input().split())
a = [int(i) for i in input().split()]
g = [k] * n
maxi = max(a)
ans = []
if a.count(0) != 1:
print(-1)
sys.exit()
i = 1
f = a.index(0)
pref_t = [f]
x = [[] for y in range(maxi + 1)]
for v in range(n):
x[a[v]].append(v)
while i <= maxi:
t = x[i]
w = len(t)
z = 0
for o in pref_t:
z += g[o]
if z < w:
print(-1)
sys.exit()
u = 0
for l in pref_t:
while w > 0 and g[l] > 0:
g[l] -= 1
g[t[u]] -= 1
w -= 1
ans.append([l, t[u]])
u += 1
pref_t = t
i += 1
print(len(ans))
for row in ans:
print(row[0] + 1, row[1] + 1)
# Fri Oct 16 2020 18:10:22 GMT+0300 (Москва, стандартное время)
``` | instruction | 0 | 13,636 | 13 | 27,272 |
Yes | output | 1 | 13,636 | 13 | 27,273 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.
One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.
Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.
Input
The first line contains two space-separated integers n and k (1 ≤ k < n ≤ 105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph.
The second line contains space-separated integers d[1], d[2], ..., d[n] (0 ≤ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.
Output
If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 ≤ m ≤ 106) — the number of edges in the found graph.
In each of the next m lines print two space-separated integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.
Examples
Input
3 2
0 1 1
Output
3
1 2
1 3
3 2
Input
4 2
2 0 1 3
Output
3
1 3
1 4
2 3
Input
3 1
0 0 0
Output
-1
Submitted Solution:
```
n,k = map(int,input().split())
a = list(map(int,input().split()))
import collections
d = collections.defaultdict(list)
cnt,cnt1 = 0,0
freq = [0]*(n+10)
ans = 0
temp = []
for i in range(n):
if(a[i]==0):
cnt+=1
freq[a[i]]+=1
if(a[i]>0):
ans+=1
temp.append([i+1,a[i]])
if(cnt!=1):
print(-1)
exit(0)
for i in range(1,n):
if(freq[i+1]>0):
if(freq[i]*(k-1)<freq[i+1]):
print(-1)
exit(0)
else:
break
temp.sort(key = lambda x:x[1])
print(ans)
cnt = 0
x = temp[0][0]
y = 1
abc = []
cntr = [0]*(n+1)
for i in range(1,n):
if(cnt<k):
if(temp[i][1]==y):
freq[temp[i][1]]-=1
abc.append(temp[i][0])
cntr[x]+=1
if(cntr[x]>k):
print(-1)
exit(0)
print(x,temp[i][0])
cnt+=1
else:
y+=1
x = abc.pop()
print(x,temp[i][0])
abc.append(temp[i][0])
freq[temp[i][1]]-=1
cnt = 2
else:
if(freq[temp[i-1][1]]>0):
x = abc.pop(0)
print(x,temp[i][0])
abc.append(temp[i][0])
freq[temp[i-1][1]]-=1
cnt = 2
else:
y+=1
x = abc.pop()
print(x,temp[i][0])
abc.append(temp[i][0])
freq[temp[i][1]]-=1
cnt = 2
``` | instruction | 0 | 13,637 | 13 | 27,274 |
No | output | 1 | 13,637 | 13 | 27,275 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.
One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.
Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.
Input
The first line contains two space-separated integers n and k (1 ≤ k < n ≤ 105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph.
The second line contains space-separated integers d[1], d[2], ..., d[n] (0 ≤ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.
Output
If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 ≤ m ≤ 106) — the number of edges in the found graph.
In each of the next m lines print two space-separated integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.
Examples
Input
3 2
0 1 1
Output
3
1 2
1 3
3 2
Input
4 2
2 0 1 3
Output
3
1 3
1 4
2 3
Input
3 1
0 0 0
Output
-1
Submitted Solution:
```
import sys
input=sys.stdin.readline
n,k=map(int,input().split())
d=list(map(int,input().split()))
r=[[d[i],i] for i in range(n)]
r.sort()
if r[0][0]!=0 or r[1][0]==0:
print(-1)
exit()
v=[[] for i in range(n+1)]
cnt=[0]*n
v[0].append(r[0][1])
edges=[]
for rank,ver in r[1:]:
if len(v[rank-1])==0:
print(-1)
exit()
edges.append([v[rank-1][-1]+1,ver+1])
v[rank].append(ver)
cnt[v[rank-1][-1]]+=1
if cnt[v[rank-1][-1]]==k:
v[rank-1].pop()
print(len(edges))
for x in edges:
print(*x)
``` | instruction | 0 | 13,638 | 13 | 27,276 |
No | output | 1 | 13,638 | 13 | 27,277 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.
One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.
Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.
Input
The first line contains two space-separated integers n and k (1 ≤ k < n ≤ 105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph.
The second line contains space-separated integers d[1], d[2], ..., d[n] (0 ≤ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.
Output
If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 ≤ m ≤ 106) — the number of edges in the found graph.
In each of the next m lines print two space-separated integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.
Examples
Input
3 2
0 1 1
Output
3
1 2
1 3
3 2
Input
4 2
2 0 1 3
Output
3
1 3
1 4
2 3
Input
3 1
0 0 0
Output
-1
Submitted Solution:
```
n, k = map(int, input().split())
d = zip(list(map(int, input().split())), range(1, n + 1))
d = sorted(d)
if d[0][0] != 0:
print(-1)
else:
u = 0
check = True
graph = []
deg = [0]*(n + 1)
for v in range(1, n):
if deg[d[u][1]] >= k:
u += 1
while u < v and d[v][0] != d[u][0] + 1:
u += 1
if u == v or deg[d[v][1]] >= k:
print(-1)
check = False
break
graph.append([d[u][1], d[v][1]])
deg[d[u][1]] += 1
deg[d[v][1]] += 1
if check:
m = len(graph)
print(m)
for i in range(0, m):
print(graph[i][0], graph[i][1])
``` | instruction | 0 | 13,639 | 13 | 27,278 |
No | output | 1 | 13,639 | 13 | 27,279 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.
One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.
Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.
Input
The first line contains two space-separated integers n and k (1 ≤ k < n ≤ 105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph.
The second line contains space-separated integers d[1], d[2], ..., d[n] (0 ≤ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.
Output
If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 ≤ m ≤ 106) — the number of edges in the found graph.
In each of the next m lines print two space-separated integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.
Examples
Input
3 2
0 1 1
Output
3
1 2
1 3
3 2
Input
4 2
2 0 1 3
Output
3
1 3
1 4
2 3
Input
3 1
0 0 0
Output
-1
Submitted Solution:
```
n,k=map(int,input().split())
d=zip( list(map(int,input().split())),range(0,n) )
d=sorted(d)
last=0
du=[0]*n
fa=[0]*n
flag=1
for j in range(1,n):
while last<j and ( du[last]==k or d[last][0]+1<d[j][0] ):
last+=1
if last==j or d[last][0]+1!=d[j][0]:
print(-1)
break
fa[j]=last
du[j]+=1
du[last]+=1
else:
print(n-1)
for j in range(1,n):
print(d[fa[j]][1]+1,d[j][1]+1)
``` | instruction | 0 | 13,640 | 13 | 27,280 |
No | output | 1 | 13,640 | 13 | 27,281 |
Provide tags and a correct Python 3 solution for this coding contest problem.
ZS the Coder has drawn an undirected graph of n vertices numbered from 0 to n - 1 and m edges between them. Each edge of the graph is weighted, each weight is a positive integer.
The next day, ZS the Coder realized that some of the weights were erased! So he wants to reassign positive integer weight to each of the edges which weights were erased, so that the length of the shortest path between vertices s and t in the resulting graph is exactly L. Can you help him?
Input
The first line contains five integers n, m, L, s, t (2 ≤ n ≤ 1000, 1 ≤ m ≤ 10 000, 1 ≤ L ≤ 109, 0 ≤ s, t ≤ n - 1, s ≠ t) — the number of vertices, number of edges, the desired length of shortest path, starting vertex and ending vertex respectively.
Then, m lines describing the edges of the graph follow. i-th of them contains three integers, ui, vi, wi (0 ≤ ui, vi ≤ n - 1, ui ≠ vi, 0 ≤ wi ≤ 109). ui and vi denote the endpoints of the edge and wi denotes its weight. If wi is equal to 0 then the weight of the corresponding edge was erased.
It is guaranteed that there is at most one edge between any pair of vertices.
Output
Print "NO" (without quotes) in the only line if it's not possible to assign the weights in a required way.
Otherwise, print "YES" in the first line. Next m lines should contain the edges of the resulting graph, with weights assigned to edges which weights were erased. i-th of them should contain three integers ui, vi and wi, denoting an edge between vertices ui and vi of weight wi. The edges of the new graph must coincide with the ones in the graph from the input. The weights that were not erased must remain unchanged whereas the new weights can be any positive integer not exceeding 1018.
The order of the edges in the output doesn't matter. The length of the shortest path between s and t must be equal to L.
If there are multiple solutions, print any of them.
Examples
Input
5 5 13 0 4
0 1 5
2 1 2
3 2 3
1 4 0
4 3 4
Output
YES
0 1 5
2 1 2
3 2 3
1 4 8
4 3 4
Input
2 1 123456789 0 1
0 1 0
Output
YES
0 1 123456789
Input
2 1 999999999 1 0
0 1 1000000000
Output
NO
Note
Here's how the graph in the first sample case looks like :
<image>
In the first sample case, there is only one missing edge weight. Placing the weight of 8 gives a shortest path from 0 to 4 of length 13.
In the second sample case, there is only a single edge. Clearly, the only way is to replace the missing weight with 123456789.
In the last sample case, there is no weights to assign but the length of the shortest path doesn't match the required value, so the answer is "NO". | instruction | 0 | 13,763 | 13 | 27,526 |
Tags: binary search, constructive algorithms, graphs, shortest paths
Correct Solution:
```
from collections import defaultdict
MAX = 10 ** 14
def Dijkstra(graph, s, n):
visited = [False] * n
d = [MAX] * n
parents = {}
d[s] = 0
for i in range(n):
_, v = min((d[j], j) for j in range(n) if not visited[j])
visited[v] = True
for u, cost in graph[v]:
if d[u] > d[v] + cost:
d[u] = d[v] + cost
parents[u] = v
return parents, d
def PrintSol(graph, variableEdgesInPath, n, zeros, edgesWithZero, leave):
for v in range(n):
for u, cost in graph[v]:
if u < v:
if (v, u) in variableEdgesInPath:
print(v, u, variableEdgesInPath[(v, u)])
elif zeros and (v, u) in edgesWithZero and (v, u) not in leave:
print(v, u, MAX)
else:
print(v, u, cost)
graphWithZero = defaultdict(list)
graphWithMax = defaultdict(list)
n, m, L, s, t = map(int, input().split(' '))
edgesWithZero = set()
for _ in range(m):
u, v, l = map(int, input().split(' '))
if l == 0:
graphWithZero[u].append((v, 1))
graphWithZero[v].append((u, 1))
graphWithMax[u].append((v, MAX))
graphWithMax[v].append((u, MAX))
edgesWithZero |= {(u, v), (v, u)}
else:
graphWithZero[u].append((v, l))
graphWithZero[v].append((u, l))
graphWithMax[u].append((v, l))
graphWithMax[v].append((u, l))
a2, d2 = Dijkstra(graphWithMax, s, n)
a1, d1 = Dijkstra(graphWithZero, s, n)
if d2[t] < L:
print('NO')
elif d2[t] == L:
print('YES')
PrintSol(graphWithMax, dict(), n, False, edgesWithZero, set())
elif d1[t] <= L:
print('YES')
v = t
leave = set()
variableEdgesInPath = dict()
total = 0
while v != s:
leave |= {(v, a1[v]), (a1[v], v)}
if (v, a1[v]) in edgesWithZero:
cur = max(L - total - d2[a1[v]], 1)
variableEdgesInPath[(max(v, a1[v]), min(v, a1[v]))] = cur
total += cur
else:
total += d1[v] - d1[a1[v]]
v = a1[v]
PrintSol(graphWithZero, variableEdgesInPath, n, True, edgesWithZero, leave)
else:
print('NO')
``` | output | 1 | 13,763 | 13 | 27,527 |
Provide tags and a correct Python 3 solution for this coding contest problem.
ZS the Coder has drawn an undirected graph of n vertices numbered from 0 to n - 1 and m edges between them. Each edge of the graph is weighted, each weight is a positive integer.
The next day, ZS the Coder realized that some of the weights were erased! So he wants to reassign positive integer weight to each of the edges which weights were erased, so that the length of the shortest path between vertices s and t in the resulting graph is exactly L. Can you help him?
Input
The first line contains five integers n, m, L, s, t (2 ≤ n ≤ 1000, 1 ≤ m ≤ 10 000, 1 ≤ L ≤ 109, 0 ≤ s, t ≤ n - 1, s ≠ t) — the number of vertices, number of edges, the desired length of shortest path, starting vertex and ending vertex respectively.
Then, m lines describing the edges of the graph follow. i-th of them contains three integers, ui, vi, wi (0 ≤ ui, vi ≤ n - 1, ui ≠ vi, 0 ≤ wi ≤ 109). ui and vi denote the endpoints of the edge and wi denotes its weight. If wi is equal to 0 then the weight of the corresponding edge was erased.
It is guaranteed that there is at most one edge between any pair of vertices.
Output
Print "NO" (without quotes) in the only line if it's not possible to assign the weights in a required way.
Otherwise, print "YES" in the first line. Next m lines should contain the edges of the resulting graph, with weights assigned to edges which weights were erased. i-th of them should contain three integers ui, vi and wi, denoting an edge between vertices ui and vi of weight wi. The edges of the new graph must coincide with the ones in the graph from the input. The weights that were not erased must remain unchanged whereas the new weights can be any positive integer not exceeding 1018.
The order of the edges in the output doesn't matter. The length of the shortest path between s and t must be equal to L.
If there are multiple solutions, print any of them.
Examples
Input
5 5 13 0 4
0 1 5
2 1 2
3 2 3
1 4 0
4 3 4
Output
YES
0 1 5
2 1 2
3 2 3
1 4 8
4 3 4
Input
2 1 123456789 0 1
0 1 0
Output
YES
0 1 123456789
Input
2 1 999999999 1 0
0 1 1000000000
Output
NO
Note
Here's how the graph in the first sample case looks like :
<image>
In the first sample case, there is only one missing edge weight. Placing the weight of 8 gives a shortest path from 0 to 4 of length 13.
In the second sample case, there is only a single edge. Clearly, the only way is to replace the missing weight with 123456789.
In the last sample case, there is no weights to assign but the length of the shortest path doesn't match the required value, so the answer is "NO". | instruction | 0 | 13,764 | 13 | 27,528 |
Tags: binary search, constructive algorithms, graphs, shortest paths
Correct Solution:
```
import heapq
from collections import defaultdict
class Graph:
def __init__(self, n):
self.nodes = set(range(n))
self.edges = defaultdict(list)
self.distances = {}
def add_edge(self, from_node, to_node, distance):
self.edges[from_node].append(to_node)
self.edges[to_node].append(from_node)
self.distances[from_node, to_node] = distance
self.distances[to_node, from_node] = distance
def dijkstra(graph, initial):
visited = {initial: 0}
path = {}
h = [(0, initial)]
nodes = set(graph.nodes)
while nodes and h:
current_weight, min_node = heapq.heappop(h)
try:
while min_node not in nodes:
current_weight, min_node = heapq.heappop(h)
except IndexError:
break
nodes.remove(min_node)
for v in graph.edges[min_node]:
weight = current_weight + graph.distances[min_node, v]
if v not in visited or weight < visited[v]:
visited[v] = weight
heapq.heappush(h, (weight, v))
path[v] = min_node
return visited, path
n, m, L, s, t = map(int, input().split())
min_g = Graph(n)
max_g = Graph(n)
g = Graph(n)
for _ in range(m):
u, v, w = map(int, input().split())
if w == 0:
min_w = 1
max_w = int(1e18)
else:
min_w = max_w = w
min_g.add_edge(u, v, min_w)
max_g.add_edge(u, v, max_w)
g.add_edge(u, v, w)
min_ls, min_p = dijkstra(min_g, s)
try:
min_l = min_ls[t]
max_l = dijkstra(max_g, s)[0][t]
except KeyError:
min_l = 0
max_l = -1
if min_l <= L <= max_l:
while min_l < L:
a = s
b = z = t
while z != s:
if g.distances[z, min_p[z]] == 0:
max_g.distances[z, min_p[z]] = min_g.distances[z, min_p[z]]
max_g.distances[min_p[z], z] = min_g.distances[z, min_p[z]]
a = z
b = min_p[z]
z = min_p[z]
new_dist = min_g.distances[a, b] + L - min_l
max_g.distances[a, b] = new_dist
max_g.distances[b, a] = new_dist
min_g = max_g
min_ls, min_p = dijkstra(min_g, s)
min_l = min_ls[t]
if min_l == L:
print('YES')
print('\n'.join('%s %s %s' % (u, v, w) for (u, v), w in min_g.distances.items() if u < v))
else:
print('NO')
else:
print('NO')
``` | output | 1 | 13,764 | 13 | 27,529 |
Provide tags and a correct Python 3 solution for this coding contest problem.
ZS the Coder has drawn an undirected graph of n vertices numbered from 0 to n - 1 and m edges between them. Each edge of the graph is weighted, each weight is a positive integer.
The next day, ZS the Coder realized that some of the weights were erased! So he wants to reassign positive integer weight to each of the edges which weights were erased, so that the length of the shortest path between vertices s and t in the resulting graph is exactly L. Can you help him?
Input
The first line contains five integers n, m, L, s, t (2 ≤ n ≤ 1000, 1 ≤ m ≤ 10 000, 1 ≤ L ≤ 109, 0 ≤ s, t ≤ n - 1, s ≠ t) — the number of vertices, number of edges, the desired length of shortest path, starting vertex and ending vertex respectively.
Then, m lines describing the edges of the graph follow. i-th of them contains three integers, ui, vi, wi (0 ≤ ui, vi ≤ n - 1, ui ≠ vi, 0 ≤ wi ≤ 109). ui and vi denote the endpoints of the edge and wi denotes its weight. If wi is equal to 0 then the weight of the corresponding edge was erased.
It is guaranteed that there is at most one edge between any pair of vertices.
Output
Print "NO" (without quotes) in the only line if it's not possible to assign the weights in a required way.
Otherwise, print "YES" in the first line. Next m lines should contain the edges of the resulting graph, with weights assigned to edges which weights were erased. i-th of them should contain three integers ui, vi and wi, denoting an edge between vertices ui and vi of weight wi. The edges of the new graph must coincide with the ones in the graph from the input. The weights that were not erased must remain unchanged whereas the new weights can be any positive integer not exceeding 1018.
The order of the edges in the output doesn't matter. The length of the shortest path between s and t must be equal to L.
If there are multiple solutions, print any of them.
Examples
Input
5 5 13 0 4
0 1 5
2 1 2
3 2 3
1 4 0
4 3 4
Output
YES
0 1 5
2 1 2
3 2 3
1 4 8
4 3 4
Input
2 1 123456789 0 1
0 1 0
Output
YES
0 1 123456789
Input
2 1 999999999 1 0
0 1 1000000000
Output
NO
Note
Here's how the graph in the first sample case looks like :
<image>
In the first sample case, there is only one missing edge weight. Placing the weight of 8 gives a shortest path from 0 to 4 of length 13.
In the second sample case, there is only a single edge. Clearly, the only way is to replace the missing weight with 123456789.
In the last sample case, there is no weights to assign but the length of the shortest path doesn't match the required value, so the answer is "NO". | instruction | 0 | 13,765 | 13 | 27,530 |
Tags: binary search, constructive algorithms, graphs, shortest paths
Correct Solution:
```
from collections import defaultdict
MAX_WEIGHT = 10 ** 14
def compute_path(graph, s, n):
visited = [False] * n
distances = [MAX_WEIGHT] * n
ancestors = {}
distances[s] = 0
for i in range(n):
_, v = min((distances[j], j) for j in range(n) if not visited[j])
visited[v] = True
for to, length in graph[v]:
if distances[to] > distances[v] + length:
distances[to] = distances[v] + length
ancestors[to] = v
return ancestors, distances
def output(graph, n_edges, extra, n, zeros, erased, leave):
for i in range(n):
for to, length in graph[i]:
if to < i:
if (i, to) in n_edges:
print(i, to, n_edges[(i, to)])
elif zeros and (i, to) in erased and (i, to) not in leave:
print(i, to, MAX_WEIGHT)
else:
print(i, to, length)
graph_with_0 = defaultdict(list)
graph_with_max = defaultdict(list)
n, m, L, s, t = map(int, input().split(' '))
erased = set()
for _ in range(m):
u, v, l = map(int, input().split(' '))
if l == 0:
graph_with_0[u].append((v, 1))
graph_with_0[v].append((u, 1))
graph_with_max[u].append((v, MAX_WEIGHT))
graph_with_max[v].append((u, MAX_WEIGHT))
erased |= {(u, v), (v, u)}
else:
graph_with_0[u].append((v, l))
graph_with_0[v].append((u, l))
graph_with_max[u].append((v, l))
graph_with_max[v].append((u, l))
a1, d1 = compute_path(graph_with_0, s, n)
a2, d2 = compute_path(graph_with_max, s, n)
if d2[t] < L:
print('NO')
elif d2[t] == L:
print('YES')
output(graph_with_max, dict(), 0, n, False, erased, set())
elif d1[t] <= L:
print('YES')
v = t
leave = set()
n_edges = dict()
total = 0
while v != s:
leave |= {(v, a1[v]), (a1[v], v)}
if (v, a1[v]) in erased:
cur = max(L - total - d2[a1[v]], 1)
n_edges[(max(v, a1[v]), min(v, a1[v]))] = cur
total += cur
else:
total += d1[v] - d1[a1[v]]
v = a1[v]
output(graph_with_0, n_edges, L - d1[t], n, True, erased, leave)
else:
print('NO')
``` | output | 1 | 13,765 | 13 | 27,531 |
Provide tags and a correct Python 3 solution for this coding contest problem.
ZS the Coder has drawn an undirected graph of n vertices numbered from 0 to n - 1 and m edges between them. Each edge of the graph is weighted, each weight is a positive integer.
The next day, ZS the Coder realized that some of the weights were erased! So he wants to reassign positive integer weight to each of the edges which weights were erased, so that the length of the shortest path between vertices s and t in the resulting graph is exactly L. Can you help him?
Input
The first line contains five integers n, m, L, s, t (2 ≤ n ≤ 1000, 1 ≤ m ≤ 10 000, 1 ≤ L ≤ 109, 0 ≤ s, t ≤ n - 1, s ≠ t) — the number of vertices, number of edges, the desired length of shortest path, starting vertex and ending vertex respectively.
Then, m lines describing the edges of the graph follow. i-th of them contains three integers, ui, vi, wi (0 ≤ ui, vi ≤ n - 1, ui ≠ vi, 0 ≤ wi ≤ 109). ui and vi denote the endpoints of the edge and wi denotes its weight. If wi is equal to 0 then the weight of the corresponding edge was erased.
It is guaranteed that there is at most one edge between any pair of vertices.
Output
Print "NO" (without quotes) in the only line if it's not possible to assign the weights in a required way.
Otherwise, print "YES" in the first line. Next m lines should contain the edges of the resulting graph, with weights assigned to edges which weights were erased. i-th of them should contain three integers ui, vi and wi, denoting an edge between vertices ui and vi of weight wi. The edges of the new graph must coincide with the ones in the graph from the input. The weights that were not erased must remain unchanged whereas the new weights can be any positive integer not exceeding 1018.
The order of the edges in the output doesn't matter. The length of the shortest path between s and t must be equal to L.
If there are multiple solutions, print any of them.
Examples
Input
5 5 13 0 4
0 1 5
2 1 2
3 2 3
1 4 0
4 3 4
Output
YES
0 1 5
2 1 2
3 2 3
1 4 8
4 3 4
Input
2 1 123456789 0 1
0 1 0
Output
YES
0 1 123456789
Input
2 1 999999999 1 0
0 1 1000000000
Output
NO
Note
Here's how the graph in the first sample case looks like :
<image>
In the first sample case, there is only one missing edge weight. Placing the weight of 8 gives a shortest path from 0 to 4 of length 13.
In the second sample case, there is only a single edge. Clearly, the only way is to replace the missing weight with 123456789.
In the last sample case, there is no weights to assign but the length of the shortest path doesn't match the required value, so the answer is "NO". | instruction | 0 | 13,766 | 13 | 27,532 |
Tags: binary search, constructive algorithms, graphs, shortest paths
Correct Solution:
```
from collections import defaultdict
MAX = 10 ** 14
def Dijkstra(graph, s, n):
visited = [False] * n
d = [MAX] * n
parents = {}
d[s] = 0
for i in range(n):
_, v = min((d[j], j) for j in range(n) if not visited[j])
visited[v] = True
for to, length in graph[v]:
if d[to] > d[v] + length:
d[to] = d[v] + length
parents[to] = v
return parents, d
def PrintSol(graph, n_edges, n, zeros, edgesWithZero, leave):
for i in range(n):
for to, length in graph[i]:
if to < i:
if (i, to) in n_edges:
print(i, to, n_edges[(i, to)])
elif zeros and (i, to) in edgesWithZero and (i, to) not in leave:
print(i, to, MAX)
else:
print(i, to, length)
graphWithZero = defaultdict(list)
graphWithMax = defaultdict(list)
n, m, L, s, t = map(int, input().split(' '))
edgesWithZero = set()
for _ in range(m):
u, v, l = map(int, input().split(' '))
if l == 0:
graphWithZero[u].append((v, 1))
graphWithZero[v].append((u, 1))
graphWithMax[u].append((v, MAX))
graphWithMax[v].append((u, MAX))
edgesWithZero |= {(u, v), (v, u)}
else:
graphWithZero[u].append((v, l))
graphWithZero[v].append((u, l))
graphWithMax[u].append((v, l))
graphWithMax[v].append((u, l))
a2, d2 = Dijkstra(graphWithMax, s, n)
a1, d1 = Dijkstra(graphWithZero, s, n)
if d2[t] < L:
print('NO')
elif d2[t] == L:
print('YES')
PrintSol(graphWithMax, dict(), n, False, edgesWithZero, set())
elif d1[t] <= L:
print('YES')
v = t
leave = set()
n_edges = dict()
total = 0
while v != s:
leave |= {(v, a1[v]), (a1[v], v)}
if (v, a1[v]) in edgesWithZero:
cur = max(L - total - d2[a1[v]], 1)
n_edges[(max(v, a1[v]), min(v, a1[v]))] = cur
total += cur
else:
total += d1[v] - d1[a1[v]]
v = a1[v]
PrintSol(graphWithZero, n_edges, n, True, edgesWithZero, leave)
else:
print('NO')
``` | output | 1 | 13,766 | 13 | 27,533 |
Provide tags and a correct Python 3 solution for this coding contest problem.
ZS the Coder has drawn an undirected graph of n vertices numbered from 0 to n - 1 and m edges between them. Each edge of the graph is weighted, each weight is a positive integer.
The next day, ZS the Coder realized that some of the weights were erased! So he wants to reassign positive integer weight to each of the edges which weights were erased, so that the length of the shortest path between vertices s and t in the resulting graph is exactly L. Can you help him?
Input
The first line contains five integers n, m, L, s, t (2 ≤ n ≤ 1000, 1 ≤ m ≤ 10 000, 1 ≤ L ≤ 109, 0 ≤ s, t ≤ n - 1, s ≠ t) — the number of vertices, number of edges, the desired length of shortest path, starting vertex and ending vertex respectively.
Then, m lines describing the edges of the graph follow. i-th of them contains three integers, ui, vi, wi (0 ≤ ui, vi ≤ n - 1, ui ≠ vi, 0 ≤ wi ≤ 109). ui and vi denote the endpoints of the edge and wi denotes its weight. If wi is equal to 0 then the weight of the corresponding edge was erased.
It is guaranteed that there is at most one edge between any pair of vertices.
Output
Print "NO" (without quotes) in the only line if it's not possible to assign the weights in a required way.
Otherwise, print "YES" in the first line. Next m lines should contain the edges of the resulting graph, with weights assigned to edges which weights were erased. i-th of them should contain three integers ui, vi and wi, denoting an edge between vertices ui and vi of weight wi. The edges of the new graph must coincide with the ones in the graph from the input. The weights that were not erased must remain unchanged whereas the new weights can be any positive integer not exceeding 1018.
The order of the edges in the output doesn't matter. The length of the shortest path between s and t must be equal to L.
If there are multiple solutions, print any of them.
Examples
Input
5 5 13 0 4
0 1 5
2 1 2
3 2 3
1 4 0
4 3 4
Output
YES
0 1 5
2 1 2
3 2 3
1 4 8
4 3 4
Input
2 1 123456789 0 1
0 1 0
Output
YES
0 1 123456789
Input
2 1 999999999 1 0
0 1 1000000000
Output
NO
Note
Here's how the graph in the first sample case looks like :
<image>
In the first sample case, there is only one missing edge weight. Placing the weight of 8 gives a shortest path from 0 to 4 of length 13.
In the second sample case, there is only a single edge. Clearly, the only way is to replace the missing weight with 123456789.
In the last sample case, there is no weights to assign but the length of the shortest path doesn't match the required value, so the answer is "NO". | instruction | 0 | 13,767 | 13 | 27,534 |
Tags: binary search, constructive algorithms, graphs, shortest paths
Correct Solution:
```
import heapq
from collections import defaultdict
class Graph:
def __init__(self, n):
self.nodes = set(range(n))
self.edges = defaultdict(list)
self.distances = {}
def add_edge(self, from_node, to_node, distance):
self.edges[from_node].append(to_node)
self.edges[to_node].append(from_node)
self.distances[from_node, to_node] = distance
self.distances[to_node, from_node] = distance
def dijkstra(graph, initial, end):
visited = {initial: 0}
path = {}
h = [(0, initial)]
nodes = set(graph.nodes)
while nodes and h:
current_weight, min_node = heapq.heappop(h)
try:
while min_node not in nodes:
current_weight, min_node = heapq.heappop(h)
except IndexError:
break
if min_node == end:
break
nodes.remove(min_node)
for v in graph.edges[min_node]:
weight = current_weight + graph.distances[min_node, v]
if v not in visited or weight < visited[v]:
visited[v] = weight
heapq.heappush(h, (weight, v))
path[v] = min_node
return visited, path
n, m, L, s, t = map(int, input().split())
min_g = Graph(n)
max_g = Graph(n)
g = Graph(n)
for _ in range(m):
u, v, w = map(int, input().split())
if w == 0:
min_w = 1
max_w = int(1e18)
else:
min_w = max_w = w
min_g.add_edge(u, v, min_w)
max_g.add_edge(u, v, max_w)
g.add_edge(u, v, w)
min_ls, min_p = dijkstra(min_g, s, t)
try:
min_l = min_ls[t]
max_l = dijkstra(max_g, s, t)[0][t]
except KeyError:
min_l = 0
max_l = -1
if min_l <= L <= max_l:
while min_l < L:
a = s
b = z = t
while z != s:
if g.distances[z, min_p[z]] == 0:
max_g.distances[z, min_p[z]] = min_g.distances[z, min_p[z]]
max_g.distances[min_p[z], z] = min_g.distances[z, min_p[z]]
a = z
b = min_p[z]
z = min_p[z]
new_dist = min_g.distances[a, b] + L - min_l
max_g.distances[a, b] = new_dist
max_g.distances[b, a] = new_dist
min_g = max_g
min_ls, min_p = dijkstra(min_g, s, t)
min_l = min_ls[t]
if min_l == L:
print('YES')
print('\n'.join('%s %s %s' % (u, v, w) for (u, v), w in min_g.distances.items() if u < v))
else:
print('NO')
else:
print('NO')
``` | output | 1 | 13,767 | 13 | 27,535 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
ZS the Coder has drawn an undirected graph of n vertices numbered from 0 to n - 1 and m edges between them. Each edge of the graph is weighted, each weight is a positive integer.
The next day, ZS the Coder realized that some of the weights were erased! So he wants to reassign positive integer weight to each of the edges which weights were erased, so that the length of the shortest path between vertices s and t in the resulting graph is exactly L. Can you help him?
Input
The first line contains five integers n, m, L, s, t (2 ≤ n ≤ 1000, 1 ≤ m ≤ 10 000, 1 ≤ L ≤ 109, 0 ≤ s, t ≤ n - 1, s ≠ t) — the number of vertices, number of edges, the desired length of shortest path, starting vertex and ending vertex respectively.
Then, m lines describing the edges of the graph follow. i-th of them contains three integers, ui, vi, wi (0 ≤ ui, vi ≤ n - 1, ui ≠ vi, 0 ≤ wi ≤ 109). ui and vi denote the endpoints of the edge and wi denotes its weight. If wi is equal to 0 then the weight of the corresponding edge was erased.
It is guaranteed that there is at most one edge between any pair of vertices.
Output
Print "NO" (without quotes) in the only line if it's not possible to assign the weights in a required way.
Otherwise, print "YES" in the first line. Next m lines should contain the edges of the resulting graph, with weights assigned to edges which weights were erased. i-th of them should contain three integers ui, vi and wi, denoting an edge between vertices ui and vi of weight wi. The edges of the new graph must coincide with the ones in the graph from the input. The weights that were not erased must remain unchanged whereas the new weights can be any positive integer not exceeding 1018.
The order of the edges in the output doesn't matter. The length of the shortest path between s and t must be equal to L.
If there are multiple solutions, print any of them.
Examples
Input
5 5 13 0 4
0 1 5
2 1 2
3 2 3
1 4 0
4 3 4
Output
YES
0 1 5
2 1 2
3 2 3
1 4 8
4 3 4
Input
2 1 123456789 0 1
0 1 0
Output
YES
0 1 123456789
Input
2 1 999999999 1 0
0 1 1000000000
Output
NO
Note
Here's how the graph in the first sample case looks like :
<image>
In the first sample case, there is only one missing edge weight. Placing the weight of 8 gives a shortest path from 0 to 4 of length 13.
In the second sample case, there is only a single edge. Clearly, the only way is to replace the missing weight with 123456789.
In the last sample case, there is no weights to assign but the length of the shortest path doesn't match the required value, so the answer is "NO".
Submitted Solution:
```
n, m, l, s, t = map(int, input().split())
edges = []
graph = [[] for i in range(n)]
direct = [-1] * n
correct = [-1] * n
corrpath = [[] for i in range(n)]
for i in range(m):
u, v, w = map(int, input().split())
edges.append((u, v, w))
graph[u].append((v, w, i))
graph[v].append((u, w, i))
direct[s] = 0
queue = [s]
while queue:
curr = queue.pop()
for next, w, i in graph[curr]:
if w:
if direct[curr] >= 0 and (direct[next] < 0 or direct[curr] + w < direct[next]):
direct[next] = direct[curr] + w
queue.append(next)
if correct[curr] >= 0 and (correct[next] < 0 or correct[curr] + w < correct[next]):
correct[next] = correct[curr] + w
corrpath[next] = []
corrpath[next].extend(corrpath[curr])
queue.append(next)
else:
if correct[curr] >= 0 and (correct[next] < 0 or correct[curr] + 1 < correct[next]):
correct[next] = correct[curr] + 1
corrpath[next] = [i]
corrpath[next].extend(corrpath[curr])
queue.append(next)
if direct[curr] >= 0 and (correct[next] < 0 or correct[curr] + 1 < direct[next]):
correct[next] = direct[curr] + 1
corrpath[next] = [i]
queue.append(next)
if direct[t] >= 0 and direct[t] < l:
print("NO")
elif direct[t] == l:
print("YES")
for i in range(m):
u, v, w = edges[i]
if not w: w = 1
print(u, end = " ")
print(v, end = " ")
print(w)
elif correct[t] >= 0 and correct[t] <= l:
print("YES")
delta = l - correct[t]
for i in range(m):
u, v, w = edges[i]
if not w: w = 1
if delta and i in corrpath[t]:
w += delta
delta = 0
print(u, end = " ")
print(v, end = " ")
print(w)
else:
print("NO")
``` | instruction | 0 | 13,768 | 13 | 27,536 |
No | output | 1 | 13,768 | 13 | 27,537 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
ZS the Coder has drawn an undirected graph of n vertices numbered from 0 to n - 1 and m edges between them. Each edge of the graph is weighted, each weight is a positive integer.
The next day, ZS the Coder realized that some of the weights were erased! So he wants to reassign positive integer weight to each of the edges which weights were erased, so that the length of the shortest path between vertices s and t in the resulting graph is exactly L. Can you help him?
Input
The first line contains five integers n, m, L, s, t (2 ≤ n ≤ 1000, 1 ≤ m ≤ 10 000, 1 ≤ L ≤ 109, 0 ≤ s, t ≤ n - 1, s ≠ t) — the number of vertices, number of edges, the desired length of shortest path, starting vertex and ending vertex respectively.
Then, m lines describing the edges of the graph follow. i-th of them contains three integers, ui, vi, wi (0 ≤ ui, vi ≤ n - 1, ui ≠ vi, 0 ≤ wi ≤ 109). ui and vi denote the endpoints of the edge and wi denotes its weight. If wi is equal to 0 then the weight of the corresponding edge was erased.
It is guaranteed that there is at most one edge between any pair of vertices.
Output
Print "NO" (without quotes) in the only line if it's not possible to assign the weights in a required way.
Otherwise, print "YES" in the first line. Next m lines should contain the edges of the resulting graph, with weights assigned to edges which weights were erased. i-th of them should contain three integers ui, vi and wi, denoting an edge between vertices ui and vi of weight wi. The edges of the new graph must coincide with the ones in the graph from the input. The weights that were not erased must remain unchanged whereas the new weights can be any positive integer not exceeding 1018.
The order of the edges in the output doesn't matter. The length of the shortest path between s and t must be equal to L.
If there are multiple solutions, print any of them.
Examples
Input
5 5 13 0 4
0 1 5
2 1 2
3 2 3
1 4 0
4 3 4
Output
YES
0 1 5
2 1 2
3 2 3
1 4 8
4 3 4
Input
2 1 123456789 0 1
0 1 0
Output
YES
0 1 123456789
Input
2 1 999999999 1 0
0 1 1000000000
Output
NO
Note
Here's how the graph in the first sample case looks like :
<image>
In the first sample case, there is only one missing edge weight. Placing the weight of 8 gives a shortest path from 0 to 4 of length 13.
In the second sample case, there is only a single edge. Clearly, the only way is to replace the missing weight with 123456789.
In the last sample case, there is no weights to assign but the length of the shortest path doesn't match the required value, so the answer is "NO".
Submitted Solution:
```
class Node:
length = None
through = None
def __str__(self):
return str(self.value)
def __init__(self, value):
self.value = value
self.connections = {}
nodes = {}
nodesWithoutZeros = {}
inputs = []
# maxW = -1
n, m, l, s, t = list(map(int, input().split()))
areZeros = False
for _ in range(m):
u, v, w = list(map(int, input().split()))
# if w > maxW:
# maxW = w
if not u in nodes.keys():
nodes[u] = Node(u)
if not v in nodes.keys():
nodes[v] = Node(v)
if w != 0:
if not u in nodesWithoutZeros.keys():
nodesWithoutZeros[u] = Node(u)
if not v in nodesWithoutZeros.keys():
nodesWithoutZeros[v] = Node(v)
nodesWithoutZeros[u].connections[v] = w
nodesWithoutZeros[v].connections[u] = w
else:
areZeros = True
inputs.append((u, v))
nodes[u].connections[v] = w
nodes[v].connections[u] = w
sortedNodes = []
def add(arr, no):
if no in arr:
arr.remove(no)
if len(arr) == 0:
arr.append(no)
return
i = len(arr)//2
while True:
if arr[i].length == no.length:
arr.insert(i, no)
elif arr[i].length > no.length:
new = (i + len(arr)) // 2
if new == i:
arr.insert(i+1, no)
return
i = new
else:
new = (len(arr) - i) // 2
if new == i:
arr.insert(i, no)
return
i = new
# minLengths = {}
# toGo = set(s)
done = set()
nodes[s].length = 0
add(sortedNodes, nodes[s])
while len(sortedNodes) > 0:
nod = sortedNodes.pop()
le = nod.length
for k, v in nod.connections.items():
if k in done:
continue
if v == 0:
v = 1
nodee = nodes[k]
if nodee.length == None:
nodee.length = v + le
nodee.through = nod.value
add(sortedNodes, nodee)
continue
if v + le < nodee.length:
nodee.length = le + v
nodee.through = nod.value
add(sortedNodes, nodee)
done.add(nod.value)
sortedNodes = []
done = set()
if s in nodesWithoutZeros.keys():
nodesWithoutZeros[s].length = 0
add(sortedNodes, nodesWithoutZeros[s])
while len(sortedNodes) > 0:
nod = sortedNodes.pop()
le = nod.length
for k, v in nod.connections.items():
if k in done:
continue
if v == 0:
v = 1
nodee = nodesWithoutZeros[k]
if nodee.length == None:
nodee.length = v + le
nodee.through = nod.value
add(sortedNodes, nodee)
continue
if v + le < nodee.length:
nodee.length = le + v
nodee.through = nod.value
add(sortedNodes, nodee)
done.add(nod.value)
if len(nodesWithoutZeros) > 0 and nodesWithoutZeros[t].length != None and nodesWithoutZeros[t].length < l:
print("NO")
elif len(nodesWithoutZeros) > 0 and areZeros == False and nodesWithoutZeros[t].length != None and nodesWithoutZeros[t].length != l:
print("NO")
elif nodes[t].length == None or nodes[t].length > l:
print("NO")
else:
toFill = []
sumL = 0
cur = t
while cur != s:
nod = nodes[cur]
if nod.connections[nod.through] == 0:
# nod.connections[nod.through] = 1
# nodes[nod.through].connections[cur] = 1
toFill.append(nod.value)
else:
sumL += nod.connections[nod.through]
cur = nod.through
sumL = l - sumL
if sumL < len(toFill):
print("NO")
while len(toFill) > 1:
nod = nodes[toFill.pop()]
nod.connections[nod.through] = 1
nodes[nod.through].connections[nod.value] = 1
sumL -= 1
nod = nodes[toFill.pop()]
nod.connections[nod.through] = sumL
nodes[nod.through].connections[nod.value] = sumL
for nod in nodes.values():
if nod.length == 0:
nod.length = l + 1
def getOutStr(inp):
va1 = inp[0]
va2 = inp[1]
node1 = nodes[va1]
return "{} {} {}".format(va1, va2, node1.connections[va2])
print("\n".join(map(getOutStr, inputs)))
``` | instruction | 0 | 13,769 | 13 | 27,538 |
No | output | 1 | 13,769 | 13 | 27,539 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
ZS the Coder has drawn an undirected graph of n vertices numbered from 0 to n - 1 and m edges between them. Each edge of the graph is weighted, each weight is a positive integer.
The next day, ZS the Coder realized that some of the weights were erased! So he wants to reassign positive integer weight to each of the edges which weights were erased, so that the length of the shortest path between vertices s and t in the resulting graph is exactly L. Can you help him?
Input
The first line contains five integers n, m, L, s, t (2 ≤ n ≤ 1000, 1 ≤ m ≤ 10 000, 1 ≤ L ≤ 109, 0 ≤ s, t ≤ n - 1, s ≠ t) — the number of vertices, number of edges, the desired length of shortest path, starting vertex and ending vertex respectively.
Then, m lines describing the edges of the graph follow. i-th of them contains three integers, ui, vi, wi (0 ≤ ui, vi ≤ n - 1, ui ≠ vi, 0 ≤ wi ≤ 109). ui and vi denote the endpoints of the edge and wi denotes its weight. If wi is equal to 0 then the weight of the corresponding edge was erased.
It is guaranteed that there is at most one edge between any pair of vertices.
Output
Print "NO" (without quotes) in the only line if it's not possible to assign the weights in a required way.
Otherwise, print "YES" in the first line. Next m lines should contain the edges of the resulting graph, with weights assigned to edges which weights were erased. i-th of them should contain three integers ui, vi and wi, denoting an edge between vertices ui and vi of weight wi. The edges of the new graph must coincide with the ones in the graph from the input. The weights that were not erased must remain unchanged whereas the new weights can be any positive integer not exceeding 1018.
The order of the edges in the output doesn't matter. The length of the shortest path between s and t must be equal to L.
If there are multiple solutions, print any of them.
Examples
Input
5 5 13 0 4
0 1 5
2 1 2
3 2 3
1 4 0
4 3 4
Output
YES
0 1 5
2 1 2
3 2 3
1 4 8
4 3 4
Input
2 1 123456789 0 1
0 1 0
Output
YES
0 1 123456789
Input
2 1 999999999 1 0
0 1 1000000000
Output
NO
Note
Here's how the graph in the first sample case looks like :
<image>
In the first sample case, there is only one missing edge weight. Placing the weight of 8 gives a shortest path from 0 to 4 of length 13.
In the second sample case, there is only a single edge. Clearly, the only way is to replace the missing weight with 123456789.
In the last sample case, there is no weights to assign but the length of the shortest path doesn't match the required value, so the answer is "NO".
Submitted Solution:
```
from collections import defaultdict
MAX_WEIGHT = 10 ** 14
def compute_path(graph, s, n):
visited = [False] * n
distances = [MAX_WEIGHT] * n
ancestors = {}
distances[s] = 0
for i in range(n):
_, v = min((distances[j], j) for j in range(n) if not visited[j])
visited[v] = True
for to, length in graph[v]:
if distances[to] > distances[v] + length:
distances[to] = distances[v] + length
ancestors[to] = v
return ancestors, distances
def output(graph, u, v, extra, n, zeros, erased, leave):
for i in range(n):
for to, length in graph[i]:
if to < i:
if (i, to) == (u, v):
print(i, to, length + extra)
elif zeros and (i, to) in erased and (i, to) not in leave:
print(i, to, MAX_WEIGHT)
else:
print(i, to, length)
graph_with_0 = defaultdict(list)
graph_with_max = defaultdict(list)
n, m, L, s, t = map(int, input().split(' '))
erased = set()
for _ in range(m):
u, v, l = map(int, input().split(' '))
if l == 0:
graph_with_0[u].append((v, 1))
graph_with_0[v].append((u, 1))
graph_with_max[u].append((v, MAX_WEIGHT))
graph_with_max[v].append((u, MAX_WEIGHT))
erased |= {(u, v), (v, u)}
else:
graph_with_0[u].append((v, l))
graph_with_0[v].append((u, l))
graph_with_max[u].append((v, l))
graph_with_max[v].append((u, l))
a1, d1 = compute_path(graph_with_0, s, n)
a2, d2 = compute_path(graph_with_max, s, n)
if d2[t] < L:
print('NO')
elif d2[t] == L:
print('YES')
output(graph_with_max, n+1, n+1, 0, n, False, erased, set())
elif d1[t] <= L:
print('YES')
v = t
leave = set()
while v != s:
leave |= {(v, a1[v]), (a1[v], v)}
v = a1[v]
v = t
while (v, a1[v]) not in erased:
v = a1[v]
output(graph_with_0, max(v, a1[v]), min(v, a1[v]), L - d1[t], n, True, erased, leave)
else:
print('NO')
``` | instruction | 0 | 13,770 | 13 | 27,540 |
No | output | 1 | 13,770 | 13 | 27,541 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
ZS the Coder has drawn an undirected graph of n vertices numbered from 0 to n - 1 and m edges between them. Each edge of the graph is weighted, each weight is a positive integer.
The next day, ZS the Coder realized that some of the weights were erased! So he wants to reassign positive integer weight to each of the edges which weights were erased, so that the length of the shortest path between vertices s and t in the resulting graph is exactly L. Can you help him?
Input
The first line contains five integers n, m, L, s, t (2 ≤ n ≤ 1000, 1 ≤ m ≤ 10 000, 1 ≤ L ≤ 109, 0 ≤ s, t ≤ n - 1, s ≠ t) — the number of vertices, number of edges, the desired length of shortest path, starting vertex and ending vertex respectively.
Then, m lines describing the edges of the graph follow. i-th of them contains three integers, ui, vi, wi (0 ≤ ui, vi ≤ n - 1, ui ≠ vi, 0 ≤ wi ≤ 109). ui and vi denote the endpoints of the edge and wi denotes its weight. If wi is equal to 0 then the weight of the corresponding edge was erased.
It is guaranteed that there is at most one edge between any pair of vertices.
Output
Print "NO" (without quotes) in the only line if it's not possible to assign the weights in a required way.
Otherwise, print "YES" in the first line. Next m lines should contain the edges of the resulting graph, with weights assigned to edges which weights were erased. i-th of them should contain three integers ui, vi and wi, denoting an edge between vertices ui and vi of weight wi. The edges of the new graph must coincide with the ones in the graph from the input. The weights that were not erased must remain unchanged whereas the new weights can be any positive integer not exceeding 1018.
The order of the edges in the output doesn't matter. The length of the shortest path between s and t must be equal to L.
If there are multiple solutions, print any of them.
Examples
Input
5 5 13 0 4
0 1 5
2 1 2
3 2 3
1 4 0
4 3 4
Output
YES
0 1 5
2 1 2
3 2 3
1 4 8
4 3 4
Input
2 1 123456789 0 1
0 1 0
Output
YES
0 1 123456789
Input
2 1 999999999 1 0
0 1 1000000000
Output
NO
Note
Here's how the graph in the first sample case looks like :
<image>
In the first sample case, there is only one missing edge weight. Placing the weight of 8 gives a shortest path from 0 to 4 of length 13.
In the second sample case, there is only a single edge. Clearly, the only way is to replace the missing weight with 123456789.
In the last sample case, there is no weights to assign but the length of the shortest path doesn't match the required value, so the answer is "NO".
Submitted Solution:
```
from collections import defaultdict
MAX_WEIGHT = 10 ** 14
def compute_path(graph, s, n):
visited = [False] * n
distances = [MAX_WEIGHT] * n
ancestors = {}
distances[s] = 0
for i in range(n):
_, v = min((distances[j], j) for j in range(n) if not visited[j])
visited[v] = True
for to, length in graph[v]:
if distances[to] > distances[v] + length:
distances[to] = distances[v] + length
ancestors[to] = v
return ancestors, distances
def output(graph, u, v, extra, n, zeros, erased, leave):
for i in range(n):
for to, length in graph[i]:
if to < i:
if (i, to) == (u, v):
print(i, to, length + extra)
elif zeros and (i, to) in erased and (i, to) not in leave:
print(i, to, MAX_WEIGHT)
else:
print(i, to, length)
graph_with_0 = defaultdict(list)
graph_with_max = defaultdict(list)
n, m, L, s, t = map(int, input().split(' '))
erased = set()
for _ in range(m):
u, v, l = map(int, input().split(' '))
if l == 0:
graph_with_0[u].append((v, 1))
graph_with_0[v].append((u, 1))
graph_with_max[u].append((v, MAX_WEIGHT))
graph_with_max[v].append((u, MAX_WEIGHT))
erased |= {(u, v), (v, u)}
else:
graph_with_0[u].append((v, l))
graph_with_0[v].append((u, l))
graph_with_max[u].append((v, l))
graph_with_max[v].append((u, l))
a1, d1 = compute_path(graph_with_0, s, n)
a2, d2 = compute_path(graph_with_max, s, n)
if d2[t] < L:
print('NO')
elif d2[t] == L:
print('YES')
output(graph_with_max, n+1, n+1, 0, n, False, erased, set())
elif d1[t] <= L:
print('YES')
v = t
leave = set()
while v != s:
leave |= {(v, a1[v]), (a1[v], v)}
if d2[v] > L:
c, d = max(v, a1[v]), min(v, a1[v])
v = a1[v]
output(graph_with_0, c, d, L - d1[t], n, True, erased, leave)
else:
print('NO')
``` | instruction | 0 | 13,771 | 13 | 27,542 |
No | output | 1 | 13,771 | 13 | 27,543 |
Provide a correct Python 3 solution for this coding contest problem.
We have a tree with N vertices numbered 1 to N. The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i. Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied:
* For any two vertices painted in the same color, the distance between them is an even number.
Find a coloring of the vertices that satisfies the condition and print it. It can be proved that at least one such coloring exists under the constraints of this problem.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 1 \leq u_i < v_i \leq N
* 1 \leq w_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
u_1 v_1 w_1
u_2 v_2 w_2
.
.
.
u_{N - 1} v_{N - 1} w_{N - 1}
Output
Print a coloring of the vertices that satisfies the condition, in N lines. The i-th line should contain `0` if Vertex i is painted white and `1` if it is painted black.
If there are multiple colorings that satisfy the condition, any of them will be accepted.
Examples
Input
3
1 2 2
2 3 1
Output
0
0
1
Input
5
2 5 2
2 3 10
1 3 8
3 4 2
Output
1
0
1
0
1 | instruction | 0 | 13,953 | 13 | 27,906 |
"Correct Solution:
```
N, = map(int, input().split())
import sys
sys.setrecursionlimit(10**6)
d = [set() for _ in range(N+1)]
Cs = [0 for _ in range(N+1)]
for _ in range(N-1):
u, v, p = map(int, input().split())
d[u].add((v, p))
d[v].add((u, p))
def it(v, p):
for u, c in d[v]:
if u == p:
continue
Cs[u] = int(not Cs[v]) if c%2 else Cs[v]
it(u, v)
it(1, None)
for i in range(1, N+1):
print(Cs[i])
``` | output | 1 | 13,953 | 13 | 27,907 |
Provide a correct Python 3 solution for this coding contest problem.
We have a tree with N vertices numbered 1 to N. The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i. Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied:
* For any two vertices painted in the same color, the distance between them is an even number.
Find a coloring of the vertices that satisfies the condition and print it. It can be proved that at least one such coloring exists under the constraints of this problem.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 1 \leq u_i < v_i \leq N
* 1 \leq w_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
u_1 v_1 w_1
u_2 v_2 w_2
.
.
.
u_{N - 1} v_{N - 1} w_{N - 1}
Output
Print a coloring of the vertices that satisfies the condition, in N lines. The i-th line should contain `0` if Vertex i is painted white and `1` if it is painted black.
If there are multiple colorings that satisfy the condition, any of them will be accepted.
Examples
Input
3
1 2 2
2 3 1
Output
0
0
1
Input
5
2 5 2
2 3 10
1 3 8
3 4 2
Output
1
0
1
0
1 | instruction | 0 | 13,954 | 13 | 27,908 |
"Correct Solution:
```
n=int(input())
edges=[[] for i in range(n)]
import sys
sys.setrecursionlimit(10**7)
for i in range(n-1):
a,s,w=map(int,input().split())
edges[a-1].append([s-1,w]);edges[s-1].append([a-1,w])
colors=[-1]*n
colors[0]=1
def dfs(now):
for to,cost in edges[now]:
if colors[to]==-1:
colors[to]=(cost+colors[now])%2
dfs(to)
dfs(0)
print(*colors,sep="\n")
``` | output | 1 | 13,954 | 13 | 27,909 |
Provide a correct Python 3 solution for this coding contest problem.
We have a tree with N vertices numbered 1 to N. The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i. Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied:
* For any two vertices painted in the same color, the distance between them is an even number.
Find a coloring of the vertices that satisfies the condition and print it. It can be proved that at least one such coloring exists under the constraints of this problem.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 1 \leq u_i < v_i \leq N
* 1 \leq w_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
u_1 v_1 w_1
u_2 v_2 w_2
.
.
.
u_{N - 1} v_{N - 1} w_{N - 1}
Output
Print a coloring of the vertices that satisfies the condition, in N lines. The i-th line should contain `0` if Vertex i is painted white and `1` if it is painted black.
If there are multiple colorings that satisfy the condition, any of them will be accepted.
Examples
Input
3
1 2 2
2 3 1
Output
0
0
1
Input
5
2 5 2
2 3 10
1 3 8
3 4 2
Output
1
0
1
0
1 | instruction | 0 | 13,955 | 13 | 27,910 |
"Correct Solution:
```
(n,),*t=[map(int,t.split())for t in open(0)]
*e,=eval('[],'*-~n)
q=[(1,0)]
f=[-1]*n
for v,w,c in t:e[v]+=(w,c),;e[w]+=(v,c),
for v,c in q:
f[v-1]=c&1
for w,d in e[v]:q+=[(w,c+d)]*(f[w-1]<0)
print(*f)
``` | output | 1 | 13,955 | 13 | 27,911 |
Provide a correct Python 3 solution for this coding contest problem.
We have a tree with N vertices numbered 1 to N. The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i. Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied:
* For any two vertices painted in the same color, the distance between them is an even number.
Find a coloring of the vertices that satisfies the condition and print it. It can be proved that at least one such coloring exists under the constraints of this problem.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 1 \leq u_i < v_i \leq N
* 1 \leq w_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
u_1 v_1 w_1
u_2 v_2 w_2
.
.
.
u_{N - 1} v_{N - 1} w_{N - 1}
Output
Print a coloring of the vertices that satisfies the condition, in N lines. The i-th line should contain `0` if Vertex i is painted white and `1` if it is painted black.
If there are multiple colorings that satisfy the condition, any of them will be accepted.
Examples
Input
3
1 2 2
2 3 1
Output
0
0
1
Input
5
2 5 2
2 3 10
1 3 8
3 4 2
Output
1
0
1
0
1 | instruction | 0 | 13,956 | 13 | 27,912 |
"Correct Solution:
```
n=int(input())
q=[[] for i in range(n+1)]
for i in range(n-1):
a,b,c=map(int,input().split())
q[a].append((b,c))
q[b].append((a,c))
l=[-1]*n
s=[(1,0)]
while s:
a,w=s.pop()
l[a-1]=w%2
for b,c in q[a]:
if l[b-1]==-1:
s.append((b,w+c))
for i in l:
print(i)
``` | output | 1 | 13,956 | 13 | 27,913 |
Provide a correct Python 3 solution for this coding contest problem.
We have a tree with N vertices numbered 1 to N. The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i. Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied:
* For any two vertices painted in the same color, the distance between them is an even number.
Find a coloring of the vertices that satisfies the condition and print it. It can be proved that at least one such coloring exists under the constraints of this problem.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 1 \leq u_i < v_i \leq N
* 1 \leq w_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
u_1 v_1 w_1
u_2 v_2 w_2
.
.
.
u_{N - 1} v_{N - 1} w_{N - 1}
Output
Print a coloring of the vertices that satisfies the condition, in N lines. The i-th line should contain `0` if Vertex i is painted white and `1` if it is painted black.
If there are multiple colorings that satisfy the condition, any of them will be accepted.
Examples
Input
3
1 2 2
2 3 1
Output
0
0
1
Input
5
2 5 2
2 3 10
1 3 8
3 4 2
Output
1
0
1
0
1 | instruction | 0 | 13,957 | 13 | 27,914 |
"Correct Solution:
```
N = int(input())
adj = [[] for _ in range(N)]
for i in range(N-1):
u,v,w = map(int,input().split())
u,v = u-1, v-1
w %= 2
adj[u].append((v,w))
adj[v].append((u,w))
color = [None]*N
color[0] = False
stack = [0]
while stack:
u = stack.pop()
for v,w in adj[u]:
if color[v] is None:
color[v] = (w%2) ^ color[u]
stack.append(v)
for c in color:
print(1 if c else 0)
``` | output | 1 | 13,957 | 13 | 27,915 |
Provide a correct Python 3 solution for this coding contest problem.
We have a tree with N vertices numbered 1 to N. The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i. Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied:
* For any two vertices painted in the same color, the distance between them is an even number.
Find a coloring of the vertices that satisfies the condition and print it. It can be proved that at least one such coloring exists under the constraints of this problem.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 1 \leq u_i < v_i \leq N
* 1 \leq w_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
u_1 v_1 w_1
u_2 v_2 w_2
.
.
.
u_{N - 1} v_{N - 1} w_{N - 1}
Output
Print a coloring of the vertices that satisfies the condition, in N lines. The i-th line should contain `0` if Vertex i is painted white and `1` if it is painted black.
If there are multiple colorings that satisfy the condition, any of them will be accepted.
Examples
Input
3
1 2 2
2 3 1
Output
0
0
1
Input
5
2 5 2
2 3 10
1 3 8
3 4 2
Output
1
0
1
0
1 | instruction | 0 | 13,958 | 13 | 27,916 |
"Correct Solution:
```
def solve():
from collections import deque
n,*l=map(int,open(0).read().split())
con=[[] for _ in range(n)]
dist=[-1]*n
dist[0]=0
for a,b,c in zip(*[iter(l)]*3):
con[a-1].append((b-1,c%2))
con[b-1].append((a-1,c%2))
stk=deque([0])
while stk:
cur=stk.pop()
for nxt,d in con[cur]:
if dist[nxt]<0:
stk.append(nxt)
dist[nxt]=(dist[cur]+d)%2
print(*dist,sep="\n")
if __name__=="__main__":
solve()
``` | output | 1 | 13,958 | 13 | 27,917 |
Provide a correct Python 3 solution for this coding contest problem.
We have a tree with N vertices numbered 1 to N. The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i. Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied:
* For any two vertices painted in the same color, the distance between them is an even number.
Find a coloring of the vertices that satisfies the condition and print it. It can be proved that at least one such coloring exists under the constraints of this problem.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 1 \leq u_i < v_i \leq N
* 1 \leq w_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
u_1 v_1 w_1
u_2 v_2 w_2
.
.
.
u_{N - 1} v_{N - 1} w_{N - 1}
Output
Print a coloring of the vertices that satisfies the condition, in N lines. The i-th line should contain `0` if Vertex i is painted white and `1` if it is painted black.
If there are multiple colorings that satisfy the condition, any of them will be accepted.
Examples
Input
3
1 2 2
2 3 1
Output
0
0
1
Input
5
2 5 2
2 3 10
1 3 8
3 4 2
Output
1
0
1
0
1 | instruction | 0 | 13,959 | 13 | 27,918 |
"Correct Solution:
```
import sys
sys.setrecursionlimit(10**9)
n = int(input())
T = [[] for _ in range(n)]
for _ in range(n-1):
u,v,w = map(int,input().split())
u -= 1
v -= 1
w %= 2
T[u].append((v,w))
T[v].append((u,w))
ans = [0]*n
def dfs(u,p=-1,c=0):
for v,w in T[u]:
if v == p: continue
nc = (c+1)%2 if w else c
ans[v] = nc
dfs(v,u,nc)
dfs(0)
print("\n".join(map(str,ans)))
``` | output | 1 | 13,959 | 13 | 27,919 |
Provide a correct Python 3 solution for this coding contest problem.
We have a tree with N vertices numbered 1 to N. The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i. Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied:
* For any two vertices painted in the same color, the distance between them is an even number.
Find a coloring of the vertices that satisfies the condition and print it. It can be proved that at least one such coloring exists under the constraints of this problem.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 1 \leq u_i < v_i \leq N
* 1 \leq w_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
u_1 v_1 w_1
u_2 v_2 w_2
.
.
.
u_{N - 1} v_{N - 1} w_{N - 1}
Output
Print a coloring of the vertices that satisfies the condition, in N lines. The i-th line should contain `0` if Vertex i is painted white and `1` if it is painted black.
If there are multiple colorings that satisfy the condition, any of them will be accepted.
Examples
Input
3
1 2 2
2 3 1
Output
0
0
1
Input
5
2 5 2
2 3 10
1 3 8
3 4 2
Output
1
0
1
0
1 | instruction | 0 | 13,960 | 13 | 27,920 |
"Correct Solution:
```
N=int(input())
links=[set() for _ in [0]*N]
for i in range(1,N):
u,v,w=map(int,input().split())
u-=1
v-=1
links[u].add((v,w))
links[v].add((u,w))
ans=[-1]*N
q=[(0,0,-1)]
while q:
v,d,p=q.pop()
if d%2==0:
ans[v]=0
else:
ans[v]=1
for u,w in links[v]:
if u==p:
continue
q.append((u,w+d,v))
print('\n'.join(map(str,ans)))
``` | output | 1 | 13,960 | 13 | 27,921 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a tree with N vertices numbered 1 to N. The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i. Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied:
* For any two vertices painted in the same color, the distance between them is an even number.
Find a coloring of the vertices that satisfies the condition and print it. It can be proved that at least one such coloring exists under the constraints of this problem.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 1 \leq u_i < v_i \leq N
* 1 \leq w_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
u_1 v_1 w_1
u_2 v_2 w_2
.
.
.
u_{N - 1} v_{N - 1} w_{N - 1}
Output
Print a coloring of the vertices that satisfies the condition, in N lines. The i-th line should contain `0` if Vertex i is painted white and `1` if it is painted black.
If there are multiple colorings that satisfy the condition, any of them will be accepted.
Examples
Input
3
1 2 2
2 3 1
Output
0
0
1
Input
5
2 5 2
2 3 10
1 3 8
3 4 2
Output
1
0
1
0
1
Submitted Solution:
```
n=int(input())
path=[[] for i in range(n)]
for i in range(n-1):
a,b,c=map(int, input().split())
path[a-1].append([b-1,c%2])
path[b-1].append([a-1,c%2])
ans=[-1]*n
ans[0]=0
q=[0]
while q:
nq=[]
for k in q:
for i,j in path[k]:
if ans[i]==-1:
ans[i]=(ans[k]+j)%2
nq.append(i)
q=nq[:]
for i in ans:print(str(i))
``` | instruction | 0 | 13,961 | 13 | 27,922 |
Yes | output | 1 | 13,961 | 13 | 27,923 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a tree with N vertices numbered 1 to N. The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i. Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied:
* For any two vertices painted in the same color, the distance between them is an even number.
Find a coloring of the vertices that satisfies the condition and print it. It can be proved that at least one such coloring exists under the constraints of this problem.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 1 \leq u_i < v_i \leq N
* 1 \leq w_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
u_1 v_1 w_1
u_2 v_2 w_2
.
.
.
u_{N - 1} v_{N - 1} w_{N - 1}
Output
Print a coloring of the vertices that satisfies the condition, in N lines. The i-th line should contain `0` if Vertex i is painted white and `1` if it is painted black.
If there are multiple colorings that satisfy the condition, any of them will be accepted.
Examples
Input
3
1 2 2
2 3 1
Output
0
0
1
Input
5
2 5 2
2 3 10
1 3 8
3 4 2
Output
1
0
1
0
1
Submitted Solution:
```
N = int(input())
E = [[] for _ in range(N)]
for _ in range(N-1):
u,v,w = map(int,input().split())
u -= 1
v -= 1
E[u].append((v,w))
E[v].append((u,w))
color = [-1 for _ in range(N)]
stack = [u]
color[u] = 0
while stack:
u = stack.pop()
for v,w in E[u]:
if color[v] == -1:
stack.append(v)
if w % 2 == 0:
color[v] = color[u]
else:
color[v] = (color[u] + 1) % 2
for i in range(N):
print(color[i])
``` | instruction | 0 | 13,962 | 13 | 27,924 |
Yes | output | 1 | 13,962 | 13 | 27,925 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a tree with N vertices numbered 1 to N. The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i. Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied:
* For any two vertices painted in the same color, the distance between them is an even number.
Find a coloring of the vertices that satisfies the condition and print it. It can be proved that at least one such coloring exists under the constraints of this problem.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 1 \leq u_i < v_i \leq N
* 1 \leq w_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
u_1 v_1 w_1
u_2 v_2 w_2
.
.
.
u_{N - 1} v_{N - 1} w_{N - 1}
Output
Print a coloring of the vertices that satisfies the condition, in N lines. The i-th line should contain `0` if Vertex i is painted white and `1` if it is painted black.
If there are multiple colorings that satisfy the condition, any of them will be accepted.
Examples
Input
3
1 2 2
2 3 1
Output
0
0
1
Input
5
2 5 2
2 3 10
1 3 8
3 4 2
Output
1
0
1
0
1
Submitted Solution:
```
import sys
sys.setrecursionlimit(pow(10, 7))
def dfs(v, c):
color[v] = c
for x in glaph[v]:
u, w = x[0], x[1]
if color[u] != -1:
continue
if w%2 == 0:
dfs(u, c)
else:
dfs(u, 1-c)
n = int(input())
color = [-1]*n
glaph = [[]*n for _ in range(n)]
for _ in range(n-1):
u,v,w = map(int, input().split())
glaph[u-1].append((v-1, w))
glaph[v-1].append((u-1, w))
dfs(v=0, c=0)
for i in color:
print(i)
``` | instruction | 0 | 13,963 | 13 | 27,926 |
Yes | output | 1 | 13,963 | 13 | 27,927 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a tree with N vertices numbered 1 to N. The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i. Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied:
* For any two vertices painted in the same color, the distance between them is an even number.
Find a coloring of the vertices that satisfies the condition and print it. It can be proved that at least one such coloring exists under the constraints of this problem.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 1 \leq u_i < v_i \leq N
* 1 \leq w_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
u_1 v_1 w_1
u_2 v_2 w_2
.
.
.
u_{N - 1} v_{N - 1} w_{N - 1}
Output
Print a coloring of the vertices that satisfies the condition, in N lines. The i-th line should contain `0` if Vertex i is painted white and `1` if it is painted black.
If there are multiple colorings that satisfy the condition, any of them will be accepted.
Examples
Input
3
1 2 2
2 3 1
Output
0
0
1
Input
5
2 5 2
2 3 10
1 3 8
3 4 2
Output
1
0
1
0
1
Submitted Solution:
```
import math
import sys
sys.setrecursionlimit(30000)
N=int(input())
edges=[[] for i in range(N+1)]
d=[-1 for i in range(N+1)]
for i in range(1,N):
u,v,w=[int(i) for i in input().split()]
edges[u].append([v,w])
edges[v].append([u,w])
def kyori(u):
for v,w in edges[u]:
if d[v]==-1:
d[v]=d[u]+w
kyori(v)
d[1]=0
kyori(1)
for i in d[1:]:
if i%2==0:
print(1)
else:
print(0)
``` | instruction | 0 | 13,964 | 13 | 27,928 |
Yes | output | 1 | 13,964 | 13 | 27,929 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a tree with N vertices numbered 1 to N. The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i. Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied:
* For any two vertices painted in the same color, the distance between them is an even number.
Find a coloring of the vertices that satisfies the condition and print it. It can be proved that at least one such coloring exists under the constraints of this problem.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 1 \leq u_i < v_i \leq N
* 1 \leq w_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
u_1 v_1 w_1
u_2 v_2 w_2
.
.
.
u_{N - 1} v_{N - 1} w_{N - 1}
Output
Print a coloring of the vertices that satisfies the condition, in N lines. The i-th line should contain `0` if Vertex i is painted white and `1` if it is painted black.
If there are multiple colorings that satisfy the condition, any of them will be accepted.
Examples
Input
3
1 2 2
2 3 1
Output
0
0
1
Input
5
2 5 2
2 3 10
1 3 8
3 4 2
Output
1
0
1
0
1
Submitted Solution:
```
N, M = map(int, input().split())
X = [0] * M
Y = [0] * M
Z = [0] * M
for i in range(M):
X[i], Y[i], Z[i] = map(int, input().split())
X1 = list(set(X))
print(N-len(X1))
``` | instruction | 0 | 13,965 | 13 | 27,930 |
No | output | 1 | 13,965 | 13 | 27,931 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a tree with N vertices numbered 1 to N. The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i. Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied:
* For any two vertices painted in the same color, the distance between them is an even number.
Find a coloring of the vertices that satisfies the condition and print it. It can be proved that at least one such coloring exists under the constraints of this problem.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 1 \leq u_i < v_i \leq N
* 1 \leq w_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
u_1 v_1 w_1
u_2 v_2 w_2
.
.
.
u_{N - 1} v_{N - 1} w_{N - 1}
Output
Print a coloring of the vertices that satisfies the condition, in N lines. The i-th line should contain `0` if Vertex i is painted white and `1` if it is painted black.
If there are multiple colorings that satisfy the condition, any of them will be accepted.
Examples
Input
3
1 2 2
2 3 1
Output
0
0
1
Input
5
2 5 2
2 3 10
1 3 8
3 4 2
Output
1
0
1
0
1
Submitted Solution:
```
n = int(input())
g = [[] for _ in range(n)]
for _ in range(n-1):
u,v,w = map(int,input().split())
g[u-1].append((v-1,w))
g[v-1].append((u-1,w))
ans = [0] * n
for i in range(n):
for c in g[i]:
if c[1] % 2 == 0:
if ans[i] % 2 == 0:
ans[c[0]] = 0
else:
ans[c[0]] = 1
else:
if ans[i] % 2 == 0:
ans[c[0]] = 1
else:
ans[c[0]] = 0
for i in ans:
print(i)
``` | instruction | 0 | 13,966 | 13 | 27,932 |
No | output | 1 | 13,966 | 13 | 27,933 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a tree with N vertices numbered 1 to N. The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i. Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied:
* For any two vertices painted in the same color, the distance between them is an even number.
Find a coloring of the vertices that satisfies the condition and print it. It can be proved that at least one such coloring exists under the constraints of this problem.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 1 \leq u_i < v_i \leq N
* 1 \leq w_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
u_1 v_1 w_1
u_2 v_2 w_2
.
.
.
u_{N - 1} v_{N - 1} w_{N - 1}
Output
Print a coloring of the vertices that satisfies the condition, in N lines. The i-th line should contain `0` if Vertex i is painted white and `1` if it is painted black.
If there are multiple colorings that satisfy the condition, any of them will be accepted.
Examples
Input
3
1 2 2
2 3 1
Output
0
0
1
Input
5
2 5 2
2 3 10
1 3 8
3 4 2
Output
1
0
1
0
1
Submitted Solution:
```
N = int(input())
adj_list = { i: [] for i in range(N+1) }
for _ in range(N-1):
u,v,w = map(int, input().split())
adj_list[u].append([v,w])
adj_list[v].append([u,w])
res = [None] * N
visited = [False] * (N+1)
def dfs(node, c, w):
res[node-1] = c
visited[node] = True
for nei, nw, in adj_list[node]:
if not visited[nei]:
if (w+nw)%2 == 0:
dfs(nei, 0, w+nw)
else:
dfs(nei, 1, w+nw)
dfs(1, 0, 0)
for r in res: print(r)
``` | instruction | 0 | 13,967 | 13 | 27,934 |
No | output | 1 | 13,967 | 13 | 27,935 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a tree with N vertices numbered 1 to N. The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i. Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied:
* For any two vertices painted in the same color, the distance between them is an even number.
Find a coloring of the vertices that satisfies the condition and print it. It can be proved that at least one such coloring exists under the constraints of this problem.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 1 \leq u_i < v_i \leq N
* 1 \leq w_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
u_1 v_1 w_1
u_2 v_2 w_2
.
.
.
u_{N - 1} v_{N - 1} w_{N - 1}
Output
Print a coloring of the vertices that satisfies the condition, in N lines. The i-th line should contain `0` if Vertex i is painted white and `1` if it is painted black.
If there are multiple colorings that satisfy the condition, any of them will be accepted.
Examples
Input
3
1 2 2
2 3 1
Output
0
0
1
Input
5
2 5 2
2 3 10
1 3 8
3 4 2
Output
1
0
1
0
1
Submitted Solution:
```
from collections import deque
N = int(input())
Graph = [[] for i in range(N)]
for i in range(N-1):
u,v,w = map(int, input().split())
Graph[u-1].append((v-1, w))
Graph[v-1].append((u-1, w))
used = [0]*N
Q = deque([0])
used[0] = 1
ans = [0]*N
while Q:
i = Q.popleft()
j = ans[i]
for uv, w in Graph[i]:
if used[uv]:
continue
if w%2 != 0:
ans[uv] = 1
else:
ans[uv] = j
Q.append(uv)
used[uv] = 1
print(*ans)
``` | instruction | 0 | 13,968 | 13 | 27,936 |
No | output | 1 | 13,968 | 13 | 27,937 |
Provide a correct Python 3 solution for this coding contest problem.
There is a tree with N vertices. The vertices are numbered 1 through N. The i-th edge (1 \leq i \leq N - 1) connects Vertex x_i and y_i. For vertices v and w (1 \leq v, w \leq N), we will define the distance between v and w d(v, w) as "the number of edges contained in the path v-w".
A squirrel lives in each vertex of the tree. They are planning to move, as follows. First, they will freely choose a permutation of (1, 2, ..., N), p = (p_1, p_2, ..., p_N). Then, for each 1 \leq i \leq N, the squirrel that lived in Vertex i will move to Vertex p_i.
Since they like long travels, they have decided to maximize the total distance they traveled during the process. That is, they will choose p so that d(1, p_1) + d(2, p_2) + ... + d(N, p_N) will be maximized. How many such ways are there to choose p, modulo 10^9 + 7?
Constraints
* 2 \leq N \leq 5,000
* 1 \leq x_i, y_i \leq N
* The input graph is a tree.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_{N - 1} y_{N - 1}
Output
Print the number of the ways to choose p so that the condition is satisfied, modulo 10^9 + 7.
Examples
Input
3
1 2
2 3
Output
3
Input
4
1 2
1 3
1 4
Output
11
Input
6
1 2
1 3
1 4
2 5
2 6
Output
36
Input
7
1 2
6 3
4 5
1 7
1 5
2 3
Output
396 | instruction | 0 | 14,001 | 13 | 28,002 |
"Correct Solution:
```
from collections import defaultdict
import sys
sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def main():
def k_fix_way(com_n, com_r):
if (com_n, com_r) in kmemo:
return kmemo[(com_n, com_r)]
res = kmemo[(com_n, com_r)] = fac[com_n] * inv[com_n - com_r] * fac[com_n] * inv[com_r] * inv[
com_n - com_r] % md
return res
kmemo = {}
def centroid(u=0, pu=-1):
res = []
is_centroid = True
u_nodes = 1
for cu in to[u]:
if cu == pu: continue
res += centroid(cu, u)
cu_nodes = n_nodes[cu]
if cu_nodes > n / 2: is_centroid = False
u_nodes += cu_nodes
n_nodes[u] = u_nodes
if n - u_nodes > n / 2: is_centroid = False
if is_centroid: res.append(u)
return res
md = 10 ** 9 + 7
to = defaultdict(list)
n = int(input())
for _ in range(n - 1):
u, v = map(int, input().split())
u, v = u - 1, v - 1
to[u].append(v)
to[v].append(u)
# 部分木の頂点数を記録しながら重心を求める
n_nodes = [0] * n
cc = centroid()
# print(cc)
# 階乗の準備
n_max = n
fac = [1]
inv = [1] * (n_max + 1)
k_fac_inv = 1
for i in range(1, n_max + 1):
k_fac_inv = k_fac_inv * i % md
fac.append(k_fac_inv)
k_fac_inv = pow(k_fac_inv, md - 2, md)
for i in range(n_max, 1, -1):
inv[i] = k_fac_inv
k_fac_inv = k_fac_inv * i % md
# 重心が2つの(グラフを二等分できる)場合
if len(cc) == 2:
print(pow(fac[n // 2], 2, md))
exit()
# 重心が1つの場合
# サブツリーの頂点数のリストsubtree_node_n作成
subtree_node_n = []
c = cc[0]
for u in to[c]:
u_nodes = n_nodes[u]
if u_nodes > n / 2: continue
subtree_node_n.append(u_nodes)
if c != 0: subtree_node_n.append(n - n_nodes[c])
# print(subtree_node_n)
# dp[i][j]をi番目のサブツリーまでみて、j個の頂点を固定したときの決め方として求める
dp = [0] * n
dp[0] = 1
for i, node_n in enumerate(subtree_node_n):
for j in range(n - 1, -1, -1):
pre = dp[j]
if pre == 0: continue
for k in range(node_n, 0, -1):
dp[j + k] = (dp[j + k] + pre * k_fix_way(node_n, k)) % md
# print(dp)
# 包除原理
ans = 0
coff = 1
for j in range(n):
ans = (ans + coff * dp[j] * fac[n - j]) % md
coff *= -1
print(ans)
main()
``` | output | 1 | 14,001 | 13 | 28,003 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a tree with N vertices. The vertices are numbered 1 through N. The i-th edge (1 \leq i \leq N - 1) connects Vertex x_i and y_i. For vertices v and w (1 \leq v, w \leq N), we will define the distance between v and w d(v, w) as "the number of edges contained in the path v-w".
A squirrel lives in each vertex of the tree. They are planning to move, as follows. First, they will freely choose a permutation of (1, 2, ..., N), p = (p_1, p_2, ..., p_N). Then, for each 1 \leq i \leq N, the squirrel that lived in Vertex i will move to Vertex p_i.
Since they like long travels, they have decided to maximize the total distance they traveled during the process. That is, they will choose p so that d(1, p_1) + d(2, p_2) + ... + d(N, p_N) will be maximized. How many such ways are there to choose p, modulo 10^9 + 7?
Constraints
* 2 \leq N \leq 5,000
* 1 \leq x_i, y_i \leq N
* The input graph is a tree.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_{N - 1} y_{N - 1}
Output
Print the number of the ways to choose p so that the condition is satisfied, modulo 10^9 + 7.
Examples
Input
3
1 2
2 3
Output
3
Input
4
1 2
1 3
1 4
Output
11
Input
6
1 2
1 3
1 4
2 5
2 6
Output
36
Input
7
1 2
6 3
4 5
1 7
1 5
2 3
Output
396
Submitted Solution:
```
from collections import defaultdict
import sys
sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def main():
def k_fix_way(com_n, com_r):
return fac[com_n] * inv[com_n - com_r] * fac[com_n] * inv[com_r] * inv[com_n - com_r] % md
def centroid(u=0, pu=-1):
res = []
is_centroid = True
u_nodes = 1
for cu in to[u]:
if cu == pu: continue
res += centroid(cu, u)
cu_nodes = n_nodes[cu]
if cu_nodes > n / 2: is_centroid = False
u_nodes += cu_nodes
n_nodes[u] = u_nodes
if n - u_nodes > n / 2: is_centroid = False
if is_centroid: res.append(u)
return res
md = 10 ** 9 + 7
to = defaultdict(list)
n = int(input())
for _ in range(n - 1):
u, v = map(int, input().split())
u, v = u - 1, v - 1
to[u].append(v)
to[v].append(u)
# 部分木の頂点数を記録しながら重心を求める
n_nodes = [0] * n
cc = centroid()
# print(cc)
# 階乗の準備
n_max = n
fac = [1]
inv = [1] * (n_max + 1)
k_fac_inv = 1
for i in range(1, n_max + 1):
k_fac_inv = k_fac_inv * i % md
fac.append(k_fac_inv)
k_fac_inv = pow(k_fac_inv, md - 2, md)
for i in range(n_max, 1, -1):
inv[i] = k_fac_inv
k_fac_inv = k_fac_inv * i % md
# 重心が2つの(グラフを二等分できる)場合
if len(cc) == 2:
print(pow(fac[n // 2], 2, md))
exit()
# 重心が1つの場合
# サブツリーの頂点数のリストsubtree_node_n作成
subtree_node_n = []
c = cc[0]
for u in to[c]:
u_nodes = n_nodes[u]
if u_nodes > n / 2: continue
subtree_node_n.append(u_nodes)
if c != 0: subtree_node_n.append(n - n_nodes[c])
# print(subtree_node_n)
# dp[i][j]をi番目のサブツリーまでみて、j個の頂点を固定したときの決め方として求める
sn = len(subtree_node_n)
dp = [[0] * n for _ in range(sn + 1)]
dp[0][0] = 1
for i, node_n in enumerate(subtree_node_n):
for j in range(n):
pre = dp[i][j]
if pre == 0: continue
for k in range(node_n + 1):
dp[i + 1][j + k] = (dp[i + 1][j + k] + pre * k_fix_way(node_n, k)) % md
# p2D(dp)
# 包除原理
ans = 0
coff = 1
for j in range(n):
ans = (ans + coff * dp[sn][j] * fac[n - j]) % md
coff *= -1
print(ans)
main()
``` | instruction | 0 | 14,002 | 13 | 28,004 |
No | output | 1 | 14,002 | 13 | 28,005 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a tree with N vertices. The vertices are numbered 1 through N. The i-th edge (1 \leq i \leq N - 1) connects Vertex x_i and y_i. For vertices v and w (1 \leq v, w \leq N), we will define the distance between v and w d(v, w) as "the number of edges contained in the path v-w".
A squirrel lives in each vertex of the tree. They are planning to move, as follows. First, they will freely choose a permutation of (1, 2, ..., N), p = (p_1, p_2, ..., p_N). Then, for each 1 \leq i \leq N, the squirrel that lived in Vertex i will move to Vertex p_i.
Since they like long travels, they have decided to maximize the total distance they traveled during the process. That is, they will choose p so that d(1, p_1) + d(2, p_2) + ... + d(N, p_N) will be maximized. How many such ways are there to choose p, modulo 10^9 + 7?
Constraints
* 2 \leq N \leq 5,000
* 1 \leq x_i, y_i \leq N
* The input graph is a tree.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_{N - 1} y_{N - 1}
Output
Print the number of the ways to choose p so that the condition is satisfied, modulo 10^9 + 7.
Examples
Input
3
1 2
2 3
Output
3
Input
4
1 2
1 3
1 4
Output
11
Input
6
1 2
1 3
1 4
2 5
2 6
Output
36
Input
7
1 2
6 3
4 5
1 7
1 5
2 3
Output
396
Submitted Solution:
```
from collections import defaultdict
import sys
sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def main():
def k_fix_way(com_n, com_r):
if (com_n, com_r) in kmemo:
return kmemo[(com_n, com_r)]
res = kmemo[(com_n, com_r)] = fac[com_n] * inv[com_n - com_r] * fac[com_n] * inv[com_r] * inv[
com_n - com_r] % md
return res
kmemo = {}
def centroid(u=0, pu=-1):
res = []
is_centroid = True
u_nodes = 1
for cu in to[u]:
if cu == pu: continue
res += centroid(cu, u)
cu_nodes = n_nodes[cu]
if cu_nodes > n / 2: is_centroid = False
u_nodes += cu_nodes
n_nodes[u] = u_nodes
if n - u_nodes > n / 2: is_centroid = False
if is_centroid: res.append(u)
return res
md = 10 ** 9 + 7
to = defaultdict(list)
n = int(input())
for _ in range(n - 1):
u, v = map(int, input().split())
u, v = u - 1, v - 1
to[u].append(v)
to[v].append(u)
# 部分木の頂点数を記録しながら重心を求める
n_nodes = [0] * n
cc = centroid()
# print(cc)
# 階乗の準備
n_max = n
fac = [1]
inv = [1] * (n_max + 1)
k_fac_inv = 1
for i in range(1, n_max + 1):
k_fac_inv = k_fac_inv * i % md
fac.append(k_fac_inv)
k_fac_inv = pow(k_fac_inv, md - 2, md)
for i in range(n_max, 1, -1):
inv[i] = k_fac_inv
k_fac_inv = k_fac_inv * i % md
# 重心が2つの(グラフを二等分できる)場合
if len(cc) == 2:
print(pow(fac[n // 2], 2, md))
exit()
# 重心が1つの場合
# サブツリーの頂点数のリストsubtree_node_n作成
subtree_node_n = []
c = cc[0]
for u in to[c]:
u_nodes = n_nodes[u]
if u_nodes > n / 2: continue
subtree_node_n.append(u_nodes)
if c != 0: subtree_node_n.append(n - n_nodes[c])
# print(subtree_node_n)
# dp[i][j]をi番目のサブツリーまでみて、j個の頂点を固定したときの決め方として求める
sn = len(subtree_node_n)
dp = [0] * n
dp[0] = 1
for i, node_n in enumerate(subtree_node_n):
dp1 = [0] * n
for j in range(n):
pre = dp[j]
if pre == 0: continue
for k in range(node_n + 1):
dp1[j + k] = (dp1[j + k] + pre * k_fix_way(node_n, k)) % md
dp = dp1
# p2D(dp)
# 包除原理
ans = 0
coff = 1
for j in range(n):
ans = (ans + coff * dp[j] * fac[n - j]) % md
coff *= -1
print(ans)
main()
``` | instruction | 0 | 14,003 | 13 | 28,006 |
No | output | 1 | 14,003 | 13 | 28,007 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a tree with N vertices. The vertices are numbered 1 through N. The i-th edge (1 \leq i \leq N - 1) connects Vertex x_i and y_i. For vertices v and w (1 \leq v, w \leq N), we will define the distance between v and w d(v, w) as "the number of edges contained in the path v-w".
A squirrel lives in each vertex of the tree. They are planning to move, as follows. First, they will freely choose a permutation of (1, 2, ..., N), p = (p_1, p_2, ..., p_N). Then, for each 1 \leq i \leq N, the squirrel that lived in Vertex i will move to Vertex p_i.
Since they like long travels, they have decided to maximize the total distance they traveled during the process. That is, they will choose p so that d(1, p_1) + d(2, p_2) + ... + d(N, p_N) will be maximized. How many such ways are there to choose p, modulo 10^9 + 7?
Constraints
* 2 \leq N \leq 5,000
* 1 \leq x_i, y_i \leq N
* The input graph is a tree.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_{N - 1} y_{N - 1}
Output
Print the number of the ways to choose p so that the condition is satisfied, modulo 10^9 + 7.
Examples
Input
3
1 2
2 3
Output
3
Input
4
1 2
1 3
1 4
Output
11
Input
6
1 2
1 3
1 4
2 5
2 6
Output
36
Input
7
1 2
6 3
4 5
1 7
1 5
2 3
Output
396
Submitted Solution:
```
from collections import defaultdict
import sys
sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def main():
def k_fix_way(com_n, com_r):
if (com_n, com_r) in kmemo:
return kmemo[(com_n, com_r)]
res = kmemo[(com_n, com_r)] = fac[com_n] * inv[com_n - com_r] * fac[com_n] * inv[com_r] * inv[
com_n - com_r] % md
return res
kmemo = {}
def centroid(u=0, pu=-1):
res = []
is_centroid = True
u_nodes = 1
for cu in to[u]:
if cu == pu: continue
res += centroid(cu, u)
cu_nodes = n_nodes[cu]
if cu_nodes > n / 2: is_centroid = False
u_nodes += cu_nodes
n_nodes[u] = u_nodes
if n - u_nodes > n / 2: is_centroid = False
if is_centroid: res.append(u)
return res
md = 10 ** 9 + 7
to = defaultdict(list)
n = int(input())
for _ in range(n - 1):
u, v = map(int, input().split())
u, v = u - 1, v - 1
to[u].append(v)
to[v].append(u)
# 部分木の頂点数を記録しながら重心を求める
n_nodes = [0] * n
cc = centroid()
# print(cc)
# 階乗の準備
n_max = n
fac = [1]
inv = [1] * (n_max + 1)
k_fac_inv = 1
for i in range(1, n_max + 1):
k_fac_inv = k_fac_inv * i % md
fac.append(k_fac_inv)
k_fac_inv = pow(k_fac_inv, md - 2, md)
for i in range(n_max, 1, -1):
inv[i] = k_fac_inv
k_fac_inv = k_fac_inv * i % md
# 重心が2つの(グラフを二等分できる)場合
if len(cc) == 2:
print(pow(fac[n // 2], 2, md))
exit()
# 重心が1つの場合
# サブツリーの頂点数のリストsubtree_node_n作成
subtree_node_n = []
c = cc[0]
for u in to[c]:
u_nodes = n_nodes[u]
if u_nodes > n / 2: continue
subtree_node_n.append(u_nodes)
if c != 0: subtree_node_n.append(n - n_nodes[c])
# print(subtree_node_n)
# dp[i][j]をi番目のサブツリーまでみて、j個の頂点を固定したときの決め方として求める
dp = [0] * n
dp[0] = 1
for i, node_n in enumerate(subtree_node_n):
for j in range(n - 1, -1, -1):
pre = dp[j]
if pre == 0: continue
for k in range(node_n, 0, -1):
dp[j + k] = (dp[j + k] + pre * k_fix_way(node_n, k)) % md
# print(dp)
# 包除原理
ans = 0
coff = 1
for j in range(n):
ans = (ans + coff * dp[j] * fac[n - j]) % md
coff *= -1
print(ans)
main()
``` | instruction | 0 | 14,004 | 13 | 28,008 |
No | output | 1 | 14,004 | 13 | 28,009 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a tree with N vertices. The vertices are numbered 1 through N. The i-th edge (1 \leq i \leq N - 1) connects Vertex x_i and y_i. For vertices v and w (1 \leq v, w \leq N), we will define the distance between v and w d(v, w) as "the number of edges contained in the path v-w".
A squirrel lives in each vertex of the tree. They are planning to move, as follows. First, they will freely choose a permutation of (1, 2, ..., N), p = (p_1, p_2, ..., p_N). Then, for each 1 \leq i \leq N, the squirrel that lived in Vertex i will move to Vertex p_i.
Since they like long travels, they have decided to maximize the total distance they traveled during the process. That is, they will choose p so that d(1, p_1) + d(2, p_2) + ... + d(N, p_N) will be maximized. How many such ways are there to choose p, modulo 10^9 + 7?
Constraints
* 2 \leq N \leq 5,000
* 1 \leq x_i, y_i \leq N
* The input graph is a tree.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_{N - 1} y_{N - 1}
Output
Print the number of the ways to choose p so that the condition is satisfied, modulo 10^9 + 7.
Examples
Input
3
1 2
2 3
Output
3
Input
4
1 2
1 3
1 4
Output
11
Input
6
1 2
1 3
1 4
2 5
2 6
Output
36
Input
7
1 2
6 3
4 5
1 7
1 5
2 3
Output
396
Submitted Solution:
```
from collections import defaultdict
import sys
sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def main():
def k_fix_way(com_n, com_r):
if (com_n, com_r) in kmemo:
return kmemo[(com_n, com_r)]
res = kmemo[(com_n, com_r)] = fac[com_n] * inv[com_n - com_r] * fac[com_n] * inv[com_r] * inv[
com_n - com_r] % md
return res
kmemo = {}
def centroid(u=0, pu=-1):
res = []
is_centroid = True
u_nodes = 1
for cu in to[u]:
if cu == pu: continue
res += centroid(cu, u)
cu_nodes = n_nodes[cu]
if cu_nodes > n / 2: is_centroid = False
u_nodes += cu_nodes
n_nodes[u] = u_nodes
if n - u_nodes > n / 2: is_centroid = False
if is_centroid: res.append(u)
return res
md = 10 ** 9 + 7
to = defaultdict(list)
n = int(input())
for _ in range(n - 1):
u, v = map(int, input().split())
u, v = u - 1, v - 1
to[u].append(v)
to[v].append(u)
# 部分木の頂点数を記録しながら重心を求める
n_nodes = [0] * n
cc = centroid()
# print(cc)
# 階乗の準備
n_max = n
fac = [1]
inv = [1] * (n_max + 1)
k_fac_inv = 1
for i in range(1, n_max + 1):
k_fac_inv = k_fac_inv * i % md
fac.append(k_fac_inv)
k_fac_inv = pow(k_fac_inv, md - 2, md)
for i in range(n_max, 1, -1):
inv[i] = k_fac_inv
k_fac_inv = k_fac_inv * i % md
# 重心が2つの(グラフを二等分できる)場合
if len(cc) == 2:
print(pow(fac[n // 2], 2, md))
exit()
# 重心が1つの場合
# サブツリーの頂点数のリストsubtree_node_n作成
subtree_node_n = []
c = cc[0]
for u in to[c]:
u_nodes = n_nodes[u]
if u_nodes > n / 2: continue
subtree_node_n.append(u_nodes)
if c != 0: subtree_node_n.append(n - n_nodes[c])
# print(subtree_node_n)
# dp[i][j]をi番目のサブツリーまでみて、j個の頂点を固定したときの決め方として求める
sn = len(subtree_node_n)
dp = [[0] * n for _ in range(sn + 1)]
dp[0][0] = 1
for i, node_n in enumerate(subtree_node_n):
for j in range(n):
pre = dp[i][j]
if pre == 0: continue
for k in range(node_n + 1):
dp[i + 1][j + k] = (dp[i + 1][j + k] + pre * k_fix_way(node_n, k)) % md
# p2D(dp)
# 包除原理
ans = 0
coff = 1
for j in range(n):
ans = (ans + coff * dp[sn][j] * fac[n - j]) % md
coff *= -1
print(ans)
main()
``` | instruction | 0 | 14,005 | 13 | 28,010 |
No | output | 1 | 14,005 | 13 | 28,011 |
Provide a correct Python 3 solution for this coding contest problem.
There is a tree with N vertices, numbered 1 through N. The i-th edge in this tree connects Vertices A_i and B_i and has a length of C_i.
Joisino created a complete graph with N vertices. The length of the edge connecting Vertices u and v in this graph, is equal to the shortest distance between Vertices u and v in the tree above.
Joisino would like to know the length of the longest Hamiltonian path (see Notes) in this complete graph. Find the length of that path.
Constraints
* 2 \leq N \leq 10^5
* 1 \leq A_i < B_i \leq N
* The given graph is a tree.
* 1 \leq C_i \leq 10^8
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 B_1 C_1
A_2 B_2 C_2
:
A_{N-1} B_{N-1} C_{N-1}
Output
Print the length of the longest Hamiltonian path in the complete graph created by Joisino.
Examples
Input
5
1 2 5
3 4 7
2 3 3
2 5 2
Output
38
Input
8
2 8 8
1 5 1
4 8 2
2 5 4
3 8 6
6 8 9
2 7 12
Output
132 | instruction | 0 | 14,006 | 13 | 28,012 |
"Correct Solution:
```
import sys
input = sys.stdin.readline
from collections import defaultdict
n = int(input())
abd = [list(map(int,input().split())) for i in range(n-1)]
if n == 2:
print(abd[0][2])
exit()
graph = [[] for i in range(n+1)]
deg = [0 for i in range(n+1)]
for a,b,d in abd:
graph[a].append((b,d))
graph[b].append((a,d))
deg[a] += 1
deg[b] += 1
stack = []
root = 0
dp = [[] for i in range(n+1)]
sm = [1 for i in range(n+1)]
mx = [0 for i in range(n+1)]
for i in range(1,n+1):
if deg[i] == 1:
stack.append(i)
elif root == 0:
root = i
deg[i] += 1
ans = 0
flg = 0
while stack:
x = stack.pop()
if dp[x]:
sm[x] += sum(dp[x])
if sm[x]*2 == n:
flg = 1
for y,d in graph[x]:
if deg[y] > 1:
dp[y].append(sm[x])
if sm[x] == n-sm[x]:
ans += (sm[x]*2-1)*d
else:
ans += min(sm[x],n-sm[x])*2*d
deg[y] -= 1
if deg[y] == 1:
stack.append(y)
dmn = 10**18
if not flg:
for a,b,d in abd:
for v in (a,b):
if not mx[v]:
if dp[v]:
mx[v] = max(max(dp[v]),n-1-sm[v])
else:
mx[v] = n-2
if min(mx[a],mx[b])*2 < n:
dmn = min(dmn,d)
ans -= dmn
print(ans)
``` | output | 1 | 14,006 | 13 | 28,013 |
Provide a correct Python 3 solution for this coding contest problem.
There is a tree with N vertices, numbered 1 through N. The i-th edge in this tree connects Vertices A_i and B_i and has a length of C_i.
Joisino created a complete graph with N vertices. The length of the edge connecting Vertices u and v in this graph, is equal to the shortest distance between Vertices u and v in the tree above.
Joisino would like to know the length of the longest Hamiltonian path (see Notes) in this complete graph. Find the length of that path.
Constraints
* 2 \leq N \leq 10^5
* 1 \leq A_i < B_i \leq N
* The given graph is a tree.
* 1 \leq C_i \leq 10^8
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 B_1 C_1
A_2 B_2 C_2
:
A_{N-1} B_{N-1} C_{N-1}
Output
Print the length of the longest Hamiltonian path in the complete graph created by Joisino.
Examples
Input
5
1 2 5
3 4 7
2 3 3
2 5 2
Output
38
Input
8
2 8 8
1 5 1
4 8 2
2 5 4
3 8 6
6 8 9
2 7 12
Output
132 | instruction | 0 | 14,007 | 13 | 28,014 |
"Correct Solution:
```
import sys
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10**7)
N = int(readline())
ABC = (tuple(int(x) for x in line.split()) for line in readlines())
graph = [[] for _ in range(N+1)]
for a,b,c in ABC:
a -= 1; b -= 1
graph[a].append((b,c))
graph[b].append((a,c))
# トポロジカル順序で頂点のリストを作る
V = [0]
parent = [None]
visited = [True] + [False] * (N-1)
q = [0]
while q:
x = q.pop()
for y,_ in graph[x]:
if visited[y]:
continue
q.append(y)
V.append(y)
parent.append(x)
visited[y] = True
size = [[] for _ in range(N)] # 部分木の大きさのリスト
centroid = []
for v,p in zip(V[::-1],parent[::-1]):
size[v].append(N-1-sum(size[v]))
if all(x<=N//2 for x in size[v]):
centroid.append(v)
if p is not None:
size[p].append(N-size[v][-1])
v0 = centroid[0]
dist = [None] * N
dist[v0] = 0
q = [v0]
while q:
x = q.pop()
for y,wt in graph[x]:
if dist[y] is None:
dist[y] = dist[x] + wt
q.append(y)
if len(centroid) == 1:
dist.sort()
answer = sum(dist) * 2 - dist[0] - dist[1]
else:
answer = sum(dist) * 2 - dist[centroid[0]] - dist[centroid[1]]
print(answer)
``` | output | 1 | 14,007 | 13 | 28,015 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a tree with N vertices, numbered 1 through N. The i-th edge in this tree connects Vertices A_i and B_i and has a length of C_i.
Joisino created a complete graph with N vertices. The length of the edge connecting Vertices u and v in this graph, is equal to the shortest distance between Vertices u and v in the tree above.
Joisino would like to know the length of the longest Hamiltonian path (see Notes) in this complete graph. Find the length of that path.
Constraints
* 2 \leq N \leq 10^5
* 1 \leq A_i < B_i \leq N
* The given graph is a tree.
* 1 \leq C_i \leq 10^8
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 B_1 C_1
A_2 B_2 C_2
:
A_{N-1} B_{N-1} C_{N-1}
Output
Print the length of the longest Hamiltonian path in the complete graph created by Joisino.
Examples
Input
5
1 2 5
3 4 7
2 3 3
2 5 2
Output
38
Input
8
2 8 8
1 5 1
4 8 2
2 5 4
3 8 6
6 8 9
2 7 12
Output
132
Submitted Solution:
```
import sys
input = sys.stdin.readline
n = int(input())
abd = [list(map(int,input().split())) for i in range(n-1)]
if n == 2:
print(abd[2])
exit()
graph = [[] for i in range(n+1)]
deg = [0 for i in range(n+1)]
for a,b,d in abd:
graph[a].append((b,d))
graph[b].append((a,d))
deg[a] += 1
deg[b] += 1
stack = []
root = 0
dp = [1 for i in range(n+1)]
for i in range(1,n+1):
if deg[i] == 1:
stack.append(i)
elif root == 0:
root = i
deg[i] += 1
ans = 0
flg = 0
while stack:
x = stack.pop()
for y,d in graph[x]:
if deg[y] > 1:
dp[y] += dp[x]
if dp[x] == n-dp[x]:
flg = 1
ans += (dp[x]*2-1)*d
else:
ans += min(dp[x],n-dp[x])*2*d
deg[y] -= 1
if deg[y] == 1:
stack.append(y)
if not flg:
dmn = min(list(zip(*abd))[2])
ans -= dmn
print(ans)
``` | instruction | 0 | 14,008 | 13 | 28,016 |
No | output | 1 | 14,008 | 13 | 28,017 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.