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.
Anadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every a and b such that 1 ≤ a ≤ b ≤ 6, there is exactly one domino with a dots on one half and b dots on the other half. The set contains exactly 21 dominoes. Here is an exact illustration of his set:
<image>
Also, Anadi has an undirected graph without self-loops and multiple edges. He wants to choose some dominoes and place them on the edges of this graph. He can use at most one domino of each type. Each edge can fit at most one domino. It's not necessary to place a domino on each edge of the graph.
When placing a domino on an edge, he also chooses its direction. In other words, one half of any placed domino must be directed toward one of the endpoints of the edge and the other half must be directed toward the other endpoint. There's a catch: if there are multiple halves of dominoes directed toward the same vertex, each of these halves must contain the same number of dots.
How many dominoes at most can Anadi place on the edges of his graph?
Input
The first line contains two integers n and m (1 ≤ n ≤ 7, 0 ≤ m ≤ (n⋅(n-1))/(2)) — the number of vertices and the number of edges in the graph.
The next m lines contain two integers each. Integers in the i-th line are a_i and b_i (1 ≤ a, b ≤ n, a ≠ b) and denote that there is an edge which connects vertices a_i and b_i.
The graph might be disconnected. It's however guaranteed that the graph doesn't contain any self-loops, and that there is at most one edge between any pair of vertices.
Output
Output one integer which denotes the maximum number of dominoes which Anadi can place on the edges of the graph.
Examples
Input
4 4
1 2
2 3
3 4
4 1
Output
4
Input
7 0
Output
0
Input
3 1
1 3
Output
1
Input
7 21
1 2
1 3
1 4
1 5
1 6
1 7
2 3
2 4
2 5
2 6
2 7
3 4
3 5
3 6
3 7
4 5
4 6
4 7
5 6
5 7
6 7
Output
16
Note
Here is an illustration of Anadi's graph from the first sample test:
<image>
And here is one of the ways to place a domino on each of its edges:
<image>
Note that each vertex is faced by the halves of dominoes with the same number of dots. For instance, all halves directed toward vertex 1 have three dots.
Submitted Solution:
```
n,k = map(int,input().split())
s = [[0 for i in range(8)] for j in range(8)]
for i in range(k):
u,v = map(int,input().split())
s[u][v] = 1
s[v][u] = 1
if(n <= 6 or k == 0):
print(k)
else:
a = []
for i in range(1,8):
for j in range(1,8):
if(i == j):
continue
ct = 0
for k in range(1,8):
if s[i][k] == 1 and s[j][k] == 1:
ct += 1
#print(j,i,ct)
a.append([ct,i,j])
a.sort()
ind1 = a[0][1]
ind2 = a[0][2]
sum = sum1 = 0
#print(a[0][0],ind1,ind2)
#print(s[ind1],s[ind2])
for i in range(1,8):
if(s[ind1][i] == 1 and s[ind2][i] == 1):
sum1 += 1
elif(s[ind1][i] != s[ind2][i]):
sum1 += 1
if(s[ind1][ind2] == 1 and s[ind2][ind1] == 1):
sum1 -= 1
for i in range(1,8):
#print(s[i])
if i == ind1 or i == ind2:
continue
for j in range(1,8):
if j == ind1 or j == ind2:
continue
sum += s[i][j]
#print(sum)
print(sum1+(sum//2))
``` | instruction | 0 | 50,597 | 13 | 101,194 |
Yes | output | 1 | 50,597 | 13 | 101,195 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every a and b such that 1 ≤ a ≤ b ≤ 6, there is exactly one domino with a dots on one half and b dots on the other half. The set contains exactly 21 dominoes. Here is an exact illustration of his set:
<image>
Also, Anadi has an undirected graph without self-loops and multiple edges. He wants to choose some dominoes and place them on the edges of this graph. He can use at most one domino of each type. Each edge can fit at most one domino. It's not necessary to place a domino on each edge of the graph.
When placing a domino on an edge, he also chooses its direction. In other words, one half of any placed domino must be directed toward one of the endpoints of the edge and the other half must be directed toward the other endpoint. There's a catch: if there are multiple halves of dominoes directed toward the same vertex, each of these halves must contain the same number of dots.
How many dominoes at most can Anadi place on the edges of his graph?
Input
The first line contains two integers n and m (1 ≤ n ≤ 7, 0 ≤ m ≤ (n⋅(n-1))/(2)) — the number of vertices and the number of edges in the graph.
The next m lines contain two integers each. Integers in the i-th line are a_i and b_i (1 ≤ a, b ≤ n, a ≠ b) and denote that there is an edge which connects vertices a_i and b_i.
The graph might be disconnected. It's however guaranteed that the graph doesn't contain any self-loops, and that there is at most one edge between any pair of vertices.
Output
Output one integer which denotes the maximum number of dominoes which Anadi can place on the edges of the graph.
Examples
Input
4 4
1 2
2 3
3 4
4 1
Output
4
Input
7 0
Output
0
Input
3 1
1 3
Output
1
Input
7 21
1 2
1 3
1 4
1 5
1 6
1 7
2 3
2 4
2 5
2 6
2 7
3 4
3 5
3 6
3 7
4 5
4 6
4 7
5 6
5 7
6 7
Output
16
Note
Here is an illustration of Anadi's graph from the first sample test:
<image>
And here is one of the ways to place a domino on each of its edges:
<image>
Note that each vertex is faced by the halves of dominoes with the same number of dots. For instance, all halves directed toward vertex 1 have three dots.
Submitted Solution:
```
n, m = map(int, input().split())
s = [0 for i in range(n)]
for i in range(m):
a, b = map(int, input().split())
s[a - 1] += 1
s[b - 1] += 1
if n == 7:
m -= min(s)
print(m)
``` | instruction | 0 | 50,598 | 13 | 101,196 |
No | output | 1 | 50,598 | 13 | 101,197 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every a and b such that 1 ≤ a ≤ b ≤ 6, there is exactly one domino with a dots on one half and b dots on the other half. The set contains exactly 21 dominoes. Here is an exact illustration of his set:
<image>
Also, Anadi has an undirected graph without self-loops and multiple edges. He wants to choose some dominoes and place them on the edges of this graph. He can use at most one domino of each type. Each edge can fit at most one domino. It's not necessary to place a domino on each edge of the graph.
When placing a domino on an edge, he also chooses its direction. In other words, one half of any placed domino must be directed toward one of the endpoints of the edge and the other half must be directed toward the other endpoint. There's a catch: if there are multiple halves of dominoes directed toward the same vertex, each of these halves must contain the same number of dots.
How many dominoes at most can Anadi place on the edges of his graph?
Input
The first line contains two integers n and m (1 ≤ n ≤ 7, 0 ≤ m ≤ (n⋅(n-1))/(2)) — the number of vertices and the number of edges in the graph.
The next m lines contain two integers each. Integers in the i-th line are a_i and b_i (1 ≤ a, b ≤ n, a ≠ b) and denote that there is an edge which connects vertices a_i and b_i.
The graph might be disconnected. It's however guaranteed that the graph doesn't contain any self-loops, and that there is at most one edge between any pair of vertices.
Output
Output one integer which denotes the maximum number of dominoes which Anadi can place on the edges of the graph.
Examples
Input
4 4
1 2
2 3
3 4
4 1
Output
4
Input
7 0
Output
0
Input
3 1
1 3
Output
1
Input
7 21
1 2
1 3
1 4
1 5
1 6
1 7
2 3
2 4
2 5
2 6
2 7
3 4
3 5
3 6
3 7
4 5
4 6
4 7
5 6
5 7
6 7
Output
16
Note
Here is an illustration of Anadi's graph from the first sample test:
<image>
And here is one of the ways to place a domino on each of its edges:
<image>
Note that each vertex is faced by the halves of dominoes with the same number of dots. For instance, all halves directed toward vertex 1 have three dots.
Submitted Solution:
```
n,k = map(int,input().split())
s = [[0 for i in range(8)] for j in range(8)]
for i in range(k):
u,v = map(int,input().split())
s[u][v] = 1
s[v][u] = 1
if(n <= 6 or k == 0):
print(k)
else:
m = 10
for i in range(1,8):
s1 = sum(s[i])
if(s1 < m):
m = s1
a = []
for i in range(1,8):
if(sum(s[i]) == m ):
f = i
for j in range(1,8):
if(f == j):
continue
ct = 0
for k in range(1,8):
if s[f][k] != s[j][k]:
ct += 1
a.append([ct,i])
a.sort()
ind = a[-1][1]
sum = 0
for i in range(1,8):
if i == ind:
continue
for j in range(1,8):
if j == ind:
continue
sum += s[i][j]
print((a[-1][0]+sum)//2)
``` | instruction | 0 | 50,599 | 13 | 101,198 |
No | output | 1 | 50,599 | 13 | 101,199 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every a and b such that 1 ≤ a ≤ b ≤ 6, there is exactly one domino with a dots on one half and b dots on the other half. The set contains exactly 21 dominoes. Here is an exact illustration of his set:
<image>
Also, Anadi has an undirected graph without self-loops and multiple edges. He wants to choose some dominoes and place them on the edges of this graph. He can use at most one domino of each type. Each edge can fit at most one domino. It's not necessary to place a domino on each edge of the graph.
When placing a domino on an edge, he also chooses its direction. In other words, one half of any placed domino must be directed toward one of the endpoints of the edge and the other half must be directed toward the other endpoint. There's a catch: if there are multiple halves of dominoes directed toward the same vertex, each of these halves must contain the same number of dots.
How many dominoes at most can Anadi place on the edges of his graph?
Input
The first line contains two integers n and m (1 ≤ n ≤ 7, 0 ≤ m ≤ (n⋅(n-1))/(2)) — the number of vertices and the number of edges in the graph.
The next m lines contain two integers each. Integers in the i-th line are a_i and b_i (1 ≤ a, b ≤ n, a ≠ b) and denote that there is an edge which connects vertices a_i and b_i.
The graph might be disconnected. It's however guaranteed that the graph doesn't contain any self-loops, and that there is at most one edge between any pair of vertices.
Output
Output one integer which denotes the maximum number of dominoes which Anadi can place on the edges of the graph.
Examples
Input
4 4
1 2
2 3
3 4
4 1
Output
4
Input
7 0
Output
0
Input
3 1
1 3
Output
1
Input
7 21
1 2
1 3
1 4
1 5
1 6
1 7
2 3
2 4
2 5
2 6
2 7
3 4
3 5
3 6
3 7
4 5
4 6
4 7
5 6
5 7
6 7
Output
16
Note
Here is an illustration of Anadi's graph from the first sample test:
<image>
And here is one of the ways to place a domino on each of its edges:
<image>
Note that each vertex is faced by the halves of dominoes with the same number of dots. For instance, all halves directed toward vertex 1 have three dots.
Submitted Solution:
```
from itertools import permutations
n,m = map(int,input().split())
node = [0, 1, 2, 3, 4, 5, 6]
node = node[:n]
g = []
for _ in range(m):
a,b = map(int,input().split())
g.append((a-1,b-1))
ans = 0
for pp in permutations(node):
D = [[False] * 7 for _ in range(7)]
for i in range(7):
D[6][i] = D[i][6] = True
cnt = 0
cnt2 = 0
h = -1
if 6 in pp:
h = pp.index(6)
for a,b in g:
if a == h or b == h:
cnt2 += 1
if not D[pp[a]][pp[b]]:
D[pp[a]][pp[b]] = True
D[pp[b]][pp[a]] = True
cnt += 1
if cnt2:
cnt += 1
ans = max(ans, cnt)
print(ans)
``` | instruction | 0 | 50,600 | 13 | 101,200 |
No | output | 1 | 50,600 | 13 | 101,201 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every a and b such that 1 ≤ a ≤ b ≤ 6, there is exactly one domino with a dots on one half and b dots on the other half. The set contains exactly 21 dominoes. Here is an exact illustration of his set:
<image>
Also, Anadi has an undirected graph without self-loops and multiple edges. He wants to choose some dominoes and place them on the edges of this graph. He can use at most one domino of each type. Each edge can fit at most one domino. It's not necessary to place a domino on each edge of the graph.
When placing a domino on an edge, he also chooses its direction. In other words, one half of any placed domino must be directed toward one of the endpoints of the edge and the other half must be directed toward the other endpoint. There's a catch: if there are multiple halves of dominoes directed toward the same vertex, each of these halves must contain the same number of dots.
How many dominoes at most can Anadi place on the edges of his graph?
Input
The first line contains two integers n and m (1 ≤ n ≤ 7, 0 ≤ m ≤ (n⋅(n-1))/(2)) — the number of vertices and the number of edges in the graph.
The next m lines contain two integers each. Integers in the i-th line are a_i and b_i (1 ≤ a, b ≤ n, a ≠ b) and denote that there is an edge which connects vertices a_i and b_i.
The graph might be disconnected. It's however guaranteed that the graph doesn't contain any self-loops, and that there is at most one edge between any pair of vertices.
Output
Output one integer which denotes the maximum number of dominoes which Anadi can place on the edges of the graph.
Examples
Input
4 4
1 2
2 3
3 4
4 1
Output
4
Input
7 0
Output
0
Input
3 1
1 3
Output
1
Input
7 21
1 2
1 3
1 4
1 5
1 6
1 7
2 3
2 4
2 5
2 6
2 7
3 4
3 5
3 6
3 7
4 5
4 6
4 7
5 6
5 7
6 7
Output
16
Note
Here is an illustration of Anadi's graph from the first sample test:
<image>
And here is one of the ways to place a domino on each of its edges:
<image>
Note that each vertex is faced by the halves of dominoes with the same number of dots. For instance, all halves directed toward vertex 1 have three dots.
Submitted Solution:
```
n,m = map(int,input().split())
l =[[] for _ in range(n)]
for i in range(m):
k,p = map(int,input().split())
l[k-1].append(p)
l[p-1].append(k)
if n<7 or m==0:
print(m)
else:
k = [len(l[i]) for i in range(n)]
if m<=15 or min(k)==0:
print(m)
else:
print(m - min(k)+1)
``` | instruction | 0 | 50,601 | 13 | 101,202 |
No | output | 1 | 50,601 | 13 | 101,203 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an unweighted tree with n vertices. Recall that a tree is a connected undirected graph without cycles.
Your task is to choose three distinct vertices a, b, c on this tree such that the number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c is the maximum possible. See the notes section for a better understanding.
The simple path is the path that visits each vertex at most once.
Input
The first line contains one integer number n (3 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree.
Next n - 1 lines describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i). It is guaranteed that given graph is a tree.
Output
In the first line print one integer res — the maximum number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c.
In the second line print three integers a, b, c such that 1 ≤ a, b, c ≤ n and a ≠, b ≠ c, a ≠ c.
If there are several answers, you can print any.
Example
Input
8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
Output
5
1 8 6
Note
The picture corresponding to the first example (and another one correct answer):
<image>
If you choose vertices 1, 5, 6 then the path between 1 and 5 consists of edges (1, 2), (2, 3), (3, 4), (4, 5), the path between 1 and 6 consists of edges (1, 2), (2, 3), (3, 4), (4, 6) and the path between 5 and 6 consists of edges (4, 5), (4, 6). The union of these paths is (1, 2), (2, 3), (3, 4), (4, 5), (4, 6) so the answer is 5. It can be shown that there is no better answer. | instruction | 0 | 50,619 | 13 | 101,238 |
Tags: dfs and similar, dp, greedy, trees
Correct Solution:
```
#!/usr/bin/env python3
import queue
R = lambda: list(map(int, input().split()))
n = R()[0]
g, d, frm = [[] for _ in range(n)], [0] * n, [0] * n
for _ in range(n - 1):
u, v = R()
g[u - 1].append(v - 1)
g[v - 1].append(u - 1)
def bfs(s):
que = queue.SimpleQueue()
que.put(s)
for i in range(n):
d[i], frm[i] = -1, -1
d[s] = 0
vertex = s
while not que.empty():
u = que.get()
for v in g[u]:
if ~d[v]: continue
d[v] = d[u] + 1
frm[v] = u
if d[v] > d[vertex]: vertex = v
que.put(v)
return vertex
u = bfs(0)
v = bfs(u)
u = bfs(v)
mark, nodes = [False] * n, []
def dfs(u, fa=-1):
res = [0, u]
for v in g[u]:
if mark[v] or v == fa: continue
t, tt = dfs(v, u)
if t + 1 > res[0]:
res = [t + 1, tt]
return res
x = u
while ~x:
mark[x] = True
nodes.append(x)
x = frm[x]
mx, z = 0, nodes[1]
for x in nodes:
t, tt = dfs(x)
if t > mx:
mx, z = t, tt
print(d[u] + mx)
print(u + 1, v + 1, z + 1)
``` | output | 1 | 50,619 | 13 | 101,239 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an unweighted tree with n vertices. Recall that a tree is a connected undirected graph without cycles.
Your task is to choose three distinct vertices a, b, c on this tree such that the number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c is the maximum possible. See the notes section for a better understanding.
The simple path is the path that visits each vertex at most once.
Input
The first line contains one integer number n (3 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree.
Next n - 1 lines describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i). It is guaranteed that given graph is a tree.
Output
In the first line print one integer res — the maximum number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c.
In the second line print three integers a, b, c such that 1 ≤ a, b, c ≤ n and a ≠, b ≠ c, a ≠ c.
If there are several answers, you can print any.
Example
Input
8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
Output
5
1 8 6
Note
The picture corresponding to the first example (and another one correct answer):
<image>
If you choose vertices 1, 5, 6 then the path between 1 and 5 consists of edges (1, 2), (2, 3), (3, 4), (4, 5), the path between 1 and 6 consists of edges (1, 2), (2, 3), (3, 4), (4, 6) and the path between 5 and 6 consists of edges (4, 5), (4, 6). The union of these paths is (1, 2), (2, 3), (3, 4), (4, 5), (4, 6) so the answer is 5. It can be shown that there is no better answer. | instruction | 0 | 50,620 | 13 | 101,240 |
Tags: dfs and similar, dp, greedy, trees
Correct Solution:
```
import sys
input = sys.stdin.readline
NEGINF = -1000000
n = int(input())
adj = [[] for i in range(n)]
parent = [-1] * n
visited = [False] * n
for _ in range(n - 1):
a, b = map(int, input().split())
adj[a - 1].append(b - 1)
adj[b - 1].append(a - 1)
tup = tuple()
outs = [tup] * n
q = [(0, 0)]
while q:
node, type = q.pop()
if type == 0:
visited[node] = True
q.append((node, 1))
for v in adj[node]:
if not visited[v]:
parent[v] = node
q.append((v, 0))
else:
ones = [(0, node)]
twos = []
threes = []
for v in adj[node]:
if v != parent[node]:
a, b, c = outs[v]
ones.append((a[0] + 1, a[1], v))
twos.append((b[0] + 1, b[1], v))
threes.append(c)
ones.sort(reverse = True)
twos.sort(reverse = True)
threes.sort(reverse = True)
bestOne = (ones[0][0], ones[0][1])
bestsTwo = [(NEGINF, (0, 0))]
if len(twos) > 0:
bestsTwo.append((twos[0][0], twos[0][1]))
if len(ones) > 1:
o1 = ones[0]
o2 = ones[1]
bestsTwo.append((o1[0] + o2[0], (o1[1], o2[1])))
bestsThree = [(NEGINF, (0, 0, 0))]
if len(threes) > 0:
bestsThree.append(threes[0])
if len(ones) > 2:
o1 = ones[0]
o2 = ones[1]
o3 = ones[2]
bestsThree.append((o1[0] + o2[0] + o3[0], (o1[1], o2[1], o3[1])))
if len(twos) > 0:
o1 = ones[0]
t1 = twos[0]
if o1[2] != t1[2]:
bestsThree.append((o1[0] + t1[0], (o1[1], t1[1][0], t1[1][1])))
else:
if len(twos) > 1:
t2 = twos[1]
bestsThree.append((o1[0] + t2[0], (o1[1], t2[1][0], t2[1][1])))
if len(ones) > 1:
o2 = ones[1]
bestsThree.append((o2[0] + t1[0], (o2[1], t1[1][0], t1[1][1])))
outs[node] = (bestOne, max(bestsTwo), max(bestsThree))
final = outs[0][2]
print(final[0])
print(' '.join(map(lambda x: str(x + 1), final[1])))
``` | output | 1 | 50,620 | 13 | 101,241 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an unweighted tree with n vertices. Recall that a tree is a connected undirected graph without cycles.
Your task is to choose three distinct vertices a, b, c on this tree such that the number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c is the maximum possible. See the notes section for a better understanding.
The simple path is the path that visits each vertex at most once.
Input
The first line contains one integer number n (3 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree.
Next n - 1 lines describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i). It is guaranteed that given graph is a tree.
Output
In the first line print one integer res — the maximum number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c.
In the second line print three integers a, b, c such that 1 ≤ a, b, c ≤ n and a ≠, b ≠ c, a ≠ c.
If there are several answers, you can print any.
Example
Input
8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
Output
5
1 8 6
Note
The picture corresponding to the first example (and another one correct answer):
<image>
If you choose vertices 1, 5, 6 then the path between 1 and 5 consists of edges (1, 2), (2, 3), (3, 4), (4, 5), the path between 1 and 6 consists of edges (1, 2), (2, 3), (3, 4), (4, 6) and the path between 5 and 6 consists of edges (4, 5), (4, 6). The union of these paths is (1, 2), (2, 3), (3, 4), (4, 5), (4, 6) so the answer is 5. It can be shown that there is no better answer. | instruction | 0 | 50,621 | 13 | 101,242 |
Tags: dfs and similar, dp, greedy, trees
Correct Solution:
```
from collections import namedtuple, deque
from sys import stdin
def load_graph():
n = int(stdin.readline())
G = [set() for i in range(n)]
for line in stdin.readlines():
a, b = line.split()
a, b = int(a) - 1, int(b) - 1
# ~ print(a, b)
G[a].add(b)
G[b].add(a)
return G
# find the distance from one node to any other node
# complexity O(n)
def find_all_distances(G, node):
distances = [None] * len(G)
distances[node] = 0
queue = deque((node,))
while len(queue) > 0:
current_node = queue.popleft()
for neighbor in G[current_node]:
if distances[neighbor] is None:
distances[neighbor] = distances[current_node] + 1
queue.append(neighbor)
# ~ print(distances)
return distances
# find a pair of nodes with maximal distance
# G must be a tree, complexity O(n)
# strategy: pick node 0 as root, find a node with maximal distance to 0
# from that node, find a node with maximal distance to it
# it can be shown this pair of two nodes has maximal distance
def find_longest_pair(G):
best_dist_0 = max((d, i) for i, d in
enumerate(find_all_distances(G, 0)))
start_node = best_dist_0[1]
best_dist_start = max((d, i) for i, d in
enumerate(find_all_distances(G, start_node)))
path_length, end_node = best_dist_start
return path_length, start_node, end_node
# find a triplet of distinct nodes
# with maximized sum of pairwise distances
# G must be a tree, complexity O(n)
def find_maxdist_triplet(G):
path_length, path_a, path_b = find_longest_pair(G)
dists_a = find_all_distances(G, path_a)
dists_b = find_all_distances(G, path_b)
# ~ print(path_a, dists_a, path_b, dists_b)
sum_dists = [(dists_a[i] + dists_b[i], i)
for i in range(len(G)) if i != path_a and i != path_b]
# ~ print(sum_dists)
best_c_dist_ab, best_c = max(sum_dists)
dist_sum = path_length + best_c_dist_ab
return dist_sum, path_a, path_b, best_c
G = load_graph()
# ~ print(G)
dist_sum, path_a, path_b, path_c = find_maxdist_triplet(G)
print(dist_sum // 2)
print(path_a + 1, path_b + 1, path_c + 1)
``` | output | 1 | 50,621 | 13 | 101,243 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an unweighted tree with n vertices. Recall that a tree is a connected undirected graph without cycles.
Your task is to choose three distinct vertices a, b, c on this tree such that the number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c is the maximum possible. See the notes section for a better understanding.
The simple path is the path that visits each vertex at most once.
Input
The first line contains one integer number n (3 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree.
Next n - 1 lines describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i). It is guaranteed that given graph is a tree.
Output
In the first line print one integer res — the maximum number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c.
In the second line print three integers a, b, c such that 1 ≤ a, b, c ≤ n and a ≠, b ≠ c, a ≠ c.
If there are several answers, you can print any.
Example
Input
8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
Output
5
1 8 6
Note
The picture corresponding to the first example (and another one correct answer):
<image>
If you choose vertices 1, 5, 6 then the path between 1 and 5 consists of edges (1, 2), (2, 3), (3, 4), (4, 5), the path between 1 and 6 consists of edges (1, 2), (2, 3), (3, 4), (4, 6) and the path between 5 and 6 consists of edges (4, 5), (4, 6). The union of these paths is (1, 2), (2, 3), (3, 4), (4, 5), (4, 6) so the answer is 5. It can be shown that there is no better answer. | instruction | 0 | 50,622 | 13 | 101,244 |
Tags: dfs and similar, dp, greedy, trees
Correct Solution:
```
from collections import deque
import sys
input = sys.stdin.readline
def bfs(s):
q = deque()
q.append(s)
dist1 = [-1] * (n + 1)
dist1[s] = 0
while q:
i = q.popleft()
di = dist1[i]
for j in G[i]:
if dist1[j] == -1:
dist1[j] = di + 1
q.append(j)
a = i
q.append(i)
dist2 = [-1] * (n + 1)
dist2[i] = 0
while q:
i = q.popleft()
di = dist2[i]
for j in G[i]:
if dist2[j] == -1:
dist2[j] = di + 1
q.append(j)
b = i
d = dist2[i]
ans = d
dist3 = [-1] * (n + 1)
while d:
dist3[i] = 0
q.append(i)
for j in G[i]:
if dist2[j] == d - 1:
d -= 1
i = j
break
dist3[i] = 0
q.append(i)
while q:
i = q.popleft()
di = dist3[i]
for j in G[i]:
if dist3[j] == -1:
dist3[j] = di + 1
q.append(j)
c = i
ans += dist3[i]
if a == c or b == c:
for i in range(1, n + 1):
if a ^ i and b ^ i:
c = i
break
return ans, a, b, c
n = int(input())
G = [[] for _ in range(n + 1)]
for _ in range(n - 1):
a, b = map(int, input().split())
G[a].append(b)
G[b].append(a)
ans, a, b, c = bfs(1)
print(ans)
print(a, b, c)
``` | output | 1 | 50,622 | 13 | 101,245 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an unweighted tree with n vertices. Recall that a tree is a connected undirected graph without cycles.
Your task is to choose three distinct vertices a, b, c on this tree such that the number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c is the maximum possible. See the notes section for a better understanding.
The simple path is the path that visits each vertex at most once.
Input
The first line contains one integer number n (3 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree.
Next n - 1 lines describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i). It is guaranteed that given graph is a tree.
Output
In the first line print one integer res — the maximum number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c.
In the second line print three integers a, b, c such that 1 ≤ a, b, c ≤ n and a ≠, b ≠ c, a ≠ c.
If there are several answers, you can print any.
Example
Input
8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
Output
5
1 8 6
Note
The picture corresponding to the first example (and another one correct answer):
<image>
If you choose vertices 1, 5, 6 then the path between 1 and 5 consists of edges (1, 2), (2, 3), (3, 4), (4, 5), the path between 1 and 6 consists of edges (1, 2), (2, 3), (3, 4), (4, 6) and the path between 5 and 6 consists of edges (4, 5), (4, 6). The union of these paths is (1, 2), (2, 3), (3, 4), (4, 5), (4, 6) so the answer is 5. It can be shown that there is no better answer. | instruction | 0 | 50,623 | 13 | 101,246 |
Tags: dfs and similar, dp, greedy, trees
Correct Solution:
```
def dfs(n, source, neighbors):
# Distances à la racine
dist = [-1] * n
# Pointeur sur parent
parent = [-1] * n
# Hauteur du sous-arbre
height = [-1] * n
# Pointeur sur sous-arbre le plus haut
height_ptr = [-1] * n
# Sommet le plus éloigné
deepest = 0
deepest_ptr = source
dist[source] = 0
parent[source] = source
stack = [source]
while stack:
u = stack[-1]
is_processed = True
for v in neighbors[u]:
if parent[v] == -1:
is_processed = False
dist[v] = dist[u] + 1
if dist[v] > deepest:
deepest = dist[v]
deepest_ptr = v
parent[v] = u
stack.append(v)
if is_processed:
stack.pop()
max_height = -1
max_height_ptr = -1
for v in neighbors[u]:
if parent[v] == u:
if height[v] > max_height:
max_height = height[v]
max_height_ptr = v
height[u] = 1 + max_height
height_ptr[u] = max_height_ptr
return dist, parent, deepest, deepest_ptr, height, height_ptr
# Obtient les arêtes d’un diamètre d’un arbre et un arbre DFS issu de son
# premier sommet
def find_diameter(n, r, neighbors):
_, _, _, v1, _, _ = dfs(n, r, neighbors)
_, parent, size, v2, height, height_ptr = dfs(n, v1, neighbors)
return v1, v2, size, height, height_ptr, parent
# Lecture de l’arbre
n = int(input())
neighbors = [[] for i in range(n)]
for i in range(n - 1):
a, b = map(int, input().split())
neighbors[a - 1].append(b - 1)
neighbors[b - 1].append(a - 1)
# Recherche du diamètre et soustraction de ses arêtes dans l’arbre
v1, v2, size, height, height_ptr, parent = find_diameter(n, 0, neighbors)
# Recherche d’une branche de taille maximale issue du diamètre
walker_prev = -1
walker = v2
max_height = 0
max_height_ptr = -1
while walker != v1:
for branch in neighbors[walker]:
if parent[branch] == walker and branch != walker_prev:
if height[branch] + 1 > max_height:
max_height = height[branch] + 1
max_height_ptr = branch
walker_prev = walker
walker = parent[walker]
if max_height_ptr == -1:
# Cas particulier : chemin
print(size)
print(v1 + 1, parent[v2] + 1, v2 + 1)
else:
v3 = max_height_ptr
while height_ptr[v3] != -1:
v3 = height_ptr[v3]
print(max_height + size)
print(v1 + 1, v2 + 1, v3 + 1)
``` | output | 1 | 50,623 | 13 | 101,247 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an unweighted tree with n vertices. Recall that a tree is a connected undirected graph without cycles.
Your task is to choose three distinct vertices a, b, c on this tree such that the number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c is the maximum possible. See the notes section for a better understanding.
The simple path is the path that visits each vertex at most once.
Input
The first line contains one integer number n (3 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree.
Next n - 1 lines describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i). It is guaranteed that given graph is a tree.
Output
In the first line print one integer res — the maximum number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c.
In the second line print three integers a, b, c such that 1 ≤ a, b, c ≤ n and a ≠, b ≠ c, a ≠ c.
If there are several answers, you can print any.
Example
Input
8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
Output
5
1 8 6
Note
The picture corresponding to the first example (and another one correct answer):
<image>
If you choose vertices 1, 5, 6 then the path between 1 and 5 consists of edges (1, 2), (2, 3), (3, 4), (4, 5), the path between 1 and 6 consists of edges (1, 2), (2, 3), (3, 4), (4, 6) and the path between 5 and 6 consists of edges (4, 5), (4, 6). The union of these paths is (1, 2), (2, 3), (3, 4), (4, 5), (4, 6) so the answer is 5. It can be shown that there is no better answer. | instruction | 0 | 50,624 | 13 | 101,248 |
Tags: dfs and similar, dp, greedy, trees
Correct Solution:
```
import sys
from collections import defaultdict
def diam(graph):
n=len(graph)
st,m=0,-1
mark=[0]*n
dist=[0]*n
dist2=[0]*n
ret=[0]*4
q=[]
for i in range(1,4):
q.append(st)
mark=[0]*n
mark[st]=1
dist[st]=0
far=st
#print(st,'st')
#print(dist,'dist')
#print(dist2,'dist2',i)
while(q):
#print(dist,'in while disttttttt')
#print(dist2,'in while')
u=q.pop()
if i>1:
dist2[u]+=dist[u]
if dist[u]>dist[far]:
far=u
for v in graph[u]:
if mark[v]:
continue
mark[v]=1
dist[v]=1+dist[u]
q.append(v)
ret[i]=far+1
#print(dist,'final')
#print(dist2,'finaldist2')
ret[0]=dist[far]
st=far
for i in range(n):
if i+1==ret[2] or i+1==ret[3]:
continue
if m==-1 or dist2[i]>dist2[m]:
m=i
ret[1]=m+1
ret[0]+=(dist2[m]-ret[0])//2
return ret
graph=defaultdict(list)
n=int(sys.stdin.readline())
for i in range(n-1):
u,v=map(int,sys.stdin.readline().split())
u-=1
v-=1
graph[u].append(v)
graph[v].append(u)
ans=diam(graph)
print(ans[0])
print(*ans[1:])
``` | output | 1 | 50,624 | 13 | 101,249 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an unweighted tree with n vertices. Recall that a tree is a connected undirected graph without cycles.
Your task is to choose three distinct vertices a, b, c on this tree such that the number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c is the maximum possible. See the notes section for a better understanding.
The simple path is the path that visits each vertex at most once.
Input
The first line contains one integer number n (3 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree.
Next n - 1 lines describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i). It is guaranteed that given graph is a tree.
Output
In the first line print one integer res — the maximum number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c.
In the second line print three integers a, b, c such that 1 ≤ a, b, c ≤ n and a ≠, b ≠ c, a ≠ c.
If there are several answers, you can print any.
Example
Input
8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
Output
5
1 8 6
Note
The picture corresponding to the first example (and another one correct answer):
<image>
If you choose vertices 1, 5, 6 then the path between 1 and 5 consists of edges (1, 2), (2, 3), (3, 4), (4, 5), the path between 1 and 6 consists of edges (1, 2), (2, 3), (3, 4), (4, 6) and the path between 5 and 6 consists of edges (4, 5), (4, 6). The union of these paths is (1, 2), (2, 3), (3, 4), (4, 5), (4, 6) so the answer is 5. It can be shown that there is no better answer. | instruction | 0 | 50,625 | 13 | 101,250 |
Tags: dfs and similar, dp, greedy, trees
Correct Solution:
```
import io
import os
from collections import Counter, defaultdict, deque
def longestPathFrom(root, getNbr):
# BFS
queue = deque()
queue.append(root)
parent = {}
parent[root] = None
while queue:
curr = queue.popleft()
for child in getNbr(curr):
if child not in parent:
queue.append(child)
parent[child] = curr
# When loop exits, curr is the last element that was processed. Reconstruct the path
ret = [curr]
while curr in parent and parent[curr] is not None:
curr = parent[curr]
ret.append(curr)
return ret[::-1]
def treeDiameter(graph):
"""Returns longest path in the tree"""
# One end of the diameter has to be the farthest point from an arbitrary node
# Then finding farthest node from that will give a diameter path of the graph
initNode = 0
def getNbr(node):
return graph[node]
path1 = longestPathFrom(initNode, getNbr)
assert path1[0] == initNode
path2 = longestPathFrom(path1[-1], getNbr)
return path2
def solve(N, edges):
graph = [[] for i in range(N)]
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
path = treeDiameter(graph)
pathSet = set(path)
def getNonDiameterNbr(node):
for nbr in graph[node]:
if nbr not in pathSet:
yield nbr
base = len(path) - 1
best = (0, path[1])
for i in range(1, len(path) - 1):
deepest = longestPathFrom(path[i], getNonDiameterNbr)
assert deepest[0] == path[i]
best = max(best, (len(deepest) - 1, deepest[-1]))
return (
str(base + best[0])
+ "\n"
+ " ".join(str(x + 1) for x in [path[0], best[1], path[-1]])
)
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
(N,) = [int(x) for x in input().split()]
edges = [[int(x) - 1 for x in input().split()] for i in range(N - 1)]
ans = solve(N, edges)
print(ans)
``` | output | 1 | 50,625 | 13 | 101,251 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an unweighted tree with n vertices. Recall that a tree is a connected undirected graph without cycles.
Your task is to choose three distinct vertices a, b, c on this tree such that the number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c is the maximum possible. See the notes section for a better understanding.
The simple path is the path that visits each vertex at most once.
Input
The first line contains one integer number n (3 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree.
Next n - 1 lines describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i). It is guaranteed that given graph is a tree.
Output
In the first line print one integer res — the maximum number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c.
In the second line print three integers a, b, c such that 1 ≤ a, b, c ≤ n and a ≠, b ≠ c, a ≠ c.
If there are several answers, you can print any.
Example
Input
8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
Output
5
1 8 6
Note
The picture corresponding to the first example (and another one correct answer):
<image>
If you choose vertices 1, 5, 6 then the path between 1 and 5 consists of edges (1, 2), (2, 3), (3, 4), (4, 5), the path between 1 and 6 consists of edges (1, 2), (2, 3), (3, 4), (4, 6) and the path between 5 and 6 consists of edges (4, 5), (4, 6). The union of these paths is (1, 2), (2, 3), (3, 4), (4, 5), (4, 6) so the answer is 5. It can be shown that there is no better answer. | instruction | 0 | 50,626 | 13 | 101,252 |
Tags: dfs and similar, dp, greedy, trees
Correct Solution:
```
class HLD:
def __init__(self, g):
self.g = g
self.n = len(g)
self.parent = [-1]*self.n
self.size = [1]*self.n
self.head = [0]*self.n
self.preorder = [0]*self.n
self.k = 0
self.depth = [0]*self.n
for v in range(self.n):
if self.parent[v] == -1:
self.dfs_pre(v)
self.dfs_hld(v)
def dfs_pre(self, v):
g = self.g
stack = [v]
order = [v]
while stack:
v = stack.pop()
for u in g[v]:
if self.parent[v] == u:
continue
self.parent[u] = v
self.depth[u] = self.depth[v]+1
stack.append(u)
order.append(u)
# 隣接リストの左端: heavyな頂点への辺
# 隣接リストの右端: 親への辺
while order:
v = order.pop()
child_v = g[v]
if len(child_v) and child_v[0] == self.parent[v]:
child_v[0], child_v[-1] = child_v[-1], child_v[0]
for i, u in enumerate(child_v):
if u == self.parent[v]:
continue
self.size[v] += self.size[u]
if self.size[u] > self.size[child_v[0]]:
child_v[i], child_v[0] = child_v[0], child_v[i]
def dfs_hld(self, v):
stack = [v]
while stack:
v = stack.pop()
self.preorder[v] = self.k
self.k += 1
top = self.g[v][0]
# 隣接リストを逆順に見ていく(親 > lightな頂点への辺 > heavyな頂点 (top))
# 連結成分が連続するようにならべる
for u in reversed(self.g[v]):
if u == self.parent[v]:
continue
if u == top:
self.head[u] = self.head[v]
else:
self.head[u] = u
stack.append(u)
def for_each(self, u, v):
# [u, v]上の頂点集合の区間を列挙
while True:
if self.preorder[u] > self.preorder[v]:
u, v = v, u
l = max(self.preorder[self.head[v]], self.preorder[u])
r = self.preorder[v]
yield l, r # [l, r]
if self.head[u] != self.head[v]:
v = self.parent[self.head[v]]
else:
return
def for_each_edge(self, u, v):
# [u, v]上の辺集合の区間列挙
# 辺の情報は子の頂点に
while True:
if self.preorder[u] > self.preorder[v]:
u, v = v, u
if self.head[u] != self.head[v]:
yield self.preorder[self.head[v]], self.preorder[v]
v = self.parent[self.head[v]]
else:
if u != v:
yield self.preorder[u]+1, self.preorder[v]
break
def subtree(self, v):
# 頂点vの部分木の頂点集合の区間 [l, r)
l = self.preorder[v]
r = self.preorder[v]+self.size[v]
return l, r
def lca(self, u, v):
# 頂点u, vのLCA
while True:
if self.preorder[u] > self.preorder[v]:
u, v = v, u
if self.head[u] == self.head[v]:
return u
v = self.parent[self.head[v]]
import sys
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n = int(input())
g = [[] for i in range(n)]
for i in range(n-1):
a, b = map(int, input().split())
a, b = a-1, b-1
g[a].append(b)
g[b].append(a)
INF = 10**18
from collections import deque
def bfs(s, g):
n = len(g)
d = [INF]*n
d[s] = 0
q = deque([])
q.append(s)
while q:
v = q.popleft()
for u in g[v]:
if d[u] == INF:
d[u] = d[v]+1
q.append(u)
return d
D1 = bfs(0, g)
M = max(D1)
for i in range(n):
if D1[i] == M:
x = i
break
D2 = bfs(x, g)
M = max(D2)
for i in range(n):
if D2[i] == M:
y = i
break
hld = HLD(g)
def dist(u, v):
l = hld.lca(u, v)
d = hld.depth[u]+hld.depth[v]-2*hld.depth[l]
return d
d0 = dist(x,y)
res = 0
ans = []
for i in range(n):
if i == x or i == y:
continue
d1 = dist(x, i)
d2 = dist(y, i)
temp = (d0+d1+d2)//2
if temp > res:
res = temp
ans = [x+1, y+1, i+1]
print(res)
print(*ans)
``` | output | 1 | 50,626 | 13 | 101,253 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an unweighted tree with n vertices. Recall that a tree is a connected undirected graph without cycles.
Your task is to choose three distinct vertices a, b, c on this tree such that the number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c is the maximum possible. See the notes section for a better understanding.
The simple path is the path that visits each vertex at most once.
Input
The first line contains one integer number n (3 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree.
Next n - 1 lines describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i). It is guaranteed that given graph is a tree.
Output
In the first line print one integer res — the maximum number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c.
In the second line print three integers a, b, c such that 1 ≤ a, b, c ≤ n and a ≠, b ≠ c, a ≠ c.
If there are several answers, you can print any.
Example
Input
8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
Output
5
1 8 6
Note
The picture corresponding to the first example (and another one correct answer):
<image>
If you choose vertices 1, 5, 6 then the path between 1 and 5 consists of edges (1, 2), (2, 3), (3, 4), (4, 5), the path between 1 and 6 consists of edges (1, 2), (2, 3), (3, 4), (4, 6) and the path between 5 and 6 consists of edges (4, 5), (4, 6). The union of these paths is (1, 2), (2, 3), (3, 4), (4, 5), (4, 6) so the answer is 5. It can be shown that there is no better answer.
Submitted Solution:
```
import sys
from collections import deque
n = int(input())
adj = [[] for _ in range(n)]
for u, v in (map(int, l.split()) for l in sys.stdin):
adj[u-1].append(v-1)
adj[v-1].append(u-1)
inf = 10**9
def rec(s):
prev = [-1]*n
prev[s] = inf
dq = deque([s])
last = s
while dq:
v = dq.popleft()
last = v
for dest in adj[v]:
if prev[dest] > -1:
continue
prev[dest] = v
dq.append(dest)
return last, prev
v1, _ = rec(0)
v2, prev = rec(v1)
v = prev[v2]
visited = [0]*n
visited[v] = visited[v1] = visited[v2] = 1
dia = 0
max_e, max_e_i = 0, v
while v != inf:
dia += 1
if prev[v] != inf:
visited[prev[v]] = 1
stack = [(v, 0)]
while stack:
cv, e = stack.pop()
if max_e < e:
max_e, max_e_i = e, cv
e += 1
for dest in adj[cv]:
if visited[dest]:
continue
visited[dest] = 1
stack.append((dest, e))
v = prev[v]
print(dia + max_e)
print(v1+1, v2+1, max_e_i+1)
``` | instruction | 0 | 50,627 | 13 | 101,254 |
Yes | output | 1 | 50,627 | 13 | 101,255 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an unweighted tree with n vertices. Recall that a tree is a connected undirected graph without cycles.
Your task is to choose three distinct vertices a, b, c on this tree such that the number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c is the maximum possible. See the notes section for a better understanding.
The simple path is the path that visits each vertex at most once.
Input
The first line contains one integer number n (3 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree.
Next n - 1 lines describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i). It is guaranteed that given graph is a tree.
Output
In the first line print one integer res — the maximum number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c.
In the second line print three integers a, b, c such that 1 ≤ a, b, c ≤ n and a ≠, b ≠ c, a ≠ c.
If there are several answers, you can print any.
Example
Input
8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
Output
5
1 8 6
Note
The picture corresponding to the first example (and another one correct answer):
<image>
If you choose vertices 1, 5, 6 then the path between 1 and 5 consists of edges (1, 2), (2, 3), (3, 4), (4, 5), the path between 1 and 6 consists of edges (1, 2), (2, 3), (3, 4), (4, 6) and the path between 5 and 6 consists of edges (4, 5), (4, 6). The union of these paths is (1, 2), (2, 3), (3, 4), (4, 5), (4, 6) so the answer is 5. It can be shown that there is no better answer.
Submitted Solution:
```
import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
#from bisect import bisect_left as bl, bisect_right as br, insort
#from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
#from itertools import permutations,combinations
def data(): return sys.stdin.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var) : sys.stdout.write(' '.join(map(str, var))+'\n')
def out(var) : sys.stdout.write(str(var)+'\n')
#from decimal import Decimal
#from fractions import Fraction
#sys.setrecursionlimit(100000)
#INF = float('inf')
mod = int(1e9)+7
n=int(data())
g=[[] for i in range(n+1)]
for i in range(n-1):
u,v=mdata()
g[u].append(v)
g[v].append(u)
ind=1
for i in range(1,n+1):
if len(g[i])==1:
ind=i
break
q=[ind]
v=[0]*(n+1)
vis=[0]*(n+1)
m=0
ans=0
while q:
a=q.pop()
vis[a]=1
for i in g[a]:
if vis[i]==0:
q.append(i)
v[i]=v[a]+1
if v[i]>m:
m=v[i]
ind=i
x=ind
q=[ind]
v=[0]*(n+1)
par=[0]*(n+1)
m=0
while q:
a=q.pop()
for i in g[a]:
if par[a]!=i:
q.append(i)
v[i]=v[a]+1
par[i]=a
if v[i]>m:
m=v[i]
ind=i
y=ind
a=par[y]
ans=m
m=0
ind=a
vis=[0]*(n+1)
vis[y]=1
while a!=x:
q=[a]
while q:
a1 = q.pop()
vis[a1]=1
for i in g[a1]:
if vis[i] == 0 and i!=par[a1]:
q.append(i)
if v[i]-v[a] > m:
m = v[i]-v[a]
ind = i
a=par[a]
z=ind
ans+=m
out(ans)
print(x,y,z)
``` | instruction | 0 | 50,628 | 13 | 101,256 |
Yes | output | 1 | 50,628 | 13 | 101,257 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an unweighted tree with n vertices. Recall that a tree is a connected undirected graph without cycles.
Your task is to choose three distinct vertices a, b, c on this tree such that the number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c is the maximum possible. See the notes section for a better understanding.
The simple path is the path that visits each vertex at most once.
Input
The first line contains one integer number n (3 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree.
Next n - 1 lines describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i). It is guaranteed that given graph is a tree.
Output
In the first line print one integer res — the maximum number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c.
In the second line print three integers a, b, c such that 1 ≤ a, b, c ≤ n and a ≠, b ≠ c, a ≠ c.
If there are several answers, you can print any.
Example
Input
8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
Output
5
1 8 6
Note
The picture corresponding to the first example (and another one correct answer):
<image>
If you choose vertices 1, 5, 6 then the path between 1 and 5 consists of edges (1, 2), (2, 3), (3, 4), (4, 5), the path between 1 and 6 consists of edges (1, 2), (2, 3), (3, 4), (4, 6) and the path between 5 and 6 consists of edges (4, 5), (4, 6). The union of these paths is (1, 2), (2, 3), (3, 4), (4, 5), (4, 6) so the answer is 5. It can be shown that there is no better answer.
Submitted Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
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")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=2**51, func=lambda a, b: a & b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] < key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
def main():
n = int(input())
graph = defaultdict(list)
for i in range(n - 1):
a, b = map(int, input().split())
graph[a - 1].append(b - 1)
graph[b - 1].append(a - 1)
node = [0]
ma = [0]
def dfs(v, p, dep):
if dep > ma[0]:
ma[0] = dep
node[0] = v
for i in graph[v]:
if i != p:
dfs(i, v, dep + 1)
parent = [-1] * n
def dfs1(v, p):
parent[v] = p
for i in graph[v]:
if i != p:
dfs1(i, v)
dfs(0, -1, 0)
fi = node[0]
node = [0]
ma = [0]
dfs(fi, -1, 0)
se = node[0]
dfs1(fi, -1)
k = se
que = []
que.append(k)
while (parent[k] != -1):
k = parent[k]
que.append(k)
ans = len(que) - 1
dist = [9999999] * n
e=[]
heapq.heapify(e)
for i in que:
dist[i] = 0
heapq.heappush(e, (0, i))
while e:
length, v = heapq.heappop(e)
for x in graph[v]:
if length+1 < dist[x]:
dist[x] = length+1
heapq.heappush(e, (1+length, x))
m = 0
third = 0
for i in range(n):
if dist[i]>=m and i!=fi and i!=se:
m = dist[i]
third = i
ans += m
print(ans)
print(fi + 1, se + 1, third + 1)
t = threading.Thread(target=main)
t.start()
t.join()
``` | instruction | 0 | 50,629 | 13 | 101,258 |
Yes | output | 1 | 50,629 | 13 | 101,259 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an unweighted tree with n vertices. Recall that a tree is a connected undirected graph without cycles.
Your task is to choose three distinct vertices a, b, c on this tree such that the number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c is the maximum possible. See the notes section for a better understanding.
The simple path is the path that visits each vertex at most once.
Input
The first line contains one integer number n (3 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree.
Next n - 1 lines describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i). It is guaranteed that given graph is a tree.
Output
In the first line print one integer res — the maximum number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c.
In the second line print three integers a, b, c such that 1 ≤ a, b, c ≤ n and a ≠, b ≠ c, a ≠ c.
If there are several answers, you can print any.
Example
Input
8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
Output
5
1 8 6
Note
The picture corresponding to the first example (and another one correct answer):
<image>
If you choose vertices 1, 5, 6 then the path between 1 and 5 consists of edges (1, 2), (2, 3), (3, 4), (4, 5), the path between 1 and 6 consists of edges (1, 2), (2, 3), (3, 4), (4, 6) and the path between 5 and 6 consists of edges (4, 5), (4, 6). The union of these paths is (1, 2), (2, 3), (3, 4), (4, 5), (4, 6) so the answer is 5. It can be shown that there is no better answer.
Submitted Solution:
```
from collections import namedtuple, deque
from sys import stdin
def load_graph():
n = int(stdin.readline())
G = [set() for i in range(n)]
for line in stdin.readlines():
a, b = line.split()
a, b = int(a) - 1, int(b) - 1
# ~ print(a, b)
G[a].add(b)
G[b].add(a)
return G
# find the distance from one node to any other node
# complexity O(n)
def find_all_distances(G, node):
distances = [None for i in range(len(G))]
distances[node] = 0
queue = deque((node,))
while len(queue) > 0:
current_node = queue.popleft()
for neighbor in G[current_node]:
if distances[neighbor] is None:
distances[neighbor] = distances[current_node] + 1
queue.append(neighbor)
# ~ print(distances)
return distances
# find a triplet of distinct nodes
# with maximized sum of pairwise distances
# G must be a tree, complexity O(n)
def find_maxdist_triplet(G):
distances_0 = find_all_distances(G, 0)
node_a, a_0_dist = max(enumerate(distances_0), key=lambda d: d[1])
distances_a = find_all_distances(G, node_a)
node_b, a_b_dist = max(enumerate(distances_a), key=lambda d: d[1])
distances_b = find_all_distances(G, node_b)
distances_sum = [dist_a + dist_b for dist_a, dist_b
in zip(distances_a, distances_b)]
node_c, c_ab_dist = max(((node, distance) for node, distance
in enumerate(distances_sum)
if node != node_a and node != node_b),
key=lambda d: d[1])
abc_dist = a_b_dist + c_ab_dist
# ~ print(a_b_dist, c_ab_dist)
return abc_dist, node_a, node_b, node_c
G = load_graph()
# ~ print(G)
dist_sum, path_a, path_b, path_c = find_maxdist_triplet(G)
print(dist_sum // 2)
print(path_a + 1, path_b + 1, path_c + 1)
``` | instruction | 0 | 50,630 | 13 | 101,260 |
Yes | output | 1 | 50,630 | 13 | 101,261 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an unweighted tree with n vertices. Recall that a tree is a connected undirected graph without cycles.
Your task is to choose three distinct vertices a, b, c on this tree such that the number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c is the maximum possible. See the notes section for a better understanding.
The simple path is the path that visits each vertex at most once.
Input
The first line contains one integer number n (3 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree.
Next n - 1 lines describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i). It is guaranteed that given graph is a tree.
Output
In the first line print one integer res — the maximum number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c.
In the second line print three integers a, b, c such that 1 ≤ a, b, c ≤ n and a ≠, b ≠ c, a ≠ c.
If there are several answers, you can print any.
Example
Input
8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
Output
5
1 8 6
Note
The picture corresponding to the first example (and another one correct answer):
<image>
If you choose vertices 1, 5, 6 then the path between 1 and 5 consists of edges (1, 2), (2, 3), (3, 4), (4, 5), the path between 1 and 6 consists of edges (1, 2), (2, 3), (3, 4), (4, 6) and the path between 5 and 6 consists of edges (4, 5), (4, 6). The union of these paths is (1, 2), (2, 3), (3, 4), (4, 5), (4, 6) so the answer is 5. It can be shown that there is no better answer.
Submitted Solution:
```
from sys import stdin, stdout
from collections import namedtuple
graph = []
names = ['count','elements']
def dp(current, previous):
global graph
global names
zeroes = [0,set()]
current_max = [[{k:v for k,v in zip(names, zeroes)} for _ in range(3 - i)] for i in range(3)]
for x in graph[current]:
if x == previous:
continue
max = dp(x, current)
for i in range(3):
for j in range(3 - i):
if max[i]['count'] > current_max[i][j]['count']:
for k in range (j+1, 3 - i, -1):
current_max[i][k]['count'] = current_max[i][k-1]['count']
current_max[i][k]['elements'] = current_max[i][k-1]['elements']
current_max[i][j]['count'] = max[i]['count']
current_max[i][j]['elements'] = max[i]['elements']
break
if current_max[0][0]['count'] + current_max[0][1]['count'] + current_max[0][2]['count'] > current_max[2][0]['count'] and current_max[0][2]['count'] and current_max[0][1]['count'] and current_max[0][0]['count']:
current_max[2][0]['count'] = current_max[0][0]['count'] + current_max[0][1]['count'] + current_max[0][2]['count']
current_max[2][0]['elements'] = current_max[0][0]['elements'].union(current_max[0][1]['elements'], current_max[0][2]['elements'])
if current_max[1][0]['count'] and current_max[0][0]['count'] and current_max[0][0]['elements'].difference(current_max[1][0]['elements']):
if current_max[0][0]['count'] + current_max[1][0]['count'] > current_max[2][0]['count']:
current_max[2][0]['count'] = current_max[0][0]['count'] + current_max[1][0]['count']
current_max[2][0]['elements'] = current_max[0][0]['elements'].union(current_max[1][0]['elements'])
else:
if current_max[0][1]['count'] + current_max[1][0]['count'] > current_max[2][0]['count'] and current_max[1][0]['count'] and current_max[0][1]['count'] and current_max[0][1]['elements'].difference(current_max[1][0]['elements']):
current_max[2][0]['count'] = current_max[0][1]['count'] + current_max[1][0]['count']
current_max[2][0]['elements'] = current_max[0][1]['elements'].union(current_max[1][0]['elements'])
if current_max[0][0]['count'] + current_max[1][1]['count'] > current_max[2][0]['count'] and current_max[0][0]['count'] and current_max[1][1]['count'] and current_max[0][0]['elements'].difference(current_max[1][1]['elements']):
current_max[2][0]['count'] = current_max[0][0]['count'] + current_max[1][1]['count']
current_max[2][0]['elements'] = current_max[0][0]['elements'].union(current_max[1][1]['elements'])
if current_max[0][0]['count'] + current_max[0][1]['count'] > current_max[1][0]['count'] and current_max[0][0]['count'] and current_max[0][1]['count']:
current_max[1][0]['count'] = current_max[0][0]['count'] + current_max[0][1]['count']
current_max[1][0]['elements'] = current_max[0][0]['elements'].union(current_max[0][1]['elements'])
current_max[0][0]['count'] +=1
if not current_max[0][0]['elements']:
current_max[0][0]['elements'].add(current)
if current_max[1][0]['count']:
current_max[1][0]['count'] += 1
if 96 in current_max[1][0]['elements'] and 81 in current_max[1][0]['elements']:
print(current, current_max[1])
print(graph[76])
return [current_max[0][0], current_max[1][0] , current_max[2][0]]
def main():
global graph
n = int(stdin.readline())
graph = [set() for _ in range(n+1)]
for _ in range (n-1):
x,y = list(map(int, stdin.readline().split()))
graph[x].add(y)
graph[y].add(x)
ans = dp(1, -1)
if ans[1]['count'] - 1 > ans[2]['count']:
ans[1]['elements'].add(1)
stdout.write(str(ans[1]['count'] - 1) +"\n" + " ".join(str(s) for s in ans[1]['elements']))
else:
stdout.write(str(ans[2]['count']) +"\n" + " ".join(str(s) for s in ans[2]['elements']))
main()
``` | instruction | 0 | 50,631 | 13 | 101,262 |
No | output | 1 | 50,631 | 13 | 101,263 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an unweighted tree with n vertices. Recall that a tree is a connected undirected graph without cycles.
Your task is to choose three distinct vertices a, b, c on this tree such that the number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c is the maximum possible. See the notes section for a better understanding.
The simple path is the path that visits each vertex at most once.
Input
The first line contains one integer number n (3 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree.
Next n - 1 lines describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i). It is guaranteed that given graph is a tree.
Output
In the first line print one integer res — the maximum number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c.
In the second line print three integers a, b, c such that 1 ≤ a, b, c ≤ n and a ≠, b ≠ c, a ≠ c.
If there are several answers, you can print any.
Example
Input
8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
Output
5
1 8 6
Note
The picture corresponding to the first example (and another one correct answer):
<image>
If you choose vertices 1, 5, 6 then the path between 1 and 5 consists of edges (1, 2), (2, 3), (3, 4), (4, 5), the path between 1 and 6 consists of edges (1, 2), (2, 3), (3, 4), (4, 6) and the path between 5 and 6 consists of edges (4, 5), (4, 6). The union of these paths is (1, 2), (2, 3), (3, 4), (4, 5), (4, 6) so the answer is 5. It can be shown that there is no better answer.
Submitted Solution:
```
from sys import stdin, stdout
from collections import namedtuple
graph = []
names = ['count','elements']
def dp(current, previous):
global graph
global names
zeroes = [0,set()]
current_max = [[{k:v for k,v in zip(names, zeroes)} for _ in range(3 - i)] for i in range(3)]
for x in graph[current]:
if x == previous:
continue
max = dp(x, current)
for i in range(3):
for j in range(3 - i):
if max[i]['count'] > current_max[i][j]['count']:
for k in range (j+1, 3 - i, -1):
current_max[i][k]['count'] = current_max[i][k-1]['count']
current_max[i][k]['elements'] = current_max[i][k-1]['elements']
current_max[i][j]['count'] = max[i]['count']
current_max[i][j]['elements'] = max[i]['elements']
break
if current_max[0][0]['count'] + current_max[0][1]['count'] + current_max[0][2]['count'] > current_max[2][0]['count'] and current_max[0][2]['count'] and current_max[0][1]['count'] and current_max[0][0]['count']:
current_max[2][0]['count'] = current_max[0][0]['count'] + current_max[0][1]['count'] + current_max[0][2]['count']
current_max[2][0]['elements'] = current_max[0][0]['elements'].union(current_max[0][1]['elements'], current_max[0][2]['elements'])
if current_max[1][0]['count'] and current_max[0][0]['count'] and current_max[0][0]['elements'].difference(current_max[1][0]['elements']):
if current_max[0][0]['count'] + current_max[1][0]['count'] > current_max[2][0]['count']:
current_max[2][0]['count'] = current_max[0][0]['count'] + current_max[1][0]['count']
current_max[2][0]['elements'] = current_max[0][0]['elements'].union(current_max[1][0]['elements'])
if current_max[0][1]['count'] + current_max[1][0]['count'] > current_max[2][0]['count'] and current_max[1][0]['count'] and current_max[0][1]['count'] and current_max[0][1]['elements'].difference(current_max[1][0]['elements']):
current_max[2][0]['count'] = current_max[0][1]['count'] + current_max[1][0]['count']
current_max[2][0]['elements'] = current_max[0][1]['elements'].union(current_max[1][0]['elements'])
if current_max[0][0]['count'] + current_max[1][1]['count'] > current_max[2][0]['count'] and current_max[0][0]['count'] and current_max[1][1]['count'] and current_max[0][0]['elements'].difference(current_max[1][1]['elements']):
current_max[2][0]['count'] = current_max[0][0]['count'] + current_max[1][1]['count']
current_max[2][0]['elements'] = current_max[0][0]['elements'].union(current_max[1][1]['elements'])
if current_max[0][0]['count'] + current_max[0][1]['count'] > current_max[1][0]['count'] and current_max[0][0]['count'] and current_max[0][1]['count']:
current_max[1][0]['count'] = current_max[0][0]['count'] + current_max[0][1]['count']
current_max[1][0]['elements'] = current_max[0][0]['elements'].union(current_max[0][1]['elements'])
current_max[0][0]['count'] +=1
if not current_max[0][0]['elements']:
current_max[0][0]['elements'].add(current)
if current_max[1][0]['count']:
current_max[1][0]['count'] += 1
if 96 in current_max[1][0]['elements'] and 81 in current_max[1][0]['elements']:
print(current, current_max[1])
print(graph[76])
return [current_max[0][0], current_max[1][0] , current_max[2][0]]
def main():
global graph
n = int(stdin.readline())
graph = [set() for _ in range(n+1)]
for _ in range (n-1):
x,y = list(map(int, stdin.readline().split()))
graph[x].add(y)
graph[y].add(x)
ans = dp(1, -1)
if ans[1]['count'] - 1 > ans[2]['count']:
ans[1]['elements'].add(1)
stdout.write(str(ans[1]['count'] - 1) +"\n" + " ".join(str(s) for s in ans[1]['elements']))
else:
stdout.write(str(ans[2]['count']) +"\n" + " ".join(str(s) for s in ans[2]['elements']))
main()
``` | instruction | 0 | 50,632 | 13 | 101,264 |
No | output | 1 | 50,632 | 13 | 101,265 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an unweighted tree with n vertices. Recall that a tree is a connected undirected graph without cycles.
Your task is to choose three distinct vertices a, b, c on this tree such that the number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c is the maximum possible. See the notes section for a better understanding.
The simple path is the path that visits each vertex at most once.
Input
The first line contains one integer number n (3 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree.
Next n - 1 lines describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i). It is guaranteed that given graph is a tree.
Output
In the first line print one integer res — the maximum number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c.
In the second line print three integers a, b, c such that 1 ≤ a, b, c ≤ n and a ≠, b ≠ c, a ≠ c.
If there are several answers, you can print any.
Example
Input
8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
Output
5
1 8 6
Note
The picture corresponding to the first example (and another one correct answer):
<image>
If you choose vertices 1, 5, 6 then the path between 1 and 5 consists of edges (1, 2), (2, 3), (3, 4), (4, 5), the path between 1 and 6 consists of edges (1, 2), (2, 3), (3, 4), (4, 6) and the path between 5 and 6 consists of edges (4, 5), (4, 6). The union of these paths is (1, 2), (2, 3), (3, 4), (4, 5), (4, 6) so the answer is 5. It can be shown that there is no better answer.
Submitted Solution:
```
import sys
input = sys.stdin.readline
import math
import copy
import collections
from collections import deque
def bfs(vert):
global adj,visited
q = deque()
q.append([vert,0])
while q:
temp,dist = q.popleft()
visited.add(temp)
for edge in adj[temp]:
if edge not in visited:
q.append([edge,dist+1])
if not q:
return [temp,dist]
def findpath(a,b):
global path,adj,visited
path.append(a)
visited.add(a)
if a==b:
return
if a not in adj:
return
for edge in adj[a]:
if edge not in visited:
findpath(edge,b)
if path[len(path)-1]!=b:
path.pop()
def bfs2(path):
global visited
c = -1
farthest = 0
for node in path:
temp,dist = bfs(node)
if dist>farthest:
farthest = dist
c = temp
return [c,farthest]
sys.setrecursionlimit(2*10**5)
n = int(input())
adj = dict()
for i in range(n-1):
u,v = map(int,input().split())
if u not in adj:
adj[u] = set()
if v not in adj:
adj[v] = set()
adj[v].add(u)
adj[u].add(v)
visited = set()
a,_ = bfs(1)
visited = set()
b,_ = bfs(a)
path = []
visited = set()
findpath(a,b)
visited = set(path)
c,dist = bfs2(path)
print(len(path)-1+dist)
print(a,b,c)
``` | instruction | 0 | 50,633 | 13 | 101,266 |
No | output | 1 | 50,633 | 13 | 101,267 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an unweighted tree with n vertices. Recall that a tree is a connected undirected graph without cycles.
Your task is to choose three distinct vertices a, b, c on this tree such that the number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c is the maximum possible. See the notes section for a better understanding.
The simple path is the path that visits each vertex at most once.
Input
The first line contains one integer number n (3 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree.
Next n - 1 lines describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i). It is guaranteed that given graph is a tree.
Output
In the first line print one integer res — the maximum number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c.
In the second line print three integers a, b, c such that 1 ≤ a, b, c ≤ n and a ≠, b ≠ c, a ≠ c.
If there are several answers, you can print any.
Example
Input
8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
Output
5
1 8 6
Note
The picture corresponding to the first example (and another one correct answer):
<image>
If you choose vertices 1, 5, 6 then the path between 1 and 5 consists of edges (1, 2), (2, 3), (3, 4), (4, 5), the path between 1 and 6 consists of edges (1, 2), (2, 3), (3, 4), (4, 6) and the path between 5 and 6 consists of edges (4, 5), (4, 6). The union of these paths is (1, 2), (2, 3), (3, 4), (4, 5), (4, 6) so the answer is 5. It can be shown that there is no better answer.
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
def ctd(chr): return ord(chr)-ord("a")
mod = 998244353
INF = float('inf')
# ------------------------------
def main():
n = N()
gp = [[] for _ in range(n+1)]
for _ in range(n-1):
f, t = RL()
gp[f].append(t)
gp[t].append(f)
par = [-1] * (n + 1)
def BFS(nd):
nonlocal par
q = deque()
q.append((nd, 0))
vis = [0]*(n+1)
vis[nd] = 1
lst = -1, 0
while q:
nd, d = q.popleft()
lst = nd, d
for nex in gp[nd]:
if vis[nex]==1: continue
vis[nex] = 1
q.append((nex, d+1))
par[nex] = nd
return lst
a, _ = BFS(1)
par = [-1] * (n + 1)
b, l = BFS(a)
# print(a, b, l, par)
def BFS1(node, pre, suf):
q = deque()
q.append((node, 0))
vis = [0] * (n + 1)
vis[node] = 1
lst = -1, 0
while q:
nd, d = q.popleft()
lst = nd, d
for nex in gp[nd]:
if vis[nex]==1 or nex==pre or nex==suf: continue
vis[nex] = 1
q.append((nex, d+1))
return lst
nd = b
pre = -1
c = (-1, 0)
while par[nd]!=-1:
pt, d = BFS1(nd, par[nd], pre)
if d>c[1]:
c = pt, d
pre = nd
nd = par[nd]
print(c[1]+l)
print(a, b, c[0])
if __name__ == "__main__":
main()
``` | instruction | 0 | 50,634 | 13 | 101,268 |
No | output | 1 | 50,634 | 13 | 101,269 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.
Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only three values n, d and h:
* The tree had exactly n vertices.
* The tree had diameter d. In other words, d was the biggest distance between two vertices.
* Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex.
The distance between two vertices of the tree is the number of edges on the simple path between them.
Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1".
Input
The first line contains three integers n, d and h (2 ≤ n ≤ 100 000, 1 ≤ h ≤ d ≤ n - 1) — the number of vertices, diameter, and height after rooting in vertex 1, respectively.
Output
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes).
Otherwise, describe any tree matching Limak's description. Print n - 1 lines, each with two space-separated integers – indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
Examples
Input
5 3 2
Output
1 2
1 3
3 4
3 5
Input
8 5 2
Output
-1
Input
8 4 2
Output
4 8
5 7
2 3
8 1
2 1
5 6
1 5
Note
Below you can see trees printed to the output in the first sample and the third sample.
<image> | instruction | 0 | 50,936 | 13 | 101,872 |
Tags: constructive algorithms, graphs, trees
Correct Solution:
```
# Problem: B. Bear and Forgotten Tree 3
# Contest: Codeforces - VK Cup 2016 - Round 1
# URL: https://codeforces.com/contest/639/problem/B
# Memory Limit: 256 MB
# Time Limit: 2000 ms
#
# KAPOOR'S
from sys import stdin, stdout
def INI():
return int(stdin.readline())
def INL():
return [int(_) for _ in stdin.readline().split()]
def INS():
return stdin.readline()
def MOD():
return pow(10,9)+7
def OPS(ans):
stdout.write(str(ans)+"\n")
def OPL(ans):
[stdout.write(str(_)+" ") for _ in ans]
stdout.write("\n")
if __name__=="__main__":
n,d,h=INL()
u=h
if not h<=d<=2*h or d==1 and 2<n:
OPS(-1)
else:
x=1
y=1
for _ in range(2,n+1):
if h:
OPL([x,_])
x=_
h-=1
d-=1
elif d:
OPL([y,_])
y=_
d-=1
else:
if u==1:
OPL([1,_])
else:
OPL([2,_])
``` | output | 1 | 50,936 | 13 | 101,873 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.
Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only three values n, d and h:
* The tree had exactly n vertices.
* The tree had diameter d. In other words, d was the biggest distance between two vertices.
* Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex.
The distance between two vertices of the tree is the number of edges on the simple path between them.
Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1".
Input
The first line contains three integers n, d and h (2 ≤ n ≤ 100 000, 1 ≤ h ≤ d ≤ n - 1) — the number of vertices, diameter, and height after rooting in vertex 1, respectively.
Output
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes).
Otherwise, describe any tree matching Limak's description. Print n - 1 lines, each with two space-separated integers – indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
Examples
Input
5 3 2
Output
1 2
1 3
3 4
3 5
Input
8 5 2
Output
-1
Input
8 4 2
Output
4 8
5 7
2 3
8 1
2 1
5 6
1 5
Note
Below you can see trees printed to the output in the first sample and the third sample.
<image> | instruction | 0 | 50,937 | 13 | 101,874 |
Tags: constructive algorithms, graphs, trees
Correct Solution:
```
from __future__ import print_function
import sys
from collections import *
from heapq import *
from functools import *
import re
from itertools import *
INF=float("inf")
NINF=float("-inf")
try:
input=raw_input
except:
pass
def read_string():
return input()
def read_string_line():
return [x for x in input().split(" ")]
def read_int_line():
return [int(x) for x in input().split(" ")]
def read_int():
return int(input())
n,d,h=read_int_line()
if d>n-1 or d>2*h or d < h or (d==h and d==1 and n>2):
print("-1")
exit()
for i in range(h):
print("%d %d"%(i+1,i+2))
cur=h+2
if d==h:
for i in range(cur,n+1):
print("2 %d" % i)
exit()
for i in range(d-h):
if i==0: print("1 %d"%cur)
else: print("%d %d" % (cur+i-1, cur+i))
cur =d+2
for i in range(cur,n+1):
print("%d %d"%(1,i))
``` | output | 1 | 50,937 | 13 | 101,875 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.
Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only three values n, d and h:
* The tree had exactly n vertices.
* The tree had diameter d. In other words, d was the biggest distance between two vertices.
* Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex.
The distance between two vertices of the tree is the number of edges on the simple path between them.
Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1".
Input
The first line contains three integers n, d and h (2 ≤ n ≤ 100 000, 1 ≤ h ≤ d ≤ n - 1) — the number of vertices, diameter, and height after rooting in vertex 1, respectively.
Output
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes).
Otherwise, describe any tree matching Limak's description. Print n - 1 lines, each with two space-separated integers – indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
Examples
Input
5 3 2
Output
1 2
1 3
3 4
3 5
Input
8 5 2
Output
-1
Input
8 4 2
Output
4 8
5 7
2 3
8 1
2 1
5 6
1 5
Note
Below you can see trees printed to the output in the first sample and the third sample.
<image> | instruction | 0 | 50,938 | 13 | 101,876 |
Tags: constructive algorithms, graphs, trees
Correct Solution:
```
n,d,h = (int(i) for i in input().split())
if h*2 < d or n < d+1 or d == 1 and n > 2 :
print(-1)
else:
for i in range(h):
print(i+1,i+2)
ost = h+1
if d > h:
print(1,ost+1)
for i in range(d-h-1):
print(ost+i+1,ost+i+2)
if d != h:
for i in range(1,n-d):
print(1,d+1+i)
else:
for i in range(1,n-d):
print(2,d+1+i)
``` | output | 1 | 50,938 | 13 | 101,877 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.
Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only three values n, d and h:
* The tree had exactly n vertices.
* The tree had diameter d. In other words, d was the biggest distance between two vertices.
* Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex.
The distance between two vertices of the tree is the number of edges on the simple path between them.
Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1".
Input
The first line contains three integers n, d and h (2 ≤ n ≤ 100 000, 1 ≤ h ≤ d ≤ n - 1) — the number of vertices, diameter, and height after rooting in vertex 1, respectively.
Output
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes).
Otherwise, describe any tree matching Limak's description. Print n - 1 lines, each with two space-separated integers – indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
Examples
Input
5 3 2
Output
1 2
1 3
3 4
3 5
Input
8 5 2
Output
-1
Input
8 4 2
Output
4 8
5 7
2 3
8 1
2 1
5 6
1 5
Note
Below you can see trees printed to the output in the first sample and the third sample.
<image> | instruction | 0 | 50,939 | 13 | 101,878 |
Tags: constructive algorithms, graphs, trees
Correct Solution:
```
import sys
[n,d,h]=[int(i) for i in input().split()];
if n==2:
print(1,2);
sys.exit(0);
if (d==1) or (d>2*h):
print(-1);
sys.exit(0);
for i in range(1,h+1):
print(i,i+1);
if(d+1>h+1):
print(1,h+2);
for i in range(h+3,d+2):
print(i-1,i);
for i in range(d+2,n+1):
print(h,i);
``` | output | 1 | 50,939 | 13 | 101,879 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.
Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only three values n, d and h:
* The tree had exactly n vertices.
* The tree had diameter d. In other words, d was the biggest distance between two vertices.
* Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex.
The distance between two vertices of the tree is the number of edges on the simple path between them.
Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1".
Input
The first line contains three integers n, d and h (2 ≤ n ≤ 100 000, 1 ≤ h ≤ d ≤ n - 1) — the number of vertices, diameter, and height after rooting in vertex 1, respectively.
Output
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes).
Otherwise, describe any tree matching Limak's description. Print n - 1 lines, each with two space-separated integers – indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
Examples
Input
5 3 2
Output
1 2
1 3
3 4
3 5
Input
8 5 2
Output
-1
Input
8 4 2
Output
4 8
5 7
2 3
8 1
2 1
5 6
1 5
Note
Below you can see trees printed to the output in the first sample and the third sample.
<image> | instruction | 0 | 50,940 | 13 | 101,880 |
Tags: constructive algorithms, graphs, trees
Correct Solution:
```
n,d,h=map(int,input().split())
if n ==2:
if d == h and d == 1:
print('1 2')
else:
print(-1)
elif d== 1 or d>2*h:
print(-1)
else:
for i in range(h):
print(i+1,i+2)
for i in range(d-h):
print(1 if i==0 else i+h+1,i+h+2)
for i in range(d+1,n):
print(2 if d==h else 1, i+1)
``` | output | 1 | 50,940 | 13 | 101,881 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.
Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only three values n, d and h:
* The tree had exactly n vertices.
* The tree had diameter d. In other words, d was the biggest distance between two vertices.
* Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex.
The distance between two vertices of the tree is the number of edges on the simple path between them.
Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1".
Input
The first line contains three integers n, d and h (2 ≤ n ≤ 100 000, 1 ≤ h ≤ d ≤ n - 1) — the number of vertices, diameter, and height after rooting in vertex 1, respectively.
Output
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes).
Otherwise, describe any tree matching Limak's description. Print n - 1 lines, each with two space-separated integers – indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
Examples
Input
5 3 2
Output
1 2
1 3
3 4
3 5
Input
8 5 2
Output
-1
Input
8 4 2
Output
4 8
5 7
2 3
8 1
2 1
5 6
1 5
Note
Below you can see trees printed to the output in the first sample and the third sample.
<image> | instruction | 0 | 50,941 | 13 | 101,882 |
Tags: constructive algorithms, graphs, trees
Correct Solution:
```
n,d,h = map(int, input().split())
if n<(h+1):
print(-1)
elif ((d<h) or (d>2*h)):
print(-1)
elif h==1 and d==1 and n>=3:
print(-1)
else:
count = 2
stmt=h
for i in range(h):
print(i+1, i+2)
for i in range(h, n-(d-h+1)):
print(h, h+count)
stmt+=1
count+=1
node = 1
if stmt<(n-1):
print(1, n-(d-h)+1)
for i in range(n-(d-h)+1, n):
print(i, i+1)
``` | output | 1 | 50,941 | 13 | 101,883 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.
Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only three values n, d and h:
* The tree had exactly n vertices.
* The tree had diameter d. In other words, d was the biggest distance between two vertices.
* Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex.
The distance between two vertices of the tree is the number of edges on the simple path between them.
Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1".
Input
The first line contains three integers n, d and h (2 ≤ n ≤ 100 000, 1 ≤ h ≤ d ≤ n - 1) — the number of vertices, diameter, and height after rooting in vertex 1, respectively.
Output
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes).
Otherwise, describe any tree matching Limak's description. Print n - 1 lines, each with two space-separated integers – indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
Examples
Input
5 3 2
Output
1 2
1 3
3 4
3 5
Input
8 5 2
Output
-1
Input
8 4 2
Output
4 8
5 7
2 3
8 1
2 1
5 6
1 5
Note
Below you can see trees printed to the output in the first sample and the third sample.
<image> | instruction | 0 | 50,942 | 13 | 101,884 |
Tags: constructive algorithms, graphs, trees
Correct Solution:
```
n, d, h = map(int, input().split())
if d > h * 2 or (n > 2 and h == 1 and d == 1):
print(-1)
else:
for i in range(2, h + 2):
print(i-1, i)
c = h+2
for i in range(d - h):
if i == 0:
print(1, c)
else:
print(c-1, c)
c += 1
for i in range(d+2, n+1):
print(h, i)
``` | output | 1 | 50,942 | 13 | 101,885 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.
Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only three values n, d and h:
* The tree had exactly n vertices.
* The tree had diameter d. In other words, d was the biggest distance between two vertices.
* Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex.
The distance between two vertices of the tree is the number of edges on the simple path between them.
Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1".
Input
The first line contains three integers n, d and h (2 ≤ n ≤ 100 000, 1 ≤ h ≤ d ≤ n - 1) — the number of vertices, diameter, and height after rooting in vertex 1, respectively.
Output
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes).
Otherwise, describe any tree matching Limak's description. Print n - 1 lines, each with two space-separated integers – indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
Examples
Input
5 3 2
Output
1 2
1 3
3 4
3 5
Input
8 5 2
Output
-1
Input
8 4 2
Output
4 8
5 7
2 3
8 1
2 1
5 6
1 5
Note
Below you can see trees printed to the output in the first sample and the third sample.
<image> | instruction | 0 | 50,943 | 13 | 101,886 |
Tags: constructive algorithms, graphs, trees
Correct Solution:
```
# Codeforces 639B #
n, d, h = map(int, input().split())
if h < ((d + 1) >> 1) or (n > 2 and d == 1):
print(-1)
else:
km = 2 if h != 1 else 1
print(h + 1, km)
for i in range(2, h):
print(i, i + 1)
if h != 1: print(h, 1)
if h < d: print(1, h + 2)
for i in range(h + 2, d + 1):
print(i, i + 1)
for i in range(d + 2, n + 1):
print(i, km)
``` | output | 1 | 50,943 | 13 | 101,887 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.
Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only three values n, d and h:
* The tree had exactly n vertices.
* The tree had diameter d. In other words, d was the biggest distance between two vertices.
* Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex.
The distance between two vertices of the tree is the number of edges on the simple path between them.
Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1".
Input
The first line contains three integers n, d and h (2 ≤ n ≤ 100 000, 1 ≤ h ≤ d ≤ n - 1) — the number of vertices, diameter, and height after rooting in vertex 1, respectively.
Output
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes).
Otherwise, describe any tree matching Limak's description. Print n - 1 lines, each with two space-separated integers – indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
Examples
Input
5 3 2
Output
1 2
1 3
3 4
3 5
Input
8 5 2
Output
-1
Input
8 4 2
Output
4 8
5 7
2 3
8 1
2 1
5 6
1 5
Note
Below you can see trees printed to the output in the first sample and the third sample.
<image>
Submitted Solution:
```
n,d,h = [int(i) for i in input().split()]
tree = []
while True:
if n <= d or n <= h or d < h or (n == h + 1 and d > h) or d - h > h or (n > 2 and d == 1):
tree = -1
break
for i in range(1,h + 1):
tree.append((i,i + 1))
if n == h + 1: break
if d > h:
tree.append((1,h + 2))
for i in range(h + 2,d + 1):
tree.append((i,i + 1))
if n > d + 1:
for i in range(d + 2,n + 1):
tree.append((1,i))
break
elif d == h:
for i in range(h + 2,n + 1):
tree.append((2,i))
break
if tree == -1:
print(tree)
else:
for i in range(len(tree)):
print(*tree[i])
``` | instruction | 0 | 50,944 | 13 | 101,888 |
Yes | output | 1 | 50,944 | 13 | 101,889 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.
Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only three values n, d and h:
* The tree had exactly n vertices.
* The tree had diameter d. In other words, d was the biggest distance between two vertices.
* Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex.
The distance between two vertices of the tree is the number of edges on the simple path between them.
Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1".
Input
The first line contains three integers n, d and h (2 ≤ n ≤ 100 000, 1 ≤ h ≤ d ≤ n - 1) — the number of vertices, diameter, and height after rooting in vertex 1, respectively.
Output
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes).
Otherwise, describe any tree matching Limak's description. Print n - 1 lines, each with two space-separated integers – indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
Examples
Input
5 3 2
Output
1 2
1 3
3 4
3 5
Input
8 5 2
Output
-1
Input
8 4 2
Output
4 8
5 7
2 3
8 1
2 1
5 6
1 5
Note
Below you can see trees printed to the output in the first sample and the third sample.
<image>
Submitted Solution:
```
import sys,os,io
import math,bisect,operator
inf,mod = float('inf'),10**9+7
# sys.setrecursionlimit(10 ** 6)
from itertools import groupby,accumulate
from heapq import heapify,heappop,heappush
from collections import deque,Counter,defaultdict
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
Neo = lambda : list(map(int,input().split()))
# test, = Neo()
n,d,h = Neo()
f = 0
Ans = []
for i in range(1,h+1):
if i+1 > n:
f = 1
Ans.append((i,i+1))
t = d-h
# print(t)
if d < h or h < d-h:
f = 1
k = h+1
if t > 0:
Ans.append((1,h+2))
t -= 1
k += 1
while t > 0:
if k+1 > n:
f = 1
Ans.append((k,k+1))
k += 1
t -= 1
# print(k)
if d-h == 0:
l = 0
for i in range(k+1,n+1):
l = 1
Ans.append((2,i))
if (d < 2 or h < 2) and l:
f = 1
else:
for i in range(k+1,n+1):
Ans.append((1,i))
if len(Ans) > n-1:
f = 1
if f:
print(-1)
else:
for i,j in Ans:
print(i,j)
``` | instruction | 0 | 50,945 | 13 | 101,890 |
Yes | output | 1 | 50,945 | 13 | 101,891 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.
Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only three values n, d and h:
* The tree had exactly n vertices.
* The tree had diameter d. In other words, d was the biggest distance between two vertices.
* Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex.
The distance between two vertices of the tree is the number of edges on the simple path between them.
Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1".
Input
The first line contains three integers n, d and h (2 ≤ n ≤ 100 000, 1 ≤ h ≤ d ≤ n - 1) — the number of vertices, diameter, and height after rooting in vertex 1, respectively.
Output
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes).
Otherwise, describe any tree matching Limak's description. Print n - 1 lines, each with two space-separated integers – indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
Examples
Input
5 3 2
Output
1 2
1 3
3 4
3 5
Input
8 5 2
Output
-1
Input
8 4 2
Output
4 8
5 7
2 3
8 1
2 1
5 6
1 5
Note
Below you can see trees printed to the output in the first sample and the third sample.
<image>
Submitted Solution:
```
# Codeforces 639B #
n, d, h = map(int, input().split())
if h < ((d + 1) >> 1) or (n > 2 and d == 1):
print(-1)
else:
k = 2 if h != 1 else 1
print(h + 1, k)
for i in range(2, h):
print(i, i + 1)
if h != 1: print(h, 1)
if h < d: print(1, h + 2)
for i in range(h + 2, d + 1):
print(i, i + 1)
for i in range(d + 2, n + 1):
print(i, k)
``` | instruction | 0 | 50,946 | 13 | 101,892 |
Yes | output | 1 | 50,946 | 13 | 101,893 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.
Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only three values n, d and h:
* The tree had exactly n vertices.
* The tree had diameter d. In other words, d was the biggest distance between two vertices.
* Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex.
The distance between two vertices of the tree is the number of edges on the simple path between them.
Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1".
Input
The first line contains three integers n, d and h (2 ≤ n ≤ 100 000, 1 ≤ h ≤ d ≤ n - 1) — the number of vertices, diameter, and height after rooting in vertex 1, respectively.
Output
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes).
Otherwise, describe any tree matching Limak's description. Print n - 1 lines, each with two space-separated integers – indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
Examples
Input
5 3 2
Output
1 2
1 3
3 4
3 5
Input
8 5 2
Output
-1
Input
8 4 2
Output
4 8
5 7
2 3
8 1
2 1
5 6
1 5
Note
Below you can see trees printed to the output in the first sample and the third sample.
<image>
Submitted Solution:
```
str1 = input().split()
n = int(str1[0])
d = int(str1[1])
h = int(str1[2])
if n < h + 1:
print(-1)
exit()
elif n < d + 1:
print(-1)
exit()
elif d > h * 2:
print(-1)
exit()
elif d == h == 1 and n > 2:
print(-1)
exit()
for i in range(1, h + 1):
print(i, i + 1)
count = n - h - 1
k = 0
left = d - h
dist = h - 1
if count > 0:
if d - h > 0:
count -= 1
print(1, h + 2 + left * k)
if count == 0:
exit()
for i in range(left - 1):
print(i + h + 2 + left * k, i + h + 3 + left * k)
count -= 1
if count == 0:
exit()
k += 1
while count > 0:
count -= 1
if h > 1:
print(2, n - count)
else:
print(1, n - count)
``` | instruction | 0 | 50,947 | 13 | 101,894 |
Yes | output | 1 | 50,947 | 13 | 101,895 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.
Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only three values n, d and h:
* The tree had exactly n vertices.
* The tree had diameter d. In other words, d was the biggest distance between two vertices.
* Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex.
The distance between two vertices of the tree is the number of edges on the simple path between them.
Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1".
Input
The first line contains three integers n, d and h (2 ≤ n ≤ 100 000, 1 ≤ h ≤ d ≤ n - 1) — the number of vertices, diameter, and height after rooting in vertex 1, respectively.
Output
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes).
Otherwise, describe any tree matching Limak's description. Print n - 1 lines, each with two space-separated integers – indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
Examples
Input
5 3 2
Output
1 2
1 3
3 4
3 5
Input
8 5 2
Output
-1
Input
8 4 2
Output
4 8
5 7
2 3
8 1
2 1
5 6
1 5
Note
Below you can see trees printed to the output in the first sample and the third sample.
<image>
Submitted Solution:
```
n, d, h = map(int, input().strip().split())
if 2 * h < d:
print(-1)
exit()
for i in range(1, h + 1):
print(i, i + 1)
if d > h:
print(1, h + 2)
for i in range(h + 2, d + 1):
print(i, i + 1)
for i in range(d + 2, n + 1):
print(1, i)
else:
for i in range(d + 2, n + 1):
print(2, i)
``` | instruction | 0 | 50,948 | 13 | 101,896 |
No | output | 1 | 50,948 | 13 | 101,897 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.
Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only three values n, d and h:
* The tree had exactly n vertices.
* The tree had diameter d. In other words, d was the biggest distance between two vertices.
* Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex.
The distance between two vertices of the tree is the number of edges on the simple path between them.
Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1".
Input
The first line contains three integers n, d and h (2 ≤ n ≤ 100 000, 1 ≤ h ≤ d ≤ n - 1) — the number of vertices, diameter, and height after rooting in vertex 1, respectively.
Output
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes).
Otherwise, describe any tree matching Limak's description. Print n - 1 lines, each with two space-separated integers – indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
Examples
Input
5 3 2
Output
1 2
1 3
3 4
3 5
Input
8 5 2
Output
-1
Input
8 4 2
Output
4 8
5 7
2 3
8 1
2 1
5 6
1 5
Note
Below you can see trees printed to the output in the first sample and the third sample.
<image>
Submitted Solution:
```
def main():
n, d, h = map(int, input().split())
if h * 2 < d:
print(-1)
return
res, f = [], ' '.join
for e in (2, h + 2), (h + 2, d + 2):
a = "1"
for b in map(str, range(*e)):
res.append((f((a, b))))
a = b
res.extend("1 %d" % i for i in range(d + 2, n + 1))
print('\n'.join(res))
if __name__ == '__main__':
main()
``` | instruction | 0 | 50,949 | 13 | 101,898 |
No | output | 1 | 50,949 | 13 | 101,899 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.
Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only three values n, d and h:
* The tree had exactly n vertices.
* The tree had diameter d. In other words, d was the biggest distance between two vertices.
* Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex.
The distance between two vertices of the tree is the number of edges on the simple path between them.
Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1".
Input
The first line contains three integers n, d and h (2 ≤ n ≤ 100 000, 1 ≤ h ≤ d ≤ n - 1) — the number of vertices, diameter, and height after rooting in vertex 1, respectively.
Output
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes).
Otherwise, describe any tree matching Limak's description. Print n - 1 lines, each with two space-separated integers – indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
Examples
Input
5 3 2
Output
1 2
1 3
3 4
3 5
Input
8 5 2
Output
-1
Input
8 4 2
Output
4 8
5 7
2 3
8 1
2 1
5 6
1 5
Note
Below you can see trees printed to the output in the first sample and the third sample.
<image>
Submitted Solution:
```
n, d, h = map(int, input().split())
def F(a):
res = 0
for i in range(a + 1):
res += 2**i
return res
if (d > n - 1) or (d > 2*h) or (d < h):
print(-1)
else:
v = d - h
cur = 1
for i in range(v):
print(cur, cur + 1)
cur += 1
for i in range(h):
if i == 0:
print(1, cur + 1)
else:
print(cur, cur + 1)
cur += 1
a = n - d
if a != 0:
for i in range(a - 1):
print(1, 1 + i + cur)
``` | instruction | 0 | 50,950 | 13 | 101,900 |
No | output | 1 | 50,950 | 13 | 101,901 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.
Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only three values n, d and h:
* The tree had exactly n vertices.
* The tree had diameter d. In other words, d was the biggest distance between two vertices.
* Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex.
The distance between two vertices of the tree is the number of edges on the simple path between them.
Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1".
Input
The first line contains three integers n, d and h (2 ≤ n ≤ 100 000, 1 ≤ h ≤ d ≤ n - 1) — the number of vertices, diameter, and height after rooting in vertex 1, respectively.
Output
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes).
Otherwise, describe any tree matching Limak's description. Print n - 1 lines, each with two space-separated integers – indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
Examples
Input
5 3 2
Output
1 2
1 3
3 4
3 5
Input
8 5 2
Output
-1
Input
8 4 2
Output
4 8
5 7
2 3
8 1
2 1
5 6
1 5
Note
Below you can see trees printed to the output in the first sample and the third sample.
<image>
Submitted Solution:
```
n, d, h = map(int, input().split())
if d == h and n == d + 1 or d > h and 2*h >= d:
node = 1
while node < d + 1:
if node == h + 1:
print("{0} {1}".format(1, node + 1))
else:
print("{0} {1}".format(node, node + 1))
node += 1
node += 1
while node <= n:
print("{0} {1}".format(1, node))
node += 1
else:
print(-1)
``` | instruction | 0 | 50,951 | 13 | 101,902 |
No | output | 1 | 50,951 | 13 | 101,903 |
Provide a correct Python 3 solution for this coding contest problem.
Ikta has an extraordinary feeling for undirected graphs. Ikta likes the undirected graph G and its two-point s, t pair (G, s, t) that has the greatest "beauty". The "beauty" of a pair (G, s, t) is the edge e = \\ {u, v \\} (u and v are two different points of G), and the shortest path from s to t in G. Is the number of things whose length is greater than the length of the shortest path from s to t in the undirected graph with g plus e.
Your job is to write a program that seeks its "beauty" given a pair (G, s, t).
Input
The input is given in the following format.
> N M s t
> x1 y1
> ...
> xi yi
> ...
> xM yM
>
First, the number of vertices, the number of edges, and the integers N, M, s, t representing the two vertices of the undirected graph are input. From the 2nd line to the M + 1th line, two vertices connected by edges are input. (However, let the set of G vertices be \\ {1, ..., N \\}.)
Constraints
Each variable being input satisfies the following constraints.
* 2 ≤ N ≤ 100,000
* 1 ≤ M ≤ 300,000
* 1 ≤ s, t, xi, yi ≤ N
* Different from s and t
* Guaranteed to reach t from s
Output
When the given graph is G, output the "beauty" of the set (G, s, t) in one line.
Examples
Input
3 2 1 3
1 2
2 3
Output
1
Input
9 8 7 8
2 6
4 9
8 6
9 2
3 8
1 8
8 5
7 9
Output
7
Input
4 3 1 4
1 2
3 4
4 1
Output
0
Input
9 7 8 9
9 6
6 5
3 6
3 7
2 5
8 5
1 4
Output
2 | instruction | 0 | 51,265 | 13 | 102,530 |
"Correct Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def main():
n,m,s,t = LI()
xy = [LI() for _ in range(m)]
e = collections.defaultdict(list)
for x,y in xy:
e[x].append((y,1))
e[y].append((x,1))
def search(s):
d = collections.defaultdict(lambda: inf)
d[s] = 0
q = []
heapq.heappush(q, (0, s))
v = collections.defaultdict(bool)
while len(q):
k, u = heapq.heappop(q)
if v[u]:
continue
v[u] = True
for uv, ud in e[u]:
if v[uv]:
continue
vd = k + ud
if d[uv] > vd:
d[uv] = vd
heapq.heappush(q, (vd, uv))
return d
d1 = search(s)
d2 = search(t)
tt = d1[t]
if tt == 1:
return 0
if tt == 2:
return 1
v1 = collections.defaultdict(int)
v2 = collections.defaultdict(int)
for k,v in d1.items():
v1[v] += 1
for k,v in d2.items():
v2[v] += 1
r = 0
for i in range(tt-1):
r += v1[i] * v2[tt-i-2]
return r
print(main())
``` | output | 1 | 51,265 | 13 | 102,531 |
Provide a correct Python 3 solution for this coding contest problem.
Ikta has an extraordinary feeling for undirected graphs. Ikta likes the undirected graph G and its two-point s, t pair (G, s, t) that has the greatest "beauty". The "beauty" of a pair (G, s, t) is the edge e = \\ {u, v \\} (u and v are two different points of G), and the shortest path from s to t in G. Is the number of things whose length is greater than the length of the shortest path from s to t in the undirected graph with g plus e.
Your job is to write a program that seeks its "beauty" given a pair (G, s, t).
Input
The input is given in the following format.
> N M s t
> x1 y1
> ...
> xi yi
> ...
> xM yM
>
First, the number of vertices, the number of edges, and the integers N, M, s, t representing the two vertices of the undirected graph are input. From the 2nd line to the M + 1th line, two vertices connected by edges are input. (However, let the set of G vertices be \\ {1, ..., N \\}.)
Constraints
Each variable being input satisfies the following constraints.
* 2 ≤ N ≤ 100,000
* 1 ≤ M ≤ 300,000
* 1 ≤ s, t, xi, yi ≤ N
* Different from s and t
* Guaranteed to reach t from s
Output
When the given graph is G, output the "beauty" of the set (G, s, t) in one line.
Examples
Input
3 2 1 3
1 2
2 3
Output
1
Input
9 8 7 8
2 6
4 9
8 6
9 2
3 8
1 8
8 5
7 9
Output
7
Input
4 3 1 4
1 2
3 4
4 1
Output
0
Input
9 7 8 9
9 6
6 5
3 6
3 7
2 5
8 5
1 4
Output
2 | instruction | 0 | 51,266 | 13 | 102,532 |
"Correct Solution:
```
N, M, s, t = map(int, input().split())
E = [[] for _ in range(N+1)]
for _ in range(M):
x, y = map(int, input().split())
E[x].append(y)
E[y].append(x)
closed = [False] * (N+1)
closed[s] = True
dist = [float("inf")] * (N+1)
q = [s]
for dist_ in range(N):
q_new = []
for v in q:
dist[v] = dist_
for u in E[v]:
if closed[u]:
continue
closed[u] = True
q_new.append(u)
q = q_new
if len(q) == 0:
break
dist_st = dist[t]
closed = [False] * (N+1)
closed[t] = True
dist_t = [float("inf")] * (N+1)
q = [t]
for dist_ in range(N):
q_new = []
for v in q:
dist_t[v] = dist_
for u in E[v]:
if closed[u]:
continue
closed[u] = True
q_new.append(u)
q = q_new
if len(q) == 0:
break
ds = [0] * (dist_st-1)
dt = [0] * (dist_st-1)
for d in dist:
if d < (dist_st-1):
ds[d] += 1
for d in dist_t:
if d < (dist_st-1):
dt[d] += 1
ans = 0
for a, b in zip(ds, dt[::-1]):
ans += a*b
print(ans)
``` | output | 1 | 51,266 | 13 | 102,533 |
Provide a correct Python 3 solution for this coding contest problem.
Ikta has an extraordinary feeling for undirected graphs. Ikta likes the undirected graph G and its two-point s, t pair (G, s, t) that has the greatest "beauty". The "beauty" of a pair (G, s, t) is the edge e = \\ {u, v \\} (u and v are two different points of G), and the shortest path from s to t in G. Is the number of things whose length is greater than the length of the shortest path from s to t in the undirected graph with g plus e.
Your job is to write a program that seeks its "beauty" given a pair (G, s, t).
Input
The input is given in the following format.
> N M s t
> x1 y1
> ...
> xi yi
> ...
> xM yM
>
First, the number of vertices, the number of edges, and the integers N, M, s, t representing the two vertices of the undirected graph are input. From the 2nd line to the M + 1th line, two vertices connected by edges are input. (However, let the set of G vertices be \\ {1, ..., N \\}.)
Constraints
Each variable being input satisfies the following constraints.
* 2 ≤ N ≤ 100,000
* 1 ≤ M ≤ 300,000
* 1 ≤ s, t, xi, yi ≤ N
* Different from s and t
* Guaranteed to reach t from s
Output
When the given graph is G, output the "beauty" of the set (G, s, t) in one line.
Examples
Input
3 2 1 3
1 2
2 3
Output
1
Input
9 8 7 8
2 6
4 9
8 6
9 2
3 8
1 8
8 5
7 9
Output
7
Input
4 3 1 4
1 2
3 4
4 1
Output
0
Input
9 7 8 9
9 6
6 5
3 6
3 7
2 5
8 5
1 4
Output
2 | instruction | 0 | 51,267 | 13 | 102,534 |
"Correct Solution:
```
# AOJ 2608: Minus One
# Python3 2018.6.30 bal4u
import heapq
MAX = 0x7fffffff
def dijkstra(dist, start):
Q = []
dist[start] = 0
heapq.heappush(Q, (0, start))
while Q:
t, s = heapq.heappop(Q)
if dist[s] < t: continue
for e in to[s]:
nt = t + 1
if dist[e] > nt:
dist[e] = nt
heapq.heappush(Q, (nt, e))
N, M, s, t = map(int, input().split())
s, t = s-1, t-1
to = [[] for i in range(N)]
for i in range(M):
x, y = map(int, input().split())
x, y = x-1, y-1
to[x].append(y)
to[y].append(x)
smin = [MAX]*N
dijkstra(smin, s)
tmin = [MAX]*N
dijkstra(tmin, t)
scnt = [0]*N
tcnt = [0]*N
for i in range(N):
if smin[i] < N: scnt[smin[i]] += 1
if tmin[i] < N: tcnt[tmin[i]] += 1
ans = 0
s = smin[t]-1
for i in range(s): ans += scnt[i]*tcnt[s-1-i]
print(ans)
``` | output | 1 | 51,267 | 13 | 102,535 |
Provide a correct Python 3 solution for this coding contest problem.
Ikta has an extraordinary feeling for undirected graphs. Ikta likes the undirected graph G and its two-point s, t pair (G, s, t) that has the greatest "beauty". The "beauty" of a pair (G, s, t) is the edge e = \\ {u, v \\} (u and v are two different points of G), and the shortest path from s to t in G. Is the number of things whose length is greater than the length of the shortest path from s to t in the undirected graph with g plus e.
Your job is to write a program that seeks its "beauty" given a pair (G, s, t).
Input
The input is given in the following format.
> N M s t
> x1 y1
> ...
> xi yi
> ...
> xM yM
>
First, the number of vertices, the number of edges, and the integers N, M, s, t representing the two vertices of the undirected graph are input. From the 2nd line to the M + 1th line, two vertices connected by edges are input. (However, let the set of G vertices be \\ {1, ..., N \\}.)
Constraints
Each variable being input satisfies the following constraints.
* 2 ≤ N ≤ 100,000
* 1 ≤ M ≤ 300,000
* 1 ≤ s, t, xi, yi ≤ N
* Different from s and t
* Guaranteed to reach t from s
Output
When the given graph is G, output the "beauty" of the set (G, s, t) in one line.
Examples
Input
3 2 1 3
1 2
2 3
Output
1
Input
9 8 7 8
2 6
4 9
8 6
9 2
3 8
1 8
8 5
7 9
Output
7
Input
4 3 1 4
1 2
3 4
4 1
Output
0
Input
9 7 8 9
9 6
6 5
3 6
3 7
2 5
8 5
1 4
Output
2 | instruction | 0 | 51,268 | 13 | 102,536 |
"Correct Solution:
```
import heapq
def dijkstra_heap(s):
d = [float("inf")] * n
used = [True] * n
d[s] = 0
used[s] = False
edgelist = []
for e in edge[s]:
heapq.heappush(edgelist,e)
while len(edgelist):
minedge = heapq.heappop(edgelist)
if not used[minedge[1]]:
continue
v = minedge[1]
d[v] = minedge[0]
used[v] = False
for e in edge[v]:
if used[e[1]]:
heapq.heappush(edgelist,(e[0]+d[v],e[1]))
return d
n,w,s,t = map(int,input().split())
edge = [[] for i in range(n)]
for i in range(w):
x,y = map(int,input().split())
edge[x-1].append((1,y-1))
edge[y-1].append((1,x-1))
a,b = [0]*n,[0]*n
x = dijkstra_heap(s-1)
y = dijkstra_heap(t-1)
distance = x[t-1] - 1
for t in x:
if t < n:
a[t] += 1
for t in y:
if t < n:
b[t] += 1
ans = 0
for i in range(distance + 1):
if distance - i > 0:
ans += a[i] * b[distance - i - 1]
print(ans)
``` | output | 1 | 51,268 | 13 | 102,537 |
Provide a correct Python 3 solution for this coding contest problem.
Ikta has an extraordinary feeling for undirected graphs. Ikta likes the undirected graph G and its two-point s, t pair (G, s, t) that has the greatest "beauty". The "beauty" of a pair (G, s, t) is the edge e = \\ {u, v \\} (u and v are two different points of G), and the shortest path from s to t in G. Is the number of things whose length is greater than the length of the shortest path from s to t in the undirected graph with g plus e.
Your job is to write a program that seeks its "beauty" given a pair (G, s, t).
Input
The input is given in the following format.
> N M s t
> x1 y1
> ...
> xi yi
> ...
> xM yM
>
First, the number of vertices, the number of edges, and the integers N, M, s, t representing the two vertices of the undirected graph are input. From the 2nd line to the M + 1th line, two vertices connected by edges are input. (However, let the set of G vertices be \\ {1, ..., N \\}.)
Constraints
Each variable being input satisfies the following constraints.
* 2 ≤ N ≤ 100,000
* 1 ≤ M ≤ 300,000
* 1 ≤ s, t, xi, yi ≤ N
* Different from s and t
* Guaranteed to reach t from s
Output
When the given graph is G, output the "beauty" of the set (G, s, t) in one line.
Examples
Input
3 2 1 3
1 2
2 3
Output
1
Input
9 8 7 8
2 6
4 9
8 6
9 2
3 8
1 8
8 5
7 9
Output
7
Input
4 3 1 4
1 2
3 4
4 1
Output
0
Input
9 7 8 9
9 6
6 5
3 6
3 7
2 5
8 5
1 4
Output
2 | instruction | 0 | 51,269 | 13 | 102,538 |
"Correct Solution:
```
#!usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS():return list(map(list, sys.stdin.readline().split()))
def S(): return list(sys.stdin.readline())[:-1]
def IR(n):
l = [None for i in range(n)]
for i in range(n):l[i] = I()
return l
def LIR(n):
l = [None for i in range(n)]
for i in range(n):l[i] = LI()
return l
def SR(n):
l = [None for i in range(n)]
for i in range(n):l[i] = S()
return l
def LSR(n):
l = [None for i in range(n)]
for i in range(n):l[i] = LS()
return l
sys.setrecursionlimit(1000000)
mod = 1000000007
#A
def A():
while 1:
n = I()
if n == 0:
quit()
a = LI()
m = sum(a)/n
c = 0
for i in range(n):
if a[i] <= m:
c += 1
print(c)
return
#B
def B():
while 1:
n = I()
if n == 0:
quit()
t = [0 for i in range(24*3600)]
for i in range(n):
x,y = input().split()
x = list(map(int, x.split(":")))
y = list(map(int, y.split(":")))
l = x[0]*3600+x[1]*60+x[2]
r = y[0]*3600+y[1]*60+y[2]
t[l] += 1
t[r] -= 1
ans = 0
for i in range(24*3600-1):
t[i+1] += t[i]
ans = max(ans, t[i])
print(ans)
return
#C
def C():
n = I()
if n == 0:
print(1)
elif n == 1:
print(2)
elif n == 2:
print(1)
else:
print(0)
return
#D
def D():
def dijkstra(s):
d = [float("inf") for i in range(n)]
q = [[0,s]]
d[s] = 0
while q:
dx,x = heappop(q)
for y in v[x]:
if dx+1 < d[y]:
d[y] = d[x]+1
heappush(q,[d[y],y])
return d
n,m,s,t = LI()
s -= 1
t -= 1
v = [[] for i in range(n)]
for i in range(m):
x,y = LI()
x -= 1
y -= 1
v[x].append(y)
v[y].append(x)
l = dijkstra(s)
l2 = dijkstra(t)
k = l[t]-2
d = defaultdict(int)
ans = 0
for i in l2:
d[i] += 1
for i in l:
ans += d[max(-1,k-i)]
print(ans)
return
#E
def E():
return
#F
def F():
return
#G
def G():
return
#H
def H():
return
#I
def I_():
return
#J
def J():
return
#Solve
if __name__ == "__main__":
D()
``` | output | 1 | 51,269 | 13 | 102,539 |
Provide a correct Python 3 solution for this coding contest problem.
Ikta has an extraordinary feeling for undirected graphs. Ikta likes the undirected graph G and its two-point s, t pair (G, s, t) that has the greatest "beauty". The "beauty" of a pair (G, s, t) is the edge e = \\ {u, v \\} (u and v are two different points of G), and the shortest path from s to t in G. Is the number of things whose length is greater than the length of the shortest path from s to t in the undirected graph with g plus e.
Your job is to write a program that seeks its "beauty" given a pair (G, s, t).
Input
The input is given in the following format.
> N M s t
> x1 y1
> ...
> xi yi
> ...
> xM yM
>
First, the number of vertices, the number of edges, and the integers N, M, s, t representing the two vertices of the undirected graph are input. From the 2nd line to the M + 1th line, two vertices connected by edges are input. (However, let the set of G vertices be \\ {1, ..., N \\}.)
Constraints
Each variable being input satisfies the following constraints.
* 2 ≤ N ≤ 100,000
* 1 ≤ M ≤ 300,000
* 1 ≤ s, t, xi, yi ≤ N
* Different from s and t
* Guaranteed to reach t from s
Output
When the given graph is G, output the "beauty" of the set (G, s, t) in one line.
Examples
Input
3 2 1 3
1 2
2 3
Output
1
Input
9 8 7 8
2 6
4 9
8 6
9 2
3 8
1 8
8 5
7 9
Output
7
Input
4 3 1 4
1 2
3 4
4 1
Output
0
Input
9 7 8 9
9 6
6 5
3 6
3 7
2 5
8 5
1 4
Output
2 | instruction | 0 | 51,270 | 13 | 102,540 |
"Correct Solution:
```
# coding: utf-8
import queue
n,m,s,t=map(int,input().split())
table=[[] for i in range(n)]
inf=300001
dist_s=[inf for i in range(n)]
dist_t=[inf for i in range(n)]
s_list=[0 for i in range(inf+1)]
t_list=[0 for i in range(inf+1)]
s-=1;t-=1
for i in range(m):
a,b=map(int,input().split())
a-=1;b-=1
table[a].append(b)
table[b].append(a)
dist_s[s]=0
q=queue.Queue()
q.put(s)
while not q.empty():
p=q.get()
for e in table[p]:
if dist_s[e]>dist_s[p]+1:
dist_s[e]=dist_s[p]+1
q.put(e)
dist_t[t]=0
q=queue.Queue()
q.put(t)
while not q.empty():
p=q.get()
for e in table[p]:
if dist_t[e]>dist_t[p]+1:
dist_t[e]=dist_t[p]+1
q.put(e)
for i in range(n):
s_list[dist_s[i]]+=1
t_list[dist_t[i]]+=1
mindist=dist_s[t]
ans=0
for i in range(mindist-1):
ans+=s_list[i]*t_list[(mindist-2)-i]
print(ans)
``` | output | 1 | 51,270 | 13 | 102,541 |
Provide a correct Python 3 solution for this coding contest problem.
Ikta has an extraordinary feeling for undirected graphs. Ikta likes the undirected graph G and its two-point s, t pair (G, s, t) that has the greatest "beauty". The "beauty" of a pair (G, s, t) is the edge e = \\ {u, v \\} (u and v are two different points of G), and the shortest path from s to t in G. Is the number of things whose length is greater than the length of the shortest path from s to t in the undirected graph with g plus e.
Your job is to write a program that seeks its "beauty" given a pair (G, s, t).
Input
The input is given in the following format.
> N M s t
> x1 y1
> ...
> xi yi
> ...
> xM yM
>
First, the number of vertices, the number of edges, and the integers N, M, s, t representing the two vertices of the undirected graph are input. From the 2nd line to the M + 1th line, two vertices connected by edges are input. (However, let the set of G vertices be \\ {1, ..., N \\}.)
Constraints
Each variable being input satisfies the following constraints.
* 2 ≤ N ≤ 100,000
* 1 ≤ M ≤ 300,000
* 1 ≤ s, t, xi, yi ≤ N
* Different from s and t
* Guaranteed to reach t from s
Output
When the given graph is G, output the "beauty" of the set (G, s, t) in one line.
Examples
Input
3 2 1 3
1 2
2 3
Output
1
Input
9 8 7 8
2 6
4 9
8 6
9 2
3 8
1 8
8 5
7 9
Output
7
Input
4 3 1 4
1 2
3 4
4 1
Output
0
Input
9 7 8 9
9 6
6 5
3 6
3 7
2 5
8 5
1 4
Output
2 | instruction | 0 | 51,271 | 13 | 102,542 |
"Correct Solution:
```
from collections import deque, defaultdict
n, m, s, t = map(int, input().split())
s -= 1
t -= 1
edges = [[] for _ in range(n)]
for _ in range(m):
x, y = map(int, input().split())
x -= 1
y -= 1
edges[x].append(y)
edges[y].append(x)
def dist_from(s):
INF = 10 ** 20
dist = [INF] * n
dist[s] = 0
que = deque()
que.append((0, s))
while que:
score, node = que.popleft()
for to in edges[node]:
if dist[to] > score + 1:
dist[to] = score + 1
que.append((score + 1, to))
return dist
dist_from_s = dist_from(s)
dic1 = {}
for i, d in enumerate(dist_from_s):
if d in dic1:
dic1[d].add(i)
else:
dic1[d] = {i}
dist_from_t = dist_from(t)
dic2 = {}
for i, d in enumerate(dist_from_t):
if d in dic2:
dic2[d].add(i)
else:
dic2[d] = {i}
st_dist = dist_from_s[t]
ans = 0
for key in dic1:
another_key = st_dist - key - 2
if another_key in dic2:
add = len(dic1[key]) * len(dic2[another_key])
for u in dic1[key]:
for to in edges[u]:
if to in dic2[another_key]:
add -= 1
ans += add
print(ans)
``` | output | 1 | 51,271 | 13 | 102,543 |
Provide a correct Python 3 solution for this coding contest problem.
A rooted binary tree is a tree with a root node in which every node has at most two children.
Your task is to write a program which reads a rooted binary tree T and prints the following information for each node u of T:
* node ID of u
* parent of u
* sibling of u
* the number of children of u
* depth of u
* height of u
* node type (root, internal node or leaf)
If two nodes have the same parent, they are siblings. Here, if u and v have the same parent, we say u is a sibling of v (vice versa).
The height of a node in a tree is the number of edges on the longest simple downward path from the node to a leaf.
Here, the given binary tree consists of n nodes and evey node has a unique ID from 0 to n-1.
Constraints
* 1 ≤ n ≤ 25
Input
The first line of the input includes an integer n, the number of nodes of the tree.
In the next n lines, the information of each node is given in the following format:
id left right
id is the node ID, left is ID of the left child and right is ID of the right child. If the node does not have the left (right) child, the left(right) is indicated by -1.
Output
Print the information of each node in the following format:
node id: parent = p, sibling = s, degree = deg, depth = dep, height = h, type
p is ID of its parent. If the node does not have a parent, print -1.
s is ID of its sibling. If the node does not have a sibling, print -1.
deg, dep and h are the number of children, depth and height of the node respectively.
type is a type of nodes represented by a string (root, internal node or leaf. If the root can be considered as a leaf or an internal node, print root.
Please follow the format presented in a sample output below.
Example
Input
9
0 1 4
1 2 3
2 -1 -1
3 -1 -1
4 5 8
5 6 7
6 -1 -1
7 -1 -1
8 -1 -1
Output
node 0: parent = -1, sibling = -1, degree = 2, depth = 0, height = 3, root
node 1: parent = 0, sibling = 4, degree = 2, depth = 1, height = 1, internal node
node 2: parent = 1, sibling = 3, degree = 0, depth = 2, height = 0, leaf
node 3: parent = 1, sibling = 2, degree = 0, depth = 2, height = 0, leaf
node 4: parent = 0, sibling = 1, degree = 2, depth = 1, height = 2, internal node
node 5: parent = 4, sibling = 8, degree = 2, depth = 2, height = 1, internal node
node 6: parent = 5, sibling = 7, degree = 0, depth = 3, height = 0, leaf
node 7: parent = 5, sibling = 6, degree = 0, depth = 3, height = 0, leaf
node 8: parent = 4, sibling = 5, degree = 0, depth = 2, height = 0, leaf | instruction | 0 | 51,276 | 13 | 102,552 |
"Correct Solution:
```
class Node():
def __init__(self):
self.parent = -1
self.left = -1
self.right = -1
def get_depth(u, p):
D[u] = p
if result[u].right is not None:
get_depth(result[u].right, p)
if result[u].left is not None:
get_depth(result[u].left, p+1)
def get_depth_1(u, p):
i = u
d = 0
while result[u].parent != -1:
u = result[u].parent
d += 1
D[i] = d
def get_hight(H, u):
lh, rh = 0, 0
if result[u].left != -1:
lh = get_hight(H, result[u].left)+1
if result[u].right != -1:
rh = get_hight(H, result[u].right)+1
H[u] = max(lh, rh)
return H[u]
n = int(input())
node = [list(map(int, input().split())) for _ in range(n)]
result = [Node() for _ in range(n)]
D = [0 for _ in range(n)]
H = [0 for _ in range(n)]
def initiate(li):
for l in li:
n = l[0]
left = l[1]
right = l[2]
if left != -1:
result[left].parent = n
result[n].left = left
if right != -1:
result[right].parent = n
result[n].right = right
initiate(node)
for u in range(n):
get_depth_1(u, 0)
for u in range(n):
get_hight(H, u)
final = []
for i in range(n):
node = i
parent = result[node].parent
depth = D[i]
height = H[i]
degree = 0
if result[node].left == -1 and result[node].right == -1:
typ = "leaf"
degree = 0
elif result[node].left >= 0 and result[node].right >= 0:
typ = "internal node"
degree = 2
else:
degree = 1
typ = "internal node"
if parent == -1:
typ = "root"
if result[parent].left == node:
sibling = result[parent].right
else:
sibling = result[parent].left
print("node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}".format(node, parent, sibling, degree, depth, height, typ))
``` | output | 1 | 51,276 | 13 | 102,553 |
Provide a correct Python 3 solution for this coding contest problem.
A rooted binary tree is a tree with a root node in which every node has at most two children.
Your task is to write a program which reads a rooted binary tree T and prints the following information for each node u of T:
* node ID of u
* parent of u
* sibling of u
* the number of children of u
* depth of u
* height of u
* node type (root, internal node or leaf)
If two nodes have the same parent, they are siblings. Here, if u and v have the same parent, we say u is a sibling of v (vice versa).
The height of a node in a tree is the number of edges on the longest simple downward path from the node to a leaf.
Here, the given binary tree consists of n nodes and evey node has a unique ID from 0 to n-1.
Constraints
* 1 ≤ n ≤ 25
Input
The first line of the input includes an integer n, the number of nodes of the tree.
In the next n lines, the information of each node is given in the following format:
id left right
id is the node ID, left is ID of the left child and right is ID of the right child. If the node does not have the left (right) child, the left(right) is indicated by -1.
Output
Print the information of each node in the following format:
node id: parent = p, sibling = s, degree = deg, depth = dep, height = h, type
p is ID of its parent. If the node does not have a parent, print -1.
s is ID of its sibling. If the node does not have a sibling, print -1.
deg, dep and h are the number of children, depth and height of the node respectively.
type is a type of nodes represented by a string (root, internal node or leaf. If the root can be considered as a leaf or an internal node, print root.
Please follow the format presented in a sample output below.
Example
Input
9
0 1 4
1 2 3
2 -1 -1
3 -1 -1
4 5 8
5 6 7
6 -1 -1
7 -1 -1
8 -1 -1
Output
node 0: parent = -1, sibling = -1, degree = 2, depth = 0, height = 3, root
node 1: parent = 0, sibling = 4, degree = 2, depth = 1, height = 1, internal node
node 2: parent = 1, sibling = 3, degree = 0, depth = 2, height = 0, leaf
node 3: parent = 1, sibling = 2, degree = 0, depth = 2, height = 0, leaf
node 4: parent = 0, sibling = 1, degree = 2, depth = 1, height = 2, internal node
node 5: parent = 4, sibling = 8, degree = 2, depth = 2, height = 1, internal node
node 6: parent = 5, sibling = 7, degree = 0, depth = 3, height = 0, leaf
node 7: parent = 5, sibling = 6, degree = 0, depth = 3, height = 0, leaf
node 8: parent = 4, sibling = 5, degree = 0, depth = 2, height = 0, leaf | instruction | 0 | 51,277 | 13 | 102,554 |
"Correct Solution:
```
class node:
def __init__(self, parent, left, right, depth, height):
self.p = parent
self.l = left
self.r = right
self.d = depth
self.h = height
def setDepth(u, depthPosition):
if u == -1:
return
T[u].d = depthPosition
setDepth(T[u].r, depthPosition + 1)
setDepth(T[u].l, depthPosition + 1)
def setHeight(u):
h1 = h2 = 0
if T[u].r != -1:
h1 = setHeight(T[u].r) + 1
if T[u].l != -1:
h2 = setHeight(T[u].l) + 1
T[u].h = max(h1, h2)
return max(h1, h2)
def getDegree(u):
degree = 0
if T[u].r != -1:
degree += 1
if T[u].l != -1:
degree += 1
return degree
def getSibling(u):
if T[u].p == -1:
return -1
if T[T[u].p].l != u and T[T[u].p].l != -1:
return T[T[u].p].l
if T[T[u].p].r != u and T[T[u].p].r != -1:
return T[T[u].p].r
return -1
n = int(input())
T = [node(-1, -1, -1, 0, 0) for _ in range(n)]
for _ in range(n):
info = list(map(int, input().split(" ")))
T[info[0]].l = info[1]
T[info[0]].r = info[2]
if info[1] != -1:
T[info[1]].p = info[0]
if info[2] != -1:
T[info[2]].p = info[0]
for x in T:
if x.p == -1:
setDepth(T.index(x), 0)
setHeight(T.index(x))
for i in range(n):
print("node", end = ' ')
print(i, end = ': ')
print("parent =", end = ' ')
print(T[i].p, end = ', ')
print("sibling =", end = ' ')
print(getSibling(i), end = ', ')
print("degree =", end = ' ')
print(getDegree(i), end = ', ')
print("depth =", end = ' ')
print(T[i].d, end = ', ')
print("height =", end = ' ')
print(T[i].h, end = ', ')
if T[i].p == -1: print("root")
elif T[i].r == -1 and T[i].l == -1: print("leaf")
else: print("internal node")
``` | output | 1 | 51,277 | 13 | 102,555 |
Provide a correct Python 3 solution for this coding contest problem.
A rooted binary tree is a tree with a root node in which every node has at most two children.
Your task is to write a program which reads a rooted binary tree T and prints the following information for each node u of T:
* node ID of u
* parent of u
* sibling of u
* the number of children of u
* depth of u
* height of u
* node type (root, internal node or leaf)
If two nodes have the same parent, they are siblings. Here, if u and v have the same parent, we say u is a sibling of v (vice versa).
The height of a node in a tree is the number of edges on the longest simple downward path from the node to a leaf.
Here, the given binary tree consists of n nodes and evey node has a unique ID from 0 to n-1.
Constraints
* 1 ≤ n ≤ 25
Input
The first line of the input includes an integer n, the number of nodes of the tree.
In the next n lines, the information of each node is given in the following format:
id left right
id is the node ID, left is ID of the left child and right is ID of the right child. If the node does not have the left (right) child, the left(right) is indicated by -1.
Output
Print the information of each node in the following format:
node id: parent = p, sibling = s, degree = deg, depth = dep, height = h, type
p is ID of its parent. If the node does not have a parent, print -1.
s is ID of its sibling. If the node does not have a sibling, print -1.
deg, dep and h are the number of children, depth and height of the node respectively.
type is a type of nodes represented by a string (root, internal node or leaf. If the root can be considered as a leaf or an internal node, print root.
Please follow the format presented in a sample output below.
Example
Input
9
0 1 4
1 2 3
2 -1 -1
3 -1 -1
4 5 8
5 6 7
6 -1 -1
7 -1 -1
8 -1 -1
Output
node 0: parent = -1, sibling = -1, degree = 2, depth = 0, height = 3, root
node 1: parent = 0, sibling = 4, degree = 2, depth = 1, height = 1, internal node
node 2: parent = 1, sibling = 3, degree = 0, depth = 2, height = 0, leaf
node 3: parent = 1, sibling = 2, degree = 0, depth = 2, height = 0, leaf
node 4: parent = 0, sibling = 1, degree = 2, depth = 1, height = 2, internal node
node 5: parent = 4, sibling = 8, degree = 2, depth = 2, height = 1, internal node
node 6: parent = 5, sibling = 7, degree = 0, depth = 3, height = 0, leaf
node 7: parent = 5, sibling = 6, degree = 0, depth = 3, height = 0, leaf
node 8: parent = 4, sibling = 5, degree = 0, depth = 2, height = 0, leaf | instruction | 0 | 51,278 | 13 | 102,556 |
"Correct Solution:
```
N = int(input())
binary_tree = [{"parent": -1, "sibling": -1} for _ in range(N)]
for _ in range(N):
node_input = input()
id, left, right = map(int, node_input.split())
binary_tree[id]["left"] = left
binary_tree[id]["right"] = right
degree = 0
if left != -1:
degree += 1
binary_tree[left]["parent"] = id
binary_tree[left]["sibling"] = right
if right != -1:
degree += 1
binary_tree[right]["parent"] = id
binary_tree[right]["sibling"] = left
binary_tree[id]["degree"] = degree
def measure_depth_and_height(id, depth):
H[id] = max(H[id], depth)
parent_id = binary_tree[id]["parent"]
if parent_id == -1:
return depth
return measure_depth_and_height(parent_id, depth+1)
D = [0 for i in range(N)]
H = [0 for i in range(N)]
for id in range(N):
depth = measure_depth_and_height(id, 0)
D[id] = depth
def get_type(node):
if node["parent"] == -1:
return "root"
if node["degree"] == 0:
return "leaf"
return "internal node"
for id in range(N):
node = binary_tree[id]
parent_id = node["parent"]
sibling_id = node["sibling"]
degree = node["degree"]
node_type = get_type(node)
print("node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}".format(id, parent_id, sibling_id, degree, D[id], H[id], node_type))
``` | output | 1 | 51,278 | 13 | 102,557 |
Provide a correct Python 3 solution for this coding contest problem.
A rooted binary tree is a tree with a root node in which every node has at most two children.
Your task is to write a program which reads a rooted binary tree T and prints the following information for each node u of T:
* node ID of u
* parent of u
* sibling of u
* the number of children of u
* depth of u
* height of u
* node type (root, internal node or leaf)
If two nodes have the same parent, they are siblings. Here, if u and v have the same parent, we say u is a sibling of v (vice versa).
The height of a node in a tree is the number of edges on the longest simple downward path from the node to a leaf.
Here, the given binary tree consists of n nodes and evey node has a unique ID from 0 to n-1.
Constraints
* 1 ≤ n ≤ 25
Input
The first line of the input includes an integer n, the number of nodes of the tree.
In the next n lines, the information of each node is given in the following format:
id left right
id is the node ID, left is ID of the left child and right is ID of the right child. If the node does not have the left (right) child, the left(right) is indicated by -1.
Output
Print the information of each node in the following format:
node id: parent = p, sibling = s, degree = deg, depth = dep, height = h, type
p is ID of its parent. If the node does not have a parent, print -1.
s is ID of its sibling. If the node does not have a sibling, print -1.
deg, dep and h are the number of children, depth and height of the node respectively.
type is a type of nodes represented by a string (root, internal node or leaf. If the root can be considered as a leaf or an internal node, print root.
Please follow the format presented in a sample output below.
Example
Input
9
0 1 4
1 2 3
2 -1 -1
3 -1 -1
4 5 8
5 6 7
6 -1 -1
7 -1 -1
8 -1 -1
Output
node 0: parent = -1, sibling = -1, degree = 2, depth = 0, height = 3, root
node 1: parent = 0, sibling = 4, degree = 2, depth = 1, height = 1, internal node
node 2: parent = 1, sibling = 3, degree = 0, depth = 2, height = 0, leaf
node 3: parent = 1, sibling = 2, degree = 0, depth = 2, height = 0, leaf
node 4: parent = 0, sibling = 1, degree = 2, depth = 1, height = 2, internal node
node 5: parent = 4, sibling = 8, degree = 2, depth = 2, height = 1, internal node
node 6: parent = 5, sibling = 7, degree = 0, depth = 3, height = 0, leaf
node 7: parent = 5, sibling = 6, degree = 0, depth = 3, height = 0, leaf
node 8: parent = 4, sibling = 5, degree = 0, depth = 2, height = 0, leaf | instruction | 0 | 51,279 | 13 | 102,558 |
"Correct Solution:
```
def binary(node,parent,sibling,depth,root):
if node!=-1:
id,left,right=A[node]
degree = len([i for i in (right, left) if i != -1])
if parent==-1:root="root"
elif degree!=0:root="internal node"
else:root="leaf"
B.append([node,parent,sibling,degree,depth,root])
binary(left,node,right,depth+1,root)
binary(right,node,left,depth+1,root)
def setHight(H,u):
h1,h2=0,0
if A[u][2]!=-1:
h1=setHight(H,A[u][2])+1
if A[u][1]!=-1:
h2=setHight(H,A[u][1])+1
H[u]=max(h1,h2)
return H[u]
n=int(input())
A=[list(map(int,input().split())) for i in range(n)]
B,H=[],[0]*n
top=[i for i in range(n)]
for i in range(n):
for j in (A[i][1],A[i][2]):
if j!=-1:top.remove(j)
top=top[0]
A=sorted(A)
binary(top,-1,-1,0,"root")
setHight(H,top)
for j,i in enumerate(sorted(B)):
print("node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}"
.format(i[0],i[1],i[2],i[3],i[4],H[j],i[5]))
``` | output | 1 | 51,279 | 13 | 102,559 |
Provide a correct Python 3 solution for this coding contest problem.
A rooted binary tree is a tree with a root node in which every node has at most two children.
Your task is to write a program which reads a rooted binary tree T and prints the following information for each node u of T:
* node ID of u
* parent of u
* sibling of u
* the number of children of u
* depth of u
* height of u
* node type (root, internal node or leaf)
If two nodes have the same parent, they are siblings. Here, if u and v have the same parent, we say u is a sibling of v (vice versa).
The height of a node in a tree is the number of edges on the longest simple downward path from the node to a leaf.
Here, the given binary tree consists of n nodes and evey node has a unique ID from 0 to n-1.
Constraints
* 1 ≤ n ≤ 25
Input
The first line of the input includes an integer n, the number of nodes of the tree.
In the next n lines, the information of each node is given in the following format:
id left right
id is the node ID, left is ID of the left child and right is ID of the right child. If the node does not have the left (right) child, the left(right) is indicated by -1.
Output
Print the information of each node in the following format:
node id: parent = p, sibling = s, degree = deg, depth = dep, height = h, type
p is ID of its parent. If the node does not have a parent, print -1.
s is ID of its sibling. If the node does not have a sibling, print -1.
deg, dep and h are the number of children, depth and height of the node respectively.
type is a type of nodes represented by a string (root, internal node or leaf. If the root can be considered as a leaf or an internal node, print root.
Please follow the format presented in a sample output below.
Example
Input
9
0 1 4
1 2 3
2 -1 -1
3 -1 -1
4 5 8
5 6 7
6 -1 -1
7 -1 -1
8 -1 -1
Output
node 0: parent = -1, sibling = -1, degree = 2, depth = 0, height = 3, root
node 1: parent = 0, sibling = 4, degree = 2, depth = 1, height = 1, internal node
node 2: parent = 1, sibling = 3, degree = 0, depth = 2, height = 0, leaf
node 3: parent = 1, sibling = 2, degree = 0, depth = 2, height = 0, leaf
node 4: parent = 0, sibling = 1, degree = 2, depth = 1, height = 2, internal node
node 5: parent = 4, sibling = 8, degree = 2, depth = 2, height = 1, internal node
node 6: parent = 5, sibling = 7, degree = 0, depth = 3, height = 0, leaf
node 7: parent = 5, sibling = 6, degree = 0, depth = 3, height = 0, leaf
node 8: parent = 4, sibling = 5, degree = 0, depth = 2, height = 0, leaf | instruction | 0 | 51,280 | 13 | 102,560 |
"Correct Solution:
```
#http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_7_B&lang=jp
def cal_depth(binary_tree, target_index, depth, parent, sibling):
if target_index == -1:
return 0
binary_tree[target_index]["depth"] = depth
binary_tree[target_index]["parent"] = parent
binary_tree[target_index]["sibling"] = sibling
height_left = cal_depth(binary_tree, binary_tree[target_index]["left"], depth + 1, target_index, binary_tree[target_index]["right"])
height_right = cal_depth(binary_tree, binary_tree[target_index]["right"], depth + 1, target_index, binary_tree[target_index]["left"])
height = max(height_left, height_right)
binary_tree[target_index]["height"] = height
return height + 1
def solve(node_data, node_num):
binary_tree = [{"left":-1, "right":-1, "depth":0, "parent":-1, "sibling":-1, "height":0, "degree":0} for a in range(node_num)]
root_index = sum([i for i in range(node_num)])
for node in node_data:
binary_tree[node[0]]["left"] = node[1]
binary_tree[node[0]]["right"] = node[2]
if not node[1] == -1:
root_index -= node[1]
binary_tree[node[0]]["degree"] += 1
if not node[2] == -1:
root_index -= node[2]
binary_tree[node[0]]["degree"] += 1
cal_depth(binary_tree, root_index, 0, -1,-1)
return binary_tree
def main():
node_num = int(input())
node_data = [[int(a) for a in input().split()] for i in range(node_num)]
binary_tree = solve(node_data, node_num)
for i, node in enumerate(binary_tree):
node_type = "root"
if node["left"] == -1 and node["right"] == -1 and not node["parent"] == -1:
node_type = "leaf"
elif not node["parent"] == -1:
node_type = "internal node"
print("node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}".format(i, node["parent"], node["sibling"], node["degree"], node["depth"], node["height"], node_type))
if __name__ == "__main__":
main()
``` | output | 1 | 51,280 | 13 | 102,561 |
Provide a correct Python 3 solution for this coding contest problem.
A rooted binary tree is a tree with a root node in which every node has at most two children.
Your task is to write a program which reads a rooted binary tree T and prints the following information for each node u of T:
* node ID of u
* parent of u
* sibling of u
* the number of children of u
* depth of u
* height of u
* node type (root, internal node or leaf)
If two nodes have the same parent, they are siblings. Here, if u and v have the same parent, we say u is a sibling of v (vice versa).
The height of a node in a tree is the number of edges on the longest simple downward path from the node to a leaf.
Here, the given binary tree consists of n nodes and evey node has a unique ID from 0 to n-1.
Constraints
* 1 ≤ n ≤ 25
Input
The first line of the input includes an integer n, the number of nodes of the tree.
In the next n lines, the information of each node is given in the following format:
id left right
id is the node ID, left is ID of the left child and right is ID of the right child. If the node does not have the left (right) child, the left(right) is indicated by -1.
Output
Print the information of each node in the following format:
node id: parent = p, sibling = s, degree = deg, depth = dep, height = h, type
p is ID of its parent. If the node does not have a parent, print -1.
s is ID of its sibling. If the node does not have a sibling, print -1.
deg, dep and h are the number of children, depth and height of the node respectively.
type is a type of nodes represented by a string (root, internal node or leaf. If the root can be considered as a leaf or an internal node, print root.
Please follow the format presented in a sample output below.
Example
Input
9
0 1 4
1 2 3
2 -1 -1
3 -1 -1
4 5 8
5 6 7
6 -1 -1
7 -1 -1
8 -1 -1
Output
node 0: parent = -1, sibling = -1, degree = 2, depth = 0, height = 3, root
node 1: parent = 0, sibling = 4, degree = 2, depth = 1, height = 1, internal node
node 2: parent = 1, sibling = 3, degree = 0, depth = 2, height = 0, leaf
node 3: parent = 1, sibling = 2, degree = 0, depth = 2, height = 0, leaf
node 4: parent = 0, sibling = 1, degree = 2, depth = 1, height = 2, internal node
node 5: parent = 4, sibling = 8, degree = 2, depth = 2, height = 1, internal node
node 6: parent = 5, sibling = 7, degree = 0, depth = 3, height = 0, leaf
node 7: parent = 5, sibling = 6, degree = 0, depth = 3, height = 0, leaf
node 8: parent = 4, sibling = 5, degree = 0, depth = 2, height = 0, leaf | instruction | 0 | 51,281 | 13 | 102,562 |
"Correct Solution:
```
N=int(input())
t=[0]*N
r=set(range(N))
for _ in[0]*N:
x,y,z=list(map(int,input().split()))
t[x]=[y,z]+[0]*2+[(y!=-1)+(z!=-1)]+[0]*2
r-={y,z}
def f(i,p,s,d):
if i<0:return-1
l,r=t[i][:2]
t[i][2:]=[p,s,t[i][4],d,max(f(l,i,r,d+1),f(r,i,l,d+1))+1]
return t[i][-1]
f(r.pop(),-1,-1,0)
for i in range(N):
print('node {}: parent = {}, sibling = {}, degree = {}, depth = {}, height = {}, {}'.format(i,*t[i][2:],'root'if not t[i][5]else'internal node'if t[i][4]else'leaf'))
``` | output | 1 | 51,281 | 13 | 102,563 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.