message stringlengths 2 49.9k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 446 108k | cluster float64 13 13 | __index_level_0__ int64 892 217k |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp had a tree which consisted of n vertices and was rooted at vertex 1. He decided to study BFS ([Breadth-first search](https://en.wikipedia.org/wiki/Breadth-first_search)), so he ran BFS on his tree, starting from the root. BFS can be described by the following pseudocode:
a = [] # the order in which vertices were processed
q = Queue()
q.put(1) # place the root at the end of the queue
while not q.empty():
k = q.pop() # retrieve the first vertex from the queue
a.append(k) # append k to the end of the sequence in which vertices were visited
for y in g[k]: # g[k] is the list of all children of vertex k, sorted in ascending order
q.put(y)
Monocarp was fascinated by BFS so much that, in the end, he lost his tree. Fortunately, he still has a sequence of vertices, in which order vertices were visited by the BFS algorithm (the array a from the pseudocode). Monocarp knows that each vertex was visited exactly once (since they were put and taken from the queue exactly once). Also, he knows that all children of each vertex were viewed in ascending order.
Monocarp knows that there are many trees (in the general case) with the same visiting order a, so he doesn't hope to restore his tree. Monocarp is okay with any tree that has minimum height.
The height of a tree is the maximum depth of the tree's vertices, and the depth of a vertex is the number of edges in the path from the root to it. For example, the depth of vertex 1 is 0, since it's the root, and the depth of all root's children are 1.
Help Monocarp to find any tree with given visiting order a and minimum height.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree.
The second line of each test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n; a_i ≠ a_j; a_1 = 1) — the order in which the vertices were visited by the BFS algorithm.
It's guaranteed that the total sum of n over test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case print the minimum possible height of a tree with the given visiting order a.
Example
Input
3
4
1 4 3 2
2
1 2
3
1 2 3
Output
3
1
1
Note
In the first test case, there is only one tree with the given visiting order:
<image>
In the second test case, there is only one tree with the given visiting order as well:
<image>
In the third test case, an optimal tree with the given visiting order is shown below:
<image>
Submitted Solution:
```
for _ in range(int(input())):
n = int(input())
arr = list(map(int,input().split()))
nodes = 1
newNodes = 1
ans = 1
totBreaks = 0
for i in range(2,n):
if arr[i] > arr[i-1]:
newNodes+=1
else:
totBreaks+=1
if totBreaks>=nodes:
totBreaks = 0
nodes = newNodes
ans+=1
print(ans)
``` | instruction | 0 | 81,928 | 13 | 163,856 |
Yes | output | 1 | 81,928 | 13 | 163,857 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp had a tree which consisted of n vertices and was rooted at vertex 1. He decided to study BFS ([Breadth-first search](https://en.wikipedia.org/wiki/Breadth-first_search)), so he ran BFS on his tree, starting from the root. BFS can be described by the following pseudocode:
a = [] # the order in which vertices were processed
q = Queue()
q.put(1) # place the root at the end of the queue
while not q.empty():
k = q.pop() # retrieve the first vertex from the queue
a.append(k) # append k to the end of the sequence in which vertices were visited
for y in g[k]: # g[k] is the list of all children of vertex k, sorted in ascending order
q.put(y)
Monocarp was fascinated by BFS so much that, in the end, he lost his tree. Fortunately, he still has a sequence of vertices, in which order vertices were visited by the BFS algorithm (the array a from the pseudocode). Monocarp knows that each vertex was visited exactly once (since they were put and taken from the queue exactly once). Also, he knows that all children of each vertex were viewed in ascending order.
Monocarp knows that there are many trees (in the general case) with the same visiting order a, so he doesn't hope to restore his tree. Monocarp is okay with any tree that has minimum height.
The height of a tree is the maximum depth of the tree's vertices, and the depth of a vertex is the number of edges in the path from the root to it. For example, the depth of vertex 1 is 0, since it's the root, and the depth of all root's children are 1.
Help Monocarp to find any tree with given visiting order a and minimum height.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree.
The second line of each test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n; a_i ≠ a_j; a_1 = 1) — the order in which the vertices were visited by the BFS algorithm.
It's guaranteed that the total sum of n over test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case print the minimum possible height of a tree with the given visiting order a.
Example
Input
3
4
1 4 3 2
2
1 2
3
1 2 3
Output
3
1
1
Note
In the first test case, there is only one tree with the given visiting order:
<image>
In the second test case, there is only one tree with the given visiting order as well:
<image>
In the third test case, an optimal tree with the given visiting order is shown below:
<image>
Submitted Solution:
```
for _ in range(int(input())):
n = int(input())
arr = list(map(int, input().split()))
now_index = 0
height = [0] * (n + 1)
prev_value = 1
for i in range(1, n):
if prev_value > arr[i]:
prev_value = arr[i]
now_index += 1
height[i] = height[now_index] + 1
else:
prev_value = arr[i]
height[i] = height[now_index] + 1
print(max(height))
``` | instruction | 0 | 81,929 | 13 | 163,858 |
Yes | output | 1 | 81,929 | 13 | 163,859 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp had a tree which consisted of n vertices and was rooted at vertex 1. He decided to study BFS ([Breadth-first search](https://en.wikipedia.org/wiki/Breadth-first_search)), so he ran BFS on his tree, starting from the root. BFS can be described by the following pseudocode:
a = [] # the order in which vertices were processed
q = Queue()
q.put(1) # place the root at the end of the queue
while not q.empty():
k = q.pop() # retrieve the first vertex from the queue
a.append(k) # append k to the end of the sequence in which vertices were visited
for y in g[k]: # g[k] is the list of all children of vertex k, sorted in ascending order
q.put(y)
Monocarp was fascinated by BFS so much that, in the end, he lost his tree. Fortunately, he still has a sequence of vertices, in which order vertices were visited by the BFS algorithm (the array a from the pseudocode). Monocarp knows that each vertex was visited exactly once (since they were put and taken from the queue exactly once). Also, he knows that all children of each vertex were viewed in ascending order.
Monocarp knows that there are many trees (in the general case) with the same visiting order a, so he doesn't hope to restore his tree. Monocarp is okay with any tree that has minimum height.
The height of a tree is the maximum depth of the tree's vertices, and the depth of a vertex is the number of edges in the path from the root to it. For example, the depth of vertex 1 is 0, since it's the root, and the depth of all root's children are 1.
Help Monocarp to find any tree with given visiting order a and minimum height.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree.
The second line of each test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n; a_i ≠ a_j; a_1 = 1) — the order in which the vertices were visited by the BFS algorithm.
It's guaranteed that the total sum of n over test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case print the minimum possible height of a tree with the given visiting order a.
Example
Input
3
4
1 4 3 2
2
1 2
3
1 2 3
Output
3
1
1
Note
In the first test case, there is only one tree with the given visiting order:
<image>
In the second test case, there is only one tree with the given visiting order as well:
<image>
In the third test case, an optimal tree with the given visiting order is shown below:
<image>
Submitted Solution:
```
t=int(input())
for _ in range(t):
n=int(input())
l=list(map(int,input().split()))
x=0
h=1
q=0
for i in range(1,n):
if l[i]>l[i-1]:
x+=1
else:
if q==0:
h+=1
q=x-1
else:
q-=1
``` | instruction | 0 | 81,930 | 13 | 163,860 |
No | output | 1 | 81,930 | 13 | 163,861 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp had a tree which consisted of n vertices and was rooted at vertex 1. He decided to study BFS ([Breadth-first search](https://en.wikipedia.org/wiki/Breadth-first_search)), so he ran BFS on his tree, starting from the root. BFS can be described by the following pseudocode:
a = [] # the order in which vertices were processed
q = Queue()
q.put(1) # place the root at the end of the queue
while not q.empty():
k = q.pop() # retrieve the first vertex from the queue
a.append(k) # append k to the end of the sequence in which vertices were visited
for y in g[k]: # g[k] is the list of all children of vertex k, sorted in ascending order
q.put(y)
Monocarp was fascinated by BFS so much that, in the end, he lost his tree. Fortunately, he still has a sequence of vertices, in which order vertices were visited by the BFS algorithm (the array a from the pseudocode). Monocarp knows that each vertex was visited exactly once (since they were put and taken from the queue exactly once). Also, he knows that all children of each vertex were viewed in ascending order.
Monocarp knows that there are many trees (in the general case) with the same visiting order a, so he doesn't hope to restore his tree. Monocarp is okay with any tree that has minimum height.
The height of a tree is the maximum depth of the tree's vertices, and the depth of a vertex is the number of edges in the path from the root to it. For example, the depth of vertex 1 is 0, since it's the root, and the depth of all root's children are 1.
Help Monocarp to find any tree with given visiting order a and minimum height.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree.
The second line of each test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n; a_i ≠ a_j; a_1 = 1) — the order in which the vertices were visited by the BFS algorithm.
It's guaranteed that the total sum of n over test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case print the minimum possible height of a tree with the given visiting order a.
Example
Input
3
4
1 4 3 2
2
1 2
3
1 2 3
Output
3
1
1
Note
In the first test case, there is only one tree with the given visiting order:
<image>
In the second test case, there is only one tree with the given visiting order as well:
<image>
In the third test case, an optimal tree with the given visiting order is shown below:
<image>
Submitted Solution:
```
import sys
import math
from collections import defaultdict,deque
input = sys.stdin.readline
def inar():
return [int(el) for el in input().split()]
def main():
t=int(input())
for _ in range(t):
n=int(input())
arr=inar()
ans=1
for i in range(n):
if i==0:
continue
if arr[i]>arr[i-1]:
continue
else:
ans+=1
print(ans)
if __name__ == '__main__':
main()
``` | instruction | 0 | 81,931 | 13 | 163,862 |
No | output | 1 | 81,931 | 13 | 163,863 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp had a tree which consisted of n vertices and was rooted at vertex 1. He decided to study BFS ([Breadth-first search](https://en.wikipedia.org/wiki/Breadth-first_search)), so he ran BFS on his tree, starting from the root. BFS can be described by the following pseudocode:
a = [] # the order in which vertices were processed
q = Queue()
q.put(1) # place the root at the end of the queue
while not q.empty():
k = q.pop() # retrieve the first vertex from the queue
a.append(k) # append k to the end of the sequence in which vertices were visited
for y in g[k]: # g[k] is the list of all children of vertex k, sorted in ascending order
q.put(y)
Monocarp was fascinated by BFS so much that, in the end, he lost his tree. Fortunately, he still has a sequence of vertices, in which order vertices were visited by the BFS algorithm (the array a from the pseudocode). Monocarp knows that each vertex was visited exactly once (since they were put and taken from the queue exactly once). Also, he knows that all children of each vertex were viewed in ascending order.
Monocarp knows that there are many trees (in the general case) with the same visiting order a, so he doesn't hope to restore his tree. Monocarp is okay with any tree that has minimum height.
The height of a tree is the maximum depth of the tree's vertices, and the depth of a vertex is the number of edges in the path from the root to it. For example, the depth of vertex 1 is 0, since it's the root, and the depth of all root's children are 1.
Help Monocarp to find any tree with given visiting order a and minimum height.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree.
The second line of each test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n; a_i ≠ a_j; a_1 = 1) — the order in which the vertices were visited by the BFS algorithm.
It's guaranteed that the total sum of n over test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case print the minimum possible height of a tree with the given visiting order a.
Example
Input
3
4
1 4 3 2
2
1 2
3
1 2 3
Output
3
1
1
Note
In the first test case, there is only one tree with the given visiting order:
<image>
In the second test case, there is only one tree with the given visiting order as well:
<image>
In the third test case, an optimal tree with the given visiting order is shown below:
<image>
Submitted Solution:
```
import sys
from collections import defaultdict as dd
from collections import Counter as cc
from queue import Queue
import math
import itertools
try:
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
except:
pass
input = lambda: sys.stdin.buffer.readline().rstrip()
for _ in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
a[0]=200001
a.append(-1)
elements=1
depth=0
e=1
s=0
for i in range(2,n+1):
if a[i]<a[i-1]:
s+=1
if s==elements or a[i]==-1:
elements=e
s=0
depth+=1
e=1
else:
e+=1
print(depth)
``` | instruction | 0 | 81,932 | 13 | 163,864 |
No | output | 1 | 81,932 | 13 | 163,865 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp had a tree which consisted of n vertices and was rooted at vertex 1. He decided to study BFS ([Breadth-first search](https://en.wikipedia.org/wiki/Breadth-first_search)), so he ran BFS on his tree, starting from the root. BFS can be described by the following pseudocode:
a = [] # the order in which vertices were processed
q = Queue()
q.put(1) # place the root at the end of the queue
while not q.empty():
k = q.pop() # retrieve the first vertex from the queue
a.append(k) # append k to the end of the sequence in which vertices were visited
for y in g[k]: # g[k] is the list of all children of vertex k, sorted in ascending order
q.put(y)
Monocarp was fascinated by BFS so much that, in the end, he lost his tree. Fortunately, he still has a sequence of vertices, in which order vertices were visited by the BFS algorithm (the array a from the pseudocode). Monocarp knows that each vertex was visited exactly once (since they were put and taken from the queue exactly once). Also, he knows that all children of each vertex were viewed in ascending order.
Monocarp knows that there are many trees (in the general case) with the same visiting order a, so he doesn't hope to restore his tree. Monocarp is okay with any tree that has minimum height.
The height of a tree is the maximum depth of the tree's vertices, and the depth of a vertex is the number of edges in the path from the root to it. For example, the depth of vertex 1 is 0, since it's the root, and the depth of all root's children are 1.
Help Monocarp to find any tree with given visiting order a and minimum height.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree.
The second line of each test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n; a_i ≠ a_j; a_1 = 1) — the order in which the vertices were visited by the BFS algorithm.
It's guaranteed that the total sum of n over test cases doesn't exceed 2 ⋅ 10^5.
Output
For each test case print the minimum possible height of a tree with the given visiting order a.
Example
Input
3
4
1 4 3 2
2
1 2
3
1 2 3
Output
3
1
1
Note
In the first test case, there is only one tree with the given visiting order:
<image>
In the second test case, there is only one tree with the given visiting order as well:
<image>
In the third test case, an optimal tree with the given visiting order is shown below:
<image>
Submitted Solution:
```
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 28 08:12:57 2020
@author: Dell
"""
for x in range(int(input())):
n = int(input())
m=list(map(int,input().split()))
c=1
a=0
t=1
k=0
for i in range(1,n):
if m[i]<m[i-1]:
c-=1
if c==0:
c=t
a+=1
else:
t+=k
k=0
else:
k+=1
print(a+1)
``` | instruction | 0 | 81,933 | 13 | 163,866 |
No | output | 1 | 81,933 | 13 | 163,867 |
Provide a correct Python 3 solution for this coding contest problem.
We have a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and b_i. For each k=1, ..., N, solve the problem below:
* Consider writing a number on each vertex in the tree in the following manner:
* First, write 1 on Vertex k.
* Then, for each of the numbers 2, ..., N in this order, write the number on the vertex chosen as follows:
* Choose a vertex that still does not have a number written on it and is adjacent to a vertex with a number already written on it. If there are multiple such vertices, choose one of them at random.
* Find the number of ways in which we can write the numbers on the vertices, modulo (10^9+7).
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq a_i,b_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
For each k=1, 2, ..., N in this order, print a line containing the answer to the problem.
Examples
Input
3
1 2
1 3
Output
2
1
1
Input
2
1 2
Output
1
1
Input
5
1 2
2 3
3 4
3 5
Output
2
8
12
3
3
Input
8
1 2
2 3
3 4
3 5
3 6
6 7
6 8
Output
40
280
840
120
120
504
72
72 | instruction | 0 | 82,363 | 13 | 164,726 |
"Correct Solution:
```
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 28 22:56:10 2020
"""
import sys
#import numpy as np
sys.setrecursionlimit(10 ** 9)
#def input():
# return sys.stdin.readline()[:-1]
mod = 10**9+7
N = int(input())
#X, Y = map(int,input().split())
ab = [list(map(int,input().split())) for i in range(N-1)]
fact = [1, 1] # 元テーブル
fact_inv = [1, 1] # 逆元テーブル
tmp_inv = [0, 1] # 逆元テーブル計算用テーブル
for i in range(2, N+1):
fact.append((fact[-1] * i) % mod)
tmp_inv.append((-tmp_inv[mod % i] * (mod//i)) % mod)
fact_inv.append((fact_inv[-1] * tmp_inv[-1]) % mod)
def cmb(n, r, mod):
if (r < 0 or r > n):
return 0
r = min(r, n-r)
return fact[n] * fact_inv[r] * fact_inv[n-r] % mod
#逆元作成
def inv(a,mod):
return pow(a,mod-2,mod)
graph = [[] for _ in range(N+1)]
for a, b in ab:
graph[a].append(b)
graph[b].append(a)
root = 1
parent = [0] * (N + 1)
order = []
stack = [root]
while stack:
x = stack.pop()
order.append(x)
for y in graph[x]:
if parent[x] == y:
continue
parent[y] = x
stack.append(y)
size_d = [0] * (N + 1)
dp_d = [1] * (N + 1)
for v in order[::-1]:
dp_d[v] *= fact[size_d[v]]
dp_d[v] %= mod
p = parent[v]
s = size_d[v] + 1
size_d[p] += s
dp_d[p] *= fact_inv[s] * dp_d[v]
dp_d[p] %= mod
size_u = [N - x - 1 for x in size_d]
dp_u = [1] * (N + 1)
for v in order[1:]:
p = parent[v]
x = dp_d[p] * inv(dp_d[v],mod)
x *= fact_inv[size_d[p]] * fact[size_d[v] + 1]
x *= fact[size_u[v] - 1] * fact_inv[size_u[p]]
x *= dp_u[p]
dp_u[v] = x % mod
for xd, xu, sd, su in zip(dp_d[1:], dp_u[1:], size_d[1:], size_u[1:]):
x = xd * xu * fact[sd + su] * fact_inv[sd] * fact_inv[su] % mod
print(x)
``` | output | 1 | 82,363 | 13 | 164,727 |
Provide a correct Python 3 solution for this coding contest problem.
We have a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and b_i. For each k=1, ..., N, solve the problem below:
* Consider writing a number on each vertex in the tree in the following manner:
* First, write 1 on Vertex k.
* Then, for each of the numbers 2, ..., N in this order, write the number on the vertex chosen as follows:
* Choose a vertex that still does not have a number written on it and is adjacent to a vertex with a number already written on it. If there are multiple such vertices, choose one of them at random.
* Find the number of ways in which we can write the numbers on the vertices, modulo (10^9+7).
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq a_i,b_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
For each k=1, 2, ..., N in this order, print a line containing the answer to the problem.
Examples
Input
3
1 2
1 3
Output
2
1
1
Input
2
1 2
Output
1
1
Input
5
1 2
2 3
3 4
3 5
Output
2
8
12
3
3
Input
8
1 2
2 3
3 4
3 5
3 6
6 7
6 8
Output
40
280
840
120
120
504
72
72 | instruction | 0 | 82,364 | 13 | 164,728 |
"Correct Solution:
```
import sys
input = sys.stdin.readline
from collections import deque
mod = 10 ** 9 + 7
N = int(input())
X = [[] for i in range(N)]
for i in range(N-1):
x, y = map(int, input().split())
X[x-1].append(y-1)
X[y-1].append(x-1)
P = [-1] * N
Q = deque([0])
R = []
while Q:
i = deque.popleft(Q)
R.append(i)
for a in X[i]:
if a != P[i]:
P[a] = i
X[a].remove(i)
deque.append(Q, a)
##### Settings
unit = 1
merge = lambda a, b: a * b % mod
adj_bu = lambda a, i: a * inv(SIZE[i]) % mod
adj_td = lambda a, i, p: a * inv(N-SIZE[i]) % mod
adj_butd = lambda a, i: a * inv(N) % mod
#####
nn = 200200
mod = 10**9+7
fa = [1] * (nn+1)
fainv = [1] * (nn+1)
for i in range(nn):
fa[i+1] = fa[i] * (i+1) % mod
fainv[-1] = pow(fa[-1], mod-2, mod)
for i in range(nn)[::-1]:
fainv[i] = fainv[i+1] * (i+1) % mod
inv = lambda i: fainv[i] * fa[i-1] % mod
SIZE = [1] * N
for i in R[1:][::-1]:
SIZE[P[i]] += SIZE[i]
ME = [unit] * N
XX = [0] * N
TD = [unit] * N
for i in R[1:][::-1]:
XX[i] = adj_bu(ME[i], i)
p = P[i]
ME[p] = merge(ME[p], XX[i])
XX[R[0]] = adj_bu(ME[R[0]], R[0])
for i in R:
ac = TD[i]
for j in X[i]:
TD[j] = ac
ac = merge(ac, XX[j])
ac = unit
for j in X[i][::-1]:
TD[j] = adj_td(merge(TD[j], ac), j, i)
ac = merge(ac, XX[j])
XX[j] = adj_butd(merge(ME[j], TD[j]), j)
XX = [x * fa[N] % mod for x in XX]
print(*XX, sep = "\n")
``` | output | 1 | 82,364 | 13 | 164,729 |
Provide a correct Python 3 solution for this coding contest problem.
We have a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and b_i. For each k=1, ..., N, solve the problem below:
* Consider writing a number on each vertex in the tree in the following manner:
* First, write 1 on Vertex k.
* Then, for each of the numbers 2, ..., N in this order, write the number on the vertex chosen as follows:
* Choose a vertex that still does not have a number written on it and is adjacent to a vertex with a number already written on it. If there are multiple such vertices, choose one of them at random.
* Find the number of ways in which we can write the numbers on the vertices, modulo (10^9+7).
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq a_i,b_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
For each k=1, 2, ..., N in this order, print a line containing the answer to the problem.
Examples
Input
3
1 2
1 3
Output
2
1
1
Input
2
1 2
Output
1
1
Input
5
1 2
2 3
3 4
3 5
Output
2
8
12
3
3
Input
8
1 2
2 3
3 4
3 5
3 6
6 7
6 8
Output
40
280
840
120
120
504
72
72 | instruction | 0 | 82,365 | 13 | 164,730 |
"Correct Solution:
```
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7
N = INT()
lim = N+10 # 必要そうな階乗の限界を入れる
fact = [1] * (lim+1)
fact_inv = [1] * (lim+1)
for n in range(1, lim+1):
fact[n] = (fact[n-1] * n) % mod
fact_inv[lim] = pow(fact[lim], mod-2, mod)
for n in range(lim, 0, -1):
fact_inv[n-1] = (n * fact_inv[n]) % mod
tree = [[] for _ in range(N+1)] # 1-indexed
for _ in range(N-1):
a, b = MAP()
tree[a].append(b)
tree[b].append(a)
root = 1
parent = [0]*(N+1)
order = []
stack = [root]
while stack:
x = stack.pop()
order.append(x)
for y in tree[x]:
if y == parent[x]:
continue
parent[y] = x
stack.append(y)
size_d = [0]*(N+1)
dp_d = [1]*(N+1)
for v in order[::-1]: # 根に遠いほうから(down方向のボトムアップ)
dp_d[v] *= fact[size_d[v]]
dp_d[v] %= mod
p = parent[v]
s = size_d[v] + 1
size_d[p] += s
dp_d[p] *= fact_inv[s] * dp_d[v]
dp_d[p] %= mod
size_u = [N-1-x for x in size_d]
dp_u = [1]*(N+1)
def merge(p1, p2):
den_inv1, v1 = p1
den_inv2, v2 = p2
return den_inv1*den_inv2%mod, v1*v2%mod
for v in order:
p = parent[v]
arr = [(fact_inv[size_d[node]+1], dp_d[node]) if node != p else (fact_inv[size_u[v]], dp_u[v]) for node in tree[v]]
left = [(1, 1)] + list(accumulate(arr, merge))[:-1]
right = list(accumulate(arr[::-1], merge))[-2::-1] + [(1, 1)]
contrib = [merge(x, y) for x, y in zip(left, right)]
for node, c in zip(tree[v], contrib):
if node != p:
dp_u[node] = (((c[0]*c[1])%mod)*fact[size_u[node]-1])%mod
# print(dp_u)
for xd, xu, sd, su in zip(dp_d[1:], dp_u[1:], size_d[1:], size_u[1:]):
x = xd * xu * fact[sd + su] * fact_inv[sd] * fact_inv[su] % mod
print(x)
``` | output | 1 | 82,365 | 13 | 164,731 |
Provide a correct Python 3 solution for this coding contest problem.
We have a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and b_i. For each k=1, ..., N, solve the problem below:
* Consider writing a number on each vertex in the tree in the following manner:
* First, write 1 on Vertex k.
* Then, for each of the numbers 2, ..., N in this order, write the number on the vertex chosen as follows:
* Choose a vertex that still does not have a number written on it and is adjacent to a vertex with a number already written on it. If there are multiple such vertices, choose one of them at random.
* Find the number of ways in which we can write the numbers on the vertices, modulo (10^9+7).
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq a_i,b_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
For each k=1, 2, ..., N in this order, print a line containing the answer to the problem.
Examples
Input
3
1 2
1 3
Output
2
1
1
Input
2
1 2
Output
1
1
Input
5
1 2
2 3
3 4
3 5
Output
2
8
12
3
3
Input
8
1 2
2 3
3 4
3 5
3 6
6 7
6 8
Output
40
280
840
120
120
504
72
72 | instruction | 0 | 82,366 | 13 | 164,732 |
"Correct Solution:
```
import sys
sys.setrecursionlimit(10**6)
stdin = sys.stdin
ns = lambda: stdin.readline().rstrip()
ni = lambda: int(stdin.readline().rstrip())
nm = lambda: map(int, stdin.readline().split())
nl = lambda: list(map(int, stdin.readline().split()))
n_ = 2 * 10**5 + 20
mod = 10**9 + 7
fun = [1] * (n_ + 1)
for i in range(1, n_ + 1):
fun[i] = fun[i - 1] * i % mod
rev = [1] * (n_ + 1)
rev[n_] = pow(fun[n_], mod - 2, mod)
for i in range(n_ - 1, 0, -1):
rev[i] = rev[i + 1] * (i + 1) % mod
def modinv(x, mod):
x %= mod
a, b = x, mod
u, v = 1, 0
while b:
t = a // b
a -= t * b; a, b = b, a
u -= t * v; u, v = v, u
return u % mod
def nCr(n, r):
if r > n:
return 0
return fun[n] * rev[r] % mod * rev[n - r] % mod
n = ni()
g = [list() for _ in range(n)]
for _ in range(n-1):
a,b = nm()
a -= 1; b -= 1
g[a].append(b)
g[b].append(a)
sl = [1]*n
pm = [1]*n
def dfs(v, p):
for x in g[v]:
if x == p:
continue
dfs(x, v)
sl[v] += sl[x]
pm[v] = pm[v] * pm[x] % mod
sv = sl[v] - 1
for x in g[v]:
if x == p:
continue
pm[v] = pm[v] * nCr(sv, sl[x]) % mod
sv -= sl[x]
return
def dfs2(v, p):
pp = pm[p] * modinv(nCr(n-1, sl[v]) * pm[v], mod) % mod
sp = n - sl[v]
pm[v] = pm[v] * pp % mod * nCr(n-1, sp) % mod
for x in g[v]:
if x == p:
continue
dfs2(x, v)
dfs(0, -1)
for x in g[0]:
dfs2(x, 0)
print(*pm, sep = '\n')
``` | output | 1 | 82,366 | 13 | 164,733 |
Provide a correct Python 3 solution for this coding contest problem.
We have a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and b_i. For each k=1, ..., N, solve the problem below:
* Consider writing a number on each vertex in the tree in the following manner:
* First, write 1 on Vertex k.
* Then, for each of the numbers 2, ..., N in this order, write the number on the vertex chosen as follows:
* Choose a vertex that still does not have a number written on it and is adjacent to a vertex with a number already written on it. If there are multiple such vertices, choose one of them at random.
* Find the number of ways in which we can write the numbers on the vertices, modulo (10^9+7).
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq a_i,b_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
For each k=1, 2, ..., N in this order, print a line containing the answer to the problem.
Examples
Input
3
1 2
1 3
Output
2
1
1
Input
2
1 2
Output
1
1
Input
5
1 2
2 3
3 4
3 5
Output
2
8
12
3
3
Input
8
1 2
2 3
3 4
3 5
3 6
6 7
6 8
Output
40
280
840
120
120
504
72
72 | instruction | 0 | 82,367 | 13 | 164,734 |
"Correct Solution:
```
from functools import *
from itertools import *
import sys
sys.setrecursionlimit(10**6)
input = sys.stdin.buffer.readline
M = 10**9+7
N = int(input())
@lru_cache(maxsize=None)
def mod_inv(x):
return 1 if x == 1 else M // x * -mod_inv(M%x) % M
Weight = [0]*(N+1)
Size = [0]*(N+1)
def calc_subtree(v):
W, S = 1, 1
for child in Edge[v]:
Edge[child].remove(v)
w, s = calc_subtree(child)
W = W * w % M
S += s
Weight[v] = W * S % M
Size[v] = S
return Weight[v], Size[v]
Ans = [0]*(N+1)
def calc_ans(v, a):
Ans[v] = a
for child in Edge[v]:
n = Size[child]
calc_ans(child, a * n * mod_inv(N-n) % M)
Edge = [set() for i in range(N+1)]
fact = N
for i in range(1, N):
fact = fact * i % M
a, b = map(int, input().split())
Edge[a].add(b)
Edge[b].add(a)
calc_subtree(1)
calc_ans(1, mod_inv(Weight[1]) * fact % M)
for a in islice(Ans, 1, None):
print(a)
``` | output | 1 | 82,367 | 13 | 164,735 |
Provide a correct Python 3 solution for this coding contest problem.
We have a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and b_i. For each k=1, ..., N, solve the problem below:
* Consider writing a number on each vertex in the tree in the following manner:
* First, write 1 on Vertex k.
* Then, for each of the numbers 2, ..., N in this order, write the number on the vertex chosen as follows:
* Choose a vertex that still does not have a number written on it and is adjacent to a vertex with a number already written on it. If there are multiple such vertices, choose one of them at random.
* Find the number of ways in which we can write the numbers on the vertices, modulo (10^9+7).
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq a_i,b_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
For each k=1, 2, ..., N in this order, print a line containing the answer to the problem.
Examples
Input
3
1 2
1 3
Output
2
1
1
Input
2
1 2
Output
1
1
Input
5
1 2
2 3
3 4
3 5
Output
2
8
12
3
3
Input
8
1 2
2 3
3 4
3 5
3 6
6 7
6 8
Output
40
280
840
120
120
504
72
72 | instruction | 0 | 82,368 | 13 | 164,736 |
"Correct Solution:
```
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 28 22:56:10 2020
"""
import sys
#import numpy as np
sys.setrecursionlimit(10 ** 9)
#def input():
# return sys.stdin.readline()[:-1]
mod = 10**9+7
N = int(input())
#X, Y = map(int,input().split())
#ab = [list(map(int,input().split())) for i in range(N-1)]
fact = [1, 1] # 元テーブル
fact_inv = [1, 1] # 逆元テーブル
tmp_inv = [0, 1] # 逆元テーブル計算用テーブル
for i in range(2, N+1):
fact.append((fact[-1] * i) % mod)
tmp_inv.append((-tmp_inv[mod % i] * (mod//i)) % mod)
fact_inv.append((fact_inv[-1] * tmp_inv[-1]) % mod)
def cmb(n, r, mod):
if (r < 0 or r > n):
return 0
r = min(r, n-r)
return fact[n] * fact_inv[r] * fact_inv[n-r] % mod
#逆元作成
def inv(a,mod):
return pow(a,mod-2,mod)
graph = [[] for _ in range(N+1)]
for _ in range(N-1):
a, b = map(lambda x : int(x)-1, input().split())
graph[a].append(b)
graph[b].append(a)
dp = [1] * (N + 0)
size = [0] * (N + 0)
def dfs(par, v):
for u in graph[v]:
if par == u:
continue
dfs(v, u)
size[v] += size[u]
dp[v] = dp[v] * dp[u] * fact_inv[size[u]] % mod
dp[v] = dp[v] * fact[size[v]] % mod
size[v] += 1
ans = [0] * (N + 0)
def reroot(par, val_par, size_par, v):
ans[v] = val_par * dp[v] * cmb(N-1, size_par, mod) % mod
for u in graph[v]:
if par == u:
continue
val = ans[v] * inv(dp[u] * cmb(N-1, size[u],mod),mod) % mod
reroot(v, val, N - size[u], u)
dfs(-1,1)
reroot(-1,1,0,1)
print(*ans, sep='\n')
``` | output | 1 | 82,368 | 13 | 164,737 |
Provide a correct Python 3 solution for this coding contest problem.
We have a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and b_i. For each k=1, ..., N, solve the problem below:
* Consider writing a number on each vertex in the tree in the following manner:
* First, write 1 on Vertex k.
* Then, for each of the numbers 2, ..., N in this order, write the number on the vertex chosen as follows:
* Choose a vertex that still does not have a number written on it and is adjacent to a vertex with a number already written on it. If there are multiple such vertices, choose one of them at random.
* Find the number of ways in which we can write the numbers on the vertices, modulo (10^9+7).
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq a_i,b_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
For each k=1, 2, ..., N in this order, print a line containing the answer to the problem.
Examples
Input
3
1 2
1 3
Output
2
1
1
Input
2
1 2
Output
1
1
Input
5
1 2
2 3
3 4
3 5
Output
2
8
12
3
3
Input
8
1 2
2 3
3 4
3 5
3 6
6 7
6 8
Output
40
280
840
120
120
504
72
72 | instruction | 0 | 82,369 | 13 | 164,738 |
"Correct Solution:
```
import sys
sys.setrecursionlimit(10 ** 6)
MOD = 10 ** 9 + 7
def prepare(n):
global MOD
modFacts = [0] * (n + 1)
modFacts[0] = 1
for i in range(n):
modFacts[i + 1] = (modFacts[i] * (i + 1)) % MOD
invs = [1] * (n + 1)
invs[n] = pow(modFacts[n], MOD - 2, MOD)
for i in range(n, 1, -1):
invs[i - 1] = (invs[i] * i) % MOD
return modFacts, invs
def dfs(v):
global MOD
childs = 0
var = 1
for e in edge[v]:
if path[e] == 0:
path[e] = 1
nc, nvar = dfs(e)
childs += nc
V[v][e] = (nc, nvar)
var *= nvar
var %= MOD
var *= invs[nc]
var %= MOD
var *= modFacts[childs]
var %= MOD
dp[v] = (childs, var)
return childs + 1, var
def dfs2(v, pn, pVar):
global MOD
oNodes, oVar = dp[v]
tNodes = pn + oNodes
tVar = (oVar * pVar) % MOD
tVar *= invs[oNodes] * modFacts[tNodes] * invs[pn]
tVar %= MOD
dp[v] = (tNodes, tVar)
for e in V[v].keys():
eNodes, eVar = V[v][e]
nVar = (tVar * invs[tNodes] * modFacts[eNodes] * modFacts[tNodes - eNodes]) % MOD
nVar *= pow(eVar, MOD - 2, MOD)
nVar %= MOD
dfs2(e, tNodes - eNodes + 1, nVar)
N = int(input())
edge = [[] for _ in range(N)]
for s in sys.stdin.readlines():
a, b = map(int, s.split())
edge[a - 1].append(b - 1)
edge[b - 1].append(a - 1)
modFacts, invs = prepare(N)
V = [{} for _ in range(N)]
path = [0] * N
dp = [None] * N
path[0] = 1
dfs(0)
dfs2(0, 0, 1)
for i in range(N):
print(dp[i][1])
``` | output | 1 | 82,369 | 13 | 164,739 |
Provide a correct Python 3 solution for this coding contest problem.
We have a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and b_i. For each k=1, ..., N, solve the problem below:
* Consider writing a number on each vertex in the tree in the following manner:
* First, write 1 on Vertex k.
* Then, for each of the numbers 2, ..., N in this order, write the number on the vertex chosen as follows:
* Choose a vertex that still does not have a number written on it and is adjacent to a vertex with a number already written on it. If there are multiple such vertices, choose one of them at random.
* Find the number of ways in which we can write the numbers on the vertices, modulo (10^9+7).
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq a_i,b_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
For each k=1, 2, ..., N in this order, print a line containing the answer to the problem.
Examples
Input
3
1 2
1 3
Output
2
1
1
Input
2
1 2
Output
1
1
Input
5
1 2
2 3
3 4
3 5
Output
2
8
12
3
3
Input
8
1 2
2 3
3 4
3 5
3 6
6 7
6 8
Output
40
280
840
120
120
504
72
72 | instruction | 0 | 82,370 | 13 | 164,740 |
"Correct Solution:
```
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**9)
def solve():
MOD = 10**9 + 7
N = int(input())
adjL = [[] for _ in range(N)]
for _ in range(N-1):
a, b = map(int, input().split())
a, b = a-1, b-1
adjL[a].append(b)
adjL[b].append(a)
def getInvs(n, MOD):
invs = [1] * (n+1)
for x in range(2, n+1):
invs[x] = (-(MOD//x) * invs[MOD%x]) % MOD
return invs
invs = getInvs(N, MOD)
dp = [[] for _ in range(N)]
outdegs = [0] * N
sizes = [0] * N
iPars = [-1] * N
def dfsDP(v, vPar):
outdeg = outdegs[v] = len(adjL[v])
dp[v] = [0] * outdeg
res = 1
sizes[v] = 1
for i, v2 in enumerate(adjL[v]):
if v2 == vPar:
iPars[v] = i
continue
dp[v][i] = dfsDP(v2, v)
res = res * dp[v][i] % MOD
sizes[v] += sizes[v2]
return res * invs[sizes[v]] % MOD
anss = [0] * N
def dfsAns(v, vPar, resPar):
if vPar != -1:
dp[v][iPars[v]] = resPar
outdeg = outdegs[v]
dpL = [1] * (outdeg+1)
for i in range(outdeg):
v2 = adjL[v][i]
dpL[i+1] = dpL[i] * dp[v][i] % MOD
dpR = [1] * (outdeg+1)
for i in reversed(range(outdeg)):
v2 = adjL[v][i]
dpR[i] = dpR[i+1] * dp[v][i] % MOD
anss[v] = dpL[-1] * invs[N]
for i, v2 in enumerate(adjL[v]):
if v2 == vPar: continue
dfsAns(v2, v, dpL[i] * dpR[i+1] * invs[N-sizes[v2]] % MOD)
dfsDP(0, -1)
dfsAns(0, -1, 0)
def getFact(n, MOD):
fact = 1
for i in range(1, n+1):
fact = (fact * i) % MOD
return fact
factN = getFact(N, MOD)
for v in range(N):
anss[v] = anss[v] * factN % MOD
print('\n'.join(map(str, anss)))
solve()
``` | output | 1 | 82,370 | 13 | 164,741 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and b_i. For each k=1, ..., N, solve the problem below:
* Consider writing a number on each vertex in the tree in the following manner:
* First, write 1 on Vertex k.
* Then, for each of the numbers 2, ..., N in this order, write the number on the vertex chosen as follows:
* Choose a vertex that still does not have a number written on it and is adjacent to a vertex with a number already written on it. If there are multiple such vertices, choose one of them at random.
* Find the number of ways in which we can write the numbers on the vertices, modulo (10^9+7).
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq a_i,b_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
For each k=1, 2, ..., N in this order, print a line containing the answer to the problem.
Examples
Input
3
1 2
1 3
Output
2
1
1
Input
2
1 2
Output
1
1
Input
5
1 2
2 3
3 4
3 5
Output
2
8
12
3
3
Input
8
1 2
2 3
3 4
3 5
3 6
6 7
6 8
Output
40
280
840
120
120
504
72
72
Submitted Solution:
```
def main():
from sys import stdin
input = stdin.readline
n = int(input())
ab = [list(map(int, input().split())) for _ in [0]*(n-1)]
g = [[] for _ in [0]*n]
for a, b in ab:
g[a-1].append(b-1)
g[b-1].append(a-1)
mod = 10**9+7
fact = [1, 1]
inv = [pow(i, mod-2, mod) for i in range(n+1)]
for i in range(2, n+1):
fact.append(fact[-1]*i % mod)
# merge:頂点aにbをマージするときのモノイド
# adj_bu:ボトムアップ時の調整(a:値,i:頂点)
# adj_td:トップダウン時の調整(a:値,i:頂点,p:親)
# adj_fin:最終調整(a:値,i:頂点)
def merge(a, b): return a * b % mod
def adj_bu(a, i): return a * inv[size[i]] % mod
def adj_td(a, i, p): return a * inv[n-size[i]] % mod
def adj_fin(a, i): return a * fact[n-1] % mod
# トポロジカルソートをする
# T:木の隣接グラフ表現をset化
# P:親
# q:キュー
# order:トポソしたもの
T = g
P = [-1]*n
q = [0]
ini = 1
order = []
while q:
i = q.pop()
order.append(i)
for a in T[i]:
if a != P[i]:
P[a] = i
T[a].remove(i)
q.append(a)
# サイズの処理を先に行う
# size[i]:0を根とする根付き木における、iを根とする部分木の大きさ
size = [1]*n
for i in order[1:][::-1]:
size[P[i]] += size[i]
# ボトムアップ処理をする
# ME:マージした値を一時保存
# DP:DP値、MEを調整したもの
ME = [ini]*n
DP = [0]*n
for i in order[1:][::-1]:
DP[i] = adj_bu(ME[i], i)
p = P[i]
ME[p] = merge(ME[p], DP[i])
DP[order[0]] = adj_fin(ME[order[0]], order[0])
TD = [ini]*n
# トップダウン処理をする
for i in order:
# 左からDP(結果はTDに入れている)
ac = TD[i]
for j in T[i]:
TD[j] = ac
ac = merge(ac, DP[j])
# 右からDP(結果はacに入れている、一度しか使わないのでacで問題ない)
ac = ini
for j in T[i][::-1]:
TD[j] = adj_td(merge(TD[j], ac), j, i)
ac = merge(ac, DP[j])
DP[j] = adj_fin(merge(ME[j], TD[j]), j)
for i in DP:
print(i)
main()
``` | instruction | 0 | 82,371 | 13 | 164,742 |
Yes | output | 1 | 82,371 | 13 | 164,743 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and b_i. For each k=1, ..., N, solve the problem below:
* Consider writing a number on each vertex in the tree in the following manner:
* First, write 1 on Vertex k.
* Then, for each of the numbers 2, ..., N in this order, write the number on the vertex chosen as follows:
* Choose a vertex that still does not have a number written on it and is adjacent to a vertex with a number already written on it. If there are multiple such vertices, choose one of them at random.
* Find the number of ways in which we can write the numbers on the vertices, modulo (10^9+7).
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq a_i,b_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
For each k=1, 2, ..., N in this order, print a line containing the answer to the problem.
Examples
Input
3
1 2
1 3
Output
2
1
1
Input
2
1 2
Output
1
1
Input
5
1 2
2 3
3 4
3 5
Output
2
8
12
3
3
Input
8
1 2
2 3
3 4
3 5
3 6
6 7
6 8
Output
40
280
840
120
120
504
72
72
Submitted Solution:
```
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
from bisect import bisect_right, bisect_left
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor, gamma, log
from operator import mul
from functools import reduce
from copy import deepcopy
sys.setrecursionlimit(2147483647)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 10 ** 9 + 7
n =I()
G = [[] for _ in range(n)]
for _ in range(n - 1):
a, b = LI()
G[a - 1] += [b - 1]
G[b - 1] += [a - 1]
fac = [1] * (n + 1)
inv = [1] * (n + 1)
for j in range(1, n + 1):
fac[j] = fac[j-1] * j % mod
inv[n] = pow(fac[n], mod-2, mod)
for j in range(n-1, -1, -1):
inv[j] = inv[j+1] * (j+1) % mod
def comb(n, r):
if r > n or n < 0 or r < 0:
return 0
return fac[n] * inv[n - r] * inv[r] % mod
v_num = [-1] * n
par = [-1] * n
def f(u):
ret = 1
for v in G[u]:
if v == par[u]:
continue
par[v] = u
ret += f(v)
v_num[u] = ret
if u: return ret
f(0)
dp = [0] * n
def tree_dp(x):
c = 1
remain_v = v_num[x] - 1
for y in G[x]:
if y == par[x]:
continue
c = c * tree_dp(y) * comb(remain_v, v_num[y]) % mod
remain_v -= v_num[y]
dp[x] = c
if x: return c
tree_dp(0)
ans = [0] * n
def dfs(d):
e = 1
inv_e = pow(comb(n - 1, v_num[d]) * dp[d], mod - 2, mod)
ans[d] = dp[d] * ans[par[d]] * comb(n - 1, v_num[d] - 1) * inv_e % mod
q = deque([0])
ans[0] = dp[0]
while q:
g = q.pop()
for h in G[g]:
if h == par[g]:
continue
dfs(h)
q += [h]
for j in ans:
print(j)
``` | instruction | 0 | 82,372 | 13 | 164,744 |
Yes | output | 1 | 82,372 | 13 | 164,745 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and b_i. For each k=1, ..., N, solve the problem below:
* Consider writing a number on each vertex in the tree in the following manner:
* First, write 1 on Vertex k.
* Then, for each of the numbers 2, ..., N in this order, write the number on the vertex chosen as follows:
* Choose a vertex that still does not have a number written on it and is adjacent to a vertex with a number already written on it. If there are multiple such vertices, choose one of them at random.
* Find the number of ways in which we can write the numbers on the vertices, modulo (10^9+7).
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq a_i,b_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
For each k=1, 2, ..., N in this order, print a line containing the answer to the problem.
Examples
Input
3
1 2
1 3
Output
2
1
1
Input
2
1 2
Output
1
1
Input
5
1 2
2 3
3 4
3 5
Output
2
8
12
3
3
Input
8
1 2
2 3
3 4
3 5
3 6
6 7
6 8
Output
40
280
840
120
120
504
72
72
Submitted Solution:
```
import sys
sys.setrecursionlimit(10**7)
N = int(input())
AB = [list(map(int,input().split())) for _ in [0]*(N-1)]
mod = 10**9+7
m = 10**5*2 +10
fac = [1]*m
ninv = [1]*m
finv = [1]*m
for i in range(2,m):
fac[i] = fac[i-1]*i%mod
ninv[i] = (-(mod//i)*ninv[mod%i])%mod
finv[i] = finv[i-1]*ninv[i]%mod
E = [[] for _ in [0]*N]
Ef = [[] for _ in [0]*N]
Eb = [[] for _ in [0]*N]
for a,b in AB:
a-=1
b-=1
E[a].append(b)
E[b].append(a)
done = [False]*N
done[0] = True
q = [0]
while q:
j = q.pop()
for k in E[j]:
if done[k]: continue
done[k] = True
q.append(k)
Ef[j].append(k)
Eb[k].append(j)
Vf = [None]*N
Mf = [None]*N
def getf(i):
if Mf[i]!=None:
return Mf[i]
Mc = [getf(j) for j in Ef[i]]
Vc = [Vf[j] for j in Ef[i]]
Vf[i] = 1 + sum(Vc)
Mf[i] = fac[Vf[i]-1]
for mc,vc in zip(Mc,Vc):
Mf[i] *= (mc*finv[vc])%mod
Mf[i] %= mod
return Mf[i]
def getp(i):
if i==0: return 0
p = Eb[i][0]
vp = Vf[p]
vi = Vf[i]
ret = ans[p]
ret *= (((fac[vi]*fac[N-1-vi])%mod)*finv[N-1])%mod
ret %= mod
ret *= pow(Mf[i],mod-2,mod)
ret %= mod
return ret
ans = [0]*N
ans[0] = getf(0)
q = Ef[0][:]
while q:
i = q.pop()
V = [N - Vf[i]]
M = [getp(i)]
for j in Ef[i]:
q.append(j)
V.append(Vf[j])
M.append(Mf[j])
tmp = fac[N-1]
for mc,vc in zip(M,V):
tmp *= (mc*finv[vc])%mod
tmp %= mod
ans[i] = tmp
for out in ans:
print(out)
``` | instruction | 0 | 82,373 | 13 | 164,746 |
Yes | output | 1 | 82,373 | 13 | 164,747 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and b_i. For each k=1, ..., N, solve the problem below:
* Consider writing a number on each vertex in the tree in the following manner:
* First, write 1 on Vertex k.
* Then, for each of the numbers 2, ..., N in this order, write the number on the vertex chosen as follows:
* Choose a vertex that still does not have a number written on it and is adjacent to a vertex with a number already written on it. If there are multiple such vertices, choose one of them at random.
* Find the number of ways in which we can write the numbers on the vertices, modulo (10^9+7).
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq a_i,b_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
For each k=1, 2, ..., N in this order, print a line containing the answer to the problem.
Examples
Input
3
1 2
1 3
Output
2
1
1
Input
2
1 2
Output
1
1
Input
5
1 2
2 3
3 4
3 5
Output
2
8
12
3
3
Input
8
1 2
2 3
3 4
3 5
3 6
6 7
6 8
Output
40
280
840
120
120
504
72
72
Submitted Solution:
```
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7
N = INT()
lim = N+10 # 必要そうな階乗の限界を入れる
fact = [1] * (lim+1)
fact_inv = [1] * (lim+1)
for n in range(1, lim+1):
fact[n] = (fact[n-1] * n) % mod
fact_inv[lim] = pow(fact[lim], mod-2, mod)
for n in range(lim, 0, -1):
fact_inv[n-1] = (n * fact_inv[n]) % mod
tree = [[] for _ in range(N+1)] # 1-indexed
for _ in range(N-1):
a, b = MAP()
tree[a].append(b)
tree[b].append(a)
root = 1
parent = [0] * (N + 1)
order = []
stack = [root]
while stack:
x = stack.pop()
order.append(x)
for y in tree[x]:
if y == parent[x]:
continue
parent[y] = x
stack.append(y)
size_d = [0] * (N + 1)
dp_d = [1] * (N + 1)
for v in order[::-1]: # 根に遠いほうから(down方向のボトムアップ)
dp_d[v] *= fact[size_d[v]]
dp_d[v] %= mod
p = parent[v]
s = size_d[v] + 1
size_d[p] += s
dp_d[p] *= fact_inv[s] * dp_d[v]
dp_d[p] %= mod
size_u = [N - 1 - x for x in size_d]
dp_u = [1] * (N + 1)
for v in order[1:]: # 根に近いほうから(up方向のトップダウン)
p = parent[v]
x = dp_d[p]
x *= dp_u[p]
x *= fact_inv[size_d[p]]
x *= fact[size_d[v] + 1]
x *= pow(dp_d[v], mod - 2, mod)
x *= fact[size_u[v]-1]
x *= fact_inv[size_u[p]]
dp_u[v] = x % mod
for xd, xu, sd, su in zip(dp_d[1:], dp_u[1:], size_d[1:], size_u[1:]):
x = xd * xu * fact[sd + su] * fact_inv[sd] * fact_inv[su] % mod
print(x)
``` | instruction | 0 | 82,374 | 13 | 164,748 |
Yes | output | 1 | 82,374 | 13 | 164,749 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and b_i. For each k=1, ..., N, solve the problem below:
* Consider writing a number on each vertex in the tree in the following manner:
* First, write 1 on Vertex k.
* Then, for each of the numbers 2, ..., N in this order, write the number on the vertex chosen as follows:
* Choose a vertex that still does not have a number written on it and is adjacent to a vertex with a number already written on it. If there are multiple such vertices, choose one of them at random.
* Find the number of ways in which we can write the numbers on the vertices, modulo (10^9+7).
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq a_i,b_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
For each k=1, 2, ..., N in this order, print a line containing the answer to the problem.
Examples
Input
3
1 2
1 3
Output
2
1
1
Input
2
1 2
Output
1
1
Input
5
1 2
2 3
3 4
3 5
Output
2
8
12
3
3
Input
8
1 2
2 3
3 4
3 5
3 6
6 7
6 8
Output
40
280
840
120
120
504
72
72
Submitted Solution:
```
import sys
sys.setrecursionlimit(10**6)
n = int(input())
mod = 10**9 + 7
def expo(x,n): # o(log n)
var = 1
while n>0:
if n%2 == 1:
var = (var*x) % mod
x = (x*x)%mod
n = n>>1
return var
fact = [1] * (n+10)
for i in range(1,n+10):
fact[i] = fact[i-1] * i %mod
def conbi(*x): # o()
num = 1
den = 1
# for i in range(1,sum(x)+1):
# num = (num*i)%mod
num = fact[sum(x)]
for i in x:
den = den*fact[i]%mod
# for j in range(1,i+1):
# den = (den * j)%mod
return (num*expo(den,mod-2))%mod
path = [set() for _ in range(n)]
pathq= [0]*n
for _ in range(n-1):
a,b = map(int,input().split())
a -= 1
b -= 1
path[a].add(b)
pathq[a] += 1
path[b].add(a)
pathq[b] += 1
memo = {}
def go(i,j):
if (i,j) in memo.keys():
return memo[(i,j)]
else:
memo[(i,j)] = [1,1]
cnt = []
meth = 1
for k in path[j]:
if i != k:
[x,y] = go(j,k)
meth *= y
meth %= mod
cnt.append(x)
memo[(i,j)] = [sum(cnt)%mod + 1, meth*conbi(*cnt)%mod]
return memo[(i,j)]
for i in range(n):
ans = 1
cnt = []
meth = 1
for j in path[i]:
[x,y] = go(i,j)
meth *= y
meth %= mod
cnt.append(x)
print(meth*conbi(*cnt)%mod)
``` | instruction | 0 | 82,375 | 13 | 164,750 |
No | output | 1 | 82,375 | 13 | 164,751 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and b_i. For each k=1, ..., N, solve the problem below:
* Consider writing a number on each vertex in the tree in the following manner:
* First, write 1 on Vertex k.
* Then, for each of the numbers 2, ..., N in this order, write the number on the vertex chosen as follows:
* Choose a vertex that still does not have a number written on it and is adjacent to a vertex with a number already written on it. If there are multiple such vertices, choose one of them at random.
* Find the number of ways in which we can write the numbers on the vertices, modulo (10^9+7).
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq a_i,b_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
For each k=1, 2, ..., N in this order, print a line containing the answer to the problem.
Examples
Input
3
1 2
1 3
Output
2
1
1
Input
2
1 2
Output
1
1
Input
5
1 2
2 3
3 4
3 5
Output
2
8
12
3
3
Input
8
1 2
2 3
3 4
3 5
3 6
6 7
6 8
Output
40
280
840
120
120
504
72
72
Submitted Solution:
```
import sys
sys.setrecursionlimit(5*10**5)
n = int(input())
edge = [tuple(map(int, input().split())) for _ in range(n-1)]
mod = 10 ** 9 + 7
def extGCD(a, b):
if b == 0:
return a, 1, 0
g, y, x = extGCD(b, a%b)
y -= a//b * x
return g, x, y
def moddiv(a, b):
_, inv, _ = extGCD(b, mod)
return (a * inv) % mod
N = 2 * 10 ** 5 + 10
fact = [0] * (N)
fact[0] = 1
for i in range(1, N):
fact[i] = (fact[i-1] * i) % mod
def comb(a, b):
return moddiv(moddiv(fact[a], fact[a-b]), fact[b])
connect = [set() for _ in range(n)]
for a, b in edge:
connect[a-1].add(b-1)
connect[b-1].add(a-1)
d = [{} for _ in range(n)]
def dfs(v, p):
if p in d[v]:
return d[v][p]
num, count = 0, 1
for next in connect[v]:
if next != p:
i, c = dfs(next, v)
num += i
count *= c
count %= mod
count *= comb(num, i)
count %= mod
num += 1
d[v][p] = num, count
return num, count
for i in range(n):
print(dfs(i, -1)[1])
``` | instruction | 0 | 82,376 | 13 | 164,752 |
No | output | 1 | 82,376 | 13 | 164,753 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and b_i. For each k=1, ..., N, solve the problem below:
* Consider writing a number on each vertex in the tree in the following manner:
* First, write 1 on Vertex k.
* Then, for each of the numbers 2, ..., N in this order, write the number on the vertex chosen as follows:
* Choose a vertex that still does not have a number written on it and is adjacent to a vertex with a number already written on it. If there are multiple such vertices, choose one of them at random.
* Find the number of ways in which we can write the numbers on the vertices, modulo (10^9+7).
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq a_i,b_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
For each k=1, 2, ..., N in this order, print a line containing the answer to the problem.
Examples
Input
3
1 2
1 3
Output
2
1
1
Input
2
1 2
Output
1
1
Input
5
1 2
2 3
3 4
3 5
Output
2
8
12
3
3
Input
8
1 2
2 3
3 4
3 5
3 6
6 7
6 8
Output
40
280
840
120
120
504
72
72
Submitted Solution:
```
N = int(input())
a = []
b = []
for i in range(N-1):
ai, bi = list(map(int, input().split()))
a.append(ai)
b.append(bi)
count = 0
def func_count(line, node):
print(line,node)
global count
aa = 0
for i in range(N-1):
if i==line:
continue
if a[i]==node:
aa += 1
func_count(i, b[i])
if b[i]==node:
aa += 1
func_count(i, a[i])
if aa>2:
count += aa-1
for i in range(N):
count=0
func_count(-1, i+1)
print(count)
``` | instruction | 0 | 82,377 | 13 | 164,754 |
No | output | 1 | 82,377 | 13 | 164,755 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and b_i. For each k=1, ..., N, solve the problem below:
* Consider writing a number on each vertex in the tree in the following manner:
* First, write 1 on Vertex k.
* Then, for each of the numbers 2, ..., N in this order, write the number on the vertex chosen as follows:
* Choose a vertex that still does not have a number written on it and is adjacent to a vertex with a number already written on it. If there are multiple such vertices, choose one of them at random.
* Find the number of ways in which we can write the numbers on the vertices, modulo (10^9+7).
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq a_i,b_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
For each k=1, 2, ..., N in this order, print a line containing the answer to the problem.
Examples
Input
3
1 2
1 3
Output
2
1
1
Input
2
1 2
Output
1
1
Input
5
1 2
2 3
3 4
3 5
Output
2
8
12
3
3
Input
8
1 2
2 3
3 4
3 5
3 6
6 7
6 8
Output
40
280
840
120
120
504
72
72
Submitted Solution:
```
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
import resource
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub
sys.setrecursionlimit(10**6)
input = sys.stdin.readline
INF = 2**62-1
def read_int():
return int(input())
def read_int_n():
return list(map(int, input().split()))
def read_float():
return float(input())
def read_float_n():
return list(map(float, input().split()))
def read_str():
return input().strip()
def read_str_n():
return list(map(str, input().split()))
def error_print(*args):
print(*args, file=sys.stderr)
def mt(f):
import time
def wrap(*args, **kwargs):
s = time.time()
ret = f(*args, **kwargs)
e = time.time()
error_print(e - s, 'sec')
return ret
return wrap
class Mod:
def __init__(self, m):
self.m = m
def add(self, a, b):
return (a + b) % self.m
def sub(self, a, b):
return (a - b) % self.m
def mul(self, a, b):
return ((a % self.m) * (b % self.m)) % self.m
def div(self, a, b):
return self.mul(a, pow(b, self.m-2, self.m))
def pow(self, a, b):
return pow(a, b, self.m)
M = Mod(10**9 + 7)
fact_ = [1] * (2 * (10**5) + 1)
for i in range(1, 2 * (10**5)+1):
fact_[i] = M.mul(fact_[i-1], i)
def fact(n):
return fact_[n]
@mt
def slv(N, AB):
g = defaultdict(set)
for a, b in AB:
g[a].add(b)
g[b].add(a)
memo = {}
def f(u, p, flag=False):
if (u, p) in memo:
return memo[(u, p)]
r = 1
n =1
if p == 0 or flag:
for v in g[u]:
if v == p:
continue
n_, r_ = f(v, u, flag)
n += n_
r = M.mul(r, r_)
r = M.div(r, fact(n_))
r = M.mul(r, fact(n-1))
else:
np, rp = f(p, u, False)
na, ra = f(u, 0, False)
r = M.div(ra, rp)
r = mul(r, fact(np))
n = na - np
r = M.div(r, fact(na-1))
r = M.mul(r, fact(n-1))
memo[(u, p)] = n, r
return n, r
f(1, 0, True)
# for k, v in memo.items():
# print(k, v)
for i in range(1, N+1):
print(f(i, 0, False)[1])
def main():
N = read_int()
AB = [read_int_n() for _ in range(N-1)]
(slv(N, AB))
# N = (10**5) * 2
# AB = [(_, _+1) for _ in range(N-1)]
# (slv(N, AB))
if __name__ == '__main__':
main()
``` | instruction | 0 | 82,378 | 13 | 164,756 |
No | output | 1 | 82,378 | 13 | 164,757 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i.
<image>Illustration for the second example, the first integer is a_i and the integer in parentheses is c_i
After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices.
Help him to restore initial integers!
Input
The first line contains an integer n (1 ≤ n ≤ 2000) — the number of vertices in the tree.
The next n lines contain descriptions of vertices: the i-th line contains two integers p_i and c_i (0 ≤ p_i ≤ n; 0 ≤ c_i ≤ n-1), where p_i is the parent of vertex i or 0 if vertex i is root, and c_i is the number of vertices j in the subtree of vertex i, such that a_j < a_i.
It is guaranteed that the values of p_i describe a rooted tree with n vertices.
Output
If a solution exists, in the first line print "YES", and in the second line output n integers a_i (1 ≤ a_i ≤ {10}^{9}). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all a_i are between 1 and 10^9.
If there are no solutions, print "NO".
Examples
Input
3
2 0
0 2
2 0
Output
YES
1 2 1
Input
5
0 1
1 3
2 1
3 0
2 0
Output
YES
2 3 2 1 2 | instruction | 0 | 82,709 | 13 | 165,418 |
Tags: constructive algorithms, data structures, dfs and similar, graphs, greedy, trees
Correct Solution:
```
import io
import os
import sys
from collections import Counter, defaultdict, deque
sys.setrecursionlimit(10 ** 5)
def solve(N, PC):
children = [[] for i in range(N)]
cost = [None for i in range(N)]
root = None
for i, (p, c) in enumerate(PC):
cost[i] = c
p -= 1
if p != -1:
children[p].append(i)
else:
root = i
def getOrder(node):
ret = []
for child in children[node]:
ret.extend(getOrder(child))
i = cost[node]
if not (0 <= i <= len(ret)):
print("NO")
exit()
return ret[:i] + [node] + ret[i:]
order = getOrder(root)
nodeToVal = {}
for v, node in enumerate(order):
nodeToVal[node] = str(v + 1)
return "YES\n" + " ".join(nodeToVal[i] for i in range(N))
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
(N,) = [int(x) for x in input().split()]
PC = [[int(x) for x in input().split()] for i in range(N)]
ans = solve(N, PC)
print(ans)
``` | output | 1 | 82,709 | 13 | 165,419 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i.
<image>Illustration for the second example, the first integer is a_i and the integer in parentheses is c_i
After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices.
Help him to restore initial integers!
Input
The first line contains an integer n (1 ≤ n ≤ 2000) — the number of vertices in the tree.
The next n lines contain descriptions of vertices: the i-th line contains two integers p_i and c_i (0 ≤ p_i ≤ n; 0 ≤ c_i ≤ n-1), where p_i is the parent of vertex i or 0 if vertex i is root, and c_i is the number of vertices j in the subtree of vertex i, such that a_j < a_i.
It is guaranteed that the values of p_i describe a rooted tree with n vertices.
Output
If a solution exists, in the first line print "YES", and in the second line output n integers a_i (1 ≤ a_i ≤ {10}^{9}). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all a_i are between 1 and 10^9.
If there are no solutions, print "NO".
Examples
Input
3
2 0
0 2
2 0
Output
YES
1 2 1
Input
5
0 1
1 3
2 1
3 0
2 0
Output
YES
2 3 2 1 2 | instruction | 0 | 82,710 | 13 | 165,420 |
Tags: constructive algorithms, data structures, dfs and similar, graphs, greedy, trees
Correct Solution:
```
import sys
input = sys.stdin.readline
n=int(input())
C=[(0,0)]+[tuple(map(int,input().split())) for i in range(n)]
V=n+1
EDGEIN=[0]*V# その点に入るEDGEの個数
EDGEOUT=[-1]*V# EDGEの行き先
for i in range(1,n+1):
p,x=C[i]
if p!=0:
EDGEIN[p]+=1
EDGEOUT[i]=p
from collections import deque
QUE = deque()
ANS=[0]*V
USE=[[] for i in range(V)]
for i in range(1,V):
if EDGEIN[i]==0:
QUE.append(i)# 行き先のない点をQUEに入れる
ANS[i]=i
if C[i][1]!=0:
print("NO")
sys.exit()
USE[i].append(i)
TOP_SORT=[]
while QUE:
x=QUE.pop()
TOP_SORT.append(x)# 行き先がない点を答えに入れる
to=EDGEOUT[x]
EDGEIN[to]-=1# 行き先がない点を削除し,そこから一歩先の点のEDGEINを一つ減らす.
if EDGEIN[to]==0:
QUE.appendleft(to)
for po in TOP_SORT:
#print(po)
to=EDGEOUT[po]
if ANS[po]!=0:
USE[to].extend(USE[po])
USE[po]=[]
else:
x=C[po][1]
USE[po].sort()
if len(USE[po])<x:
print("NO")
sys.exit()
elif len(USE[po])==x:
#print(po,USE[po])
ANS[po]=max(ANS)+1
USE[to].append(ANS[po])
USE[to].extend(USE[po])
USE[po]=[]
else:
#print(po,x,USE[po])
if x!=0:
AP=USE[po][x]
else:
AP=1
for i in range(1,n+1):
if ANS[i]>=AP:
ANS[i]+=1
for i in range(1,n+1):
for j in range(len(USE[i])):
if USE[i][j]>=AP:
USE[i][j]+=1
ANS[po]=AP
USE[to].append(ANS[po])
USE[to].extend(USE[po])
USE[po]=[]
#print(ANS)
#print(USE)
#print()
compression_dict={a: ind for ind, a in enumerate(sorted(set(ANS)))}
ANS=[compression_dict[a] for a in ANS]
print("YES")
print(*ANS[1:])
``` | output | 1 | 82,710 | 13 | 165,421 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i.
<image>Illustration for the second example, the first integer is a_i and the integer in parentheses is c_i
After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices.
Help him to restore initial integers!
Input
The first line contains an integer n (1 ≤ n ≤ 2000) — the number of vertices in the tree.
The next n lines contain descriptions of vertices: the i-th line contains two integers p_i and c_i (0 ≤ p_i ≤ n; 0 ≤ c_i ≤ n-1), where p_i is the parent of vertex i or 0 if vertex i is root, and c_i is the number of vertices j in the subtree of vertex i, such that a_j < a_i.
It is guaranteed that the values of p_i describe a rooted tree with n vertices.
Output
If a solution exists, in the first line print "YES", and in the second line output n integers a_i (1 ≤ a_i ≤ {10}^{9}). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all a_i are between 1 and 10^9.
If there are no solutions, print "NO".
Examples
Input
3
2 0
0 2
2 0
Output
YES
1 2 1
Input
5
0 1
1 3
2 1
3 0
2 0
Output
YES
2 3 2 1 2 | instruction | 0 | 82,711 | 13 | 165,422 |
Tags: constructive algorithms, data structures, dfs and similar, graphs, greedy, trees
Correct Solution:
```
# Legends Always Come Up with Solution
# Author: Manvir Singh
import os
import sys
from io import BytesIO, IOBase
from array import array
class SortedList:
def __init__(self, iterable=None, _load=200):
"""Initialize sorted list instance."""
if iterable is None:
iterable = []
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError('{0!r} not in list'.format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return 'SortedList({0})'.format(list(self))
def dfs(c,p):
global tree,a,b,ans
if a[c]>=len(b):
print("NO")
exit()
ans[c]=b[a[c]]
b.discard(b[a[c]])
s[c]=1
for i in tree[c]:
if i!=p:
dfs(i,c)
s[c]+=s[i]
def main():
global tree,a,b,ans,s
n = int(input())
tree = [array("i", []) for _ in range(n + 1)]
a = array("i", [0] * (n + 1))
s= array("i", [0] * (n + 1))
ans = array("i", [0] * (n + 1))
for i in range(1,n+1):
p,c=map(int,input().split())
tree[p].append(i)
a[i]=c
b=SortedList(range(1,n+1))
dfs(tree[0][0],0)
if b:
print("NO")
else:
an="YES"
for i in range(1,n+1):
if a[i]>s[i]-1:
an="NO"
print(an)
if an=="YES":
print(*ans[1:])
# 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")
if __name__ == "__main__":
main()
``` | output | 1 | 82,711 | 13 | 165,423 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i.
<image>Illustration for the second example, the first integer is a_i and the integer in parentheses is c_i
After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices.
Help him to restore initial integers!
Input
The first line contains an integer n (1 ≤ n ≤ 2000) — the number of vertices in the tree.
The next n lines contain descriptions of vertices: the i-th line contains two integers p_i and c_i (0 ≤ p_i ≤ n; 0 ≤ c_i ≤ n-1), where p_i is the parent of vertex i or 0 if vertex i is root, and c_i is the number of vertices j in the subtree of vertex i, such that a_j < a_i.
It is guaranteed that the values of p_i describe a rooted tree with n vertices.
Output
If a solution exists, in the first line print "YES", and in the second line output n integers a_i (1 ≤ a_i ≤ {10}^{9}). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all a_i are between 1 and 10^9.
If there are no solutions, print "NO".
Examples
Input
3
2 0
0 2
2 0
Output
YES
1 2 1
Input
5
0 1
1 3
2 1
3 0
2 0
Output
YES
2 3 2 1 2 | instruction | 0 | 82,712 | 13 | 165,424 |
Tags: constructive algorithms, data structures, dfs and similar, graphs, greedy, trees
Correct Solution:
```
import sys
zz=1
sys.setrecursionlimit(10**5)
if zz:
input=sys.stdin.readline
else:
sys.stdin=open('input.txt', 'r')
sys.stdout=open('all.txt','w')
di=[[-1,0],[1,0],[0,1],[0,-1]]
def fori(n):
return [fi() for i in range(n)]
def inc(d,c,x=1):
d[c]=d[c]+x if c in d else x
def ii():
return input().rstrip()
def li():
return [int(xx) for xx in input().split()]
def fli():
return [float(x) for x in input().split()]
def comp(a,b):
if(a>b):
return 2
return 2 if a==b else 0
def gi():
return [xx for xx in input().split()]
def gtc(tc,ans):
print("Case #"+str(tc)+":",ans)
def cil(n,m):
return n//m+int(n%m>0)
def fi():
return int(input())
def pro(a):
return reduce(lambda a,b:a*b,a)
def swap(a,i,j):
a[i],a[j]=a[j],a[i]
def si():
return list(input().rstrip())
def mi():
return map(int,input().split())
def gh():
sys.stdout.flush()
def isvalid(i,j,n,m):
return 0<=i<n and 0<=j<m
def bo(i):
return ord(i)-ord('a')
def graph(n,m):
for i in range(m):
x,y=mi()
a[x].append(y)
a[y].append(x)
t=1
uu=t
flag=1
def dfs(i,p=-1,val=1):
c=0
for j in a[i]:
if j!=p:
c+=dfs(j,i,val+c)
if c<ch[i]:
flag=0
return False
c+=1
for j in a[i]:
if j!=p:
dfs2(j,i,val+ch[i])
ans[i]=val+ch[i]
return c
def dfs2(i,p=-1,val=1):
if ans[i]>=val:
ans[i]+=1
for j in a[i]:
if j!=p:
dfs2(j,i,val)
while t>0:
t-=1
n=fi()
a=[[] for i in range(n+1)]
ch=[0]*(n+1)
ans=[0]*(n+1)
for i in range(n):
p,c=mi()
ch[i+1]=c
if p==0:
root=i+1
else:
a[p].append(i+1)
a[i+1].append(p)
dfs(root)
if flag==0 or ans[1:].count(0):
print("NO")
continue
print("YES")
print(*ans[1:])
``` | output | 1 | 82,712 | 13 | 165,425 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i.
<image>Illustration for the second example, the first integer is a_i and the integer in parentheses is c_i
After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices.
Help him to restore initial integers!
Input
The first line contains an integer n (1 ≤ n ≤ 2000) — the number of vertices in the tree.
The next n lines contain descriptions of vertices: the i-th line contains two integers p_i and c_i (0 ≤ p_i ≤ n; 0 ≤ c_i ≤ n-1), where p_i is the parent of vertex i or 0 if vertex i is root, and c_i is the number of vertices j in the subtree of vertex i, such that a_j < a_i.
It is guaranteed that the values of p_i describe a rooted tree with n vertices.
Output
If a solution exists, in the first line print "YES", and in the second line output n integers a_i (1 ≤ a_i ≤ {10}^{9}). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all a_i are between 1 and 10^9.
If there are no solutions, print "NO".
Examples
Input
3
2 0
0 2
2 0
Output
YES
1 2 1
Input
5
0 1
1 3
2 1
3 0
2 0
Output
YES
2 3 2 1 2 | instruction | 0 | 82,713 | 13 | 165,426 |
Tags: constructive algorithms, data structures, dfs and similar, graphs, greedy, trees
Correct Solution:
```
from sys import stdin, stdout
valid = True
def getnumberfromtree(node, dic, slist):
rst = []
leftCnt = slist[node]
global valid
for next in dic[node]:
subRst = getnumberfromtree(next, dic, slist)
if subRst is None:
return None
rst.extend(subRst)
#print(leftCnt)
#print(rst)
if leftCnt > len(rst):
valid = False
return None
rst.insert(leftCnt, node)
return rst
if __name__ == '__main__':
n = int(stdin.readline())
dic = [[] for i in range(n)]
root = 0
slist = [0]*n
for i in range(n):
pc = list(map(int, stdin.readline().split()))
slist[i] = pc[1]
if pc[0] == 0:
root = i
else:
dic[pc[0]-1].append(i)
#print(root)
#print(dic)
res = getnumberfromtree(root, dic, slist)
#print(valid)
if valid:
stdout.write('YES' + '\n')
for i in range(len(res)):
stdout.write(str(res.index(i) + 1) + ' ')
else:
stdout.write('NO')
``` | output | 1 | 82,713 | 13 | 165,427 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i.
<image>Illustration for the second example, the first integer is a_i and the integer in parentheses is c_i
After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices.
Help him to restore initial integers!
Input
The first line contains an integer n (1 ≤ n ≤ 2000) — the number of vertices in the tree.
The next n lines contain descriptions of vertices: the i-th line contains two integers p_i and c_i (0 ≤ p_i ≤ n; 0 ≤ c_i ≤ n-1), where p_i is the parent of vertex i or 0 if vertex i is root, and c_i is the number of vertices j in the subtree of vertex i, such that a_j < a_i.
It is guaranteed that the values of p_i describe a rooted tree with n vertices.
Output
If a solution exists, in the first line print "YES", and in the second line output n integers a_i (1 ≤ a_i ≤ {10}^{9}). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all a_i are between 1 and 10^9.
If there are no solutions, print "NO".
Examples
Input
3
2 0
0 2
2 0
Output
YES
1 2 1
Input
5
0 1
1 3
2 1
3 0
2 0
Output
YES
2 3 2 1 2 | instruction | 0 | 82,714 | 13 | 165,428 |
Tags: constructive algorithms, data structures, dfs and similar, graphs, greedy, trees
Correct Solution:
```
import sys
# BIT aka Fenwick tree
# sum
class BIT():
def __init__(self, n):
self.n = n
self.tree = [0] * n
def _F(self, i):
return i & (i + 1)
def _getSum(self, r):
'''
sum on interval [0, r]
'''
result = 0
while r >= 0:
result += self.tree[r]
r = self._F(r) - 1
return result
def getSum(self, l, r):
'''
sum on interval [l, r]
'''
return self._getSum(r) - self._getSum(l - 1)
def _H(self, i):
return i | (i + 1)
def add(self, i, value=1):
while i < self.n:
self.tree[i] += value
i = self._H(i)
# inf = open('input.txt', 'r')
# reader = (line.rstrip() for line in inf)
reader = (line.rstrip() for line in sys.stdin)
input = reader.__next__
n = int(input())
cs = [0] * n
ps = [0] * n
children = [[] for _ in range(n)]
for i in range(n):
p, c = map(int, input().split())
if p > 0:
ps[i] = p - 1
children[p - 1].append(i)
else:
root = i
cs[i] = c
# inf.close()
visited = [False] * n
stack = [root]
prev = -1
rank = [1] * n
while stack:
v = stack.pop()
if not visited[v]:
visited[v] = True
for to in children[v]:
stack.append(v)
stack.append(to)
else:
rank[v] += rank[prev]
prev = v
# print(rank)
unused = BIT(n)
for i in range(n):
unused.add(i)
ans = [None] * n
stack = [root]
while stack:
v = stack.pop()
kth = cs[v] + 1
if kth > rank[v]:
print('NO')
sys.exit()
L = -1
R = n-1
while L + 1 < R:
m = (L + R) >> 1
if unused.getSum(0, m) < kth:
L = m
else:
R = m
ans[v] = R + 1
unused.add(R, -1)
stack.extend(children[v])
print('YES')
print(*ans)
``` | output | 1 | 82,714 | 13 | 165,429 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i.
<image>Illustration for the second example, the first integer is a_i and the integer in parentheses is c_i
After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices.
Help him to restore initial integers!
Input
The first line contains an integer n (1 ≤ n ≤ 2000) — the number of vertices in the tree.
The next n lines contain descriptions of vertices: the i-th line contains two integers p_i and c_i (0 ≤ p_i ≤ n; 0 ≤ c_i ≤ n-1), where p_i is the parent of vertex i or 0 if vertex i is root, and c_i is the number of vertices j in the subtree of vertex i, such that a_j < a_i.
It is guaranteed that the values of p_i describe a rooted tree with n vertices.
Output
If a solution exists, in the first line print "YES", and in the second line output n integers a_i (1 ≤ a_i ≤ {10}^{9}). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all a_i are between 1 and 10^9.
If there are no solutions, print "NO".
Examples
Input
3
2 0
0 2
2 0
Output
YES
1 2 1
Input
5
0 1
1 3
2 1
3 0
2 0
Output
YES
2 3 2 1 2 | instruction | 0 | 82,715 | 13 | 165,430 |
Tags: constructive algorithms, data structures, dfs and similar, graphs, greedy, trees
Correct Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO,IOBase
class SortedList:
def __init__(self,iterable=None,_load=200):
"""Initialize sorted list instance."""
if iterable is None:
iterable = []
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i:i+_load] for i in range(0,_len,_load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i|i+1<len(_fen_tree):
_fen_tree[i|i+1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self,index,value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index<len(_fen_tree):
_fen_tree[index] += value
index |= index+1
def _fen_query(self,end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end-1]
end &= end-1
return x
def _fen_findkth(self,k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k<_list_lens[0]:
return 0,k
if k>=self._len-_list_lens[-1]:
return len(_list_lens)-1,k+_list_lens[-1]-self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx+(1<<d)
if right_idx<len(_fen_tree) and k>=_fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx+1,k
def _delete(self,pos,idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos,-1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self,value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0,0
_lists = self._lists
_mins = self._mins
lo,pos = -1,len(_lists)-1
while lo+1<pos:
mi = (lo+pos)>>1
if value<=_mins[mi]:
pos = mi
else:
lo = mi
if pos and value<=_lists[pos-1][-1]:
pos -= 1
_list = _lists[pos]
lo,idx = -1,len(_list)
while lo+1<idx:
mi = (lo+idx)>>1
if value<=_list[mi]:
idx = mi
else:
lo = mi
return pos,idx
def _loc_right(self,value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0,0
_lists = self._lists
_mins = self._mins
pos,hi = 0,len(_lists)
while pos+1<hi:
mi = (pos+hi)>>1
if value<_mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo,idx = -1,len(_list)
while lo+1<idx:
mi = (lo+idx)>>1
if value<_list[mi]:
idx = mi
else:
lo = mi
return pos,idx
def add(self,value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos,idx = self._loc_right(value)
self._fen_update(pos,1)
_list = _lists[pos]
_list.insert(idx,value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load+_load<len(_list):
_lists.insert(pos+1,_list[_load:])
_list_lens.insert(pos+1,len(_list)-_load)
_mins.insert(pos+1,_list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self,value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos,idx = self._loc_right(value)
if idx and _lists[pos][idx-1]==value:
self._delete(pos,idx-1)
def remove(self,value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len==self._len:
raise ValueError('{0!r} not in list'.format(value))
def pop(self,index=-1):
"""Remove and return value at `index` in sorted list."""
pos,idx = self._fen_findkth(self._len+index if index<0 else index)
value = self._lists[pos][idx]
self._delete(pos,idx)
return value
def bisect_left(self,value):
"""Return the first index to insert `value` in the sorted list."""
pos,idx = self._loc_left(value)
return self._fen_query(pos)+idx
def bisect_right(self,value):
"""Return the last index to insert `value` in the sorted list."""
pos,idx = self._loc_right(value)
return self._fen_query(pos)+idx
def count(self,value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value)-self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self,index):
"""Lookup value at `index` in sorted list."""
pos,idx = self._fen_findkth(self._len+index if index<0 else index)
return self._lists[pos][idx]
def __delitem__(self,index):
"""Remove value at `index` from sorted list."""
pos,idx = self._fen_findkth(self._len+index if index<0 else index)
self._delete(pos,idx)
def __contains__(self,value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos,idx = self._loc_left(value)
return idx<len(_lists[pos]) and _lists[pos][idx]==value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return 'SortedList({0})'.format(list(self))
def dfs(root,path,ans,n):
st = [root]
nums = SortedList(range(1,n+1))
lst = [-1]*n
cou = 0
val = [-1]*n
if ans[st[-1]] >= len(nums):
print('NO')
return
val[st[-1]-1] = nums[ans[st[-1]]]
nums.discard(nums[ans[st[-1]]])
lst[st[-1]-1] = cou
cou += 1
while len(st):
if not len(path[st[-1]]):
y,z = 0,st[-1]-1
for j in range(n):
if lst[j] > lst[z] and val[j] < val[z]:
y += 1
if y != ans[z+1]:
print('NO')
return
st.pop()
continue
st.append(path[st[-1]].pop())
if ans[st[-1]] >= len(nums):
print('NO')
return
val[st[-1]-1] = nums[ans[st[-1]]]
nums.discard(nums[ans[st[-1]]])
lst[st[-1]-1] = cou
cou += 1
if val.count(-1):
print('NO')
else:
print('YES')
print(*val)
def main():
n = int(input())
path = [[] for _ in range(n+1)]
ans = [0]*(n+1)
for i in range(1,n+1):
p,c = map(int,input().split())
if p:
path[p].append(i)
else:
root = i
ans[i] = c
dfs(root,path,ans,n)
#Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == '__main__':
main()
``` | output | 1 | 82,715 | 13 | 165,431 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i.
<image>Illustration for the second example, the first integer is a_i and the integer in parentheses is c_i
After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices.
Help him to restore initial integers!
Input
The first line contains an integer n (1 ≤ n ≤ 2000) — the number of vertices in the tree.
The next n lines contain descriptions of vertices: the i-th line contains two integers p_i and c_i (0 ≤ p_i ≤ n; 0 ≤ c_i ≤ n-1), where p_i is the parent of vertex i or 0 if vertex i is root, and c_i is the number of vertices j in the subtree of vertex i, such that a_j < a_i.
It is guaranteed that the values of p_i describe a rooted tree with n vertices.
Output
If a solution exists, in the first line print "YES", and in the second line output n integers a_i (1 ≤ a_i ≤ {10}^{9}). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all a_i are between 1 and 10^9.
If there are no solutions, print "NO".
Examples
Input
3
2 0
0 2
2 0
Output
YES
1 2 1
Input
5
0 1
1 3
2 1
3 0
2 0
Output
YES
2 3 2 1 2 | instruction | 0 | 82,716 | 13 | 165,432 |
Tags: constructive algorithms, data structures, dfs and similar, graphs, greedy, trees
Correct Solution:
```
mod = 1000000007
eps = 10**-9
def main():
import sys
from collections import deque
input = sys.stdin.readline
N = int(input())
par = [0] * (N+1)
child = [[] for _ in range(N+1)]
C = [0] * (N+1)
for v in range(1, N+1):
p, c = map(int, input().split())
par[v] = p
C[v] = c
child[p].append(v)
if p == 0:
root = v
que = deque()
que.append(root)
seq = []
while que:
v = que.popleft()
seq.append(v)
for u in child[v]:
que.append(u)
seq.reverse()
size = [1] * (N+1)
for v in seq:
for u in child[v]:
size[v] += size[u]
order = [[] for _ in range(N+1)]
for v in seq:
if C[v] > size[v] - 1:
print("NO")
exit()
for u in child[v]:
order[v].extend(order[u])
order[v].insert(C[v], v)
print("YES")
ans = [0] * N
for i, v in enumerate(order[root]):
ans[v-1] = i+1
print(*ans)
if __name__ == '__main__':
main()
``` | output | 1 | 82,716 | 13 | 165,433 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i.
<image>Illustration for the second example, the first integer is a_i and the integer in parentheses is c_i
After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices.
Help him to restore initial integers!
Input
The first line contains an integer n (1 ≤ n ≤ 2000) — the number of vertices in the tree.
The next n lines contain descriptions of vertices: the i-th line contains two integers p_i and c_i (0 ≤ p_i ≤ n; 0 ≤ c_i ≤ n-1), where p_i is the parent of vertex i or 0 if vertex i is root, and c_i is the number of vertices j in the subtree of vertex i, such that a_j < a_i.
It is guaranteed that the values of p_i describe a rooted tree with n vertices.
Output
If a solution exists, in the first line print "YES", and in the second line output n integers a_i (1 ≤ a_i ≤ {10}^{9}). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all a_i are between 1 and 10^9.
If there are no solutions, print "NO".
Examples
Input
3
2 0
0 2
2 0
Output
YES
1 2 1
Input
5
0 1
1 3
2 1
3 0
2 0
Output
YES
2 3 2 1 2
Submitted Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO,IOBase
class SortedList:
def __init__(self,iterable=None,_load=200):
"""Initialize sorted list instance."""
if iterable is None:
iterable = []
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i:i+_load] for i in range(0,_len,_load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i|i+1<len(_fen_tree):
_fen_tree[i|i+1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self,index,value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index<len(_fen_tree):
_fen_tree[index] += value
index |= index+1
def _fen_query(self,end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end-1]
end &= end-1
return x
def _fen_findkth(self,k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k<_list_lens[0]:
return 0,k
if k>=self._len-_list_lens[-1]:
return len(_list_lens)-1,k+_list_lens[-1]-self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx+(1<<d)
if right_idx<len(_fen_tree) and k>=_fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx+1,k
def _delete(self,pos,idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos,-1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self,value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0,0
_lists = self._lists
_mins = self._mins
lo,pos = -1,len(_lists)-1
while lo+1<pos:
mi = (lo+pos)>>1
if value<=_mins[mi]:
pos = mi
else:
lo = mi
if pos and value<=_lists[pos-1][-1]:
pos -= 1
_list = _lists[pos]
lo,idx = -1,len(_list)
while lo+1<idx:
mi = (lo+idx)>>1
if value<=_list[mi]:
idx = mi
else:
lo = mi
return pos,idx
def _loc_right(self,value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0,0
_lists = self._lists
_mins = self._mins
pos,hi = 0,len(_lists)
while pos+1<hi:
mi = (pos+hi)>>1
if value<_mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo,idx = -1,len(_list)
while lo+1<idx:
mi = (lo+idx)>>1
if value<_list[mi]:
idx = mi
else:
lo = mi
return pos,idx
def add(self,value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos,idx = self._loc_right(value)
self._fen_update(pos,1)
_list = _lists[pos]
_list.insert(idx,value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load+_load<len(_list):
_lists.insert(pos+1,_list[_load:])
_list_lens.insert(pos+1,len(_list)-_load)
_mins.insert(pos+1,_list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self,value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos,idx = self._loc_right(value)
if idx and _lists[pos][idx-1]==value:
self._delete(pos,idx-1)
def remove(self,value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len==self._len:
raise ValueError('{0!r} not in list'.format(value))
def pop(self,index=-1):
"""Remove and return value at `index` in sorted list."""
pos,idx = self._fen_findkth(self._len+index if index<0 else index)
value = self._lists[pos][idx]
self._delete(pos,idx)
return value
def bisect_left(self,value):
"""Return the first index to insert `value` in the sorted list."""
pos,idx = self._loc_left(value)
return self._fen_query(pos)+idx
def bisect_right(self,value):
"""Return the last index to insert `value` in the sorted list."""
pos,idx = self._loc_right(value)
return self._fen_query(pos)+idx
def count(self,value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value)-self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self,index):
"""Lookup value at `index` in sorted list."""
pos,idx = self._fen_findkth(self._len+index if index<0 else index)
return self._lists[pos][idx]
def __delitem__(self,index):
"""Remove value at `index` from sorted list."""
pos,idx = self._fen_findkth(self._len+index if index<0 else index)
self._delete(pos,idx)
def __contains__(self,value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos,idx = self._loc_left(value)
return idx<len(_lists[pos]) and _lists[pos][idx]==value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return 'SortedList({0})'.format(list(self))
def dfs(root,path,ans,n):
st = [root]
nums = SortedList(range(1,n+1))
val = [-1]*n
if ans[st[-1]] >= len(nums):
print('NO')
return
val[st[-1]-1] = nums[ans[st[-1]]]
nums.discard(nums[ans[st[-1]]])
while len(st):
if not len(path[st[-1]]):
if len(nums) and nums[0] <= val[st[-1]-1]:
print('NO')
return
st.pop()
continue
st.append(path[st[-1]].pop())
if ans[st[-1]] >= len(nums):
print('NO')
return
val[st[-1]-1] = nums[ans[st[-1]]]
nums.discard(nums[ans[st[-1]]])
print('YES')
print(*val)
def main():
n = int(input())
path = [[] for _ in range(n+1)]
ans = [0]*(n+1)
for i in range(1,n+1):
p,c = map(int,input().split())
if p:
path[p].append(i)
else:
root = i
ans[i] = c
dfs(root,path,ans,n)
#Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == '__main__':
main()
``` | instruction | 0 | 82,717 | 13 | 165,434 |
Yes | output | 1 | 82,717 | 13 | 165,435 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i.
<image>Illustration for the second example, the first integer is a_i and the integer in parentheses is c_i
After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices.
Help him to restore initial integers!
Input
The first line contains an integer n (1 ≤ n ≤ 2000) — the number of vertices in the tree.
The next n lines contain descriptions of vertices: the i-th line contains two integers p_i and c_i (0 ≤ p_i ≤ n; 0 ≤ c_i ≤ n-1), where p_i is the parent of vertex i or 0 if vertex i is root, and c_i is the number of vertices j in the subtree of vertex i, such that a_j < a_i.
It is guaranteed that the values of p_i describe a rooted tree with n vertices.
Output
If a solution exists, in the first line print "YES", and in the second line output n integers a_i (1 ≤ a_i ≤ {10}^{9}). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all a_i are between 1 and 10^9.
If there are no solutions, print "NO".
Examples
Input
3
2 0
0 2
2 0
Output
YES
1 2 1
Input
5
0 1
1 3
2 1
3 0
2 0
Output
YES
2 3 2 1 2
Submitted Solution:
```
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(2500)
from collections import defaultdict
children = defaultdict(set)
num_bigger = dict()
ans = dict()
n = int(input())
root = None
for me in range(1, n+1):
parent, b = input().split(' ')
parent, b = int(parent), int(b)
num_bigger[me] = b
if parent == 0:
root = me
else:
children[parent].add(me)
assert(root)
def sorted_of(elem):
ret = []
for child in children[elem]:
ret += sorted_of(child)
if num_bigger[elem] <= len(ret):
ret.insert(num_bigger[elem], elem)
else:
print("NO")
sys.exit()
return ret
try:
s = sorted_of(root)
except Exception as e:
print("exception", str(e))
sys.exit()
for i in range(n):
ans[s[i]] = i+1
print("YES")
print(' '.join(str(ans[i]) for i in range(1, n+1)))
``` | instruction | 0 | 82,718 | 13 | 165,436 |
Yes | output | 1 | 82,718 | 13 | 165,437 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i.
<image>Illustration for the second example, the first integer is a_i and the integer in parentheses is c_i
After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices.
Help him to restore initial integers!
Input
The first line contains an integer n (1 ≤ n ≤ 2000) — the number of vertices in the tree.
The next n lines contain descriptions of vertices: the i-th line contains two integers p_i and c_i (0 ≤ p_i ≤ n; 0 ≤ c_i ≤ n-1), where p_i is the parent of vertex i or 0 if vertex i is root, and c_i is the number of vertices j in the subtree of vertex i, such that a_j < a_i.
It is guaranteed that the values of p_i describe a rooted tree with n vertices.
Output
If a solution exists, in the first line print "YES", and in the second line output n integers a_i (1 ≤ a_i ≤ {10}^{9}). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all a_i are between 1 and 10^9.
If there are no solutions, print "NO".
Examples
Input
3
2 0
0 2
2 0
Output
YES
1 2 1
Input
5
0 1
1 3
2 1
3 0
2 0
Output
YES
2 3 2 1 2
Submitted Solution:
```
import sys
input = sys.stdin.readline
from collections import deque
sys.setrecursionlimit(100000)
class Graph(object):
"""docstring for Graph"""
def __init__(self,n,d): # Number of nodes and d is True if directed
self.n = n
self.graph = [[] for i in range(n)]
self.parent = [-1 for i in range(n)]
self.directed = d
def addEdge(self,x,y):
self.graph[x].append(y)
if not self.directed:
self.graph[y].append(x)
def bfs(self, root): # NORMAL BFS
self.parent = [-1 for i in range(self.n)]
queue = [root]
queue = deque(queue)
vis = [0]*self.n
while len(queue)!=0:
element = queue.popleft()
vis[element] = 1
for i in self.graph[element]:
if vis[i]==0:
queue.append(i)
self.parent[i] = element
def dfs(self, root, ans): # Iterative DFS
stack=[root]
vis=[0]*self.n
stack2=[]
while len(stack)!=0: # INITIAL TRAVERSAL
element = stack.pop()
if vis[element]:
continue
vis[element] = 1
stack2.append(element)
for i in self.graph[element]:
if vis[i]==0:
self.parent[i] = element
stack.append(i)
while len(stack2)!=0: # BACKTRACING. Modify the loop according to the question
element = stack2.pop()
m = 0
for i in self.graph[element]:
if i!=self.parent[element]:
m += ans[i]
ans[element] = m
return ans
def shortestpath(self, source, dest): # Calculate Shortest Path between two nodes
self.bfs(source)
path = [dest]
while self.parent[path[-1]]!=-1:
path.append(parent[path[-1]])
return path[::-1]
def ifcycle(self):
self.bfs(0)
queue = [0]
vis = [0]*n
queue = deque(queue)
while len(queue)!=0:
element = queue.popleft()
vis[element] = 1
for i in graph[element]:
if vis[i]==1 and i!=parent[element]:
return True
if vis[i]==0:
queue.append(i)
vis[i] = 1
return False
def reroot(self, root, ans):
stack = [root]
vis = [0]*n
while len(stack)!=0:
e = stack[-1]
if vis[e]:
stack.pop()
# Reverse_The_Change()
continue
vis[e] = 1
for i in graph[e]:
if not vis[e]:
stack.append(i)
if self.parent[e]==-1:
continue
# Change_The_Answers()
def calc(self,root):
r = []
for i in self.graph[root]:
if i!=self.parent[root]:
temp = self.calc(i)
if not temp:
return False
else:
r += temp
if v[root]>len(r):
return False
r.insert(v[root],root)
return r
n = int(input())
g = Graph(n,False)
v = [0]*n
for i in range(n):
p,c = map(int,input().split())
v[i] = c
if p!=0:
g.addEdge(i,p-1)
g.parent[i] = p-1
else:
root = i
# print (g.graph)
a = g.calc(root)
if not a:
print ("NO")
exit()
ans = [0]*n
# print (a,g.graph)
for i in range(n):
ans[a[i]] = i+1
print ("YES")
print (*ans)
``` | instruction | 0 | 82,719 | 13 | 165,438 |
Yes | output | 1 | 82,719 | 13 | 165,439 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i.
<image>Illustration for the second example, the first integer is a_i and the integer in parentheses is c_i
After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices.
Help him to restore initial integers!
Input
The first line contains an integer n (1 ≤ n ≤ 2000) — the number of vertices in the tree.
The next n lines contain descriptions of vertices: the i-th line contains two integers p_i and c_i (0 ≤ p_i ≤ n; 0 ≤ c_i ≤ n-1), where p_i is the parent of vertex i or 0 if vertex i is root, and c_i is the number of vertices j in the subtree of vertex i, such that a_j < a_i.
It is guaranteed that the values of p_i describe a rooted tree with n vertices.
Output
If a solution exists, in the first line print "YES", and in the second line output n integers a_i (1 ≤ a_i ≤ {10}^{9}). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all a_i are between 1 and 10^9.
If there are no solutions, print "NO".
Examples
Input
3
2 0
0 2
2 0
Output
YES
1 2 1
Input
5
0 1
1 3
2 1
3 0
2 0
Output
YES
2 3 2 1 2
Submitted Solution:
```
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(2500)
from collections import defaultdict
children = defaultdict(set)
num_bigger = dict()
ans = dict()
n = int(input())
root = None
for me in range(1, n+1):
parent, b = input().split(' ')
parent, b = int(parent), int(b)
num_bigger[me] = b
if parent == 0:
root = me
else:
children[parent].add(me)
assert(root)
def sorted_of(elem):
ret = []
for child in children[elem]:
ret += sorted_of(child)
if num_bigger[elem] <= len(ret):
ret.insert(num_bigger[elem], elem)
else:
print("NO")
sys.exit()
return ret
s = sorted_of(root)
for i in range(n):
ans[s[i]] = i+1
print("YES")
print(' '.join(str(ans[i]) for i in range(1, n+1)))
``` | instruction | 0 | 82,720 | 13 | 165,440 |
Yes | output | 1 | 82,720 | 13 | 165,441 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i.
<image>Illustration for the second example, the first integer is a_i and the integer in parentheses is c_i
After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices.
Help him to restore initial integers!
Input
The first line contains an integer n (1 ≤ n ≤ 2000) — the number of vertices in the tree.
The next n lines contain descriptions of vertices: the i-th line contains two integers p_i and c_i (0 ≤ p_i ≤ n; 0 ≤ c_i ≤ n-1), where p_i is the parent of vertex i or 0 if vertex i is root, and c_i is the number of vertices j in the subtree of vertex i, such that a_j < a_i.
It is guaranteed that the values of p_i describe a rooted tree with n vertices.
Output
If a solution exists, in the first line print "YES", and in the second line output n integers a_i (1 ≤ a_i ≤ {10}^{9}). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all a_i are between 1 and 10^9.
If there are no solutions, print "NO".
Examples
Input
3
2 0
0 2
2 0
Output
YES
1 2 1
Input
5
0 1
1 3
2 1
3 0
2 0
Output
YES
2 3 2 1 2
Submitted Solution:
```
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
from collections import deque,defaultdict
n=int(input())
tree=[[] for s in range(n)];nums=[];root=0
for s in range(n):
p,c=map(int,input().split())
p-=1
if p!=-1:
tree[p].append(s);tree[s].append(p)
else:
root=s
nums.append(c)
dp={}
queue=deque([root]);vis=set([root])
depth=defaultdict(list);dd={};cv=0;pr=1
while len(queue)>0:
v0=queue.popleft()
for s in tree[v0]:
if not(s in vis):
queue.append(s);vis.add(s)
depth[cv].append(v0);dd[v0]=cv
pr-=1
if pr==0:
pr=len(queue);cv+=1
cv-=1;broke=False
while cv>=0:
#bfs down from every node
for node in depth[cv]:
if len(tree[node])==1 and node!=root:
dp[node]=1
else:
queue=deque([node])
count=nums[node];numbers=[]
while len(queue)>0:
v0=queue.popleft()
for s in tree[v0]:
if dd[s]>dd[v0]:
queue.append(s)
numbers.append((dp[s],s))
if count>len(numbers):
broke=True;break
else:
numbers.sort(key=lambda x: x[0])
numsofar=1
for s in range(count):
numsofar=numbers[s][0]+1
dp[node]=numsofar
for s in range(count,len(numbers)):
dp[numbers[s][1]]+=1
cv-=1
ans=[1 for s in range(n)]
for i in dp:
ans[i]=dp[i]
if broke==True:
print("NO")
else:
print("YES")
print(*ans)
``` | instruction | 0 | 82,721 | 13 | 165,442 |
No | output | 1 | 82,721 | 13 | 165,443 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i.
<image>Illustration for the second example, the first integer is a_i and the integer in parentheses is c_i
After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices.
Help him to restore initial integers!
Input
The first line contains an integer n (1 ≤ n ≤ 2000) — the number of vertices in the tree.
The next n lines contain descriptions of vertices: the i-th line contains two integers p_i and c_i (0 ≤ p_i ≤ n; 0 ≤ c_i ≤ n-1), where p_i is the parent of vertex i or 0 if vertex i is root, and c_i is the number of vertices j in the subtree of vertex i, such that a_j < a_i.
It is guaranteed that the values of p_i describe a rooted tree with n vertices.
Output
If a solution exists, in the first line print "YES", and in the second line output n integers a_i (1 ≤ a_i ≤ {10}^{9}). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all a_i are between 1 and 10^9.
If there are no solutions, print "NO".
Examples
Input
3
2 0
0 2
2 0
Output
YES
1 2 1
Input
5
0 1
1 3
2 1
3 0
2 0
Output
YES
2 3 2 1 2
Submitted Solution:
```
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
from collections import defaultdict,deque
import heapq
n=int(input());graph=[[] for s in range(n)]
cs=[];a=[-1 for s in range(n)];root=0
for j in range(n):
p,c=map(int,input().split());cs.append(c)
if p!=0:
p-=1
graph[p].append(j);graph[j].append(p)
else:
root=j
if n==1:
print("YES")
print(1)
else:
depth=defaultdict(list);dd={}
q=deque([root]);v1=set([root]);cv=0;pr=1
while len(q)>0:
v0=q.popleft()
for s in graph[v0]:
if not(s in v1):
q.append(s);v1.add(s)
depth[cv].append(v0);dd[v0]=cv;pr-=1
if pr==0:
cv+=1;pr=len(q)
cv-=1;maxcv=cv;dict1=defaultdict(list);add=2**2001
ans=[];broke=False
while cv>=0:
if cv==maxcv:
cnter=0
for s in depth[cv]:
num=add*(2**cnter)
cnter+=1
if cs[s]>0:
broke=True;break
else:
for b in graph[s]:
dict1[b].append(num)
ans.append((num,s))
else:
for s in depth[cv]:
for b in graph[s]:
if dd[b]<dd[s]:
for i in dict1[s]:
heapq.heappush(dict1[b],i)
if cs[s]==len(dict1[s]):
num=max(dict1[s])+add
elif cs[s]==0:
num=(heapq.heappop(dict1[s]))//2
else:
temp=cs[s];num=0
while temp>0:
num=heapq.heappop(dict1[s])
temp-=1
num=(num+heapq.heappop(dict1[s]))//2
ans.append((num,s))
for b in graph[s]:
if dd[b]<dd[s]:
heapq.heappush(dict1[b],num)
cv-=1
ans.sort(key=lambda x: x[0])
sorts=[(s+1,ans[s][1]) for s in range(n)];sorts.sort(key=lambda x: x[1])
answer=[s[0] for s in sorts]
print(*answer)
``` | instruction | 0 | 82,722 | 13 | 165,444 |
No | output | 1 | 82,722 | 13 | 165,445 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i.
<image>Illustration for the second example, the first integer is a_i and the integer in parentheses is c_i
After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices.
Help him to restore initial integers!
Input
The first line contains an integer n (1 ≤ n ≤ 2000) — the number of vertices in the tree.
The next n lines contain descriptions of vertices: the i-th line contains two integers p_i and c_i (0 ≤ p_i ≤ n; 0 ≤ c_i ≤ n-1), where p_i is the parent of vertex i or 0 if vertex i is root, and c_i is the number of vertices j in the subtree of vertex i, such that a_j < a_i.
It is guaranteed that the values of p_i describe a rooted tree with n vertices.
Output
If a solution exists, in the first line print "YES", and in the second line output n integers a_i (1 ≤ a_i ≤ {10}^{9}). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all a_i are between 1 and 10^9.
If there are no solutions, print "NO".
Examples
Input
3
2 0
0 2
2 0
Output
YES
1 2 1
Input
5
0 1
1 3
2 1
3 0
2 0
Output
YES
2 3 2 1 2
Submitted Solution:
```
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
from collections import deque,defaultdict
n=int(input())
tree=[[] for s in range(n)];nums=[];root=0
for s in range(n):
p,c=map(int,input().split())
p-=1
if p!=-1:
tree[p].append(s);tree[s].append(p)
else:
root=s
nums.append(c)
if n==1:
if nums[0]==0:
print("YES")
print(1)
else:
print("NO")
else:
dp={}
queue=deque([root]);vis=set([root])
depth=defaultdict(list);dd={};cv=0;pr=1
while len(queue)>0:
v0=queue.popleft()
for s in tree[v0]:
if not(s in vis):
queue.append(s);vis.add(s)
depth[cv].append(v0);dd[v0]=cv
pr-=1
if pr==0:
pr=len(queue);cv+=1
cv-=1;broke=False
while cv>=0:
#bfs down from every node
for node in depth[cv]:
count=nums[node]
if len(tree[node])==1 and node!=root:
dp[node]=1
if count>0:
broke=True;break
else:
queue=deque([node])
numbers=[]
while len(queue)>0:
v0=queue.popleft()
for s in tree[v0]:
if dd[s]>dd[v0] and s in dp:
queue.append(s)
numbers.append((dp[s],s))
if count>len(numbers):
broke=True;break
else:
numbers.sort(key=lambda x: x[0])
print(numbers)
dp[node]=numbers[count-1][0]+1
for s in range(count,len(numbers)):
dp[numbers[s][1]]+=1
cv-=1
ans=[1 for s in range(n)]
for i in dp:
ans[i]=dp[i]
if broke==True:
print("NO")
else:
print("YES")
print(*ans)
``` | instruction | 0 | 82,723 | 13 | 165,446 |
No | output | 1 | 82,723 | 13 | 165,447 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i.
<image>Illustration for the second example, the first integer is a_i and the integer in parentheses is c_i
After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices.
Help him to restore initial integers!
Input
The first line contains an integer n (1 ≤ n ≤ 2000) — the number of vertices in the tree.
The next n lines contain descriptions of vertices: the i-th line contains two integers p_i and c_i (0 ≤ p_i ≤ n; 0 ≤ c_i ≤ n-1), where p_i is the parent of vertex i or 0 if vertex i is root, and c_i is the number of vertices j in the subtree of vertex i, such that a_j < a_i.
It is guaranteed that the values of p_i describe a rooted tree with n vertices.
Output
If a solution exists, in the first line print "YES", and in the second line output n integers a_i (1 ≤ a_i ≤ {10}^{9}). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all a_i are between 1 and 10^9.
If there are no solutions, print "NO".
Examples
Input
3
2 0
0 2
2 0
Output
YES
1 2 1
Input
5
0 1
1 3
2 1
3 0
2 0
Output
YES
2 3 2 1 2
Submitted Solution:
```
n=int(input());root=None
c=[None for x in range(n+1)]
parent=[None for x in range(n+1)]
for i in range(1,n+1):
pi,ci=[int(x) for x in input().split()]
c[i]=ci
if pi==0:root=i
parent[i]=pi
def parent_array_tograph(parent):
l=len(parent);graph=dict()
for i in range(1,l):
if parent[i] not in graph:
graph[parent[i]]=[i]
else:
graph[parent[i]].append(i)
return graph
graph=parent_array_tograph(parent)
######directed
def dfs(graph,n,currnode):
visited=[False for x in range(n+1)]
stack=[currnode]
ans=[]
while stack:
currnode=stack[-1]
if visited[currnode]==False:
visited[currnode]=True
ans.append(currnode)
if currnode in graph:
for neighbour in graph[currnode]:
if visited[neighbour]==False:
visited[neighbour]=True
stack.append(neighbour)
ans.append(neighbour)
break #####if we remove break it becomes bfs
else:
stack.pop() ####we are backtracking to previous node which is in our stack
else:
stack.pop()
return ans
ans=dfs(graph,n,root)
result=[None for x in range(n+1)]
value=[True for x in range(n+1)]
notpossibe=False
for i in range(len(ans)):
ci=c[ans[i]]
index=1
while ci!=0:
if value[index]==True:
ci-=1
index+=1
else:index+=1
while True:
if index==n+1:
notpossibe=True
break
if value[index]==True:
value[index]=False
result[ans[i]]=index
break
else:
index+=1
if notpossibe==True:
break
if notpossibe==False:
print("YES")
print(*result[1:])
else:
print("NO")
``` | instruction | 0 | 82,724 | 13 | 165,448 |
No | output | 1 | 82,724 | 13 | 165,449 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.
Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only three values n, d and h:
* The tree had exactly n vertices.
* The tree had diameter d. In other words, d was the biggest distance between two vertices.
* Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex.
The distance between two vertices of the tree is the number of edges on the simple path between them.
Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1".
Input
The first line contains three integers n, d and h (2 ≤ n ≤ 100 000, 1 ≤ h ≤ d ≤ n - 1) — the number of vertices, diameter, and height after rooting in vertex 1, respectively.
Output
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes).
Otherwise, describe any tree matching Limak's description. Print n - 1 lines, each with two space-separated integers – indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
Examples
Input
5 3 2
Output
1 2
1 3
3 4
3 5
Input
8 5 2
Output
-1
Input
8 4 2
Output
4 8
5 7
2 3
8 1
2 1
5 6
1 5
Note
Below you can see trees printed to the output in the first sample and the third sample.
<image> | instruction | 0 | 83,010 | 13 | 166,020 |
Tags: constructive algorithms, graphs, trees
Correct Solution:
```
n,d,h = map(int, input().split())
if d > 2*h or (h==1 and d==1 and n > 2):
print(-1)
elif h == d and n > h+1:
for i in range(h):
print(str(i+1)+" "+str(i+2))
for i in range(h+2,n+1):
print("2 "+str(i))
else:
for i in range(h):
print(str(i+1)+" "+str(i+2))
if d > h:
print("1 "+str(h+2))
for i in range(d-h-1):
print(str(h+2+i)+" "+str(h+3+i))
for i in range(d+2,n+1):
print("1 "+str(i))
``` | output | 1 | 83,010 | 13 | 166,021 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.
Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only three values n, d and h:
* The tree had exactly n vertices.
* The tree had diameter d. In other words, d was the biggest distance between two vertices.
* Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex.
The distance between two vertices of the tree is the number of edges on the simple path between them.
Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1".
Input
The first line contains three integers n, d and h (2 ≤ n ≤ 100 000, 1 ≤ h ≤ d ≤ n - 1) — the number of vertices, diameter, and height after rooting in vertex 1, respectively.
Output
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes).
Otherwise, describe any tree matching Limak's description. Print n - 1 lines, each with two space-separated integers – indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
Examples
Input
5 3 2
Output
1 2
1 3
3 4
3 5
Input
8 5 2
Output
-1
Input
8 4 2
Output
4 8
5 7
2 3
8 1
2 1
5 6
1 5
Note
Below you can see trees printed to the output in the first sample and the third sample.
<image> | instruction | 0 | 83,011 | 13 | 166,022 |
Tags: constructive algorithms, graphs, trees
Correct Solution:
```
[n,d,h]=[int(i) for i in input().split()]
if d>2*h or (n>2 and d==1):
print(-1)
else:
for i in range(1,h+1):
print(i,i+1)
if d>h:
print(1,h+2)
for i in range(h+2,d+1):
print(i,i+1)
for i in range(d+2,n+1):
print(1,i)
else:
for i in range(d+2,n+1):
print(2,i)
``` | output | 1 | 83,011 | 13 | 166,023 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.
Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only three values n, d and h:
* The tree had exactly n vertices.
* The tree had diameter d. In other words, d was the biggest distance between two vertices.
* Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex.
The distance between two vertices of the tree is the number of edges on the simple path between them.
Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1".
Input
The first line contains three integers n, d and h (2 ≤ n ≤ 100 000, 1 ≤ h ≤ d ≤ n - 1) — the number of vertices, diameter, and height after rooting in vertex 1, respectively.
Output
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes).
Otherwise, describe any tree matching Limak's description. Print n - 1 lines, each with two space-separated integers – indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
Examples
Input
5 3 2
Output
1 2
1 3
3 4
3 5
Input
8 5 2
Output
-1
Input
8 4 2
Output
4 8
5 7
2 3
8 1
2 1
5 6
1 5
Note
Below you can see trees printed to the output in the first sample and the third sample.
<image> | instruction | 0 | 83,012 | 13 | 166,024 |
Tags: constructive algorithms, graphs, trees
Correct Solution:
```
n, d, h = map(int, input().split())
if d > h * 2 or (n > 2 and h == 1 and d == 1):
print(-1)
else:
for i in range(2, h + 2):
print(i-1, i)
c = h+2
for i in range(d - h):
if i == 0:
print(1, h + 2)
else:
print(h + 2 + i - 1, h + 2 + i)
for i in range(d+2, n+1):
print(h, i)
``` | output | 1 | 83,012 | 13 | 166,025 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.
Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only three values n, d and h:
* The tree had exactly n vertices.
* The tree had diameter d. In other words, d was the biggest distance between two vertices.
* Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex.
The distance between two vertices of the tree is the number of edges on the simple path between them.
Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1".
Input
The first line contains three integers n, d and h (2 ≤ n ≤ 100 000, 1 ≤ h ≤ d ≤ n - 1) — the number of vertices, diameter, and height after rooting in vertex 1, respectively.
Output
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes).
Otherwise, describe any tree matching Limak's description. Print n - 1 lines, each with two space-separated integers – indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
Examples
Input
5 3 2
Output
1 2
1 3
3 4
3 5
Input
8 5 2
Output
-1
Input
8 4 2
Output
4 8
5 7
2 3
8 1
2 1
5 6
1 5
Note
Below you can see trees printed to the output in the first sample and the third sample.
<image> | instruction | 0 | 83,013 | 13 | 166,026 |
Tags: constructive algorithms, graphs, trees
Correct Solution:
```
n, d, h = (int(i) for i in input().split())
if d > 2 * h:
print(-1)
exit()
if n >= 3 and d == 1:
print(-1)
exit()
a = [int(i+2) for i in range(n-1)]
a.sort(reverse = True)
b, c = 2, 3
if d == h and d != n - 1:
print(1,2)
a.pop()
for i in range(n - d):
print(2,a.pop())
if d >= 3:
while len(a) > 0:
s = a.pop()
print(c,s)
c = s
exit()
if d == n - 1:
for i in range(1,h+1):
print(i,i+1)
u = [int(i) for i in range(h+2,n+1)]
y = 1
while len(u) > 0:
s = u.pop()
print(y,s)
y = s
else:
for i in range(n - d + 1):
print(1,a.pop())
for i in range(h - 1):
s = a.pop()
print(b,s)
b = s
while len(a) > 0:
s = a.pop()
print(c,s)
c = s
``` | output | 1 | 83,013 | 13 | 166,027 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.
Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only three values n, d and h:
* The tree had exactly n vertices.
* The tree had diameter d. In other words, d was the biggest distance between two vertices.
* Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex.
The distance between two vertices of the tree is the number of edges on the simple path between them.
Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1".
Input
The first line contains three integers n, d and h (2 ≤ n ≤ 100 000, 1 ≤ h ≤ d ≤ n - 1) — the number of vertices, diameter, and height after rooting in vertex 1, respectively.
Output
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes).
Otherwise, describe any tree matching Limak's description. Print n - 1 lines, each with two space-separated integers – indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
Examples
Input
5 3 2
Output
1 2
1 3
3 4
3 5
Input
8 5 2
Output
-1
Input
8 4 2
Output
4 8
5 7
2 3
8 1
2 1
5 6
1 5
Note
Below you can see trees printed to the output in the first sample and the third sample.
<image> | instruction | 0 | 83,014 | 13 | 166,028 |
Tags: constructive algorithms, graphs, trees
Correct Solution:
```
n,d,h=map(int,input().split())
if((n>2 and d==1)or 2*h<d):exit(print(-1))
for i in range(h):print(i+1,i+2)
if(d!=h):
print(1,h+2)
for i in range(d-h-1):print(i+h+2,i+h+3)
for i in range(n-d-1):print(1+(d==h),i+d+2)
# Made By Mostafa_Khaled
``` | output | 1 | 83,014 | 13 | 166,029 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.
Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only three values n, d and h:
* The tree had exactly n vertices.
* The tree had diameter d. In other words, d was the biggest distance between two vertices.
* Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex.
The distance between two vertices of the tree is the number of edges on the simple path between them.
Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1".
Input
The first line contains three integers n, d and h (2 ≤ n ≤ 100 000, 1 ≤ h ≤ d ≤ n - 1) — the number of vertices, diameter, and height after rooting in vertex 1, respectively.
Output
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes).
Otherwise, describe any tree matching Limak's description. Print n - 1 lines, each with two space-separated integers – indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
Examples
Input
5 3 2
Output
1 2
1 3
3 4
3 5
Input
8 5 2
Output
-1
Input
8 4 2
Output
4 8
5 7
2 3
8 1
2 1
5 6
1 5
Note
Below you can see trees printed to the output in the first sample and the third sample.
<image> | instruction | 0 | 83,015 | 13 | 166,030 |
Tags: constructive algorithms, graphs, trees
Correct Solution:
```
import sys,os,io
import math,bisect,operator
inf,mod = float('inf'),10**9+7
# sys.setrecursionlimit(10 ** 6)
from itertools import groupby,accumulate
from heapq import heapify,heappop,heappush
from collections import deque,Counter,defaultdict
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
Neo = lambda : list(map(int,input().split()))
# test, = Neo()
n,d,h = Neo()
f = 0
Ans = []
for i in range(1,h+1):
if i+1 > n:
f = 1
Ans.append((i,i+1))
t = d-h
# print(t)
if d < h or h < d-h:
f = 1
k = h+1
if t > 0:
Ans.append((1,h+2))
t -= 1
k += 1
while t > 0:
if k+1 > n:
f = 1
Ans.append((k,k+1))
k += 1
t -= 1
# print(k)
if d-h == 0:
l = 0
for i in range(k+1,n+1):
l = 1
Ans.append((2,i))
if (d < 2 or h < 2) and l:
f = 1
else:
for i in range(k+1,n+1):
Ans.append((1,i))
if len(Ans) > n-1:
f = 1
if f:
print(-1)
else:
for i,j in Ans:
print(i,j)
``` | output | 1 | 83,015 | 13 | 166,031 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.
Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only three values n, d and h:
* The tree had exactly n vertices.
* The tree had diameter d. In other words, d was the biggest distance between two vertices.
* Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex.
The distance between two vertices of the tree is the number of edges on the simple path between them.
Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1".
Input
The first line contains three integers n, d and h (2 ≤ n ≤ 100 000, 1 ≤ h ≤ d ≤ n - 1) — the number of vertices, diameter, and height after rooting in vertex 1, respectively.
Output
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes).
Otherwise, describe any tree matching Limak's description. Print n - 1 lines, each with two space-separated integers – indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
Examples
Input
5 3 2
Output
1 2
1 3
3 4
3 5
Input
8 5 2
Output
-1
Input
8 4 2
Output
4 8
5 7
2 3
8 1
2 1
5 6
1 5
Note
Below you can see trees printed to the output in the first sample and the third sample.
<image> | instruction | 0 | 83,016 | 13 | 166,032 |
Tags: constructive algorithms, graphs, trees
Correct Solution:
```
n,d,h=list(map(int,input().split()))
if 2*h<d or (h==d==1 and n>2):
print(-1)
else:
ans=[]
z=1
for i in range(h):
ans.append((i+1,i+2))
z=i+2
k=d-h
if k>0:
ans.append((1,z+1))
z+=1
k-=1
#print(ans)
for i in range(k):
ans.append((z,z+1))
z+=1
z+=1
#print(ans,z)
for i in range(z,n+1):
ans.append((1,i))
for a,b in ans:
print(a,b)
else:
for i in range(z+1,n+1):
ans.append((2,i))
for a,b in ans:
print(a,b)
``` | output | 1 | 83,016 | 13 | 166,033 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.
Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only three values n, d and h:
* The tree had exactly n vertices.
* The tree had diameter d. In other words, d was the biggest distance between two vertices.
* Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex.
The distance between two vertices of the tree is the number of edges on the simple path between them.
Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1".
Input
The first line contains three integers n, d and h (2 ≤ n ≤ 100 000, 1 ≤ h ≤ d ≤ n - 1) — the number of vertices, diameter, and height after rooting in vertex 1, respectively.
Output
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes).
Otherwise, describe any tree matching Limak's description. Print n - 1 lines, each with two space-separated integers – indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
Examples
Input
5 3 2
Output
1 2
1 3
3 4
3 5
Input
8 5 2
Output
-1
Input
8 4 2
Output
4 8
5 7
2 3
8 1
2 1
5 6
1 5
Note
Below you can see trees printed to the output in the first sample and the third sample.
<image> | instruction | 0 | 83,017 | 13 | 166,034 |
Tags: constructive algorithms, graphs, trees
Correct Solution:
```
n,d,h = [int(i) for i in input().split()]
if d > 2*h or (d == 1 and n > 2):
print (-1)
else:
for i in range(1,h+1):
print(i,i+1)
if d > h:
print (1,h+2)
for i in range(h+2,d+1):
print (i,i+1)
for i in range(d+2,n+1):
print (1,i)
else:
for i in range(h+2,n+1):
print (2,i)
``` | output | 1 | 83,017 | 13 | 166,035 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.
Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only three values n, d and h:
* The tree had exactly n vertices.
* The tree had diameter d. In other words, d was the biggest distance between two vertices.
* Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex.
The distance between two vertices of the tree is the number of edges on the simple path between them.
Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1".
Input
The first line contains three integers n, d and h (2 ≤ n ≤ 100 000, 1 ≤ h ≤ d ≤ n - 1) — the number of vertices, diameter, and height after rooting in vertex 1, respectively.
Output
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes).
Otherwise, describe any tree matching Limak's description. Print n - 1 lines, each with two space-separated integers – indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
Examples
Input
5 3 2
Output
1 2
1 3
3 4
3 5
Input
8 5 2
Output
-1
Input
8 4 2
Output
4 8
5 7
2 3
8 1
2 1
5 6
1 5
Note
Below you can see trees printed to the output in the first sample and the third sample.
<image>
Submitted Solution:
```
n,d,h=[int(i) for i in input().split()]
if (n>d and h<=d<=2*h) is False:
print(-1)
elif h==1:
if d==1 and n>2:
print(-1)
elif d==1 and n==2:
print('1 2')
elif d==2:
s=[]
for i in range(2,n+1):
s+=['1 '+str(i)]
print('\n'.join(s))
else:
s=[]
for i in range(1,h+1):
s+=[str(i)+' '+str(i+1)]
j=d-h
if j>0:
s+=['1 '+str(h+2)]
for i in range(h+2,d+1):
s+=[str(i)+' '+str(1+i)]
for i in range(d+2,n+1):
s+=['2 '+str(i)]
print('\n'.join(s))
``` | instruction | 0 | 83,018 | 13 | 166,036 |
Yes | output | 1 | 83,018 | 13 | 166,037 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.
Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only three values n, d and h:
* The tree had exactly n vertices.
* The tree had diameter d. In other words, d was the biggest distance between two vertices.
* Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex.
The distance between two vertices of the tree is the number of edges on the simple path between them.
Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1".
Input
The first line contains three integers n, d and h (2 ≤ n ≤ 100 000, 1 ≤ h ≤ d ≤ n - 1) — the number of vertices, diameter, and height after rooting in vertex 1, respectively.
Output
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes).
Otherwise, describe any tree matching Limak's description. Print n - 1 lines, each with two space-separated integers – indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
Examples
Input
5 3 2
Output
1 2
1 3
3 4
3 5
Input
8 5 2
Output
-1
Input
8 4 2
Output
4 8
5 7
2 3
8 1
2 1
5 6
1 5
Note
Below you can see trees printed to the output in the first sample and the third sample.
<image>
Submitted Solution:
```
n, d, h = map(int, input().split())
result = [0] * (d+1)
if d > 2 * h or (d == h and d == 1 and n > 2):
print(-1)
else:
result[d-h] = 1
j = 2
for i in range(d+1):
if result[i] == 0:
result[i] = j
j += 1
for i in range(d):
print(result[i], result[i+1])
main = len(result)
dif = n - main
if result[0] != 1:
for i in range(dif):
print(1, j)
j += 1
else:
for i in range(dif):
print(result[1], j)
j += 1
``` | instruction | 0 | 83,019 | 13 | 166,038 |
Yes | output | 1 | 83,019 | 13 | 166,039 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.
Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only three values n, d and h:
* The tree had exactly n vertices.
* The tree had diameter d. In other words, d was the biggest distance between two vertices.
* Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex.
The distance between two vertices of the tree is the number of edges on the simple path between them.
Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1".
Input
The first line contains three integers n, d and h (2 ≤ n ≤ 100 000, 1 ≤ h ≤ d ≤ n - 1) — the number of vertices, diameter, and height after rooting in vertex 1, respectively.
Output
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes).
Otherwise, describe any tree matching Limak's description. Print n - 1 lines, each with two space-separated integers – indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
Examples
Input
5 3 2
Output
1 2
1 3
3 4
3 5
Input
8 5 2
Output
-1
Input
8 4 2
Output
4 8
5 7
2 3
8 1
2 1
5 6
1 5
Note
Below you can see trees printed to the output in the first sample and the third sample.
<image>
Submitted Solution:
```
from __future__ import print_function
import sys
from collections import *
from heapq import *
from functools import *
import re
from itertools import *
INF=float("inf")
NINF=float("-inf")
try:
input=raw_input
except:
pass
def read_string():
return input()
def read_string_line():
return [x for x in input().split(" ")]
def read_int_line():
return [int(x) for x in input().split(" ")]
def read_int():
return int(input())
n,d,h=read_int_line()
if d>n-1 or d>2*h or d < h or (d==h and d==1 and n>2):
print("-1")
exit()
for i in range(h):
print("%d %d"%(i+1,i+2))
cur=h+2
if d==h:
for i in range(cur,n+1):
print("2 %d" % i)
exit()
for i in range(d-h):
if i==0: print("1 %d"%cur)
else: print("%d %d" % (cur+i-1, cur+i))
cur =d+2
for i in range(cur,n+1):
print("%d %d"%(1,i))
``` | instruction | 0 | 83,020 | 13 | 166,040 |
Yes | output | 1 | 83,020 | 13 | 166,041 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.
Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only three values n, d and h:
* The tree had exactly n vertices.
* The tree had diameter d. In other words, d was the biggest distance between two vertices.
* Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex.
The distance between two vertices of the tree is the number of edges on the simple path between them.
Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1".
Input
The first line contains three integers n, d and h (2 ≤ n ≤ 100 000, 1 ≤ h ≤ d ≤ n - 1) — the number of vertices, diameter, and height after rooting in vertex 1, respectively.
Output
If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes).
Otherwise, describe any tree matching Limak's description. Print n - 1 lines, each with two space-separated integers – indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.
Examples
Input
5 3 2
Output
1 2
1 3
3 4
3 5
Input
8 5 2
Output
-1
Input
8 4 2
Output
4 8
5 7
2 3
8 1
2 1
5 6
1 5
Note
Below you can see trees printed to the output in the first sample and the third sample.
<image>
Submitted Solution:
```
n,d,h=map(int,input().split())
if n ==2:
if d == h and d == 1:
print('1 2')
else:
print(-1)
elif d== 1 or d>2*h:
print(-1)
else:
for i in range(h):
print(i+1,i+2)
for i in range(d-h):
print(1 if i==0 else i+h+1,i+h+2)
for i in range(d+1,n):
print(2 if d==h else 1, i+1)
``` | instruction | 0 | 83,021 | 13 | 166,042 |
Yes | output | 1 | 83,021 | 13 | 166,043 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.