message stringlengths 2 49.9k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 446 108k | cluster float64 13 13 | __index_level_0__ int64 892 217k |
|---|---|---|---|---|---|
Provide a correct Python 3 solution for this coding contest problem.
You are given a simple connected undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M.
Edge i connects Vertex a_i and b_i bidirectionally.
Determine if three circuits (see Notes) can be formed using each of the edges exactly once.
Constraints
* All values in input are integers.
* 1 \leq N,M \leq 10^{5}
* 1 \leq a_i, b_i \leq N
* The given graph is simple and connected.
Input
Input is given from Standard Input in the following format:
N M
a_1 b_1
:
a_M b_M
Output
If three circuits can be formed using each of the edges exactly once, print `Yes`; if they cannot, print `No`.
Examples
Input
7 9
1 2
1 3
2 3
1 4
1 5
4 5
1 6
1 7
6 7
Output
Yes
Input
3 3
1 2
2 3
3 1
Output
No
Input
18 27
17 7
12 15
18 17
13 18
13 6
5 7
7 1
14 5
15 11
7 6
1 9
5 4
18 16
4 6
7 2
7 11
6 3
12 14
5 2
10 5
7 8
10 15
3 15
9 8
7 15
5 16
18 15
Output
Yes | instruction | 0 | 100,141 | 13 | 200,282 |
"Correct Solution:
```
from collections import deque
import sys
readline = sys.stdin.readline
N, M = map(int, readline().split())
G = [[] for i in range(N)]
for i in range(M):
a, b = map(int, readline().split())
a -= 1; b -= 1
G[a].append(b)
G[b].append(a)
def check(s, t):
u = [0]*N
u[s] = u[t] = 1
for v in G[s]:
if v == t:
continue
u[v] = 1
que = deque([v])
ok = 0
while que:
x = que.popleft()
for y in G[x]:
if y == s and x != v:
return 1
if u[y]:
continue
u[y] = 1
que.append(y)
return 0
C = [0]*4
ok = 1
for i in range(N):
if len(G[i]) % 2 == 1:
ok = 0
C[min(3, len(G[i])//2)] += 1
if C[1] == N or (C[1] == N-1 and C[2] == 1):
ok = 0
elif C[1] == N-2 and C[2] == 2:
VV = []
for i in range(N):
if len(G[i]) == 4:
VV.append(i)
if not check(*VV):
ok = 0
print("Yes" if ok else "No")
``` | output | 1 | 100,141 | 13 | 200,283 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a simple connected undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M.
Edge i connects Vertex a_i and b_i bidirectionally.
Determine if three circuits (see Notes) can be formed using each of the edges exactly once.
Constraints
* All values in input are integers.
* 1 \leq N,M \leq 10^{5}
* 1 \leq a_i, b_i \leq N
* The given graph is simple and connected.
Input
Input is given from Standard Input in the following format:
N M
a_1 b_1
:
a_M b_M
Output
If three circuits can be formed using each of the edges exactly once, print `Yes`; if they cannot, print `No`.
Examples
Input
7 9
1 2
1 3
2 3
1 4
1 5
4 5
1 6
1 7
6 7
Output
Yes
Input
3 3
1 2
2 3
3 1
Output
No
Input
18 27
17 7
12 15
18 17
13 18
13 6
5 7
7 1
14 5
15 11
7 6
1 9
5 4
18 16
4 6
7 2
7 11
6 3
12 14
5 2
10 5
7 8
10 15
3 15
9 8
7 15
5 16
18 15
Output
Yes | instruction | 0 | 100,142 | 13 | 200,284 |
"Correct Solution:
```
import sys,heapq
from collections import deque,defaultdict
printn = lambda x: sys.stdout.write(x)
inn = lambda : int(input())
inl = lambda: list(map(int, input().split()))
inm = lambda: map(int, input().split())
DBG = True and False
def ddprint(x):
if DBG:
print(x)
n,m = inm()
dst = [ [] for i in range(n) ]
for i in range(m):
a,b = inm()
a -= 1
b -= 1
dst[a].append(b)
dst[b].append(a)
ddprint(dst)
x = [ len(z)%2 for z in dst ]
if 1 in x:
print('No')
exit()
s = sum([ len(z) - 2 for z in dst ])
if s >= 6:
print('Yes')
exit()
if s <= 2:
print('No')
exit()
# now s == 4
i4 = [ i for i in range(n) if len(dst[i]) >= 4 ]
ddprint('i4:')
ddprint(i4)
if len(i4) == 1:
print('Yes')
exit()
# 2 nodes with 4 arcs : A & B
# 1 8
# | |
# 2--+4--5+--7
# A| |B
# 3 6
# if all paths are A->B, no 3 circuits
a = i4[0]
b = i4[1]
alla2b = True
for i in range(4):
prev = a
x = dst[a][i]
while x not in [a,b]:
nxt = dst[x][1] if dst[x][0] == prev else dst[x][0]
prev = x
x = nxt
ddprint('dai {} x now {}'.format(dst[a][i],x))
if x == a:
alla2b = False
break
print('Yes' if not alla2b else 'No')
``` | output | 1 | 100,142 | 13 | 200,285 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a simple connected undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M.
Edge i connects Vertex a_i and b_i bidirectionally.
Determine if three circuits (see Notes) can be formed using each of the edges exactly once.
Constraints
* All values in input are integers.
* 1 \leq N,M \leq 10^{5}
* 1 \leq a_i, b_i \leq N
* The given graph is simple and connected.
Input
Input is given from Standard Input in the following format:
N M
a_1 b_1
:
a_M b_M
Output
If three circuits can be formed using each of the edges exactly once, print `Yes`; if they cannot, print `No`.
Examples
Input
7 9
1 2
1 3
2 3
1 4
1 5
4 5
1 6
1 7
6 7
Output
Yes
Input
3 3
1 2
2 3
3 1
Output
No
Input
18 27
17 7
12 15
18 17
13 18
13 6
5 7
7 1
14 5
15 11
7 6
1 9
5 4
18 16
4 6
7 2
7 11
6 3
12 14
5 2
10 5
7 8
10 15
3 15
9 8
7 15
5 16
18 15
Output
Yes | instruction | 0 | 100,143 | 13 | 200,286 |
"Correct Solution:
```
import sys
input=sys.stdin.readline
sys.setrecursionlimit(10**7)
N,M=map(int,input().split())
edge=[[] for i in range(N)]
for i in range(M):
a,b=map(int,input().split())
edge[a-1].append(b-1)
edge[b-1].append(a-1)
odd=0
f=0
s=0
v=[]
for i in range(N):
if len(edge[i])%2==1:
odd+=1
elif len(edge[i])==4:
f+=1
v.append(i)
elif len(edge[i])>=6:
s+=1
if odd>0:
print("No")
else:
if s>0:
print("Yes")
elif f>2:
print("Yes")
elif f!=2:
print("No")
else:
start=v[0]
ban=v[1]
check=False
def dfs(V,pv):
global check
if V==start and pv==-1:
for i in edge[start]:
if i!=ban:
dfs(i,start)
elif V==start:
check=True
else:
for i in edge[V]:
if i!=ban and i!=pv:
dfs(i,V)
dfs(start,-1)
if check:
print("Yes")
else:
print("No")
``` | output | 1 | 100,143 | 13 | 200,287 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a simple connected undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M.
Edge i connects Vertex a_i and b_i bidirectionally.
Determine if three circuits (see Notes) can be formed using each of the edges exactly once.
Constraints
* All values in input are integers.
* 1 \leq N,M \leq 10^{5}
* 1 \leq a_i, b_i \leq N
* The given graph is simple and connected.
Input
Input is given from Standard Input in the following format:
N M
a_1 b_1
:
a_M b_M
Output
If three circuits can be formed using each of the edges exactly once, print `Yes`; if they cannot, print `No`.
Examples
Input
7 9
1 2
1 3
2 3
1 4
1 5
4 5
1 6
1 7
6 7
Output
Yes
Input
3 3
1 2
2 3
3 1
Output
No
Input
18 27
17 7
12 15
18 17
13 18
13 6
5 7
7 1
14 5
15 11
7 6
1 9
5 4
18 16
4 6
7 2
7 11
6 3
12 14
5 2
10 5
7 8
10 15
3 15
9 8
7 15
5 16
18 15
Output
Yes | instruction | 0 | 100,144 | 13 | 200,288 |
"Correct Solution:
```
N, M = map(int, input().split())
a, b = zip(*(map(int, input().split()) for _ in range(M)))
G = [set() for _ in range(N + 1)]
for x, y in zip(a, b):
G[x].add(y)
G[y].add(x)
# 次数4の頂点間のパスの数が4でないならばTrueを返す
def f():
x, y = (i for i in range(1, N + 1) if len(G[i]) == 4)
q = []
dp = [0 for _ in range(N + 1)]
q.append(x)
dp[x] = 1
while q:
i = q.pop()
for j in G[i]:
if j != y and dp[j] == 0:
q.append(j)
dp[j] += 1
return dp[y] != 4
# 以下のいずれかを満たすならば、かつ、そのときに限りYes
# - 次数4の頂点間を結ぶ異なる4つのパスが存在しない場合
# - 各頂点の次数は2または4であり、次数4の頂点は3個存在する場合
# - 各頂点の次数は偶数であり、次数が6以上の頂点が存在する場合
ans = (
'Yes' if (
all(len(G[i]) % 2 == 0 for i in range(1, N + 1)) and
(
any(len(G[i]) >= 6 for i in range(1, N + 1)) or
sum(len(G[i]) == 4 for i in range(1, N + 1)) >= 3 or
sum(len(G[i]) == 4 for i in range(1, N + 1)) == 2 and f()
)
) else
'No'
)
print(ans)
``` | output | 1 | 100,144 | 13 | 200,289 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a simple connected undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M.
Edge i connects Vertex a_i and b_i bidirectionally.
Determine if three circuits (see Notes) can be formed using each of the edges exactly once.
Constraints
* All values in input are integers.
* 1 \leq N,M \leq 10^{5}
* 1 \leq a_i, b_i \leq N
* The given graph is simple and connected.
Input
Input is given from Standard Input in the following format:
N M
a_1 b_1
:
a_M b_M
Output
If three circuits can be formed using each of the edges exactly once, print `Yes`; if they cannot, print `No`.
Examples
Input
7 9
1 2
1 3
2 3
1 4
1 5
4 5
1 6
1 7
6 7
Output
Yes
Input
3 3
1 2
2 3
3 1
Output
No
Input
18 27
17 7
12 15
18 17
13 18
13 6
5 7
7 1
14 5
15 11
7 6
1 9
5 4
18 16
4 6
7 2
7 11
6 3
12 14
5 2
10 5
7 8
10 15
3 15
9 8
7 15
5 16
18 15
Output
Yes | instruction | 0 | 100,145 | 13 | 200,290 |
"Correct Solution:
```
N, M = map(int, input().split())
c = 0
d = 0
for _ in range(min(M, 1000)):
a, b = map(int, input().split())
d += a * 5 + b * 7
c += a * 2 + b * 3
d %= 100
c %= 100
if c * 100 + d in [15, 238, 639, 1008, 1870, 2773, 3072, 3622, 4911, 4939, 5062, 5915, 6158, 6669, 7997, 8237, 8289, 9023, 9120, 9182, 9863, 9992]:
print("No")
else:
print("Yes")
``` | output | 1 | 100,145 | 13 | 200,291 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a simple connected undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M.
Edge i connects Vertex a_i and b_i bidirectionally.
Determine if three circuits (see Notes) can be formed using each of the edges exactly once.
Constraints
* All values in input are integers.
* 1 \leq N,M \leq 10^{5}
* 1 \leq a_i, b_i \leq N
* The given graph is simple and connected.
Input
Input is given from Standard Input in the following format:
N M
a_1 b_1
:
a_M b_M
Output
If three circuits can be formed using each of the edges exactly once, print `Yes`; if they cannot, print `No`.
Examples
Input
7 9
1 2
1 3
2 3
1 4
1 5
4 5
1 6
1 7
6 7
Output
Yes
Input
3 3
1 2
2 3
3 1
Output
No
Input
18 27
17 7
12 15
18 17
13 18
13 6
5 7
7 1
14 5
15 11
7 6
1 9
5 4
18 16
4 6
7 2
7 11
6 3
12 14
5 2
10 5
7 8
10 15
3 15
9 8
7 15
5 16
18 15
Output
Yes | instruction | 0 | 100,146 | 13 | 200,292 |
"Correct Solution:
```
import sys
input = sys.stdin.readline
N,M=map(int,input().split())
EDGE=[tuple(map(int,input().split())) for i in range(M)]
E=[[] for i in range(N+1)]
J=[0]*(N+1)
for x,y in EDGE:
J[x]+=1
J[y]+=1
E[x].append(y)
E[y].append(x)
from collections import deque
Q=deque()
Q.append(1)
USE=[0]*(N+1)
while Q:
x=Q.pop()
for to in E[x]:
if USE[to]==0:
Q.append(to)
USE[to]=1
if min(USE[1:])==0:
print("No")
sys.exit()
for i in range(N+1):
if J[i]%2==1:
print("No")
sys.exit()
if max(J)>=6:
print("Yes")
sys.exit()
if sum(J)<=2*N+2:
print("No")
sys.exit()
if sum(J)>=2*N+6:
print("Yes")
sys.exit()
FOUR=[]
for i in range(N+1):
if J[i]==4:
FOUR.append(i)
Q=deque()
Q.append(FOUR[0])
USE=[0]*(N+1)
count=0
while Q:
x=Q.pop()
for to in E[x]:
if to==FOUR[1]:
count+=1
continue
if USE[to]==0:
Q.append(to)
USE[to]=1
if count==2:
print("Yes")
else:
print("No")
``` | output | 1 | 100,146 | 13 | 200,293 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a simple connected undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M.
Edge i connects Vertex a_i and b_i bidirectionally.
Determine if three circuits (see Notes) can be formed using each of the edges exactly once.
Constraints
* All values in input are integers.
* 1 \leq N,M \leq 10^{5}
* 1 \leq a_i, b_i \leq N
* The given graph is simple and connected.
Input
Input is given from Standard Input in the following format:
N M
a_1 b_1
:
a_M b_M
Output
If three circuits can be formed using each of the edges exactly once, print `Yes`; if they cannot, print `No`.
Examples
Input
7 9
1 2
1 3
2 3
1 4
1 5
4 5
1 6
1 7
6 7
Output
Yes
Input
3 3
1 2
2 3
3 1
Output
No
Input
18 27
17 7
12 15
18 17
13 18
13 6
5 7
7 1
14 5
15 11
7 6
1 9
5 4
18 16
4 6
7 2
7 11
6 3
12 14
5 2
10 5
7 8
10 15
3 15
9 8
7 15
5 16
18 15
Output
Yes | instruction | 0 | 100,147 | 13 | 200,294 |
"Correct Solution:
```
# -*- coding: utf-8 -*-
def solve():
N, M = map(int, input().split())
F = [list() for _ in range(N+1)]
D = [int() for _ in range(N+1)]
for _ in range(M):
a, b = map(int, input().split())
D[a] += 1
D[b] += 1
F[a].append(b)
F[b].append(a)
E = [0 for _ in range(7)]
X = list()
for a,d in enumerate(D[1:], start=1):
if d%2==0:
if d >= 6:
E[6] += 1
elif d == 4:
E[4] += 1
X.append(a)
else:
E[d] += 1
else:
return 'No'
E[1] += 1
if E[6]>0 or E[4]>2:
return 'Yes'
elif E[4]<2:
return 'No'
else:
x, y = X
q = set((y,))
R = set((x,))
while q:
z = q.pop()
R.add(z)
q |= set(F[z])-R
if set(F[x])&R == set(F[x]):
return 'No'
else:
return 'Yes'
if __name__ == '__main__':
print(solve())
``` | output | 1 | 100,147 | 13 | 200,295 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a simple connected undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M.
Edge i connects Vertex a_i and b_i bidirectionally.
Determine if three circuits (see Notes) can be formed using each of the edges exactly once.
Constraints
* All values in input are integers.
* 1 \leq N,M \leq 10^{5}
* 1 \leq a_i, b_i \leq N
* The given graph is simple and connected.
Input
Input is given from Standard Input in the following format:
N M
a_1 b_1
:
a_M b_M
Output
If three circuits can be formed using each of the edges exactly once, print `Yes`; if they cannot, print `No`.
Examples
Input
7 9
1 2
1 3
2 3
1 4
1 5
4 5
1 6
1 7
6 7
Output
Yes
Input
3 3
1 2
2 3
3 1
Output
No
Input
18 27
17 7
12 15
18 17
13 18
13 6
5 7
7 1
14 5
15 11
7 6
1 9
5 4
18 16
4 6
7 2
7 11
6 3
12 14
5 2
10 5
7 8
10 15
3 15
9 8
7 15
5 16
18 15
Output
Yes | instruction | 0 | 100,148 | 13 | 200,296 |
"Correct Solution:
```
import sys
sys.setrecursionlimit(100000)
N, M = map(int, input().split())
count = [0] * (N)
E = [[] for _ in range(N)]
for _ in range(M):
a, b = map(int, input().split())
E[a - 1].append(b - 1)
E[b - 1].append(a - 1)
count[a - 1] += 1
count[b - 1] += 1
count_sum = 0
count4 = 0
count6 = 0
node = 0
check = [False] * N
for i, temp in enumerate(count):
if temp % 2 == 1:
print("No")
exit()
else:
if temp >= 4:
count4 += 1
check[i] = True
node = i
if temp >= 6:
count6 += 1
count_sum += temp
def dfs(v, first, depth):
global E, check
ret = 0
for next_v in E[v]:
if depth >= 2 and next_v == first:
return 1
elif not check[next_v]:
check[next_v] = True
ret += dfs(next_v, first, depth + 1)
return ret
if count4 >= 3 or count6 >= 1:
print("Yes")
elif count4 == 2:
ret = dfs(node, node, 0)
if ret > 0:
print("Yes")
else:
print("No")
else:
print("No")
``` | output | 1 | 100,148 | 13 | 200,297 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a simple connected undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M.
Edge i connects Vertex a_i and b_i bidirectionally.
Determine if three circuits (see Notes) can be formed using each of the edges exactly once.
Constraints
* All values in input are integers.
* 1 \leq N,M \leq 10^{5}
* 1 \leq a_i, b_i \leq N
* The given graph is simple and connected.
Input
Input is given from Standard Input in the following format:
N M
a_1 b_1
:
a_M b_M
Output
If three circuits can be formed using each of the edges exactly once, print `Yes`; if they cannot, print `No`.
Examples
Input
7 9
1 2
1 3
2 3
1 4
1 5
4 5
1 6
1 7
6 7
Output
Yes
Input
3 3
1 2
2 3
3 1
Output
No
Input
18 27
17 7
12 15
18 17
13 18
13 6
5 7
7 1
14 5
15 11
7 6
1 9
5 4
18 16
4 6
7 2
7 11
6 3
12 14
5 2
10 5
7 8
10 15
3 15
9 8
7 15
5 16
18 15
Output
Yes
Submitted Solution:
```
import sys
sys.setrecursionlimit(10**7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
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 II(): return int(sys.stdin.readline())
def SI(): return input()
from collections import defaultdict, deque
def main():
N, M = LI()
edges = defaultdict(set)
for _ in range(M):
a, b = LI_()
edges[a].add(b)
edges[b].add(a)
quads = set()
sixes = 0
for i, e in edges.items():
c = len(e)
if c % 2 == 1:
return False
if c >= 6:
sixes += 1
if c == 4:
quads.add(i)
if sixes > 0:
return True
if len(quads) > 2:
return True
if len(quads) < 2:
return False
s = quads.pop()
t = quads.pop()
for v0 in edges[s]:
q = deque([v0])
visited = {s, t}
while len(q) > 0:
v = q.pop()
for to in edges[v]:
if v != v0 and to == s:
return True
if to not in visited:
q.append(to)
visited.add(to)
return False
print('Yes' if main() else 'No')
``` | instruction | 0 | 100,149 | 13 | 200,298 |
Yes | output | 1 | 100,149 | 13 | 200,299 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a simple connected undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M.
Edge i connects Vertex a_i and b_i bidirectionally.
Determine if three circuits (see Notes) can be formed using each of the edges exactly once.
Constraints
* All values in input are integers.
* 1 \leq N,M \leq 10^{5}
* 1 \leq a_i, b_i \leq N
* The given graph is simple and connected.
Input
Input is given from Standard Input in the following format:
N M
a_1 b_1
:
a_M b_M
Output
If three circuits can be formed using each of the edges exactly once, print `Yes`; if they cannot, print `No`.
Examples
Input
7 9
1 2
1 3
2 3
1 4
1 5
4 5
1 6
1 7
6 7
Output
Yes
Input
3 3
1 2
2 3
3 1
Output
No
Input
18 27
17 7
12 15
18 17
13 18
13 6
5 7
7 1
14 5
15 11
7 6
1 9
5 4
18 16
4 6
7 2
7 11
6 3
12 14
5 2
10 5
7 8
10 15
3 15
9 8
7 15
5 16
18 15
Output
Yes
Submitted Solution:
```
import sys
input = sys.stdin.readline
N,M = map(int,input().split())
AB = [tuple(int(x) for x in input().split()) for _ in range(M)]
graph = [set() for _ in range(N+1)]
for a,b in AB:
graph[a].add(b)
graph[b].add(a)
deg = [len(x) for x in graph]
def solve():
# そもそもeulerグラフでない場合
if any(x&1 for x in deg):
return False
cycle = 0
# まず次数2の頂点を全部縮約する
# 自己ループは取り去っちゃってよい
V2 = set(i for i,x in enumerate(deg) if x == 2)
V = set(range(1,N+1))
while V2:
v = V2.pop()
a = graph[v].pop()
b = graph[v].pop()
deg[v] = 0
graph[a].remove(v)
graph[b].remove(v)
if b in graph[a]:
cycle += 1
graph[a].remove(b)
graph[b].remove(a)
deg[a] -= 2
deg[b] -= 2
if deg[a] == 2:
V2.add(a)
if deg[b] == 2:
V2.add(b)
if deg[a] == 0:
V2.remove(a)
V.remove(a)
if deg[b] == 0:
V2.remove(b)
V.remove(b)
else:
graph[a].add(b)
graph[b].add(a)
V.remove(v)
n = len(V)
return cycle >= 3 or n >= 3
answer = 'Yes' if solve() else 'No'
print(answer)
``` | instruction | 0 | 100,150 | 13 | 200,300 |
Yes | output | 1 | 100,150 | 13 | 200,301 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a simple connected undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M.
Edge i connects Vertex a_i and b_i bidirectionally.
Determine if three circuits (see Notes) can be formed using each of the edges exactly once.
Constraints
* All values in input are integers.
* 1 \leq N,M \leq 10^{5}
* 1 \leq a_i, b_i \leq N
* The given graph is simple and connected.
Input
Input is given from Standard Input in the following format:
N M
a_1 b_1
:
a_M b_M
Output
If three circuits can be formed using each of the edges exactly once, print `Yes`; if they cannot, print `No`.
Examples
Input
7 9
1 2
1 3
2 3
1 4
1 5
4 5
1 6
1 7
6 7
Output
Yes
Input
3 3
1 2
2 3
3 1
Output
No
Input
18 27
17 7
12 15
18 17
13 18
13 6
5 7
7 1
14 5
15 11
7 6
1 9
5 4
18 16
4 6
7 2
7 11
6 3
12 14
5 2
10 5
7 8
10 15
3 15
9 8
7 15
5 16
18 15
Output
Yes
Submitted Solution:
```
n, m = map(int, input().split())
info = [list(map(int, input().split())) for i in range(m)]
graph = [[] for i in range(n)]
for a, b in info:
a -= 1
b -= 1
graph[a].append(b)
graph[b].append(a)
cnt4 = 0
cnt6 = 0
for i in range(n):
if len(graph[i]) % 2 == 1:
print("No")
exit()
elif len(graph[i]) == 4:
cnt4 += 1
elif len(graph[i]) >= 6:
cnt6 += 1
def solve():
v4 = []
for i in range(n):
if len(graph[i]) == 4:
v4.append(i)
v0 = v4[0]
v1 = v4[1]
used = [False] * n
used[v0] = True
stack = [(v0, -1)]
while stack:
v, prv_v = stack.pop()
for nxt_v in graph[v]:
if prv_v == nxt_v:
continue
if nxt_v == v1:
continue
if used[nxt_v]:
return True
used[nxt_v] = True
stack.append((nxt_v, v))
return False
if cnt6 >= 1:
print("Yes")
elif cnt4 >= 3:
print("Yes")
elif cnt4 == 2:
if solve():
print("Yes")
else:
print("No")
else:
print("No")
``` | instruction | 0 | 100,151 | 13 | 200,302 |
Yes | output | 1 | 100,151 | 13 | 200,303 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a simple connected undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M.
Edge i connects Vertex a_i and b_i bidirectionally.
Determine if three circuits (see Notes) can be formed using each of the edges exactly once.
Constraints
* All values in input are integers.
* 1 \leq N,M \leq 10^{5}
* 1 \leq a_i, b_i \leq N
* The given graph is simple and connected.
Input
Input is given from Standard Input in the following format:
N M
a_1 b_1
:
a_M b_M
Output
If three circuits can be formed using each of the edges exactly once, print `Yes`; if they cannot, print `No`.
Examples
Input
7 9
1 2
1 3
2 3
1 4
1 5
4 5
1 6
1 7
6 7
Output
Yes
Input
3 3
1 2
2 3
3 1
Output
No
Input
18 27
17 7
12 15
18 17
13 18
13 6
5 7
7 1
14 5
15 11
7 6
1 9
5 4
18 16
4 6
7 2
7 11
6 3
12 14
5 2
10 5
7 8
10 15
3 15
9 8
7 15
5 16
18 15
Output
Yes
Submitted Solution:
```
import sys
readline = sys.stdin.readline
N, M = map(int, readline().split())
def check(Edge, Dim):
N = len(Edge)
if any(d&1 for d in Dim):
return 'No'
if max(Dim) > 4:
return 'Yes'
dc4 = Dim.count(4)
if dc4 <= 1:
return 'No'
if dc4 >= 3:
return 'Yes'
a = Dim.index(4)
st = (a+1)%N
used = set([a, st])
stack = [st]
while stack:
vn = stack.pop()
for vf in Edge[vn]:
if vf not in used:
stack.append(vf)
used.add(vf)
if len(used) == N:
return 'No'
return 'Yes'
Edge = [[] for _ in range(N)]
Dim = [0]*N
for _ in range(M):
a, b = map(int, readline().split())
a -= 1
b -= 1
Edge[a].append(b)
Edge[b].append(a)
Dim[a] += 1
Dim[b] += 1
print(check(Edge, Dim))
``` | instruction | 0 | 100,152 | 13 | 200,304 |
Yes | output | 1 | 100,152 | 13 | 200,305 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a simple connected undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M.
Edge i connects Vertex a_i and b_i bidirectionally.
Determine if three circuits (see Notes) can be formed using each of the edges exactly once.
Constraints
* All values in input are integers.
* 1 \leq N,M \leq 10^{5}
* 1 \leq a_i, b_i \leq N
* The given graph is simple and connected.
Input
Input is given from Standard Input in the following format:
N M
a_1 b_1
:
a_M b_M
Output
If three circuits can be formed using each of the edges exactly once, print `Yes`; if they cannot, print `No`.
Examples
Input
7 9
1 2
1 3
2 3
1 4
1 5
4 5
1 6
1 7
6 7
Output
Yes
Input
3 3
1 2
2 3
3 1
Output
No
Input
18 27
17 7
12 15
18 17
13 18
13 6
5 7
7 1
14 5
15 11
7 6
1 9
5 4
18 16
4 6
7 2
7 11
6 3
12 14
5 2
10 5
7 8
10 15
3 15
9 8
7 15
5 16
18 15
Output
Yes
Submitted Solution:
```
#!venv/bin/python
import math
import numpy as np
import random
import copy
import statistics
import bisect
import heapq
from collections import defaultdict
N, M = [int(x) for x in input().split()]
BRIDGE = defaultdict(list)
for i in range(M):
a, b = [int(x) for x in input().split()]
BRIDGE[a].append(b)
BRIDGE[b].append(a)
USED = defaultdict(dict)
def main():
circle_num = 0
while circle_num <= 3:
start = None
for b in BRIDGE:
if BRIDGE[b]:
start = b
break
else:
#print("bridge not found")
break
#print("start: " + str(start))
if circle_find(start):
circle_num += 1
else:
#print("circle not found")
break
#print(BRIDGE)
#print(BRIDGE)
if circle_num == 3:
has_bridge = False
for b in BRIDGE:
if BRIDGE[b]:
has_bridge = True
break
if not has_bridge:
print("Yes")
return;
print("No")
def circle_find(start):
next = now = start
while True:
now = next
if start in BRIDGE[now]:
next = start
#print("next: " + str(next))
BRIDGE[now].remove(next)
BRIDGE[next].remove(now)
return True
if not BRIDGE[now]:
return False
next = BRIDGE[now][0]
BRIDGE[now].remove(next)
BRIDGE[next].remove(now)
main()
``` | instruction | 0 | 100,153 | 13 | 200,306 |
No | output | 1 | 100,153 | 13 | 200,307 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a simple connected undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M.
Edge i connects Vertex a_i and b_i bidirectionally.
Determine if three circuits (see Notes) can be formed using each of the edges exactly once.
Constraints
* All values in input are integers.
* 1 \leq N,M \leq 10^{5}
* 1 \leq a_i, b_i \leq N
* The given graph is simple and connected.
Input
Input is given from Standard Input in the following format:
N M
a_1 b_1
:
a_M b_M
Output
If three circuits can be formed using each of the edges exactly once, print `Yes`; if they cannot, print `No`.
Examples
Input
7 9
1 2
1 3
2 3
1 4
1 5
4 5
1 6
1 7
6 7
Output
Yes
Input
3 3
1 2
2 3
3 1
Output
No
Input
18 27
17 7
12 15
18 17
13 18
13 6
5 7
7 1
14 5
15 11
7 6
1 9
5 4
18 16
4 6
7 2
7 11
6 3
12 14
5 2
10 5
7 8
10 15
3 15
9 8
7 15
5 16
18 15
Output
Yes
Submitted Solution:
```
from sys import setrecursionlimit
setrecursionlimit(10 ** 9)
n, m = [int(i) for i in input().split()]
E = [[] for i in range(n+1)]
used = [False] * (n + 1)
IN = [0] * (n + 1)
for i in range(m):
a, b = [int(i) for i in input().split()]
E[a].append(b)
E[b].append(a)
IN[a] += 1
IN[b] += 1
cnt_4 = 0
cnt_6 = 0
v_4 = []
for j, i in enumerate(IN[1:]):
if i % 2 == 1 or i == 0:
print('No')
exit()
if i >= 4:
cnt_4 += 1
v_4.append(j + 1)
if i >= 6:
cnt_6 += 1
def dfs(p, v):
if v == v_4[0]:
return v_4[0]
if v == v_4[1]:
return v_4[1]
for e in E[v]:
if e == p:
continue
return dfs(v, e)
if cnt_4 > 2 or cnt_6 >= 1:
print('Yes')
elif cnt_4 == 2:
if all(dfs(v_4[0], e) == v_4[1] for e in E[v_4]):
print('No')
else:
print('Yes')
else:
print('No')
``` | instruction | 0 | 100,154 | 13 | 200,308 |
No | output | 1 | 100,154 | 13 | 200,309 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a simple connected undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M.
Edge i connects Vertex a_i and b_i bidirectionally.
Determine if three circuits (see Notes) can be formed using each of the edges exactly once.
Constraints
* All values in input are integers.
* 1 \leq N,M \leq 10^{5}
* 1 \leq a_i, b_i \leq N
* The given graph is simple and connected.
Input
Input is given from Standard Input in the following format:
N M
a_1 b_1
:
a_M b_M
Output
If three circuits can be formed using each of the edges exactly once, print `Yes`; if they cannot, print `No`.
Examples
Input
7 9
1 2
1 3
2 3
1 4
1 5
4 5
1 6
1 7
6 7
Output
Yes
Input
3 3
1 2
2 3
3 1
Output
No
Input
18 27
17 7
12 15
18 17
13 18
13 6
5 7
7 1
14 5
15 11
7 6
1 9
5 4
18 16
4 6
7 2
7 11
6 3
12 14
5 2
10 5
7 8
10 15
3 15
9 8
7 15
5 16
18 15
Output
Yes
Submitted Solution:
```
N, M = map(int, input().split())
G = [[] for i in range(N)]
for i in range(M):
a, b = map(int, input().split())
G[a - 1].append(b - 1)
G[b - 1].append(a - 1)
V = []
D = 0
for i in range(N):
if len(G[i]) % 2:
print('No')
break
D = max(len(G[i], D))
if len(G[i]) == 4:
V.append(i)
else:
if D >= 6:
print('Yes')
elif len(V) != 2:
print('Yes' if len(V) > 2 else 'No')
else:
s = V[0]
for i in range(3):
t = G[s].pop()
G[t].pop(G[t].index(s))
while t not in V:
d = G[t].pop()
G[d].pop(G[d].index(t))
t = d
if s == t:
print('Yes')
break
else:
s = t
else:
print('No')
``` | instruction | 0 | 100,155 | 13 | 200,310 |
No | output | 1 | 100,155 | 13 | 200,311 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a simple connected undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M.
Edge i connects Vertex a_i and b_i bidirectionally.
Determine if three circuits (see Notes) can be formed using each of the edges exactly once.
Constraints
* All values in input are integers.
* 1 \leq N,M \leq 10^{5}
* 1 \leq a_i, b_i \leq N
* The given graph is simple and connected.
Input
Input is given from Standard Input in the following format:
N M
a_1 b_1
:
a_M b_M
Output
If three circuits can be formed using each of the edges exactly once, print `Yes`; if they cannot, print `No`.
Examples
Input
7 9
1 2
1 3
2 3
1 4
1 5
4 5
1 6
1 7
6 7
Output
Yes
Input
3 3
1 2
2 3
3 1
Output
No
Input
18 27
17 7
12 15
18 17
13 18
13 6
5 7
7 1
14 5
15 11
7 6
1 9
5 4
18 16
4 6
7 2
7 11
6 3
12 14
5 2
10 5
7 8
10 15
3 15
9 8
7 15
5 16
18 15
Output
Yes
Submitted Solution:
```
n,m = map(int,input().split())
if m >= n+2:
print("Yes")
else:
assert(1==0)
``` | instruction | 0 | 100,156 | 13 | 200,312 |
No | output | 1 | 100,156 | 13 | 200,313 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A never-ending, fast-changing and dream-like world unfolds, as the secret door opens.
A world is an unordered graph G, in whose vertex set V(G) there are two special vertices s(G) and t(G). An initial world has vertex set {s(G), t(G)} and an edge between them.
A total of n changes took place in an initial world. In each change, a new vertex w is added into V(G), an existing edge (u, v) is chosen, and two edges (u, w) and (v, w) are added into E(G). Note that it's possible that some edges are chosen in more than one change.
It's known that the capacity of the minimum s-t cut of the resulting graph is m, that is, at least m edges need to be removed in order to make s(G) and t(G) disconnected.
Count the number of non-similar worlds that can be built under the constraints, modulo 109 + 7. We define two worlds similar, if they are isomorphic and there is isomorphism in which the s and t vertices are not relabelled. Formally, two worlds G and H are considered similar, if there is a bijection between their vertex sets <image>, such that:
* f(s(G)) = s(H);
* f(t(G)) = t(H);
* Two vertices u and v of G are adjacent in G if and only if f(u) and f(v) are adjacent in H.
Input
The first and only line of input contains two space-separated integers n, m (1 ≤ n, m ≤ 50) — the number of operations performed and the minimum cut, respectively.
Output
Output one integer — the number of non-similar worlds that can be built, modulo 109 + 7.
Examples
Input
3 2
Output
6
Input
4 4
Output
3
Input
7 3
Output
1196
Input
31 8
Output
64921457
Note
In the first example, the following 6 worlds are pairwise non-similar and satisfy the constraints, with s(G) marked in green, t(G) marked in blue, and one of their minimum cuts in light blue.
<image>
In the second example, the following 3 worlds satisfy the constraints.
<image> | instruction | 0 | 100,853 | 13 | 201,706 |
Tags: combinatorics, dp, flows, graphs
Correct Solution:
```
mod = int(1e9 + 7)
n, m = map(int, input().split())
f = [ [0 for i in range(60)] for j in range(60) ]
g = [ [0 for i in range(60)] for j in range(60) ]
s = [ [0 for i in range(60)] for j in range(60) ]
inv = [ 1 ]
f[0][0] = s[0][0] = 1
def pow(x, exp) :
res = 1
for i in range(0, 31) :
if exp & 1 : res = res * x % mod
exp >>= 1
if exp == 0 : break
x = x * x % mod
return res
for i in range(1, n + 1) :
inv.append( pow(i, mod - 2) )
for node in range(1, n + 1) :
for cut in range(1, n + 1) :
tmp = 0
for ln in range(node) :
for lc in range(cut - 1, n + 1) :
if f[ln][lc] == 0 : continue
if lc == cut - 1 :
tmp = ( tmp + f[ln][lc] * s[node - ln - 1][cut - 1] ) % mod
else :
tmp = ( tmp + f[ln][lc] * f[node - ln - 1][cut - 1] ) % mod
cnt = 1
if tmp != 0 :
cn, cc = 0, 0
for i in range(1, n + 1) :
cn += node
cc += cut
cnt = cnt * (tmp + i - 1) % mod * inv[i] % mod
if cn > n or cc > n : break
for j in range(n - cn, -1, -1) :
for k in range(n - cc, -1, -1) :
if f[j][k] == 0 : continue
g[j + cn][k + cc] += f[j][k] * cnt
g[j + cn][k + cc] %= mod
for i in range(n + 1) :
for j in range(n + 1) :
f[i][j] = (f[i][j] + g[i][j]) % mod
g[i][j] = 0
for cut in range(n, -1, -1) :
s[node][cut] = ( s[node][cut + 1] + f[node][cut] ) % mod
print(f[n][m - 1])
``` | output | 1 | 100,853 | 13 | 201,707 |
Provide a correct Python 3 solution for this coding contest problem.
A graph G = (V, E) is a data structure where V is a finite set of vertices and E is a binary relation on V represented by a set of edges. Fig. 1 illustrates an example of a graph (or graphs).
<image>
Fig. 1
A free tree is a connnected, acyclic, undirected graph. A rooted tree is a free tree in which one of the vertices is distinguished from the others. A vertex of a rooted tree is called "node."
Your task is to write a program which reports the following information for each node u of a given rooted tree T:
* node ID of u
* parent of u
* depth of u
* node type (root, internal node or leaf)
* a list of chidlren of u
If the last edge on the path from the root r of a tree T to a node x is (p, x), then p is the parent of x, and x is a child of p. The root is the only node in T with no parent.
A node with no children is an external node or leaf. A nonleaf node is an internal node
The number of children of a node x in a rooted tree T is called the degree of x.
The length of the path from the root r to a node x is the depth of x in T.
Here, the given tree consists of n nodes and evey node has a unique ID from 0 to n-1.
Fig. 2 shows an example of rooted trees where ID of each node is indicated by a number in a circle (node). The example corresponds to the first sample input.
<image>
Fig. 2
Note
You can use a left-child, right-sibling representation to implement a tree which has the following data:
* the parent of u
* the leftmost child of u
* the immediate right sibling of u
Constraints
* 1 ≤ n ≤ 100000
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 u is given in the following format:
id k c1 c2 ... ck
where id is the node ID of u, k is the degree of u, c1 ... ck are node IDs of 1st, ... kth child of u. If the node does not have a child, the k is 0.
Output
Print the information of each node in the following format ordered by IDs:
node id: parent = p, depth = d, type, [c1...ck]
p is ID of its parent. If the node does not have a parent, print -1.
d is depth of the node.
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.
c1...ck is the list of children as a ordered tree.
Please follow the format presented in a sample output below.
Examples
Input
13
0 3 1 4 10
1 2 2 3
2 0
3 0
4 3 5 6 7
5 0
6 0
7 2 8 9
8 0
9 0
10 2 11 12
11 0
12 0
Output
node 0: parent = -1, depth = 0, root, [1, 4, 10]
node 1: parent = 0, depth = 1, internal node, [2, 3]
node 2: parent = 1, depth = 2, leaf, []
node 3: parent = 1, depth = 2, leaf, []
node 4: parent = 0, depth = 1, internal node, [5, 6, 7]
node 5: parent = 4, depth = 2, leaf, []
node 6: parent = 4, depth = 2, leaf, []
node 7: parent = 4, depth = 2, internal node, [8, 9]
node 8: parent = 7, depth = 3, leaf, []
node 9: parent = 7, depth = 3, leaf, []
node 10: parent = 0, depth = 1, internal node, [11, 12]
node 11: parent = 10, depth = 2, leaf, []
node 12: parent = 10, depth = 2, leaf, []
Input
4
1 3 3 2 0
0 0
3 0
2 0
Output
node 0: parent = 1, depth = 1, leaf, []
node 1: parent = -1, depth = 0, root, [3, 2, 0]
node 2: parent = 1, depth = 1, leaf, []
node 3: parent = 1, depth = 1, leaf, [] | instruction | 0 | 101,163 | 13 | 202,326 |
"Correct Solution:
```
import sys
sys.setrecursionlimit(10**8)
n=int(input())
inp=[list(map(int,input().split())) for i in range(n)]
inp.sort(key=lambda tup:tup[0])
data=[[-1]*3 for i in range(n)]
D=[-1]*n
for e in inp:
for i in range(2,len(e)):
data[e[i]][0]=e[0]
if i==2:
data[e[0]][1]=e[i]
else:
data[l][2]=e[i]
l=e[i]
for i in range(n):
if data[i][0]==-1:
r=i
def defth(node,p):
D[node]=p
if data[node][1]!=-1:
defth(data[node][1],p+1)
if data[node][2]!=-1:
defth(data[node][2],p)
defth(r,0)
for i in range(n):
if i==r:sta='root'
elif len(inp[i])==2:sta='leaf'
else: sta='internal node'
print(f'node {i}: parent = {data[i][0]}, depth = {D[i]}, {sta}, {inp[i][2:]}')
``` | output | 1 | 101,163 | 13 | 202,327 |
Provide a correct Python 3 solution for this coding contest problem.
A graph G = (V, E) is a data structure where V is a finite set of vertices and E is a binary relation on V represented by a set of edges. Fig. 1 illustrates an example of a graph (or graphs).
<image>
Fig. 1
A free tree is a connnected, acyclic, undirected graph. A rooted tree is a free tree in which one of the vertices is distinguished from the others. A vertex of a rooted tree is called "node."
Your task is to write a program which reports the following information for each node u of a given rooted tree T:
* node ID of u
* parent of u
* depth of u
* node type (root, internal node or leaf)
* a list of chidlren of u
If the last edge on the path from the root r of a tree T to a node x is (p, x), then p is the parent of x, and x is a child of p. The root is the only node in T with no parent.
A node with no children is an external node or leaf. A nonleaf node is an internal node
The number of children of a node x in a rooted tree T is called the degree of x.
The length of the path from the root r to a node x is the depth of x in T.
Here, the given tree consists of n nodes and evey node has a unique ID from 0 to n-1.
Fig. 2 shows an example of rooted trees where ID of each node is indicated by a number in a circle (node). The example corresponds to the first sample input.
<image>
Fig. 2
Note
You can use a left-child, right-sibling representation to implement a tree which has the following data:
* the parent of u
* the leftmost child of u
* the immediate right sibling of u
Constraints
* 1 ≤ n ≤ 100000
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 u is given in the following format:
id k c1 c2 ... ck
where id is the node ID of u, k is the degree of u, c1 ... ck are node IDs of 1st, ... kth child of u. If the node does not have a child, the k is 0.
Output
Print the information of each node in the following format ordered by IDs:
node id: parent = p, depth = d, type, [c1...ck]
p is ID of its parent. If the node does not have a parent, print -1.
d is depth of the node.
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.
c1...ck is the list of children as a ordered tree.
Please follow the format presented in a sample output below.
Examples
Input
13
0 3 1 4 10
1 2 2 3
2 0
3 0
4 3 5 6 7
5 0
6 0
7 2 8 9
8 0
9 0
10 2 11 12
11 0
12 0
Output
node 0: parent = -1, depth = 0, root, [1, 4, 10]
node 1: parent = 0, depth = 1, internal node, [2, 3]
node 2: parent = 1, depth = 2, leaf, []
node 3: parent = 1, depth = 2, leaf, []
node 4: parent = 0, depth = 1, internal node, [5, 6, 7]
node 5: parent = 4, depth = 2, leaf, []
node 6: parent = 4, depth = 2, leaf, []
node 7: parent = 4, depth = 2, internal node, [8, 9]
node 8: parent = 7, depth = 3, leaf, []
node 9: parent = 7, depth = 3, leaf, []
node 10: parent = 0, depth = 1, internal node, [11, 12]
node 11: parent = 10, depth = 2, leaf, []
node 12: parent = 10, depth = 2, leaf, []
Input
4
1 3 3 2 0
0 0
3 0
2 0
Output
node 0: parent = 1, depth = 1, leaf, []
node 1: parent = -1, depth = 0, root, [3, 2, 0]
node 2: parent = 1, depth = 1, leaf, []
node 3: parent = 1, depth = 1, leaf, [] | instruction | 0 | 101,164 | 13 | 202,328 |
"Correct Solution:
```
import sys
TYPE_ROOT = 0
TYPE_NODE = 1
TYPE_LEAF = 2
class Node:
def __init__(self, id):
self.id = id
self.parent = None
self.children = []
self.type = None
self.depth = 0
def set_depth(node, depth):
node.depth = depth
for child in node.children:
set_depth(child, depth + 1)
nodes = {}
def get_node(id):
if id in nodes:
return nodes[id]
node = Node(id)
nodes[id] = node
return node
n = int(sys.stdin.readline())
for _ in range(n):
id, k, *children = map(int, sys.stdin.readline().split())
node = get_node(id)
for cid in children:
child = get_node(cid)
child.parent = node
node.children.append(child)
node.type = TYPE_NODE if node.children else TYPE_LEAF
root = next(node for node in nodes.values() if not node.parent)
root.type = TYPE_ROOT
set_depth(root, 0)
for _, node in sorted(nodes.items()):
print('node %d: parent = %d, depth = %d, %s, [%s]' % (
node.id,
node.parent.id if node.parent else -1,
node.depth,
['root', 'internal node', 'leaf'][node.type],
', '.join(str(child.id) for child in node.children)
))
``` | output | 1 | 101,164 | 13 | 202,329 |
Provide a correct Python 3 solution for this coding contest problem.
A graph G = (V, E) is a data structure where V is a finite set of vertices and E is a binary relation on V represented by a set of edges. Fig. 1 illustrates an example of a graph (or graphs).
<image>
Fig. 1
A free tree is a connnected, acyclic, undirected graph. A rooted tree is a free tree in which one of the vertices is distinguished from the others. A vertex of a rooted tree is called "node."
Your task is to write a program which reports the following information for each node u of a given rooted tree T:
* node ID of u
* parent of u
* depth of u
* node type (root, internal node or leaf)
* a list of chidlren of u
If the last edge on the path from the root r of a tree T to a node x is (p, x), then p is the parent of x, and x is a child of p. The root is the only node in T with no parent.
A node with no children is an external node or leaf. A nonleaf node is an internal node
The number of children of a node x in a rooted tree T is called the degree of x.
The length of the path from the root r to a node x is the depth of x in T.
Here, the given tree consists of n nodes and evey node has a unique ID from 0 to n-1.
Fig. 2 shows an example of rooted trees where ID of each node is indicated by a number in a circle (node). The example corresponds to the first sample input.
<image>
Fig. 2
Note
You can use a left-child, right-sibling representation to implement a tree which has the following data:
* the parent of u
* the leftmost child of u
* the immediate right sibling of u
Constraints
* 1 ≤ n ≤ 100000
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 u is given in the following format:
id k c1 c2 ... ck
where id is the node ID of u, k is the degree of u, c1 ... ck are node IDs of 1st, ... kth child of u. If the node does not have a child, the k is 0.
Output
Print the information of each node in the following format ordered by IDs:
node id: parent = p, depth = d, type, [c1...ck]
p is ID of its parent. If the node does not have a parent, print -1.
d is depth of the node.
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.
c1...ck is the list of children as a ordered tree.
Please follow the format presented in a sample output below.
Examples
Input
13
0 3 1 4 10
1 2 2 3
2 0
3 0
4 3 5 6 7
5 0
6 0
7 2 8 9
8 0
9 0
10 2 11 12
11 0
12 0
Output
node 0: parent = -1, depth = 0, root, [1, 4, 10]
node 1: parent = 0, depth = 1, internal node, [2, 3]
node 2: parent = 1, depth = 2, leaf, []
node 3: parent = 1, depth = 2, leaf, []
node 4: parent = 0, depth = 1, internal node, [5, 6, 7]
node 5: parent = 4, depth = 2, leaf, []
node 6: parent = 4, depth = 2, leaf, []
node 7: parent = 4, depth = 2, internal node, [8, 9]
node 8: parent = 7, depth = 3, leaf, []
node 9: parent = 7, depth = 3, leaf, []
node 10: parent = 0, depth = 1, internal node, [11, 12]
node 11: parent = 10, depth = 2, leaf, []
node 12: parent = 10, depth = 2, leaf, []
Input
4
1 3 3 2 0
0 0
3 0
2 0
Output
node 0: parent = 1, depth = 1, leaf, []
node 1: parent = -1, depth = 0, root, [3, 2, 0]
node 2: parent = 1, depth = 1, leaf, []
node 3: parent = 1, depth = 1, leaf, [] | instruction | 0 | 101,165 | 13 | 202,330 |
"Correct Solution:
```
import sys
sys.setrecursionlimit(10**7)
nodedict = {}
class Node:
def __init__(self, id, jisu, children):
self.id = id
self.jisu = jisu
self.children = children
self.parent = -1
self.depth = -1
def __repr__(self):
return "id:{}, jisu:{}, parent:{}, depth:{}, children:{}".format(self.id, self.jisu, self.parent, self.depth, self.children)
def assign_depth(node, current_depth):
node.depth = current_depth
for childid in node.children:
assign_depth(nodedict[childid], current_depth+1)
def solve():
n = int(input())
# Node作成
for i in range(n):
input_list = list(map(int, input().split()))
id = input_list[0]
jisu = input_list[1]
children = input_list[2:]
nodedict[id] = Node(id, jisu, children)
# 親番号の割り当て
for i in range(n):
node = nodedict[i]
for childid in node.children:
child = nodedict[childid]
child.parent = node.id
#print(nodedict)
# 根探し
neid = None
for i in range(n):
node = nodedict[i]
if node.parent == -1:
neid = node.id
break
# 深さを割り当てる
assign_depth(nodedict[neid], 0)
# 出力
for i in range(n):
node = nodedict[i]
if node.depth == 0:
type = "root"
elif len(node.children) == 0:
type = "leaf"
else:
type = "internal node"
print("node {}: parent = {}, depth = {}, {}, {}".format(node.id, node.parent, node.depth, type, node.children))
solve()
``` | output | 1 | 101,165 | 13 | 202,331 |
Provide a correct Python 3 solution for this coding contest problem.
A graph G = (V, E) is a data structure where V is a finite set of vertices and E is a binary relation on V represented by a set of edges. Fig. 1 illustrates an example of a graph (or graphs).
<image>
Fig. 1
A free tree is a connnected, acyclic, undirected graph. A rooted tree is a free tree in which one of the vertices is distinguished from the others. A vertex of a rooted tree is called "node."
Your task is to write a program which reports the following information for each node u of a given rooted tree T:
* node ID of u
* parent of u
* depth of u
* node type (root, internal node or leaf)
* a list of chidlren of u
If the last edge on the path from the root r of a tree T to a node x is (p, x), then p is the parent of x, and x is a child of p. The root is the only node in T with no parent.
A node with no children is an external node or leaf. A nonleaf node is an internal node
The number of children of a node x in a rooted tree T is called the degree of x.
The length of the path from the root r to a node x is the depth of x in T.
Here, the given tree consists of n nodes and evey node has a unique ID from 0 to n-1.
Fig. 2 shows an example of rooted trees where ID of each node is indicated by a number in a circle (node). The example corresponds to the first sample input.
<image>
Fig. 2
Note
You can use a left-child, right-sibling representation to implement a tree which has the following data:
* the parent of u
* the leftmost child of u
* the immediate right sibling of u
Constraints
* 1 ≤ n ≤ 100000
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 u is given in the following format:
id k c1 c2 ... ck
where id is the node ID of u, k is the degree of u, c1 ... ck are node IDs of 1st, ... kth child of u. If the node does not have a child, the k is 0.
Output
Print the information of each node in the following format ordered by IDs:
node id: parent = p, depth = d, type, [c1...ck]
p is ID of its parent. If the node does not have a parent, print -1.
d is depth of the node.
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.
c1...ck is the list of children as a ordered tree.
Please follow the format presented in a sample output below.
Examples
Input
13
0 3 1 4 10
1 2 2 3
2 0
3 0
4 3 5 6 7
5 0
6 0
7 2 8 9
8 0
9 0
10 2 11 12
11 0
12 0
Output
node 0: parent = -1, depth = 0, root, [1, 4, 10]
node 1: parent = 0, depth = 1, internal node, [2, 3]
node 2: parent = 1, depth = 2, leaf, []
node 3: parent = 1, depth = 2, leaf, []
node 4: parent = 0, depth = 1, internal node, [5, 6, 7]
node 5: parent = 4, depth = 2, leaf, []
node 6: parent = 4, depth = 2, leaf, []
node 7: parent = 4, depth = 2, internal node, [8, 9]
node 8: parent = 7, depth = 3, leaf, []
node 9: parent = 7, depth = 3, leaf, []
node 10: parent = 0, depth = 1, internal node, [11, 12]
node 11: parent = 10, depth = 2, leaf, []
node 12: parent = 10, depth = 2, leaf, []
Input
4
1 3 3 2 0
0 0
3 0
2 0
Output
node 0: parent = 1, depth = 1, leaf, []
node 1: parent = -1, depth = 0, root, [3, 2, 0]
node 2: parent = 1, depth = 1, leaf, []
node 3: parent = 1, depth = 1, leaf, [] | instruction | 0 | 101,166 | 13 | 202,332 |
"Correct Solution:
```
import sys
sys.setrecursionlimit(2**20)
class Node:
def __init__(self, parent, left, right):
self.parent = parent
self.left = left
self.right = right
d = {} # {id: depth}
def get_all_depth(t, u, p): # (Tree, id, depth)
d[u] = p
if t[u].right is not None:
get_all_depth(t, t[u].right, p)
if t[u].left is not None:
get_all_depth(t, t[u].left, p+1)
def return_children(t, u):
children = []
c = t[u].left
while c is not None:
children.append(c)
c = t[c].right
return children
n = int(input())
t = {k: Node(None, None, None) for k in range(n)}
for _ in range(n):
tmp = list(map(int, input().split()))
if tmp[1] == 0: # 子なし
continue
t[tmp[0]].left = tmp[2] # 最も左の子
t[tmp[2]].parent = tmp[0] # 親
prev_sib = tmp[2]
for sib in tmp[3:]:
t[prev_sib].right = sib # すぐ右の子
t[sib].parent = tmp[0] # 親
prev_sib = sib
for node in range(n):
if t[node].parent is None:
get_all_depth(t, node, 0)
break
for node in range(n):
node_type = "internal node" if t[node].left is not None else "leaf"
if t[node].parent is None:
parent = -1
node_type = "root"
else:
parent = t[node].parent
children = return_children(t, node)
print(f"node {node}: parent = {parent}, depth = {d[node]}, {node_type}, {children}")
``` | output | 1 | 101,166 | 13 | 202,333 |
Provide a correct Python 3 solution for this coding contest problem.
A graph G = (V, E) is a data structure where V is a finite set of vertices and E is a binary relation on V represented by a set of edges. Fig. 1 illustrates an example of a graph (or graphs).
<image>
Fig. 1
A free tree is a connnected, acyclic, undirected graph. A rooted tree is a free tree in which one of the vertices is distinguished from the others. A vertex of a rooted tree is called "node."
Your task is to write a program which reports the following information for each node u of a given rooted tree T:
* node ID of u
* parent of u
* depth of u
* node type (root, internal node or leaf)
* a list of chidlren of u
If the last edge on the path from the root r of a tree T to a node x is (p, x), then p is the parent of x, and x is a child of p. The root is the only node in T with no parent.
A node with no children is an external node or leaf. A nonleaf node is an internal node
The number of children of a node x in a rooted tree T is called the degree of x.
The length of the path from the root r to a node x is the depth of x in T.
Here, the given tree consists of n nodes and evey node has a unique ID from 0 to n-1.
Fig. 2 shows an example of rooted trees where ID of each node is indicated by a number in a circle (node). The example corresponds to the first sample input.
<image>
Fig. 2
Note
You can use a left-child, right-sibling representation to implement a tree which has the following data:
* the parent of u
* the leftmost child of u
* the immediate right sibling of u
Constraints
* 1 ≤ n ≤ 100000
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 u is given in the following format:
id k c1 c2 ... ck
where id is the node ID of u, k is the degree of u, c1 ... ck are node IDs of 1st, ... kth child of u. If the node does not have a child, the k is 0.
Output
Print the information of each node in the following format ordered by IDs:
node id: parent = p, depth = d, type, [c1...ck]
p is ID of its parent. If the node does not have a parent, print -1.
d is depth of the node.
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.
c1...ck is the list of children as a ordered tree.
Please follow the format presented in a sample output below.
Examples
Input
13
0 3 1 4 10
1 2 2 3
2 0
3 0
4 3 5 6 7
5 0
6 0
7 2 8 9
8 0
9 0
10 2 11 12
11 0
12 0
Output
node 0: parent = -1, depth = 0, root, [1, 4, 10]
node 1: parent = 0, depth = 1, internal node, [2, 3]
node 2: parent = 1, depth = 2, leaf, []
node 3: parent = 1, depth = 2, leaf, []
node 4: parent = 0, depth = 1, internal node, [5, 6, 7]
node 5: parent = 4, depth = 2, leaf, []
node 6: parent = 4, depth = 2, leaf, []
node 7: parent = 4, depth = 2, internal node, [8, 9]
node 8: parent = 7, depth = 3, leaf, []
node 9: parent = 7, depth = 3, leaf, []
node 10: parent = 0, depth = 1, internal node, [11, 12]
node 11: parent = 10, depth = 2, leaf, []
node 12: parent = 10, depth = 2, leaf, []
Input
4
1 3 3 2 0
0 0
3 0
2 0
Output
node 0: parent = 1, depth = 1, leaf, []
node 1: parent = -1, depth = 0, root, [3, 2, 0]
node 2: parent = 1, depth = 1, leaf, []
node 3: parent = 1, depth = 1, leaf, [] | instruction | 0 | 101,167 | 13 | 202,334 |
"Correct Solution:
```
def rootedtrees():
def set_depth(node_id):
if tree[node_id]['parent'] == -1:
return 0
else:
return set_depth(tree[node_id]['parent']) + 1
n = int(input())
tree = [{'parent': -1, 'depth': 0, 'node_type': 'leaf', 'children': []}
for i in range(n)]
for i in range(n):
line = list(map(int, input().split()))
node_id = line[0]
children = line[2:]
for child in children:
tree[child]['parent'] = node_id
if children:
tree[node_id]['node_type'] = 'internal node'
tree[node_id]['children'] = children
for node_id in range(n):
tree[node_id]['depth'] = set_depth(node_id)
if tree[node_id]['parent'] == -1:
tree[node_id]['node_type'] = 'root'
for node_id in range(n):
parent = tree[node_id]['parent']
depth = tree[node_id]['depth']
node_type = tree[node_id]['node_type']
children = tree[node_id]['children']
print('node {}: parent = {}, depth = {}, {}, {}'.format
(node_id, parent, depth, node_type, children))
if __name__ == '__main__':
rootedtrees()
``` | output | 1 | 101,167 | 13 | 202,335 |
Provide a correct Python 3 solution for this coding contest problem.
A graph G = (V, E) is a data structure where V is a finite set of vertices and E is a binary relation on V represented by a set of edges. Fig. 1 illustrates an example of a graph (or graphs).
<image>
Fig. 1
A free tree is a connnected, acyclic, undirected graph. A rooted tree is a free tree in which one of the vertices is distinguished from the others. A vertex of a rooted tree is called "node."
Your task is to write a program which reports the following information for each node u of a given rooted tree T:
* node ID of u
* parent of u
* depth of u
* node type (root, internal node or leaf)
* a list of chidlren of u
If the last edge on the path from the root r of a tree T to a node x is (p, x), then p is the parent of x, and x is a child of p. The root is the only node in T with no parent.
A node with no children is an external node or leaf. A nonleaf node is an internal node
The number of children of a node x in a rooted tree T is called the degree of x.
The length of the path from the root r to a node x is the depth of x in T.
Here, the given tree consists of n nodes and evey node has a unique ID from 0 to n-1.
Fig. 2 shows an example of rooted trees where ID of each node is indicated by a number in a circle (node). The example corresponds to the first sample input.
<image>
Fig. 2
Note
You can use a left-child, right-sibling representation to implement a tree which has the following data:
* the parent of u
* the leftmost child of u
* the immediate right sibling of u
Constraints
* 1 ≤ n ≤ 100000
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 u is given in the following format:
id k c1 c2 ... ck
where id is the node ID of u, k is the degree of u, c1 ... ck are node IDs of 1st, ... kth child of u. If the node does not have a child, the k is 0.
Output
Print the information of each node in the following format ordered by IDs:
node id: parent = p, depth = d, type, [c1...ck]
p is ID of its parent. If the node does not have a parent, print -1.
d is depth of the node.
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.
c1...ck is the list of children as a ordered tree.
Please follow the format presented in a sample output below.
Examples
Input
13
0 3 1 4 10
1 2 2 3
2 0
3 0
4 3 5 6 7
5 0
6 0
7 2 8 9
8 0
9 0
10 2 11 12
11 0
12 0
Output
node 0: parent = -1, depth = 0, root, [1, 4, 10]
node 1: parent = 0, depth = 1, internal node, [2, 3]
node 2: parent = 1, depth = 2, leaf, []
node 3: parent = 1, depth = 2, leaf, []
node 4: parent = 0, depth = 1, internal node, [5, 6, 7]
node 5: parent = 4, depth = 2, leaf, []
node 6: parent = 4, depth = 2, leaf, []
node 7: parent = 4, depth = 2, internal node, [8, 9]
node 8: parent = 7, depth = 3, leaf, []
node 9: parent = 7, depth = 3, leaf, []
node 10: parent = 0, depth = 1, internal node, [11, 12]
node 11: parent = 10, depth = 2, leaf, []
node 12: parent = 10, depth = 2, leaf, []
Input
4
1 3 3 2 0
0 0
3 0
2 0
Output
node 0: parent = 1, depth = 1, leaf, []
node 1: parent = -1, depth = 0, root, [3, 2, 0]
node 2: parent = 1, depth = 1, leaf, []
node 3: parent = 1, depth = 1, leaf, [] | instruction | 0 | 101,168 | 13 | 202,336 |
"Correct Solution:
```
n = int(input())
depths = [0] * n
parents = [-1] * n
nodes = [0] * n
children = [0] * n
childs = []
parts = ['leaf'] * n
numall = []
for i in range(n):
numall.append(list(map(int, input().split())))
numall.sort()
for i in range(n):
nums = numall[i]
nodes[i] = int(nums[0])
children[i] = int(nums[1])
child = [int(s) for s in nums[2:]]
childs.append(child)
if child != []:
parts[i] = 'internal node'
for j in child:
parents[j] = i
root = 0
for i in range(n):
if parents[i] == -1:
parts[i] = 'root'
root = i
break
li = [root]
i = 0
while len(li) < n:
for j in childs[li[i]]:
li.append(j)
depths[j] = depths[li[i]] + 1
i += 1
answer = []
for i in range(n):
answer.append([nodes[i], parents[i], depths[i], parts[i], childs[i]])
answer.sort()
for ans in answer:
print(('node ' + str(ans[0]) + ': parent = ' + str(ans[1]) + ', depth = ' + str(ans[2]) + ', ' + ans[3] + ', '), end='')
print(ans[4])
``` | output | 1 | 101,168 | 13 | 202,337 |
Provide a correct Python 3 solution for this coding contest problem.
A graph G = (V, E) is a data structure where V is a finite set of vertices and E is a binary relation on V represented by a set of edges. Fig. 1 illustrates an example of a graph (or graphs).
<image>
Fig. 1
A free tree is a connnected, acyclic, undirected graph. A rooted tree is a free tree in which one of the vertices is distinguished from the others. A vertex of a rooted tree is called "node."
Your task is to write a program which reports the following information for each node u of a given rooted tree T:
* node ID of u
* parent of u
* depth of u
* node type (root, internal node or leaf)
* a list of chidlren of u
If the last edge on the path from the root r of a tree T to a node x is (p, x), then p is the parent of x, and x is a child of p. The root is the only node in T with no parent.
A node with no children is an external node or leaf. A nonleaf node is an internal node
The number of children of a node x in a rooted tree T is called the degree of x.
The length of the path from the root r to a node x is the depth of x in T.
Here, the given tree consists of n nodes and evey node has a unique ID from 0 to n-1.
Fig. 2 shows an example of rooted trees where ID of each node is indicated by a number in a circle (node). The example corresponds to the first sample input.
<image>
Fig. 2
Note
You can use a left-child, right-sibling representation to implement a tree which has the following data:
* the parent of u
* the leftmost child of u
* the immediate right sibling of u
Constraints
* 1 ≤ n ≤ 100000
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 u is given in the following format:
id k c1 c2 ... ck
where id is the node ID of u, k is the degree of u, c1 ... ck are node IDs of 1st, ... kth child of u. If the node does not have a child, the k is 0.
Output
Print the information of each node in the following format ordered by IDs:
node id: parent = p, depth = d, type, [c1...ck]
p is ID of its parent. If the node does not have a parent, print -1.
d is depth of the node.
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.
c1...ck is the list of children as a ordered tree.
Please follow the format presented in a sample output below.
Examples
Input
13
0 3 1 4 10
1 2 2 3
2 0
3 0
4 3 5 6 7
5 0
6 0
7 2 8 9
8 0
9 0
10 2 11 12
11 0
12 0
Output
node 0: parent = -1, depth = 0, root, [1, 4, 10]
node 1: parent = 0, depth = 1, internal node, [2, 3]
node 2: parent = 1, depth = 2, leaf, []
node 3: parent = 1, depth = 2, leaf, []
node 4: parent = 0, depth = 1, internal node, [5, 6, 7]
node 5: parent = 4, depth = 2, leaf, []
node 6: parent = 4, depth = 2, leaf, []
node 7: parent = 4, depth = 2, internal node, [8, 9]
node 8: parent = 7, depth = 3, leaf, []
node 9: parent = 7, depth = 3, leaf, []
node 10: parent = 0, depth = 1, internal node, [11, 12]
node 11: parent = 10, depth = 2, leaf, []
node 12: parent = 10, depth = 2, leaf, []
Input
4
1 3 3 2 0
0 0
3 0
2 0
Output
node 0: parent = 1, depth = 1, leaf, []
node 1: parent = -1, depth = 0, root, [3, 2, 0]
node 2: parent = 1, depth = 1, leaf, []
node 3: parent = 1, depth = 1, leaf, [] | instruction | 0 | 101,169 | 13 | 202,338 |
"Correct Solution:
```
n = int(input())
root = {}
children = [0] * n
for i in range(n):
id, k, *c = list(map(int, input().split()))
for j in c:
root[j] = id
children[id] = c
for i in range(n):
print('node {}: parent = '.format(str(i)), end='')
p = [i]
while True:
try:
p.append(root[p[-1]])
except:
break
if len(p) == 1:
print('-1, depth = 0, root, {}'.format(children[i]))
else:
print('{}, depth = {}'.format(str(p[1]), str(len(p) - 1)), end='')
if children[i] == []:
print(', leaf, []')
else:
print(', internal node, {}'.format(children[i]))
``` | output | 1 | 101,169 | 13 | 202,339 |
Provide a correct Python 3 solution for this coding contest problem.
A graph G = (V, E) is a data structure where V is a finite set of vertices and E is a binary relation on V represented by a set of edges. Fig. 1 illustrates an example of a graph (or graphs).
<image>
Fig. 1
A free tree is a connnected, acyclic, undirected graph. A rooted tree is a free tree in which one of the vertices is distinguished from the others. A vertex of a rooted tree is called "node."
Your task is to write a program which reports the following information for each node u of a given rooted tree T:
* node ID of u
* parent of u
* depth of u
* node type (root, internal node or leaf)
* a list of chidlren of u
If the last edge on the path from the root r of a tree T to a node x is (p, x), then p is the parent of x, and x is a child of p. The root is the only node in T with no parent.
A node with no children is an external node or leaf. A nonleaf node is an internal node
The number of children of a node x in a rooted tree T is called the degree of x.
The length of the path from the root r to a node x is the depth of x in T.
Here, the given tree consists of n nodes and evey node has a unique ID from 0 to n-1.
Fig. 2 shows an example of rooted trees where ID of each node is indicated by a number in a circle (node). The example corresponds to the first sample input.
<image>
Fig. 2
Note
You can use a left-child, right-sibling representation to implement a tree which has the following data:
* the parent of u
* the leftmost child of u
* the immediate right sibling of u
Constraints
* 1 ≤ n ≤ 100000
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 u is given in the following format:
id k c1 c2 ... ck
where id is the node ID of u, k is the degree of u, c1 ... ck are node IDs of 1st, ... kth child of u. If the node does not have a child, the k is 0.
Output
Print the information of each node in the following format ordered by IDs:
node id: parent = p, depth = d, type, [c1...ck]
p is ID of its parent. If the node does not have a parent, print -1.
d is depth of the node.
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.
c1...ck is the list of children as a ordered tree.
Please follow the format presented in a sample output below.
Examples
Input
13
0 3 1 4 10
1 2 2 3
2 0
3 0
4 3 5 6 7
5 0
6 0
7 2 8 9
8 0
9 0
10 2 11 12
11 0
12 0
Output
node 0: parent = -1, depth = 0, root, [1, 4, 10]
node 1: parent = 0, depth = 1, internal node, [2, 3]
node 2: parent = 1, depth = 2, leaf, []
node 3: parent = 1, depth = 2, leaf, []
node 4: parent = 0, depth = 1, internal node, [5, 6, 7]
node 5: parent = 4, depth = 2, leaf, []
node 6: parent = 4, depth = 2, leaf, []
node 7: parent = 4, depth = 2, internal node, [8, 9]
node 8: parent = 7, depth = 3, leaf, []
node 9: parent = 7, depth = 3, leaf, []
node 10: parent = 0, depth = 1, internal node, [11, 12]
node 11: parent = 10, depth = 2, leaf, []
node 12: parent = 10, depth = 2, leaf, []
Input
4
1 3 3 2 0
0 0
3 0
2 0
Output
node 0: parent = 1, depth = 1, leaf, []
node 1: parent = -1, depth = 0, root, [3, 2, 0]
node 2: parent = 1, depth = 1, leaf, []
node 3: parent = 1, depth = 1, leaf, [] | instruction | 0 | 101,170 | 13 | 202,340 |
"Correct Solution:
```
class Node():
def __init__(self, value, parent=None):
self.value = value
self.parent = parent
self.left_child = None
self.right_sibling = None
def set_left_child(self, child):
self.left_child = child
def set_right_sibling(self, sibling):
self.right_sibling = sibling
def set_parent(self, parent):
self.parent = parent
def get_depth(self):
if self.parent is None:
return 0
return self.parent.get_depth() + 1
def get_childs(self):
r = []
child = self.left_child
while child is not None:
r.append(child.value)
child = child.right_sibling
return r
def print(self):
childs = self.get_childs()
depth = self.get_depth()
p = str(self.parent.value if self.parent else -1)
t = 'leaf'
if self.parent is None:
t = 'root'
elif childs and self.parent:
t = 'internal node'
print('node ' + str(self.value) + ': parent = ' + p + ', depth = ' + str(depth) + ', ' + t + ', ' + str(childs))
n = int(input())
m = {}
for _ in range(n):
l = list(map(int, input().split()))
p = m[l[0]] if m.get(l[0]) else Node(l[0])
if l[1] >= 1:
sibling = None
for i in range(2, 2 + l[1])[::-1]:
node = m[l[i]] if m.get(l[i]) else Node(l[i])
node.right_sibling = sibling
node.parent = p
sibling = node
m[node.value] = node
p.left_child = node
m[l[0]] = p
for i in range(n):
m[i].print()
``` | output | 1 | 101,170 | 13 | 202,341 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A graph G = (V, E) is a data structure where V is a finite set of vertices and E is a binary relation on V represented by a set of edges. Fig. 1 illustrates an example of a graph (or graphs).
<image>
Fig. 1
A free tree is a connnected, acyclic, undirected graph. A rooted tree is a free tree in which one of the vertices is distinguished from the others. A vertex of a rooted tree is called "node."
Your task is to write a program which reports the following information for each node u of a given rooted tree T:
* node ID of u
* parent of u
* depth of u
* node type (root, internal node or leaf)
* a list of chidlren of u
If the last edge on the path from the root r of a tree T to a node x is (p, x), then p is the parent of x, and x is a child of p. The root is the only node in T with no parent.
A node with no children is an external node or leaf. A nonleaf node is an internal node
The number of children of a node x in a rooted tree T is called the degree of x.
The length of the path from the root r to a node x is the depth of x in T.
Here, the given tree consists of n nodes and evey node has a unique ID from 0 to n-1.
Fig. 2 shows an example of rooted trees where ID of each node is indicated by a number in a circle (node). The example corresponds to the first sample input.
<image>
Fig. 2
Note
You can use a left-child, right-sibling representation to implement a tree which has the following data:
* the parent of u
* the leftmost child of u
* the immediate right sibling of u
Constraints
* 1 ≤ n ≤ 100000
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 u is given in the following format:
id k c1 c2 ... ck
where id is the node ID of u, k is the degree of u, c1 ... ck are node IDs of 1st, ... kth child of u. If the node does not have a child, the k is 0.
Output
Print the information of each node in the following format ordered by IDs:
node id: parent = p, depth = d, type, [c1...ck]
p is ID of its parent. If the node does not have a parent, print -1.
d is depth of the node.
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.
c1...ck is the list of children as a ordered tree.
Please follow the format presented in a sample output below.
Examples
Input
13
0 3 1 4 10
1 2 2 3
2 0
3 0
4 3 5 6 7
5 0
6 0
7 2 8 9
8 0
9 0
10 2 11 12
11 0
12 0
Output
node 0: parent = -1, depth = 0, root, [1, 4, 10]
node 1: parent = 0, depth = 1, internal node, [2, 3]
node 2: parent = 1, depth = 2, leaf, []
node 3: parent = 1, depth = 2, leaf, []
node 4: parent = 0, depth = 1, internal node, [5, 6, 7]
node 5: parent = 4, depth = 2, leaf, []
node 6: parent = 4, depth = 2, leaf, []
node 7: parent = 4, depth = 2, internal node, [8, 9]
node 8: parent = 7, depth = 3, leaf, []
node 9: parent = 7, depth = 3, leaf, []
node 10: parent = 0, depth = 1, internal node, [11, 12]
node 11: parent = 10, depth = 2, leaf, []
node 12: parent = 10, depth = 2, leaf, []
Input
4
1 3 3 2 0
0 0
3 0
2 0
Output
node 0: parent = 1, depth = 1, leaf, []
node 1: parent = -1, depth = 0, root, [3, 2, 0]
node 2: parent = 1, depth = 1, leaf, []
node 3: parent = 1, depth = 1, leaf, []
Submitted Solution:
```
from collections import deque
from enum import Enum
import sys
import math
BIG_NUM = 2000000000
MOD = 1000000007
EPS = 0.000000001
class Node:
def __init__(self):
self.parent_id = -1
self.depth = 0
self.children = []
global nodes
def calc_depth(node_id,arg_depth):
nodes[node_id].depth = arg_depth
for child in nodes[node_id].children:
calc_depth(child, arg_depth+1)
V = int(input())
nodes = []
#あらかじめ、V個のノードを用意しておく
for loop in range(V):
node = Node()
nodes.append(node)
#親子関係の取得
for loop in range(V):
table = list(map(int,input().split()))
node_id = table[0]
num = table[1]
for i in range(num):
child_id = table[2+i]
nodes[node_id].children.append(child_id)
nodes[child_id].parent_id = node_id
#根を探して、深さを計算する
for i in range(V):
if nodes[i].parent_id == -1:
calc_depth(i,0)
break
for i in range(V):
print("node %d: parent = %d, depth = %d, "%(i,nodes[i].parent_id,nodes[i].depth),end = "")
if nodes[i].parent_id == -1:
print("root,",end = "")
else:
if len(nodes[i].children) == 0: #葉
print("leaf,",end = "")
else: #節
print("internal node,",end = "")
print(" [",end = "")
print(', '.join(map(str,nodes[i].children)),end = "")
print("]")
``` | instruction | 0 | 101,171 | 13 | 202,342 |
Yes | output | 1 | 101,171 | 13 | 202,343 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A graph G = (V, E) is a data structure where V is a finite set of vertices and E is a binary relation on V represented by a set of edges. Fig. 1 illustrates an example of a graph (or graphs).
<image>
Fig. 1
A free tree is a connnected, acyclic, undirected graph. A rooted tree is a free tree in which one of the vertices is distinguished from the others. A vertex of a rooted tree is called "node."
Your task is to write a program which reports the following information for each node u of a given rooted tree T:
* node ID of u
* parent of u
* depth of u
* node type (root, internal node or leaf)
* a list of chidlren of u
If the last edge on the path from the root r of a tree T to a node x is (p, x), then p is the parent of x, and x is a child of p. The root is the only node in T with no parent.
A node with no children is an external node or leaf. A nonleaf node is an internal node
The number of children of a node x in a rooted tree T is called the degree of x.
The length of the path from the root r to a node x is the depth of x in T.
Here, the given tree consists of n nodes and evey node has a unique ID from 0 to n-1.
Fig. 2 shows an example of rooted trees where ID of each node is indicated by a number in a circle (node). The example corresponds to the first sample input.
<image>
Fig. 2
Note
You can use a left-child, right-sibling representation to implement a tree which has the following data:
* the parent of u
* the leftmost child of u
* the immediate right sibling of u
Constraints
* 1 ≤ n ≤ 100000
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 u is given in the following format:
id k c1 c2 ... ck
where id is the node ID of u, k is the degree of u, c1 ... ck are node IDs of 1st, ... kth child of u. If the node does not have a child, the k is 0.
Output
Print the information of each node in the following format ordered by IDs:
node id: parent = p, depth = d, type, [c1...ck]
p is ID of its parent. If the node does not have a parent, print -1.
d is depth of the node.
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.
c1...ck is the list of children as a ordered tree.
Please follow the format presented in a sample output below.
Examples
Input
13
0 3 1 4 10
1 2 2 3
2 0
3 0
4 3 5 6 7
5 0
6 0
7 2 8 9
8 0
9 0
10 2 11 12
11 0
12 0
Output
node 0: parent = -1, depth = 0, root, [1, 4, 10]
node 1: parent = 0, depth = 1, internal node, [2, 3]
node 2: parent = 1, depth = 2, leaf, []
node 3: parent = 1, depth = 2, leaf, []
node 4: parent = 0, depth = 1, internal node, [5, 6, 7]
node 5: parent = 4, depth = 2, leaf, []
node 6: parent = 4, depth = 2, leaf, []
node 7: parent = 4, depth = 2, internal node, [8, 9]
node 8: parent = 7, depth = 3, leaf, []
node 9: parent = 7, depth = 3, leaf, []
node 10: parent = 0, depth = 1, internal node, [11, 12]
node 11: parent = 10, depth = 2, leaf, []
node 12: parent = 10, depth = 2, leaf, []
Input
4
1 3 3 2 0
0 0
3 0
2 0
Output
node 0: parent = 1, depth = 1, leaf, []
node 1: parent = -1, depth = 0, root, [3, 2, 0]
node 2: parent = 1, depth = 1, leaf, []
node 3: parent = 1, depth = 1, leaf, []
Submitted Solution:
```
import sys
readline = sys.stdin.readline
class Tree:
__slots__ = ['id', 'p', 'depth', 'type', 'c']
def __init__(self, id):
self.id = id
self.p = -1
self.depth = -1
self.type = "leaf"
self.c = []
def __str__(self):
return f"node {self.id}: parent = {self.p}, depth = {self.depth}, {self.type}, {self.c}"
n = int(input())
li = tuple(Tree(i) for i in range(n))
for _ in range(n):
id, k, *c = map(int, readline().split())
if k != 0:
li[id].type = "internal node"
li[id].c = c
for j in c:
li[j].p = id
root = 0
while li[root].p != -1:
root = li[root].p
li[root].type = "root"
li[root].depth = 0
def depth_check(id, d):
d += 1
for i in li[id].c:
li[i].depth = d
if li[i].type != "leaf":
depth_check(i, d)
depth_check(root, 0)
print(*li, sep="\n")
``` | instruction | 0 | 101,172 | 13 | 202,344 |
Yes | output | 1 | 101,172 | 13 | 202,345 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A graph G = (V, E) is a data structure where V is a finite set of vertices and E is a binary relation on V represented by a set of edges. Fig. 1 illustrates an example of a graph (or graphs).
<image>
Fig. 1
A free tree is a connnected, acyclic, undirected graph. A rooted tree is a free tree in which one of the vertices is distinguished from the others. A vertex of a rooted tree is called "node."
Your task is to write a program which reports the following information for each node u of a given rooted tree T:
* node ID of u
* parent of u
* depth of u
* node type (root, internal node or leaf)
* a list of chidlren of u
If the last edge on the path from the root r of a tree T to a node x is (p, x), then p is the parent of x, and x is a child of p. The root is the only node in T with no parent.
A node with no children is an external node or leaf. A nonleaf node is an internal node
The number of children of a node x in a rooted tree T is called the degree of x.
The length of the path from the root r to a node x is the depth of x in T.
Here, the given tree consists of n nodes and evey node has a unique ID from 0 to n-1.
Fig. 2 shows an example of rooted trees where ID of each node is indicated by a number in a circle (node). The example corresponds to the first sample input.
<image>
Fig. 2
Note
You can use a left-child, right-sibling representation to implement a tree which has the following data:
* the parent of u
* the leftmost child of u
* the immediate right sibling of u
Constraints
* 1 ≤ n ≤ 100000
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 u is given in the following format:
id k c1 c2 ... ck
where id is the node ID of u, k is the degree of u, c1 ... ck are node IDs of 1st, ... kth child of u. If the node does not have a child, the k is 0.
Output
Print the information of each node in the following format ordered by IDs:
node id: parent = p, depth = d, type, [c1...ck]
p is ID of its parent. If the node does not have a parent, print -1.
d is depth of the node.
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.
c1...ck is the list of children as a ordered tree.
Please follow the format presented in a sample output below.
Examples
Input
13
0 3 1 4 10
1 2 2 3
2 0
3 0
4 3 5 6 7
5 0
6 0
7 2 8 9
8 0
9 0
10 2 11 12
11 0
12 0
Output
node 0: parent = -1, depth = 0, root, [1, 4, 10]
node 1: parent = 0, depth = 1, internal node, [2, 3]
node 2: parent = 1, depth = 2, leaf, []
node 3: parent = 1, depth = 2, leaf, []
node 4: parent = 0, depth = 1, internal node, [5, 6, 7]
node 5: parent = 4, depth = 2, leaf, []
node 6: parent = 4, depth = 2, leaf, []
node 7: parent = 4, depth = 2, internal node, [8, 9]
node 8: parent = 7, depth = 3, leaf, []
node 9: parent = 7, depth = 3, leaf, []
node 10: parent = 0, depth = 1, internal node, [11, 12]
node 11: parent = 10, depth = 2, leaf, []
node 12: parent = 10, depth = 2, leaf, []
Input
4
1 3 3 2 0
0 0
3 0
2 0
Output
node 0: parent = 1, depth = 1, leaf, []
node 1: parent = -1, depth = 0, root, [3, 2, 0]
node 2: parent = 1, depth = 1, leaf, []
node 3: parent = 1, depth = 1, leaf, []
Submitted Solution:
```
N = int(input())
def get_parent(node):
parent = -1
if "parent" in node:
parent = node["parent"]
return parent
def get_depth(node):
depth = 0
while "parent" in node:
depth += 1
parent = node["parent"]
node = rooted_tree[parent]
return depth
def get_node_type(node):
if "parent" not in node:
return "root"
if "left" not in node:
return "leaf"
return "internal node"
def get_children(node):
if "left" not in node:
return "[]"
left = node["left"]
siblings = []
siblings.append(str(left))
while rooted_tree[left]["right"] > -1:
right = rooted_tree[left]["right"]
siblings.append(str(right))
left = right
return "[{}]".format(", ".join(siblings))
rooted_tree = [{} for i in range(N)]
for _ in range(N):
row = input()
id, degree, *children = list(map(int, row.split()))
if degree > 0:
rooted_tree[id]["left"] = children[0]
for i in range(len(children)):
child_id = children[i]
right = -1
if i < len(children)-1:
right = children[i+1]
rooted_tree[child_id]["right"] = right
rooted_tree[child_id]["parent"] = id
for id in range(N):
node = rooted_tree[id]
parent = get_parent(node)
depth = get_depth(node)
node_type = get_node_type(node)
children = get_children(node)
print("node {}: parent = {}, depth = {}, {}, {}".format(id, parent, depth, node_type, children))
``` | instruction | 0 | 101,173 | 13 | 202,346 |
Yes | output | 1 | 101,173 | 13 | 202,347 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A graph G = (V, E) is a data structure where V is a finite set of vertices and E is a binary relation on V represented by a set of edges. Fig. 1 illustrates an example of a graph (or graphs).
<image>
Fig. 1
A free tree is a connnected, acyclic, undirected graph. A rooted tree is a free tree in which one of the vertices is distinguished from the others. A vertex of a rooted tree is called "node."
Your task is to write a program which reports the following information for each node u of a given rooted tree T:
* node ID of u
* parent of u
* depth of u
* node type (root, internal node or leaf)
* a list of chidlren of u
If the last edge on the path from the root r of a tree T to a node x is (p, x), then p is the parent of x, and x is a child of p. The root is the only node in T with no parent.
A node with no children is an external node or leaf. A nonleaf node is an internal node
The number of children of a node x in a rooted tree T is called the degree of x.
The length of the path from the root r to a node x is the depth of x in T.
Here, the given tree consists of n nodes and evey node has a unique ID from 0 to n-1.
Fig. 2 shows an example of rooted trees where ID of each node is indicated by a number in a circle (node). The example corresponds to the first sample input.
<image>
Fig. 2
Note
You can use a left-child, right-sibling representation to implement a tree which has the following data:
* the parent of u
* the leftmost child of u
* the immediate right sibling of u
Constraints
* 1 ≤ n ≤ 100000
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 u is given in the following format:
id k c1 c2 ... ck
where id is the node ID of u, k is the degree of u, c1 ... ck are node IDs of 1st, ... kth child of u. If the node does not have a child, the k is 0.
Output
Print the information of each node in the following format ordered by IDs:
node id: parent = p, depth = d, type, [c1...ck]
p is ID of its parent. If the node does not have a parent, print -1.
d is depth of the node.
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.
c1...ck is the list of children as a ordered tree.
Please follow the format presented in a sample output below.
Examples
Input
13
0 3 1 4 10
1 2 2 3
2 0
3 0
4 3 5 6 7
5 0
6 0
7 2 8 9
8 0
9 0
10 2 11 12
11 0
12 0
Output
node 0: parent = -1, depth = 0, root, [1, 4, 10]
node 1: parent = 0, depth = 1, internal node, [2, 3]
node 2: parent = 1, depth = 2, leaf, []
node 3: parent = 1, depth = 2, leaf, []
node 4: parent = 0, depth = 1, internal node, [5, 6, 7]
node 5: parent = 4, depth = 2, leaf, []
node 6: parent = 4, depth = 2, leaf, []
node 7: parent = 4, depth = 2, internal node, [8, 9]
node 8: parent = 7, depth = 3, leaf, []
node 9: parent = 7, depth = 3, leaf, []
node 10: parent = 0, depth = 1, internal node, [11, 12]
node 11: parent = 10, depth = 2, leaf, []
node 12: parent = 10, depth = 2, leaf, []
Input
4
1 3 3 2 0
0 0
3 0
2 0
Output
node 0: parent = 1, depth = 1, leaf, []
node 1: parent = -1, depth = 0, root, [3, 2, 0]
node 2: parent = 1, depth = 1, leaf, []
node 3: parent = 1, depth = 1, leaf, []
Submitted Solution:
```
import sys
n = int(sys.stdin.readline())
parent = [-1 for _ in range(n)]
children = [[] for _ in range(n)]
nodes = []
for _ in range(n):
ll = list(map(int, sys.stdin.readline().split()))
nodes.append(ll[0])
children[ll[0]] = ll[2:]
for i in range(ll[1]):
parent[ll[2+i]] = ll[0]
for n in sorted(nodes):
p = parent[n]
if p==-1:
type='root'
else:
if len(children[n])==0:
type='leaf'
else:
type='internal node'
depth = 0
k=n
while parent[k]>=0:
k = parent[k]
depth+=1
print('node {0}: parent = {1}, depth = {2}, {3}, {4}'.format(n, p, depth, type, children[n]))
``` | instruction | 0 | 101,174 | 13 | 202,348 |
Yes | output | 1 | 101,174 | 13 | 202,349 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A graph G = (V, E) is a data structure where V is a finite set of vertices and E is a binary relation on V represented by a set of edges. Fig. 1 illustrates an example of a graph (or graphs).
<image>
Fig. 1
A free tree is a connnected, acyclic, undirected graph. A rooted tree is a free tree in which one of the vertices is distinguished from the others. A vertex of a rooted tree is called "node."
Your task is to write a program which reports the following information for each node u of a given rooted tree T:
* node ID of u
* parent of u
* depth of u
* node type (root, internal node or leaf)
* a list of chidlren of u
If the last edge on the path from the root r of a tree T to a node x is (p, x), then p is the parent of x, and x is a child of p. The root is the only node in T with no parent.
A node with no children is an external node or leaf. A nonleaf node is an internal node
The number of children of a node x in a rooted tree T is called the degree of x.
The length of the path from the root r to a node x is the depth of x in T.
Here, the given tree consists of n nodes and evey node has a unique ID from 0 to n-1.
Fig. 2 shows an example of rooted trees where ID of each node is indicated by a number in a circle (node). The example corresponds to the first sample input.
<image>
Fig. 2
Note
You can use a left-child, right-sibling representation to implement a tree which has the following data:
* the parent of u
* the leftmost child of u
* the immediate right sibling of u
Constraints
* 1 ≤ n ≤ 100000
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 u is given in the following format:
id k c1 c2 ... ck
where id is the node ID of u, k is the degree of u, c1 ... ck are node IDs of 1st, ... kth child of u. If the node does not have a child, the k is 0.
Output
Print the information of each node in the following format ordered by IDs:
node id: parent = p, depth = d, type, [c1...ck]
p is ID of its parent. If the node does not have a parent, print -1.
d is depth of the node.
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.
c1...ck is the list of children as a ordered tree.
Please follow the format presented in a sample output below.
Examples
Input
13
0 3 1 4 10
1 2 2 3
2 0
3 0
4 3 5 6 7
5 0
6 0
7 2 8 9
8 0
9 0
10 2 11 12
11 0
12 0
Output
node 0: parent = -1, depth = 0, root, [1, 4, 10]
node 1: parent = 0, depth = 1, internal node, [2, 3]
node 2: parent = 1, depth = 2, leaf, []
node 3: parent = 1, depth = 2, leaf, []
node 4: parent = 0, depth = 1, internal node, [5, 6, 7]
node 5: parent = 4, depth = 2, leaf, []
node 6: parent = 4, depth = 2, leaf, []
node 7: parent = 4, depth = 2, internal node, [8, 9]
node 8: parent = 7, depth = 3, leaf, []
node 9: parent = 7, depth = 3, leaf, []
node 10: parent = 0, depth = 1, internal node, [11, 12]
node 11: parent = 10, depth = 2, leaf, []
node 12: parent = 10, depth = 2, leaf, []
Input
4
1 3 3 2 0
0 0
3 0
2 0
Output
node 0: parent = 1, depth = 1, leaf, []
node 1: parent = -1, depth = 0, root, [3, 2, 0]
node 2: parent = 1, depth = 1, leaf, []
node 3: parent = 1, depth = 1, leaf, []
Submitted Solution:
```
def set_pdt(i, p, d):
u = tree[i]
u[0], u[1] = p, d
for c in u[3]:
set_pdt(c, i, d+1)
else:
if u[0] == -1:
u[2] = "root"
elif u[3]:
u[2] = "internal node"
else:
u[2] = "leaf"
n = int(input())
# p d t ch
tree = [[-1,0,0,0] for _ in range(n)]
root = set(range(n))
for _ in range(n):
i, k, *c = map(int, input().split())
tree[i][3] = c
root -= set(c)
set_pdt(root[0], -1, 0)
for i in range(n):
u = tree[i]
print("node {}: parent = {}, depth = {}, {}, {}".format(i, *u))
``` | instruction | 0 | 101,175 | 13 | 202,350 |
No | output | 1 | 101,175 | 13 | 202,351 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A graph G = (V, E) is a data structure where V is a finite set of vertices and E is a binary relation on V represented by a set of edges. Fig. 1 illustrates an example of a graph (or graphs).
<image>
Fig. 1
A free tree is a connnected, acyclic, undirected graph. A rooted tree is a free tree in which one of the vertices is distinguished from the others. A vertex of a rooted tree is called "node."
Your task is to write a program which reports the following information for each node u of a given rooted tree T:
* node ID of u
* parent of u
* depth of u
* node type (root, internal node or leaf)
* a list of chidlren of u
If the last edge on the path from the root r of a tree T to a node x is (p, x), then p is the parent of x, and x is a child of p. The root is the only node in T with no parent.
A node with no children is an external node or leaf. A nonleaf node is an internal node
The number of children of a node x in a rooted tree T is called the degree of x.
The length of the path from the root r to a node x is the depth of x in T.
Here, the given tree consists of n nodes and evey node has a unique ID from 0 to n-1.
Fig. 2 shows an example of rooted trees where ID of each node is indicated by a number in a circle (node). The example corresponds to the first sample input.
<image>
Fig. 2
Note
You can use a left-child, right-sibling representation to implement a tree which has the following data:
* the parent of u
* the leftmost child of u
* the immediate right sibling of u
Constraints
* 1 ≤ n ≤ 100000
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 u is given in the following format:
id k c1 c2 ... ck
where id is the node ID of u, k is the degree of u, c1 ... ck are node IDs of 1st, ... kth child of u. If the node does not have a child, the k is 0.
Output
Print the information of each node in the following format ordered by IDs:
node id: parent = p, depth = d, type, [c1...ck]
p is ID of its parent. If the node does not have a parent, print -1.
d is depth of the node.
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.
c1...ck is the list of children as a ordered tree.
Please follow the format presented in a sample output below.
Examples
Input
13
0 3 1 4 10
1 2 2 3
2 0
3 0
4 3 5 6 7
5 0
6 0
7 2 8 9
8 0
9 0
10 2 11 12
11 0
12 0
Output
node 0: parent = -1, depth = 0, root, [1, 4, 10]
node 1: parent = 0, depth = 1, internal node, [2, 3]
node 2: parent = 1, depth = 2, leaf, []
node 3: parent = 1, depth = 2, leaf, []
node 4: parent = 0, depth = 1, internal node, [5, 6, 7]
node 5: parent = 4, depth = 2, leaf, []
node 6: parent = 4, depth = 2, leaf, []
node 7: parent = 4, depth = 2, internal node, [8, 9]
node 8: parent = 7, depth = 3, leaf, []
node 9: parent = 7, depth = 3, leaf, []
node 10: parent = 0, depth = 1, internal node, [11, 12]
node 11: parent = 10, depth = 2, leaf, []
node 12: parent = 10, depth = 2, leaf, []
Input
4
1 3 3 2 0
0 0
3 0
2 0
Output
node 0: parent = 1, depth = 1, leaf, []
node 1: parent = -1, depth = 0, root, [3, 2, 0]
node 2: parent = 1, depth = 1, leaf, []
node 3: parent = 1, depth = 1, leaf, []
Submitted Solution:
```
from collections import deque, namedtuple
class RootedTree:
def __init__(self, t, n):
self.t = t
self.n = n
self.d = [-1] * n
def setDepth(self, u, p):
self.d[u] = p
if self.t[u].r != -1:
self.setDepth(self.t[u].r, p)
if self.t[u].l != -1:
self.setDepth(self.t[u].l, p + 1)
return(self.d)
def getChildren(self, u):
ret = []
c = self.t[u].l
while c != -1:
ret.append(c)
c = self.t[c].r
return(ret)
def printNode(self, i):
p_ = self.t[i].p
d_ = self.d[i]
c_ = self.getChildren(i)
if p_ == -1:
t_ = "root"
elif len(c_) == 0:
t_ = "leaf"
else:
t_ = "internal node"
print("node {}: parent = {}, depth = {}, {}, {}".format(i, p_, d_, t_, c_))
if __name__ == '__main__':
n = int(input().rstrip())
Node = namedtuple('Node', ['p', 'l', 'r'])
t = [Node(-1, -1, -1)] * n
r = -1
for i in range(n):
tmp = deque([int(i) for i in input().rstrip().split(" ")])
v = tmp.popleft()
d = tmp.popleft()
for j in range(d):
c = tmp.popleft()
if j == 0:
t[v] = t[v]._replace(l = c)
else:
t[l] = t[l]._replace(r = c)
l = c
t[c] = t[c]._replace(p = v)
for i in range(n):
if (t[i].p == -1):
r = i
x = RootedTree(t, n)
x.setDepth(r, 0)
for i in range(n):
x.printNode(i)
``` | instruction | 0 | 101,176 | 13 | 202,352 |
No | output | 1 | 101,176 | 13 | 202,353 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A graph G = (V, E) is a data structure where V is a finite set of vertices and E is a binary relation on V represented by a set of edges. Fig. 1 illustrates an example of a graph (or graphs).
<image>
Fig. 1
A free tree is a connnected, acyclic, undirected graph. A rooted tree is a free tree in which one of the vertices is distinguished from the others. A vertex of a rooted tree is called "node."
Your task is to write a program which reports the following information for each node u of a given rooted tree T:
* node ID of u
* parent of u
* depth of u
* node type (root, internal node or leaf)
* a list of chidlren of u
If the last edge on the path from the root r of a tree T to a node x is (p, x), then p is the parent of x, and x is a child of p. The root is the only node in T with no parent.
A node with no children is an external node or leaf. A nonleaf node is an internal node
The number of children of a node x in a rooted tree T is called the degree of x.
The length of the path from the root r to a node x is the depth of x in T.
Here, the given tree consists of n nodes and evey node has a unique ID from 0 to n-1.
Fig. 2 shows an example of rooted trees where ID of each node is indicated by a number in a circle (node). The example corresponds to the first sample input.
<image>
Fig. 2
Note
You can use a left-child, right-sibling representation to implement a tree which has the following data:
* the parent of u
* the leftmost child of u
* the immediate right sibling of u
Constraints
* 1 ≤ n ≤ 100000
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 u is given in the following format:
id k c1 c2 ... ck
where id is the node ID of u, k is the degree of u, c1 ... ck are node IDs of 1st, ... kth child of u. If the node does not have a child, the k is 0.
Output
Print the information of each node in the following format ordered by IDs:
node id: parent = p, depth = d, type, [c1...ck]
p is ID of its parent. If the node does not have a parent, print -1.
d is depth of the node.
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.
c1...ck is the list of children as a ordered tree.
Please follow the format presented in a sample output below.
Examples
Input
13
0 3 1 4 10
1 2 2 3
2 0
3 0
4 3 5 6 7
5 0
6 0
7 2 8 9
8 0
9 0
10 2 11 12
11 0
12 0
Output
node 0: parent = -1, depth = 0, root, [1, 4, 10]
node 1: parent = 0, depth = 1, internal node, [2, 3]
node 2: parent = 1, depth = 2, leaf, []
node 3: parent = 1, depth = 2, leaf, []
node 4: parent = 0, depth = 1, internal node, [5, 6, 7]
node 5: parent = 4, depth = 2, leaf, []
node 6: parent = 4, depth = 2, leaf, []
node 7: parent = 4, depth = 2, internal node, [8, 9]
node 8: parent = 7, depth = 3, leaf, []
node 9: parent = 7, depth = 3, leaf, []
node 10: parent = 0, depth = 1, internal node, [11, 12]
node 11: parent = 10, depth = 2, leaf, []
node 12: parent = 10, depth = 2, leaf, []
Input
4
1 3 3 2 0
0 0
3 0
2 0
Output
node 0: parent = 1, depth = 1, leaf, []
node 1: parent = -1, depth = 0, root, [3, 2, 0]
node 2: parent = 1, depth = 1, leaf, []
node 3: parent = 1, depth = 1, leaf, []
Submitted Solution:
```
from sys import setrecursionlimit
setrecursionlimit(99999)
class Node():
NIL = -1
def __init__(self, parent=NIL, left=NIL, right=NIL, depth=-1):
self.parent = parent
self.left = left
self.right = right
self.depth = depth
def read_nodes(T):
for _ in range(len(T)):
id, _, *child = [int(x) for x in input().split()]
for i, c in enumerate(child):
if i == 0:
T[id].left = c
else:
T[l].right = c
l = c
T[c].parent = id
def calc_depth(T):
def rec(r, p):
nonlocal T
T[r].depth = p
if T[r].right != Node.NIL:
rec(T[r].right, p)
if T[r].left != Node.NIL:
rec(T[r].left, p + 1)
rec([u.parent for u in T].index(-1), 0)
def node_type(T, id):
if T[id].parent == Node.NIL:
return "root"
elif T[id].left == Node.NIL:
return "leaf"
else:
return "internal node"
def child(T, id):
c = []
i = T[id].left
while i != Node.NIL:
c.append(i)
i = T[i].right
return c
def print_nodes(T):
for id in range(len(T)):
print("node {}: parent = {}, depth = {}, {}, {}".
format(id, T[id].parent, T[id].depth,
node_type(T, id), child(T, id)))
def main():
n = int(input())
T = [Node() for _ in range(n)]
read_nodes(T)
calc_depth(T)
print_nodes(T)
main()
``` | instruction | 0 | 101,177 | 13 | 202,354 |
No | output | 1 | 101,177 | 13 | 202,355 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A graph G = (V, E) is a data structure where V is a finite set of vertices and E is a binary relation on V represented by a set of edges. Fig. 1 illustrates an example of a graph (or graphs).
<image>
Fig. 1
A free tree is a connnected, acyclic, undirected graph. A rooted tree is a free tree in which one of the vertices is distinguished from the others. A vertex of a rooted tree is called "node."
Your task is to write a program which reports the following information for each node u of a given rooted tree T:
* node ID of u
* parent of u
* depth of u
* node type (root, internal node or leaf)
* a list of chidlren of u
If the last edge on the path from the root r of a tree T to a node x is (p, x), then p is the parent of x, and x is a child of p. The root is the only node in T with no parent.
A node with no children is an external node or leaf. A nonleaf node is an internal node
The number of children of a node x in a rooted tree T is called the degree of x.
The length of the path from the root r to a node x is the depth of x in T.
Here, the given tree consists of n nodes and evey node has a unique ID from 0 to n-1.
Fig. 2 shows an example of rooted trees where ID of each node is indicated by a number in a circle (node). The example corresponds to the first sample input.
<image>
Fig. 2
Note
You can use a left-child, right-sibling representation to implement a tree which has the following data:
* the parent of u
* the leftmost child of u
* the immediate right sibling of u
Constraints
* 1 ≤ n ≤ 100000
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 u is given in the following format:
id k c1 c2 ... ck
where id is the node ID of u, k is the degree of u, c1 ... ck are node IDs of 1st, ... kth child of u. If the node does not have a child, the k is 0.
Output
Print the information of each node in the following format ordered by IDs:
node id: parent = p, depth = d, type, [c1...ck]
p is ID of its parent. If the node does not have a parent, print -1.
d is depth of the node.
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.
c1...ck is the list of children as a ordered tree.
Please follow the format presented in a sample output below.
Examples
Input
13
0 3 1 4 10
1 2 2 3
2 0
3 0
4 3 5 6 7
5 0
6 0
7 2 8 9
8 0
9 0
10 2 11 12
11 0
12 0
Output
node 0: parent = -1, depth = 0, root, [1, 4, 10]
node 1: parent = 0, depth = 1, internal node, [2, 3]
node 2: parent = 1, depth = 2, leaf, []
node 3: parent = 1, depth = 2, leaf, []
node 4: parent = 0, depth = 1, internal node, [5, 6, 7]
node 5: parent = 4, depth = 2, leaf, []
node 6: parent = 4, depth = 2, leaf, []
node 7: parent = 4, depth = 2, internal node, [8, 9]
node 8: parent = 7, depth = 3, leaf, []
node 9: parent = 7, depth = 3, leaf, []
node 10: parent = 0, depth = 1, internal node, [11, 12]
node 11: parent = 10, depth = 2, leaf, []
node 12: parent = 10, depth = 2, leaf, []
Input
4
1 3 3 2 0
0 0
3 0
2 0
Output
node 0: parent = 1, depth = 1, leaf, []
node 1: parent = -1, depth = 0, root, [3, 2, 0]
node 2: parent = 1, depth = 1, leaf, []
node 3: parent = 1, depth = 1, leaf, []
Submitted Solution:
```
import sys
def dep(u, p):
D[u] = p
if tree[u][2] != NIL:
dep(tree[u][2], p)
if tree[u][1] != NIL:
dep(tree[u][1], p+1)
def print_ans():
for i in range(n):
print("node {}: parent = {}, depth = {}, {}, {}"
.format(i, tree[i][0], D[i], tree[i][4], tree[i][3]))
if __name__ == "__main__":
NIL = -1
n = int(sys.stdin.readline())
tree = [[NIL, NIL, NIL] for i in range(n)]
D = [0 for i in range(n)]
for a in sys.stdin.readlines():
a = list(map(int, a.split()))
tree[a[0]].append(a[2:])
if a[1] > 0:
tree[a[0]][1] = a[2] # ???????????????
for i in range(a[1]):
tree[a[i+2]][0] = a[0] # ????????????
if i != a[1] - 1:
tree[a[i+2]][2] = a[i+3] # ??????????????????
for i in range(n):
if tree[i][0] == NIL:
tree[i].append("root")
r = i
elif tree[i][1] == NIL:
tree[i].append("leaf")
else:
tree[i].append("internal node")
dep(r, 0)
print_ans()
``` | instruction | 0 | 101,178 | 13 | 202,356 |
No | output | 1 | 101,178 | 13 | 202,357 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices. You are playing a game on this tree.
Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black vertex and paint it black.
Each time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.
Let's see the following example:
<image>
Vertices 1 and 4 are painted black already. If you choose the vertex 2, you will gain 4 points for the connected component consisting of vertices 2, 3, 5 and 6. If you choose the vertex 9, you will gain 3 points for the connected component consisting of vertices 7, 8 and 9.
Your task is to maximize the number of points you gain.
Input
The first line contains an integer n — the number of vertices in the tree (2 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the indices of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum number of points you gain if you will play optimally.
Examples
Input
9
1 2
2 3
2 5
2 6
1 4
4 9
9 7
9 8
Output
36
Input
5
1 2
1 3
2 4
2 5
Output
14
Note
The first example tree is shown in the problem statement. | instruction | 0 | 101,270 | 13 | 202,540 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
from sys import stdin
si = iter(stdin)
num = int(next(si))
nodeedge = [[] for _ in range(num + 1)]
nodescore = [0] * (num + 1)
nodecount = [0] * (num + 1)
for _ in range(num-1):
u,v = map(int, next(si).split())
nodeedge[u].append(v)
nodeedge[v].append(u)
p = 0
q = 1
n = 1
inlist = [False] * (num + 1)
nodelist = [n]
inlist[n] = True
for p in range(num):
for m in nodeedge[nodelist[p]]:
if not inlist[m]:
nodelist.append(m)
inlist[m] = True
for p in range(num-1, -1, -1):
nodes = 1
score = 0
n = nodelist[p]
for m in nodeedge[n]:
nodes += nodecount[m]
score += nodescore[m]
score += nodes
nodecount[n] = nodes
nodescore[n] = score
updated = [False] * (num + 1)
updated[nodelist[0]] = True
best = 0
for p in range(num):
n = nodelist[p]
for m in nodeedge[n]:
if not updated[m]:
nodescore[m] = nodescore[n] - 2 * nodecount[m] + num
updated[m] = True
if nodescore[m] > best:
best = nodescore[m]
print(best)
``` | output | 1 | 101,270 | 13 | 202,541 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices. You are playing a game on this tree.
Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black vertex and paint it black.
Each time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.
Let's see the following example:
<image>
Vertices 1 and 4 are painted black already. If you choose the vertex 2, you will gain 4 points for the connected component consisting of vertices 2, 3, 5 and 6. If you choose the vertex 9, you will gain 3 points for the connected component consisting of vertices 7, 8 and 9.
Your task is to maximize the number of points you gain.
Input
The first line contains an integer n — the number of vertices in the tree (2 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the indices of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum number of points you gain if you will play optimally.
Examples
Input
9
1 2
2 3
2 5
2 6
1 4
4 9
9 7
9 8
Output
36
Input
5
1 2
1 3
2 4
2 5
Output
14
Note
The first example tree is shown in the problem statement. | instruction | 0 | 101,271 | 13 | 202,542 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
import sys
from collections import deque
input = sys.stdin.readline
n=int(input())
E=[[] for i in range(n+1)]
for i in range(n-1):
x,y=map(int,input().split())
E[x].append(y)
E[y].append(x)
H=[-1]*(n+1)
H[1]=0
QUE=deque([1])
fromnode=[-1]*(n+1)
while QUE:
x=QUE.pop()
for to in E[x]:
if H[to]==-1:
H[to]=H[x]+1
fromnode[to]=x
QUE.append(to)
S=list(range(1,n+1))
S.sort(key=lambda x:H[x],reverse=True)
DP1=[0]*(n+1) # from the other nodes to 1
Size=[0]*(n+1)
for s in S:
for to in E[s]:
if Size[to]!=0:
Size[s]+=Size[to]
DP1[s]+=DP1[to]
Size[s]+=1
DP1[s]+=Size[s]
ANS=[0]*(n+1)
ANS[1]=DP1[1]
for s in S[::-1][1:]:
ANS[s]=ANS[fromnode[s]]+n-2*Size[s]
print(max(ANS))
``` | output | 1 | 101,271 | 13 | 202,543 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices. You are playing a game on this tree.
Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black vertex and paint it black.
Each time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.
Let's see the following example:
<image>
Vertices 1 and 4 are painted black already. If you choose the vertex 2, you will gain 4 points for the connected component consisting of vertices 2, 3, 5 and 6. If you choose the vertex 9, you will gain 3 points for the connected component consisting of vertices 7, 8 and 9.
Your task is to maximize the number of points you gain.
Input
The first line contains an integer n — the number of vertices in the tree (2 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the indices of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum number of points you gain if you will play optimally.
Examples
Input
9
1 2
2 3
2 5
2 6
1 4
4 9
9 7
9 8
Output
36
Input
5
1 2
1 3
2 4
2 5
Output
14
Note
The first example tree is shown in the problem statement. | instruction | 0 | 101,272 | 13 | 202,544 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
import sys
input = sys.stdin.readline
n = int(input())
ab = [list(map(int,input().split())) for i in range(n-1)]
graph = [[] for i in range(n+1)]
deg = [0]*(n+1)
for a,b in ab:
graph[a].append(b)
graph[b].append(a)
deg[a] += 1
deg[b] += 1
if n == 2:
print(3)
exit()
root = 0
stack = []
for i in range(1,n+1):
if deg[i] == 1:
stack.append(i)
elif not root:
root = i
deg[root] += 1
dpp = [[] for i in range(n+1)]
dpv = [[] for i in range(n+1)]
pnt = [0]*(n+1)
vtxs = [0]*(n+1)
while stack:
x = stack.pop()
vtxs[x] = sum(dpv[x])+1
pnt[x] = sum(dpp[x])+vtxs[x]
for y in graph[x]:
if deg[y] > 1:
dpp[y].append(pnt[x])
dpv[y].append(vtxs[x])
deg[y] -= 1
if deg[y] == 1:
stack.append(y)
pntsum = [0]*(n+1)
pntsum[root] = pnt[root]
stack = [root]
while stack:
x = stack.pop()
if x == root:
deg[x] -= 1
pntsum[x] = sum(dpp[x])+n
for y in graph[x]:
if deg[y] == 1:
dpp[y].append(pntsum[x]-vtxs[y]-pnt[y])
dpv[y].append(n-vtxs[y])
deg[y] -= 1
stack.append(y)
print(max(pntsum))
``` | output | 1 | 101,272 | 13 | 202,545 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices. You are playing a game on this tree.
Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black vertex and paint it black.
Each time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.
Let's see the following example:
<image>
Vertices 1 and 4 are painted black already. If you choose the vertex 2, you will gain 4 points for the connected component consisting of vertices 2, 3, 5 and 6. If you choose the vertex 9, you will gain 3 points for the connected component consisting of vertices 7, 8 and 9.
Your task is to maximize the number of points you gain.
Input
The first line contains an integer n — the number of vertices in the tree (2 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the indices of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum number of points you gain if you will play optimally.
Examples
Input
9
1 2
2 3
2 5
2 6
1 4
4 9
9 7
9 8
Output
36
Input
5
1 2
1 3
2 4
2 5
Output
14
Note
The first example tree is shown in the problem statement. | instruction | 0 | 101,273 | 13 | 202,546 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
###pyrival template for fast IO
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")
##make the tree
n=int(input())
tree={1:[]}
for i in range(n-1):
a,b=[int(x) for x in input().split()]
if a not in tree:
tree[a]=[b]
else:
tree[a].append(b)
if b not in tree:
tree[b]=[a]
else:
tree[b].append(a)
###### undirected dfs thats not n2 in worst case
def dfs(graph,n,currnode):
visited=[False for x in range(n+1)]
stack=[currnode]
parent=[0 for x in range(n+1)]
index=[0 for x in range(n+1)]
ans=[1 for x in range(n+1)]
arr=[]
while stack:
currnode=stack[-1]
if visited[currnode]==False:
visited[currnode]=True
arr.append(currnode)
for i in range(index[currnode],len(graph[currnode])):
neighbour=graph[currnode][i]
if visited[neighbour]==False:
visited[neighbour]=True
stack.append(neighbour)
parent[neighbour]=currnode
arr.append(neighbour)
index[currnode]+=1
break
else:
ans[parent[currnode]]+=ans[currnode]
####prefix sum arr
stack.pop()
return ans,parent,arr
a,parent,arr=dfs(tree,n,1)
ans=[0 for x in range(n+1)]
ans[1]=sum(a[1:]) #total sum of prefix sum
s=ans[1]
'''
rooting forula
node=2
a[parent[node]]-=a[node]
a[node]+=a[parent[node]]
print(sum(a[1:]))
'''
def dfs1(graph,n,currnode):
global s
visited=[False for x in range(n+1)]
stack=[currnode]
index=[0 for x in range(n+1)]
while stack:
currnode=stack[-1]
if visited[currnode]==False:
visited[currnode]=True
for i in range(index[currnode],len(graph[currnode])):
neighbour=graph[currnode][i]
if visited[neighbour]==False:
visited[neighbour]=True
stack.append(neighbour)
index[currnode]+=1
###re rooting our ans arr
a[parent[neighbour]]-=a[neighbour]
s-=a[neighbour]
a[neighbour]+=a[parent[neighbour]]
s+=a[parent[neighbour]]
ans[neighbour]=s##optimise this
break
else:
##changing state back to its parent after backtacking
a[currnode]-=a[parent[currnode]]
s-=a[parent[currnode]]
a[parent[currnode]]+=a[currnode]
s+=a[currnode]
stack.pop()
return
dfs1(tree,n,1)
print(max(ans[1:]))
``` | output | 1 | 101,273 | 13 | 202,547 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices. You are playing a game on this tree.
Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black vertex and paint it black.
Each time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.
Let's see the following example:
<image>
Vertices 1 and 4 are painted black already. If you choose the vertex 2, you will gain 4 points for the connected component consisting of vertices 2, 3, 5 and 6. If you choose the vertex 9, you will gain 3 points for the connected component consisting of vertices 7, 8 and 9.
Your task is to maximize the number of points you gain.
Input
The first line contains an integer n — the number of vertices in the tree (2 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the indices of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum number of points you gain if you will play optimally.
Examples
Input
9
1 2
2 3
2 5
2 6
1 4
4 9
9 7
9 8
Output
36
Input
5
1 2
1 3
2 4
2 5
Output
14
Note
The first example tree is shown in the problem statement. | instruction | 0 | 101,274 | 13 | 202,548 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
import sys
from collections import deque
from random import randrange
input = sys.stdin.readline
print = sys.stdout.write
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
n = int(input())
tree = [[] for i in range(n + 1)]
for i in range(n - 1):
a,b = map(int,input().strip().split())
tree[a].append(b)
tree[b].append(a)
dp = [0 for i in range(n + 1)]
s = [0 for i in range(n + 1)]
ans = [0 for i in range(n + 1)]
@bootstrap
def dfs(node,pd,dist):
for child in tree[node]:
if child == pd:
continue
yield dfs(child,node,dist + 1)
dp[node] += dp[child]
s[node] += s[child]
s[node] += 1
dp[node] += dist
yield dp[node]
root = randrange(1,n + 1)
dfs(root,-1,1)
q = deque(); ans[root] = dp[root]
for start in tree[root]:
q.append((start,root))
while len(q) > 0:
node,pd = q.popleft()
ans[node] = ans[pd] - s[node] + (s[root] - s[node])
for child in tree[node]:
if child == pd:
continue
q.append((child,node))
print(str(max(ans)))
``` | output | 1 | 101,274 | 13 | 202,549 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices. You are playing a game on this tree.
Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black vertex and paint it black.
Each time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.
Let's see the following example:
<image>
Vertices 1 and 4 are painted black already. If you choose the vertex 2, you will gain 4 points for the connected component consisting of vertices 2, 3, 5 and 6. If you choose the vertex 9, you will gain 3 points for the connected component consisting of vertices 7, 8 and 9.
Your task is to maximize the number of points you gain.
Input
The first line contains an integer n — the number of vertices in the tree (2 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the indices of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum number of points you gain if you will play optimally.
Examples
Input
9
1 2
2 3
2 5
2 6
1 4
4 9
9 7
9 8
Output
36
Input
5
1 2
1 3
2 4
2 5
Output
14
Note
The first example tree is shown in the problem statement. | instruction | 0 | 101,275 | 13 | 202,550 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
class Graph:
def __init__(self, n_vertices, edges, directed=True):
self.n_vertices = n_vertices
self.edges = edges
self.directed = directed
@property
def adj(self):
try:
return self._adj
except AttributeError:
adj = [[] for _ in range(self.n_vertices)]
if self.directed:
for u,v in self.edges:
adj[u].append(v)
else:
for u,v in self.edges:
adj[u].append(v)
adj[v].append(u)
self._adj = adj
return adj
class RootedTree(Graph):
def __init__(self, n_vertices, edges, root_vertex=0):
self.root = root_vertex
super().__init__(n_vertices, edges, False)
@property
def parent(self):
try:
return self._parent
except AttributeError:
adj = self.adj
parent = [None]*self.n_vertices
parent[self.root] = -1
stack = [self.root]
for _ in range(self.n_vertices):
v = stack.pop()
for u in adj[v]:
if parent[u] is None:
parent[u] = v
stack.append(u)
self._parent = parent
return parent
@property
def children(self):
try:
return self._children
except AttributeError:
children = [None]*self.n_vertices
for v,(l,p) in enumerate(zip(self.adj,self.parent)):
children[v] = [u for u in l if u != p]
self._children = children
return children
@property
def dfs_order(self):
try:
return self._dfs_order
except AttributeError:
order = [None]*self.n_vertices
children = self.children
stack = [self.root]
for i in range(self.n_vertices):
v = stack.pop()
order[i] = v
for u in children[v]:
stack.append(u)
self._dfs_order = order
return order
from functools import reduce
from itertools import accumulate,chain
def rerooting(rooted_tree, merge, identity, finalize):
N = rooted_tree.n_vertices
parent = rooted_tree.parent
children = rooted_tree.children
order = rooted_tree.dfs_order
# from leaf to parent
dp_down = [None]*N
for v in reversed(order[1:]):
dp_down[v] = finalize(reduce(merge,
(dp_down[c] for c in children[v]),
identity), v)
# from parent to leaf
dp_up = [None]*N
dp_up[0] = identity
for v in order:
if len(children[v]) == 0:
continue
temp = (dp_up[v],)+tuple(dp_down[u] for u in children[v])+(identity,)
left = accumulate(temp[:-2],merge)
right = tuple(accumulate(reversed(temp[2:]),merge))
for u,l,r in zip(children[v],left,reversed(right)):
dp_up[u] = finalize(merge(l,r), v)
res = [None]*N
for v,l in enumerate(children):
res[v] = reduce(merge,
(dp_down[u] for u in children[v]),
identity)
res[v] = finalize(merge(res[v], dp_up[v]), v)
return res
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
if __name__ == '__main__':
n = int(readline())
temp = map(lambda x:int(x)-1, read().split())
edges = zip(temp,temp)
def merge(x,y):
p1, s1 = x
p2, s2 = y
return p1+p2,s1+s2
def finalize(x,v):
p, s = x
return p+s+1, s+1
t = RootedTree(n, edges, 0)
res = rerooting(t, merge, (0,0), finalize)
print(max(res)[0])
``` | output | 1 | 101,275 | 13 | 202,551 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices. You are playing a game on this tree.
Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black vertex and paint it black.
Each time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.
Let's see the following example:
<image>
Vertices 1 and 4 are painted black already. If you choose the vertex 2, you will gain 4 points for the connected component consisting of vertices 2, 3, 5 and 6. If you choose the vertex 9, you will gain 3 points for the connected component consisting of vertices 7, 8 and 9.
Your task is to maximize the number of points you gain.
Input
The first line contains an integer n — the number of vertices in the tree (2 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the indices of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum number of points you gain if you will play optimally.
Examples
Input
9
1 2
2 3
2 5
2 6
1 4
4 9
9 7
9 8
Output
36
Input
5
1 2
1 3
2 4
2 5
Output
14
Note
The first example tree is shown in the problem statement. | instruction | 0 | 101,276 | 13 | 202,552 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
import sys
def getpar(Edge, p):
N = len(Edge)
par = [0]*N
par[0] = -1
par[p] -1
stack = [p]
visited = set([p])
while stack:
vn = stack.pop()
for vf in Edge[vn]:
if vf in visited:
continue
visited.add(vf)
par[vf] = vn
stack.append(vf)
return par
def topological_sort_tree(E, r):
Q = [r]
L = []
visited = set([r])
while Q:
vn = Q.pop()
L.append(vn)
for vf in E[vn]:
if vf not in visited:
visited.add(vf)
Q.append(vf)
return L
def getcld(p):
res = [[] for _ in range(len(p))]
for i, v in enumerate(p[1:], 1):
res[v].append(i)
return res
N = int(input())
Edge = [[] for _ in range(N)]
for _ in range(N-1):
a, b = map(int, sys.stdin.readline().split())
a -= 1
b -= 1
Edge[a].append(b)
Edge[b].append(a)
P = getpar(Edge, 0)
L = topological_sort_tree(Edge, 0)
C = getcld(P)
dp1 = [1]*N
size = [1]*N
for l in L[N-1:0:-1]:
p = P[l]
dp1[p] = dp1[p] + dp1[l] + size[l]
size[p] = size[p] + size[l]
dp2 = [1]*N
dp2[0] = dp1[0]
for l in L[1:]:
p = P[l]
dp2[l] = dp2[p] + N - 2*size[l]
print(max(dp2))
``` | output | 1 | 101,276 | 13 | 202,553 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices. You are playing a game on this tree.
Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black vertex and paint it black.
Each time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.
Let's see the following example:
<image>
Vertices 1 and 4 are painted black already. If you choose the vertex 2, you will gain 4 points for the connected component consisting of vertices 2, 3, 5 and 6. If you choose the vertex 9, you will gain 3 points for the connected component consisting of vertices 7, 8 and 9.
Your task is to maximize the number of points you gain.
Input
The first line contains an integer n — the number of vertices in the tree (2 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the indices of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum number of points you gain if you will play optimally.
Examples
Input
9
1 2
2 3
2 5
2 6
1 4
4 9
9 7
9 8
Output
36
Input
5
1 2
1 3
2 4
2 5
Output
14
Note
The first example tree is shown in the problem statement. | instruction | 0 | 101,277 | 13 | 202,554 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
import sys
import threading
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
N = int(input())
graph = [[] for _ in range(N)]
for _ in range(N-1):
a, b = map(int, input().split())
graph[a-1].append(b-1)
graph[b-1].append(a-1)
dp = [1]*N
checked1 = [False]*N
checked = [False]*N
ans = 0
def dfs(p):
checked1[p] = True
for np in graph[p]:
if not checked1[np]:
dfs(np)
dp[p] += dp[np]
def reroot(p, score):
global ans
ans = max(ans, score)
checked[p] = True
for np in graph[p]:
if not checked[np]:
root = dp[p]
goto = dp[np]
dp[np] = root
dp[p] = root - goto
reroot(np, score + root - 2*goto)
dp[np] = goto
dp[p] = root
def main():
dfs(0)
reroot(0, sum(dp))
print(ans)
if __name__ == "__main__":
threading.stack_size(1024 * 100000)
thread = threading.Thread(target=main)
thread.start()
thread.join()
``` | output | 1 | 101,277 | 13 | 202,555 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices. You are playing a game on this tree.
Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black vertex and paint it black.
Each time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.
Let's see the following example:
<image>
Vertices 1 and 4 are painted black already. If you choose the vertex 2, you will gain 4 points for the connected component consisting of vertices 2, 3, 5 and 6. If you choose the vertex 9, you will gain 3 points for the connected component consisting of vertices 7, 8 and 9.
Your task is to maximize the number of points you gain.
Input
The first line contains an integer n — the number of vertices in the tree (2 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the indices of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum number of points you gain if you will play optimally.
Examples
Input
9
1 2
2 3
2 5
2 6
1 4
4 9
9 7
9 8
Output
36
Input
5
1 2
1 3
2 4
2 5
Output
14
Note
The first example tree is shown in the problem statement.
Submitted Solution:
```
# ///////////////////////////////////////////////////////////////////////////
# //////////////////// PYTHON IS THE BEST ////////////////////////
# ///////////////////////////////////////////////////////////////////////////
import sys,os,io
import math
from collections import defaultdict
from io import BytesIO, IOBase
from types import GeneratorType
BUFSIZE = 8192
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
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")
def ii():
return int(input())
def li():
return list(map(int,input().split()))
# ///////////////////////////////////////////////////////////////////////////
# //////////////////// DO NOT TOUCH BEFORE THIS LINE ////////////////////////
# ///////////////////////////////////////////////////////////////////////////
if(os.path.exists('input.txt')):
sys.stdin = open("input.txt","r") ; sys.stdout = open("output.txt","w")
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
n = ii()
adj = [[] for i in range(n)]
for i in range(n-1):
u,v = li()
u-=1
v-=1
adj[u].append(v)
adj[v].append(u)
ans = 0
size = [0]*n
@bootstrap
def dfs(node,parent):
sz = 0
for kid in adj[node]:
if kid!=parent:
sz+=yield dfs(kid,node)
size[node] = sz+1
yield size[node]
dfs(0,-1)
# print(size)
parentscore = 0
@bootstrap
def dfs(node,parent):
global parentscore
parentscore += size[node]
cnt = 0
for kid in adj[node]:
if kid!=parent:
yield dfs(kid,node)
yield
dfs(0,-1)
# print(parentscore)
@bootstrap
def dfs(node,parent,parentscore):
global ans
ans = max(ans,parentscore)
# print(parent,node,parentscore)
for kid in adj[node]:
if kid!=parent:
yield dfs(kid,node,parentscore+n-2*size[kid])
yield
dfs(0,-1,parentscore)
print(ans)
``` | instruction | 0 | 101,278 | 13 | 202,556 |
Yes | output | 1 | 101,278 | 13 | 202,557 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices. You are playing a game on this tree.
Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black vertex and paint it black.
Each time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.
Let's see the following example:
<image>
Vertices 1 and 4 are painted black already. If you choose the vertex 2, you will gain 4 points for the connected component consisting of vertices 2, 3, 5 and 6. If you choose the vertex 9, you will gain 3 points for the connected component consisting of vertices 7, 8 and 9.
Your task is to maximize the number of points you gain.
Input
The first line contains an integer n — the number of vertices in the tree (2 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the indices of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum number of points you gain if you will play optimally.
Examples
Input
9
1 2
2 3
2 5
2 6
1 4
4 9
9 7
9 8
Output
36
Input
5
1 2
1 3
2 4
2 5
Output
14
Note
The first example tree is shown in the problem statement.
Submitted Solution:
```
import sys
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n = int(input())
g = [[] for _ in range(n)]
for i in range(n-1):
u, v = map(int, input().split())
u, v = u-1, v-1
g[u].append(v)
g[v].append(u)
s = []
s.append(0)
order = []
parent = [-1]*n
while s:
v = s.pop()
order.append(v)
for u in g[v]:
if parent[v] != u:
s.append(u)
parent[u] = v
order.reverse()
dp = [0]*n
subtree = [1]*n
for v in order:
dp[v] += subtree[v]
if parent[v] != -1:
subtree[parent[v]] += subtree[v]
dp[parent[v]] += dp[v]
#print(dp)
#print(subtree)
order.reverse()
ans = [0]*n
for v in order:
ans[v] = dp[v]
for u in g[v]:
temp = ans[v]
temp -= dp[u]+subtree[u]
#print(u, temp)
dp[u] -= subtree[u]
subtree[u] = n
dp[u] += subtree[u]
dp[u] += temp
print(max(ans))
``` | instruction | 0 | 101,279 | 13 | 202,558 |
Yes | output | 1 | 101,279 | 13 | 202,559 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices. You are playing a game on this tree.
Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black vertex and paint it black.
Each time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.
Let's see the following example:
<image>
Vertices 1 and 4 are painted black already. If you choose the vertex 2, you will gain 4 points for the connected component consisting of vertices 2, 3, 5 and 6. If you choose the vertex 9, you will gain 3 points for the connected component consisting of vertices 7, 8 and 9.
Your task is to maximize the number of points you gain.
Input
The first line contains an integer n — the number of vertices in the tree (2 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the indices of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum number of points you gain if you will play optimally.
Examples
Input
9
1 2
2 3
2 5
2 6
1 4
4 9
9 7
9 8
Output
36
Input
5
1 2
1 3
2 4
2 5
Output
14
Note
The first example tree is shown in the problem statement.
Submitted Solution:
```
from sys import stdin
def create_nodelist():
p = 0
q = 1
n = 1
inlist = [False] * (num+1)
nodelist = [n]
inlist[n] = True
while p < q:
for m in nodeedge[nodelist[p]]:
if not inlist[m]:
nodelist.append(m)
q+=1
inlist[m] = True
p+=1
assert len(nodelist) == num
return nodelist
def base_nodescores(nodelist):
for p in range(num-1, -1, -1):
nodes = 1
score = 0
n = nodelist[p]
for m in nodeedge[n]:
nodes += nodecount[m]
score += nodescore[m]
score += nodes
nodecount[n] = nodes
nodescore[n] = score
def update_nodescores(nodelist):
updated = [False] * (num+1)
updated[nodelist[0]] = True
for p in range(num):
n = nodelist[p]
for m in nodeedge[n]:
if not updated[m]:
nodescore[m] = nodescore[n] - 2*nodecount[m] + num
updated[m] = True
si = iter(stdin)
num = int(next(si))
nodeedge = [[] for _ in range(num + 1)]
nodescore = [0] * (num + 1)
nodecount = [0] * (num + 1)
for _ in range(num-1):
u,v = map(int, next(si).split())
nodeedge[u].append(v)
nodeedge[v].append(u)
nodelist = create_nodelist()
base_nodescores(nodelist)
update_nodescores(nodelist)
print(max(nodescore))
``` | instruction | 0 | 101,280 | 13 | 202,560 |
Yes | output | 1 | 101,280 | 13 | 202,561 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices. You are playing a game on this tree.
Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black vertex and paint it black.
Each time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.
Let's see the following example:
<image>
Vertices 1 and 4 are painted black already. If you choose the vertex 2, you will gain 4 points for the connected component consisting of vertices 2, 3, 5 and 6. If you choose the vertex 9, you will gain 3 points for the connected component consisting of vertices 7, 8 and 9.
Your task is to maximize the number of points you gain.
Input
The first line contains an integer n — the number of vertices in the tree (2 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the indices of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum number of points you gain if you will play optimally.
Examples
Input
9
1 2
2 3
2 5
2 6
1 4
4 9
9 7
9 8
Output
36
Input
5
1 2
1 3
2 4
2 5
Output
14
Note
The first example tree is shown in the problem statement.
Submitted Solution:
```
from sys import *
from queue import deque
n = int(stdin.readline())
adj = [[] for i in range(n)]
for i in range(n-1):
u,v = map(int, stdin.readline().split())
adj[u-1].append(v-1)
adj[v-1].append(u-1)
root = 0
# root the tree
def rooted(root):
new_adj = [[] for i in range(n)]
pi = [-1]*n
visited = [False]*n
visited[root] = True
todo = [root]
while todo:
top = todo.pop()
for nbr in adj[top]:
if not visited[nbr]:
visited[nbr] = True
todo.append(nbr)
pi[nbr] = top
new_adj[top].append(nbr)
return new_adj, pi
adj, pi = rooted(root)
size = [0]*n
subtree = [0]*n
dists = [0]*n
# post-order: process children, then parent
def fill_size(v):
s = 1
subt = 0
for nbr in adj[v]:
rs, rsubt = fill_size(nbr)
s += rs
subt += rsubt + rs
size[v] = s
subtree[v] = subt
return s, subt
#fill_size(root)
#iterative version
final = []
todo = [root]
while todo:
v = todo.pop()
for w in adj[v]:
todo.append(w)
final.append(v)
for v in reversed(final):
s = 1
subt = 0
for child in adj[v]:
s += size[child]
subt += size[child] + subtree[child]
size[v] = s
subtree[v] = subt
# preorder: process parent, then children
dists[root] = subtree[root]
def fill_dists(v):
if v != root:
dists[v] = dists[pi[v]] - size[v] + (n - size[v])
for nbr in adj[v]:
fill_dists(nbr)
#fill_dists(root)
#iterative version
todo = deque([root])
while todo:
top = todo.popleft()
if top != root:
dists[top] = dists[pi[top]] - size[top] + (n - size[top])
for nbr in adj[top]:
todo.append(nbr)
print(max(dists) + n)
``` | instruction | 0 | 101,281 | 13 | 202,562 |
Yes | output | 1 | 101,281 | 13 | 202,563 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices. You are playing a game on this tree.
Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black vertex and paint it black.
Each time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.
Let's see the following example:
<image>
Vertices 1 and 4 are painted black already. If you choose the vertex 2, you will gain 4 points for the connected component consisting of vertices 2, 3, 5 and 6. If you choose the vertex 9, you will gain 3 points for the connected component consisting of vertices 7, 8 and 9.
Your task is to maximize the number of points you gain.
Input
The first line contains an integer n — the number of vertices in the tree (2 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the indices of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum number of points you gain if you will play optimally.
Examples
Input
9
1 2
2 3
2 5
2 6
1 4
4 9
9 7
9 8
Output
36
Input
5
1 2
1 3
2 4
2 5
Output
14
Note
The first example tree is shown in the problem statement.
Submitted Solution:
```
n = int(input())
uvs = [[0, 0] for i in range(n)]
for i in range(n - 1):
uvs[i][0], uvs[i][1] = map(int, input().split(' '))
if n == 9:
print(36)
elif n == 5:
print(14)
``` | instruction | 0 | 101,282 | 13 | 202,564 |
No | output | 1 | 101,282 | 13 | 202,565 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices. You are playing a game on this tree.
Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black vertex and paint it black.
Each time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.
Let's see the following example:
<image>
Vertices 1 and 4 are painted black already. If you choose the vertex 2, you will gain 4 points for the connected component consisting of vertices 2, 3, 5 and 6. If you choose the vertex 9, you will gain 3 points for the connected component consisting of vertices 7, 8 and 9.
Your task is to maximize the number of points you gain.
Input
The first line contains an integer n — the number of vertices in the tree (2 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the indices of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum number of points you gain if you will play optimally.
Examples
Input
9
1 2
2 3
2 5
2 6
1 4
4 9
9 7
9 8
Output
36
Input
5
1 2
1 3
2 4
2 5
Output
14
Note
The first example tree is shown in the problem statement.
Submitted Solution:
```
g = {}
p = {}
n = int(input())
dp_1 = [0] * (n+1)
size = [0] * (n+1)
dp_2 = [None for _ in range(n+1)]
for _ in range(n-1):
u, v = map(int, input().split())
if u not in g:
g[u] = []
g[u].append(v)
if v not in g:
g[v] = []
g[v].append(u)
def dfs(p, dp_1, dp_2, size):
p[1] = 0
i = 0
S = [1]
while i < len(S):
cur = S[i]
for x in g[cur]:
if x == p[cur]:continue
p[x] = cur
S.append(x)
i += 1
for cur in S[::-1]:
if len(g[cur]) == 1 and cur!=1:
dp_1[cur] = 1
size[cur] = 1
dp_2[cur] = [1, 1]
else:
size[cur] = 1
max_val = 0
length = 0
for x in g[cur]:
if x == p[cur]:continue
size[cur] += size[x]
dp_1[cur] = size[cur]
for x in g[cur]:
if x == p[cur]:continue
dp_1[cur] += dp_1[x]
for x in g[cur]:
if x == p[cur]:continue
new_val = dp_2[x][0] + dp_2[x][1] * (size[cur]-size[x]) + (dp_1[cur]-dp_1[x]-size[x])
if new_val > max_val:
max_val, length = new_val, dp_2[x][1] + 1
elif new_val == max_val and dp_2[x][1] + 1 > length:
length = dp_2[x][1] + 1
dp_2[cur] = [max_val, length]
dfs(p, dp_1, dp_2, size)
print(dp_2[1][0])
#7
#7 6
#7 5
#7 2
#7 1
#5 4
#5 3
``` | instruction | 0 | 101,283 | 13 | 202,566 |
No | output | 1 | 101,283 | 13 | 202,567 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices. You are playing a game on this tree.
Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black vertex and paint it black.
Each time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.
Let's see the following example:
<image>
Vertices 1 and 4 are painted black already. If you choose the vertex 2, you will gain 4 points for the connected component consisting of vertices 2, 3, 5 and 6. If you choose the vertex 9, you will gain 3 points for the connected component consisting of vertices 7, 8 and 9.
Your task is to maximize the number of points you gain.
Input
The first line contains an integer n — the number of vertices in the tree (2 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the indices of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum number of points you gain if you will play optimally.
Examples
Input
9
1 2
2 3
2 5
2 6
1 4
4 9
9 7
9 8
Output
36
Input
5
1 2
1 3
2 4
2 5
Output
14
Note
The first example tree is shown in the problem statement.
Submitted Solution:
```
from collections import defaultdict as dd
v=int(input())
graph=dd(list)
deg=dd(int)
for edges in range(v-1):
a,b=map(int,input().split())
graph[a].append(b)
graph[b].append(a)
deg[a]+=1
deg[b]+=1
for i in deg:
if deg[i]==1:
leaf=i
break
visited=[0 for i in range(v+1)]
def dfs(graph,node=leaf,pts=0,vert=0):
visited[node]=1
if node!=leaf and deg[node]==1:
return 1
else:
for i in graph[node]:
if not visited[i]:
return(pts+vert+dfs(graph,i,pts,vert-1))
print(dfs(graph,leaf,0,v))
``` | instruction | 0 | 101,284 | 13 | 202,568 |
No | output | 1 | 101,284 | 13 | 202,569 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices. You are playing a game on this tree.
Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black vertex and paint it black.
Each time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.
Let's see the following example:
<image>
Vertices 1 and 4 are painted black already. If you choose the vertex 2, you will gain 4 points for the connected component consisting of vertices 2, 3, 5 and 6. If you choose the vertex 9, you will gain 3 points for the connected component consisting of vertices 7, 8 and 9.
Your task is to maximize the number of points you gain.
Input
The first line contains an integer n — the number of vertices in the tree (2 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the indices of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum number of points you gain if you will play optimally.
Examples
Input
9
1 2
2 3
2 5
2 6
1 4
4 9
9 7
9 8
Output
36
Input
5
1 2
1 3
2 4
2 5
Output
14
Note
The first example tree is shown in the problem statement.
Submitted Solution:
```
g = {}
p = {}
n = int(input())
dp_1 = [0] * (n+1)
size = [0] * (n+1)
dp_2 = [None for _ in range(n+1)]
for _ in range(n-1):
u, v = map(int, input().split())
if u not in g:
g[u] = []
g[u].append(v)
if v not in g:
g[v] = []
g[v].append(u)
def dfs(p, dp_1, dp_2, size):
root = 1
s_ = 1
for x in g:
if len(g[x]) > s_:
root = x
s_ = len(g[x])
p[root] = 0
i = 0
S = [root]
while i < len(S):
cur = S[i]
for x in g[cur]:
if x == p[cur]:continue
p[x] = cur
S.append(x)
i += 1
for cur in S[::-1]:
if len(g[cur]) == 1 and cur!=1:
dp_1[cur] = 1
size[cur] = 1
dp_2[cur] = [1, 1]
else:
size[cur] = 1
max_val = 0
length = 0
for x in g[cur]:
if x == p[cur]:continue
size[cur] += size[x]
dp_1[cur] = size[cur]
for x in g[cur]:
if x == p[cur]:continue
dp_1[cur] += dp_1[x]
for x in g[cur]:
if x == p[cur]:continue
new_val = dp_2[x][0] + dp_2[x][1] * (size[cur]-size[x]) + (dp_1[cur]-dp_1[x]-size[x])
if new_val > max_val:
max_val, length = new_val, dp_2[x][1] + 1
dp_2[cur] = [max_val, length]
return root
root = dfs(p, dp_1, dp_2, size)
print(dp_2[root][0])
#7
#7 6
#7 5
#7 2
#7 1
#5 4
#5 3
``` | instruction | 0 | 101,285 | 13 | 202,570 |
No | output | 1 | 101,285 | 13 | 202,571 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND).
Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all.
Input
The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers.
The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}).
Output
If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle.
Examples
Input
4
3 6 28 9
Output
4
Input
5
5 12 9 16 48
Output
3
Input
4
1 2 4 8
Output
-1
Note
In the first example, the shortest cycle is (9, 3, 6, 28).
In the second example, the shortest cycle is (5, 12, 9).
The graph has no cycles in the third example. | instruction | 0 | 101,286 | 13 | 202,572 |
Tags: bitmasks, brute force, graphs, shortest paths
Correct Solution:
```
#!/usr/bin/python3
import math
import sys
DEBUG = False
def inp():
return sys.stdin.readline().rstrip()
def dprint(*value, sep=' ', end='\n'):
if DEBUG:
print(*value, sep=sep, end=end)
INF = 70
def solve(N, A):
B = [set() for _ in range(63)]
for i, a in enumerate(A):
if a == 0:
continue
m = 1
for j in range(63):
if a & m:
B[j].add((a, i))
if len(B[j]) == 3:
return 3
m <<= 1
G = {}
for b in B:
if len(b) <= 1:
continue
(p, _), (q, _) = list(b)
if p == q:
continue
if p not in G:
G[p] = set()
if q not in G:
G[q] = set()
G[p].add(q)
G[q].add(p)
dprint(G)
best = INF
for start in G:
nodes = set([start])
level = 1
visited = set()
while nodes and level * 2 <= best:
nnodes = set()
for i in nodes:
for j in G[i]:
if j in nodes:
best = level * 2 - 1
break
if j in nnodes:
best = min(best, level * 2)
elif j not in visited:
nnodes.add(j)
if best == level * 2 - 1:
break
visited |= nodes
nodes = nnodes
level += 1
if best == INF:
return -1
return best
def main():
N = int(inp())
A = [int(e) for e in inp().split()]
print(solve(N, A))
if __name__ == '__main__':
main()
``` | output | 1 | 101,286 | 13 | 202,573 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.