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.
Gardener Alex loves to grow trees. We remind that tree is a connected acyclic graph on n vertices.
Today he decided to grow a rooted binary tree. A binary tree is a tree where any vertex has no more than two sons. Luckily, Alex has a permutation of numbers from 1 to n which he was presented at his last birthday, so he decided to grow a tree according to this permutation. To do so he does the following process: he finds a minimum element and makes it a root of the tree. After that permutation is divided into two parts: everything that is to the left of the minimum element, and everything that is to the right. The minimum element on the left part becomes the left son of the root, and the minimum element on the right part becomes the right son of the root. After that, this process is repeated recursively on both parts.
Now Alex wants to grow a forest of trees: one tree for each cyclic shift of the permutation. He is interested in what cyclic shift gives the tree of minimum depth. Unfortunately, growing a forest is a hard and long process, but Alex wants the answer right now. Will you help him?
We remind that cyclic shift of permutation a_1, a_2, …, a_k, …, a_n for k elements to the left is the permutation a_{k + 1}, a_{k + 2}, …, a_n, a_1, a_2, …, a_k.
Input
First line contains an integer number n ~ (1 ⩽ n ⩽ 200 000) — length of the permutation.
Second line contains n integer numbers a_1, a_2, …, a_n ~ (1 ⩽ a_i ⩽ n), and it is guaranteed that all numbers occur exactly one time.
Output
Print two numbers separated with space: minimum possible depth of a tree and how many elements we need to shift left to achieve this depth. The number of elements should be a number from 0 to n - 1. If there are several possible answers, print any of them.
Example
Input
4
1 2 3 4
Output
3 2
Note
The following picture depicts all possible trees for sample test and cyclic shifts on which they are achieved.
<image>
Submitted Solution:
```
n = int(input())
arr = list(map(int, input().split()))
t = arr[-1] - arr[0]
print(t, t-1)
``` | instruction | 0 | 24,859 | 13 | 49,718 |
No | output | 1 | 24,859 | 13 | 49,719 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gardener Alex loves to grow trees. We remind that tree is a connected acyclic graph on n vertices.
Today he decided to grow a rooted binary tree. A binary tree is a tree where any vertex has no more than two sons. Luckily, Alex has a permutation of numbers from 1 to n which he was presented at his last birthday, so he decided to grow a tree according to this permutation. To do so he does the following process: he finds a minimum element and makes it a root of the tree. After that permutation is divided into two parts: everything that is to the left of the minimum element, and everything that is to the right. The minimum element on the left part becomes the left son of the root, and the minimum element on the right part becomes the right son of the root. After that, this process is repeated recursively on both parts.
Now Alex wants to grow a forest of trees: one tree for each cyclic shift of the permutation. He is interested in what cyclic shift gives the tree of minimum depth. Unfortunately, growing a forest is a hard and long process, but Alex wants the answer right now. Will you help him?
We remind that cyclic shift of permutation a_1, a_2, …, a_k, …, a_n for k elements to the left is the permutation a_{k + 1}, a_{k + 2}, …, a_n, a_1, a_2, …, a_k.
Input
First line contains an integer number n ~ (1 ⩽ n ⩽ 200 000) — length of the permutation.
Second line contains n integer numbers a_1, a_2, …, a_n ~ (1 ⩽ a_i ⩽ n), and it is guaranteed that all numbers occur exactly one time.
Output
Print two numbers separated with space: minimum possible depth of a tree and how many elements we need to shift left to achieve this depth. The number of elements should be a number from 0 to n - 1. If there are several possible answers, print any of them.
Example
Input
4
1 2 3 4
Output
3 2
Note
The following picture depicts all possible trees for sample test and cyclic shifts on which they are achieved.
<image>
Submitted Solution:
```
n = int(input())
a = list(map(int, input().split()))
l = len(a)
mid = l // 2
mn = min(a)
ind = a.index(mn)
k = ind - mid
d = l // 2 + 1
print(d, k)
``` | instruction | 0 | 24,860 | 13 | 49,720 |
No | output | 1 | 24,860 | 13 | 49,721 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gardener Alex loves to grow trees. We remind that tree is a connected acyclic graph on n vertices.
Today he decided to grow a rooted binary tree. A binary tree is a tree where any vertex has no more than two sons. Luckily, Alex has a permutation of numbers from 1 to n which he was presented at his last birthday, so he decided to grow a tree according to this permutation. To do so he does the following process: he finds a minimum element and makes it a root of the tree. After that permutation is divided into two parts: everything that is to the left of the minimum element, and everything that is to the right. The minimum element on the left part becomes the left son of the root, and the minimum element on the right part becomes the right son of the root. After that, this process is repeated recursively on both parts.
Now Alex wants to grow a forest of trees: one tree for each cyclic shift of the permutation. He is interested in what cyclic shift gives the tree of minimum depth. Unfortunately, growing a forest is a hard and long process, but Alex wants the answer right now. Will you help him?
We remind that cyclic shift of permutation a_1, a_2, …, a_k, …, a_n for k elements to the left is the permutation a_{k + 1}, a_{k + 2}, …, a_n, a_1, a_2, …, a_k.
Input
First line contains an integer number n ~ (1 ⩽ n ⩽ 200 000) — length of the permutation.
Second line contains n integer numbers a_1, a_2, …, a_n ~ (1 ⩽ a_i ⩽ n), and it is guaranteed that all numbers occur exactly one time.
Output
Print two numbers separated with space: minimum possible depth of a tree and how many elements we need to shift left to achieve this depth. The number of elements should be a number from 0 to n - 1. If there are several possible answers, print any of them.
Example
Input
4
1 2 3 4
Output
3 2
Note
The following picture depicts all possible trees for sample test and cyclic shifts on which they are achieved.
<image>
Submitted Solution:
```
import math
n = int(input())
a = list(map(int, input().split()))
b = [1] * n
max_value = 1
max_index = 0
for i in range(n):
j = 1
while j < n and a[(i + j) % n] > a[i]:
j += 1
b[i] = j
if j > max_value:
max_value = j
max_index = i
shift = max_index + max_value // 2
depth = int(math.log2(max_value)) + 1
print(depth, shift)
``` | instruction | 0 | 24,861 | 13 | 49,722 |
No | output | 1 | 24,861 | 13 | 49,723 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gardener Alex loves to grow trees. We remind that tree is a connected acyclic graph on n vertices.
Today he decided to grow a rooted binary tree. A binary tree is a tree where any vertex has no more than two sons. Luckily, Alex has a permutation of numbers from 1 to n which he was presented at his last birthday, so he decided to grow a tree according to this permutation. To do so he does the following process: he finds a minimum element and makes it a root of the tree. After that permutation is divided into two parts: everything that is to the left of the minimum element, and everything that is to the right. The minimum element on the left part becomes the left son of the root, and the minimum element on the right part becomes the right son of the root. After that, this process is repeated recursively on both parts.
Now Alex wants to grow a forest of trees: one tree for each cyclic shift of the permutation. He is interested in what cyclic shift gives the tree of minimum depth. Unfortunately, growing a forest is a hard and long process, but Alex wants the answer right now. Will you help him?
We remind that cyclic shift of permutation a_1, a_2, …, a_k, …, a_n for k elements to the left is the permutation a_{k + 1}, a_{k + 2}, …, a_n, a_1, a_2, …, a_k.
Input
First line contains an integer number n ~ (1 ⩽ n ⩽ 200 000) — length of the permutation.
Second line contains n integer numbers a_1, a_2, …, a_n ~ (1 ⩽ a_i ⩽ n), and it is guaranteed that all numbers occur exactly one time.
Output
Print two numbers separated with space: minimum possible depth of a tree and how many elements we need to shift left to achieve this depth. The number of elements should be a number from 0 to n - 1. If there are several possible answers, print any of them.
Example
Input
4
1 2 3 4
Output
3 2
Note
The following picture depicts all possible trees for sample test and cyclic shifts on which they are achieved.
<image>
Submitted Solution:
```
def h(arr):
if len(arr) == 0:
return 0
i = arr.index(min(arr))
return max(h(arr[:i]), h(arr[i + 1:])) + 1
n = int(input())
arr = list(map(int, input().split()))
minimal = float("inf")
index = 0
for i in range(n):
arr = arr[1:] + [arr[0]]
res = h(arr)
if res < minimal:
minimal = res
index = n - i - 1
print(minimal, index)
``` | instruction | 0 | 24,862 | 13 | 49,724 |
No | output | 1 | 24,862 | 13 | 49,725 |
Provide tags and a correct Python 3 solution for this coding contest problem.
DZY loves planting, and he enjoys solving tree problems.
DZY has a weighted tree (connected undirected graph without cycles) containing n nodes (they are numbered from 1 to n). He defines the function g(x, y) (1 ≤ x, y ≤ n) as the longest edge in the shortest path between nodes x and y. Specially g(z, z) = 0 for every z.
For every integer sequence p1, p2, ..., pn (1 ≤ pi ≤ n), DZY defines f(p) as <image>.
DZY wants to find such a sequence p that f(p) has maximum possible value. But there is one more restriction: the element j can appear in p at most xj times.
Please, find the maximum possible f(p) under the described restrictions.
Input
The first line contains an integer n (1 ≤ n ≤ 3000).
Each of the next n - 1 lines contains three integers ai, bi, ci (1 ≤ ai, bi ≤ n; 1 ≤ ci ≤ 10000), denoting an edge between ai and bi with length ci. It is guaranteed that these edges form a tree.
Each of the next n lines describes an element of sequence x. The j-th line contains an integer xj (1 ≤ xj ≤ n).
Output
Print a single integer representing the answer.
Examples
Input
4
1 2 1
2 3 2
3 4 3
1
1
1
1
Output
2
Input
4
1 2 1
2 3 2
3 4 3
4
4
4
4
Output
3
Note
In the first sample, one of the optimal p is [4, 3, 2, 1]. | instruction | 0 | 25,097 | 13 | 50,194 |
Tags: binary search, dsu, trees
Correct Solution:
```
n = int(input())
edges = [[int(x) for x in input().split()] for i in range(n-1)]
edges = sorted(edges)
use_count = [0]+[int(input()) for i in range(n)]
lo,hi = 0,10000
def getpar(par,u):
if par[par[u]] == par[u]:
return par[u]
par[u] = getpar(par,par[u])
return par[u]
def unite(par,sz,use,u,v):
u = getpar(par,u)
v = getpar(par,v)
par[u] = v
sz[v] += sz[u]
use[v] += use[u]
def solve(fp):
par = [i for i in range(n+1)]
sz = [1 for i in range(n+1)]
use = [use_count[i] for i in range(n+1)]
for edge in edges:
if edge[2] < fp:
unite(par,sz,use,edge[0],edge[1])
total_use = sum(use_count)
for i in range(n+1):
p = getpar(par,i)
if(p == i):
if(total_use - use[p] < sz[p]):
return False
return True
while lo < hi:
mid = (lo+hi+1)//2
if solve(mid):
lo = mid
else:
hi = mid-1
print(lo)
``` | output | 1 | 25,097 | 13 | 50,195 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer L. Construct a directed graph that satisfies the conditions below. The graph may contain multiple edges between the same pair of vertices. It can be proved that such a graph always exists.
* The number of vertices, N, is at most 20. The vertices are given ID numbers from 1 to N.
* The number of edges, M, is at most 60. Each edge has an integer length between 0 and 10^6 (inclusive).
* Every edge is directed from the vertex with the smaller ID to the vertex with the larger ID. That is, 1,2,...,N is one possible topological order of the vertices.
* There are exactly L different paths from Vertex 1 to Vertex N. The lengths of these paths are all different, and they are integers between 0 and L-1.
Here, the length of a path is the sum of the lengths of the edges contained in that path, and two paths are considered different when the sets of the edges contained in those paths are different.
Constraints
* 2 \leq L \leq 10^6
* L is an integer.
Input
Input is given from Standard Input in the following format:
L
Output
In the first line, print N and M, the number of the vertices and edges in your graph. In the i-th of the following M lines, print three integers u_i,v_i and w_i, representing the starting vertex, the ending vertex and the length of the i-th edge. If there are multiple solutions, any of them will be accepted.
Examples
Input
4
Output
8 10
1 2 0
2 3 0
3 4 0
1 5 0
2 6 0
3 7 0
4 8 0
5 6 1
6 7 1
7 8 1
Input
5
Output
5 7
1 2 0
2 3 1
3 4 0
4 5 0
2 4 0
1 3 3
3 5 1 | instruction | 0 | 25,401 | 13 | 50,802 |
"Correct Solution:
```
#18:55
l = int(input())
s = bin(l)[2:]
n = len(s)
m = 0
ans = []
for i in range(n-1):
ans.append([i+1,i+2,0])
ans.append([i+1,i+2,2**(n-2-i)])
m += 2
#print(ans,m)
imp = 2 ** (n-1)
for i in range(n-1,0,-1):
if s[i] == '1':
ans.append([1,i+1,imp])
m += 1
imp += 2 ** (n-1-i)
print(n,m)
for x in ans:
print(' '.join(list(map(str,x))))
``` | output | 1 | 25,401 | 13 | 50,803 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer L. Construct a directed graph that satisfies the conditions below. The graph may contain multiple edges between the same pair of vertices. It can be proved that such a graph always exists.
* The number of vertices, N, is at most 20. The vertices are given ID numbers from 1 to N.
* The number of edges, M, is at most 60. Each edge has an integer length between 0 and 10^6 (inclusive).
* Every edge is directed from the vertex with the smaller ID to the vertex with the larger ID. That is, 1,2,...,N is one possible topological order of the vertices.
* There are exactly L different paths from Vertex 1 to Vertex N. The lengths of these paths are all different, and they are integers between 0 and L-1.
Here, the length of a path is the sum of the lengths of the edges contained in that path, and two paths are considered different when the sets of the edges contained in those paths are different.
Constraints
* 2 \leq L \leq 10^6
* L is an integer.
Input
Input is given from Standard Input in the following format:
L
Output
In the first line, print N and M, the number of the vertices and edges in your graph. In the i-th of the following M lines, print three integers u_i,v_i and w_i, representing the starting vertex, the ending vertex and the length of the i-th edge. If there are multiple solutions, any of them will be accepted.
Examples
Input
4
Output
8 10
1 2 0
2 3 0
3 4 0
1 5 0
2 6 0
3 7 0
4 8 0
5 6 1
6 7 1
7 8 1
Input
5
Output
5 7
1 2 0
2 3 1
3 4 0
4 5 0
2 4 0
1 3 3
3 5 1 | instruction | 0 | 25,402 | 13 | 50,804 |
"Correct Solution:
```
L = int(input())
n = L.bit_length()
ans = []
for i in range(1,n):
ans.append((i,i+1,0))
ans.append((i,i+1,2**(n-i-1)))
binL = bin(L)
for i in range(1,n):
if binL[i+2] == "1":
mask = int(binL[:i+2],2)<<(n-i)
ans.append((1,i+1,L&mask))
print(n,len(ans))
for edge in ans:
print(*edge)
``` | output | 1 | 25,402 | 13 | 50,805 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer L. Construct a directed graph that satisfies the conditions below. The graph may contain multiple edges between the same pair of vertices. It can be proved that such a graph always exists.
* The number of vertices, N, is at most 20. The vertices are given ID numbers from 1 to N.
* The number of edges, M, is at most 60. Each edge has an integer length between 0 and 10^6 (inclusive).
* Every edge is directed from the vertex with the smaller ID to the vertex with the larger ID. That is, 1,2,...,N is one possible topological order of the vertices.
* There are exactly L different paths from Vertex 1 to Vertex N. The lengths of these paths are all different, and they are integers between 0 and L-1.
Here, the length of a path is the sum of the lengths of the edges contained in that path, and two paths are considered different when the sets of the edges contained in those paths are different.
Constraints
* 2 \leq L \leq 10^6
* L is an integer.
Input
Input is given from Standard Input in the following format:
L
Output
In the first line, print N and M, the number of the vertices and edges in your graph. In the i-th of the following M lines, print three integers u_i,v_i and w_i, representing the starting vertex, the ending vertex and the length of the i-th edge. If there are multiple solutions, any of them will be accepted.
Examples
Input
4
Output
8 10
1 2 0
2 3 0
3 4 0
1 5 0
2 6 0
3 7 0
4 8 0
5 6 1
6 7 1
7 8 1
Input
5
Output
5 7
1 2 0
2 3 1
3 4 0
4 5 0
2 4 0
1 3 3
3 5 1 | instruction | 0 | 25,403 | 13 | 50,806 |
"Correct Solution:
```
L = int(input())
k = L.bit_length()
ans = []
for i in range(1, k):
ans.append([i,i+1,0])
ans.append([i,i+1,1<<(k-i-1)])
for i in range(k-1):
if L & 1<<i:
mask = (1<<(k+1)) - (1<<(i+1))
w = L & mask
ans.append([1, k-i, w])
print(k, len(ans))
for i in ans:
print(*i)
``` | output | 1 | 25,403 | 13 | 50,807 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer L. Construct a directed graph that satisfies the conditions below. The graph may contain multiple edges between the same pair of vertices. It can be proved that such a graph always exists.
* The number of vertices, N, is at most 20. The vertices are given ID numbers from 1 to N.
* The number of edges, M, is at most 60. Each edge has an integer length between 0 and 10^6 (inclusive).
* Every edge is directed from the vertex with the smaller ID to the vertex with the larger ID. That is, 1,2,...,N is one possible topological order of the vertices.
* There are exactly L different paths from Vertex 1 to Vertex N. The lengths of these paths are all different, and they are integers between 0 and L-1.
Here, the length of a path is the sum of the lengths of the edges contained in that path, and two paths are considered different when the sets of the edges contained in those paths are different.
Constraints
* 2 \leq L \leq 10^6
* L is an integer.
Input
Input is given from Standard Input in the following format:
L
Output
In the first line, print N and M, the number of the vertices and edges in your graph. In the i-th of the following M lines, print three integers u_i,v_i and w_i, representing the starting vertex, the ending vertex and the length of the i-th edge. If there are multiple solutions, any of them will be accepted.
Examples
Input
4
Output
8 10
1 2 0
2 3 0
3 4 0
1 5 0
2 6 0
3 7 0
4 8 0
5 6 1
6 7 1
7 8 1
Input
5
Output
5 7
1 2 0
2 3 1
3 4 0
4 5 0
2 4 0
1 3 3
3 5 1 | instruction | 0 | 25,404 | 13 | 50,808 |
"Correct Solution:
```
import math
L = int(input())
s = int(math.log2(L))
N = s+1
count = 0
graph = []
for i in range(N-1,0,-1):
if L - 2 ** (i-1) >= 2 ** s:
graph.append([i, N ,L-2 ** (i-1)])
L = L - 2 ** (i-1)
count += 1
print(N, end = ' ')
print(2*(N-1)+count)
for i in range(N,1,-1):
print(i-1, end = ' ')
print(i, end = ' ')
print(0)
print(i - 1, end=' ')
print(i, end=' ')
print(2 ** (i-2))
for i in range(len(graph)):
print(graph[i][0], end = ' ')
print(graph[i][1], end = ' ')
print(graph[i][2])
``` | output | 1 | 25,404 | 13 | 50,809 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer L. Construct a directed graph that satisfies the conditions below. The graph may contain multiple edges between the same pair of vertices. It can be proved that such a graph always exists.
* The number of vertices, N, is at most 20. The vertices are given ID numbers from 1 to N.
* The number of edges, M, is at most 60. Each edge has an integer length between 0 and 10^6 (inclusive).
* Every edge is directed from the vertex with the smaller ID to the vertex with the larger ID. That is, 1,2,...,N is one possible topological order of the vertices.
* There are exactly L different paths from Vertex 1 to Vertex N. The lengths of these paths are all different, and they are integers between 0 and L-1.
Here, the length of a path is the sum of the lengths of the edges contained in that path, and two paths are considered different when the sets of the edges contained in those paths are different.
Constraints
* 2 \leq L \leq 10^6
* L is an integer.
Input
Input is given from Standard Input in the following format:
L
Output
In the first line, print N and M, the number of the vertices and edges in your graph. In the i-th of the following M lines, print three integers u_i,v_i and w_i, representing the starting vertex, the ending vertex and the length of the i-th edge. If there are multiple solutions, any of them will be accepted.
Examples
Input
4
Output
8 10
1 2 0
2 3 0
3 4 0
1 5 0
2 6 0
3 7 0
4 8 0
5 6 1
6 7 1
7 8 1
Input
5
Output
5 7
1 2 0
2 3 1
3 4 0
4 5 0
2 4 0
1 3 3
3 5 1 | instruction | 0 | 25,405 | 13 | 50,810 |
"Correct Solution:
```
L=int(input())
count=0
k=1
max=0
LL=format(L,'b')
N=len(LL)
M=(len(LL)-1)*2+LL.count('1')-1
#print(LL)
print(N,M)
max=2**(N-1)-1
for n in range(1,N):
print(n,n+1,0)
print(n,n+1,k)
k*=2
if LL[::-1][n-1]=='1' and n!=N:
print(n,N,max+1)
max+=2**(n-1)
``` | output | 1 | 25,405 | 13 | 50,811 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer L. Construct a directed graph that satisfies the conditions below. The graph may contain multiple edges between the same pair of vertices. It can be proved that such a graph always exists.
* The number of vertices, N, is at most 20. The vertices are given ID numbers from 1 to N.
* The number of edges, M, is at most 60. Each edge has an integer length between 0 and 10^6 (inclusive).
* Every edge is directed from the vertex with the smaller ID to the vertex with the larger ID. That is, 1,2,...,N is one possible topological order of the vertices.
* There are exactly L different paths from Vertex 1 to Vertex N. The lengths of these paths are all different, and they are integers between 0 and L-1.
Here, the length of a path is the sum of the lengths of the edges contained in that path, and two paths are considered different when the sets of the edges contained in those paths are different.
Constraints
* 2 \leq L \leq 10^6
* L is an integer.
Input
Input is given from Standard Input in the following format:
L
Output
In the first line, print N and M, the number of the vertices and edges in your graph. In the i-th of the following M lines, print three integers u_i,v_i and w_i, representing the starting vertex, the ending vertex and the length of the i-th edge. If there are multiple solutions, any of them will be accepted.
Examples
Input
4
Output
8 10
1 2 0
2 3 0
3 4 0
1 5 0
2 6 0
3 7 0
4 8 0
5 6 1
6 7 1
7 8 1
Input
5
Output
5 7
1 2 0
2 3 1
3 4 0
4 5 0
2 4 0
1 3 3
3 5 1 | instruction | 0 | 25,406 | 13 | 50,812 |
"Correct Solution:
```
import math
l = int(input()) - 1
n = int(math.log2(l + 1) + 1)
res = []
for i in range(n - 1):
res.append([i + 1, i + 2, 0])
res.append([i + 1, i + 2, 2 ** i])
i = n - 2
while l > 2 ** (n - 1) - 1:
t = l - 2 ** i + 1
if t > 2 ** (n - 1) - 1:
res.append([i + 1, n, t])
l = t - 1
i -= 1
print(n, len(res))
for i in range(len(res)):
print(res[i][0],res[i][1],res[i][2])
``` | output | 1 | 25,406 | 13 | 50,813 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer L. Construct a directed graph that satisfies the conditions below. The graph may contain multiple edges between the same pair of vertices. It can be proved that such a graph always exists.
* The number of vertices, N, is at most 20. The vertices are given ID numbers from 1 to N.
* The number of edges, M, is at most 60. Each edge has an integer length between 0 and 10^6 (inclusive).
* Every edge is directed from the vertex with the smaller ID to the vertex with the larger ID. That is, 1,2,...,N is one possible topological order of the vertices.
* There are exactly L different paths from Vertex 1 to Vertex N. The lengths of these paths are all different, and they are integers between 0 and L-1.
Here, the length of a path is the sum of the lengths of the edges contained in that path, and two paths are considered different when the sets of the edges contained in those paths are different.
Constraints
* 2 \leq L \leq 10^6
* L is an integer.
Input
Input is given from Standard Input in the following format:
L
Output
In the first line, print N and M, the number of the vertices and edges in your graph. In the i-th of the following M lines, print three integers u_i,v_i and w_i, representing the starting vertex, the ending vertex and the length of the i-th edge. If there are multiple solutions, any of them will be accepted.
Examples
Input
4
Output
8 10
1 2 0
2 3 0
3 4 0
1 5 0
2 6 0
3 7 0
4 8 0
5 6 1
6 7 1
7 8 1
Input
5
Output
5 7
1 2 0
2 3 1
3 4 0
4 5 0
2 4 0
1 3 3
3 5 1 | instruction | 0 | 25,407 | 13 | 50,814 |
"Correct Solution:
```
L = int(input())
p = 0
ans = []
while(L >= 2 ** (p + 1)):
ans.append([p + 1, p + 2, 2 ** p])
ans.append([p + 1, p + 2, 0])
p += 1
endN = p + 1
tmp = 2 ** p
L -= tmp
while(L != 0):
p = 0
while(L - 2 ** p >= 0):
p += 1
ans.append([p, endN, tmp])
L -= 2 ** (p - 1)
tmp += 2**(p - 1)
# print(p, ans)
print(endN, len(ans))
for a, b, c in ans:
print(a, b, c)
``` | output | 1 | 25,407 | 13 | 50,815 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer L. Construct a directed graph that satisfies the conditions below. The graph may contain multiple edges between the same pair of vertices. It can be proved that such a graph always exists.
* The number of vertices, N, is at most 20. The vertices are given ID numbers from 1 to N.
* The number of edges, M, is at most 60. Each edge has an integer length between 0 and 10^6 (inclusive).
* Every edge is directed from the vertex with the smaller ID to the vertex with the larger ID. That is, 1,2,...,N is one possible topological order of the vertices.
* There are exactly L different paths from Vertex 1 to Vertex N. The lengths of these paths are all different, and they are integers between 0 and L-1.
Here, the length of a path is the sum of the lengths of the edges contained in that path, and two paths are considered different when the sets of the edges contained in those paths are different.
Constraints
* 2 \leq L \leq 10^6
* L is an integer.
Input
Input is given from Standard Input in the following format:
L
Output
In the first line, print N and M, the number of the vertices and edges in your graph. In the i-th of the following M lines, print three integers u_i,v_i and w_i, representing the starting vertex, the ending vertex and the length of the i-th edge. If there are multiple solutions, any of them will be accepted.
Examples
Input
4
Output
8 10
1 2 0
2 3 0
3 4 0
1 5 0
2 6 0
3 7 0
4 8 0
5 6 1
6 7 1
7 8 1
Input
5
Output
5 7
1 2 0
2 3 1
3 4 0
4 5 0
2 4 0
1 3 3
3 5 1 | instruction | 0 | 25,408 | 13 | 50,816 |
"Correct Solution:
```
# 頂点は0番から始まるとして、出力時に+1する
def graph(L):
beki = 1
for n in range(20):
beki *= 2
if beki > L: break
ans = []
Li = 1
for i in range(n):
ans += [(i + 1, i + 2, 0)]
ans += [(i + 1, i + 2, Li)]
Li *= 2
Lnext = Li
nokori_kosu = L - Li
i = n - 1
way_i = Li // 2
while nokori_kosu > 0:
while way_i > nokori_kosu:
way_i //= 2
i -= 1
ans += [(i + 1, n + 1, Lnext)]
Lnext += way_i
nokori_kosu -= way_i
print(n + 1, len(ans))
for x in ans:
print(*x)
L = int(input())
graph(L)
``` | output | 1 | 25,408 | 13 | 50,817 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer L. Construct a directed graph that satisfies the conditions below. The graph may contain multiple edges between the same pair of vertices. It can be proved that such a graph always exists.
* The number of vertices, N, is at most 20. The vertices are given ID numbers from 1 to N.
* The number of edges, M, is at most 60. Each edge has an integer length between 0 and 10^6 (inclusive).
* Every edge is directed from the vertex with the smaller ID to the vertex with the larger ID. That is, 1,2,...,N is one possible topological order of the vertices.
* There are exactly L different paths from Vertex 1 to Vertex N. The lengths of these paths are all different, and they are integers between 0 and L-1.
Here, the length of a path is the sum of the lengths of the edges contained in that path, and two paths are considered different when the sets of the edges contained in those paths are different.
Constraints
* 2 \leq L \leq 10^6
* L is an integer.
Input
Input is given from Standard Input in the following format:
L
Output
In the first line, print N and M, the number of the vertices and edges in your graph. In the i-th of the following M lines, print three integers u_i,v_i and w_i, representing the starting vertex, the ending vertex and the length of the i-th edge. If there are multiple solutions, any of them will be accepted.
Examples
Input
4
Output
8 10
1 2 0
2 3 0
3 4 0
1 5 0
2 6 0
3 7 0
4 8 0
5 6 1
6 7 1
7 8 1
Input
5
Output
5 7
1 2 0
2 3 1
3 4 0
4 5 0
2 4 0
1 3 3
3 5 1
Submitted Solution:
```
L = int(input())
edges = []
p2 = 1
N = 1
""" 2べきのとき多重辺
0 0 0 0 ...
1 === 2 === 3 === 4 === 5 ...
1 2 4 8 ...
"""
while L >= p2 * 2:
N += 1
p2 *= 2
edges.append((N - 1, N, 0))
edges.append((N - 1, N, 2 ** (N - 2)))
rest = L - p2
tmp = p2
for i in range(N, -1, -1):
if (rest >> i) & 1:
edges.append((i + 1, N, tmp))
tmp += 2 ** i
M = len(edges)
# assert N <= 20 and M <= 60
print(N, M)
for edge in edges:
print(*edge)
``` | instruction | 0 | 25,409 | 13 | 50,818 |
Yes | output | 1 | 25,409 | 13 | 50,819 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer L. Construct a directed graph that satisfies the conditions below. The graph may contain multiple edges between the same pair of vertices. It can be proved that such a graph always exists.
* The number of vertices, N, is at most 20. The vertices are given ID numbers from 1 to N.
* The number of edges, M, is at most 60. Each edge has an integer length between 0 and 10^6 (inclusive).
* Every edge is directed from the vertex with the smaller ID to the vertex with the larger ID. That is, 1,2,...,N is one possible topological order of the vertices.
* There are exactly L different paths from Vertex 1 to Vertex N. The lengths of these paths are all different, and they are integers between 0 and L-1.
Here, the length of a path is the sum of the lengths of the edges contained in that path, and two paths are considered different when the sets of the edges contained in those paths are different.
Constraints
* 2 \leq L \leq 10^6
* L is an integer.
Input
Input is given from Standard Input in the following format:
L
Output
In the first line, print N and M, the number of the vertices and edges in your graph. In the i-th of the following M lines, print three integers u_i,v_i and w_i, representing the starting vertex, the ending vertex and the length of the i-th edge. If there are multiple solutions, any of them will be accepted.
Examples
Input
4
Output
8 10
1 2 0
2 3 0
3 4 0
1 5 0
2 6 0
3 7 0
4 8 0
5 6 1
6 7 1
7 8 1
Input
5
Output
5 7
1 2 0
2 3 1
3 4 0
4 5 0
2 4 0
1 3 3
3 5 1
Submitted Solution:
```
L=int(input())
n=L.bit_length()
if L==2**n:
n+=1
path=[]
for i in range(1,n):
path.append([i,i+1,0])
path.append([i,i+1,2**(i-1)])
k=(L-1)-(2**(n-1)-1)
cur=2**(n-1)
while k>0:
if k==1:
kk=1
else:
kk=k.bit_length()
path.append([kk,n,cur])
cur+=2**(kk-1)
k=L-cur
print(n,len(path))
for p in path:
print(*p)
``` | instruction | 0 | 25,410 | 13 | 50,820 |
Yes | output | 1 | 25,410 | 13 | 50,821 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer L. Construct a directed graph that satisfies the conditions below. The graph may contain multiple edges between the same pair of vertices. It can be proved that such a graph always exists.
* The number of vertices, N, is at most 20. The vertices are given ID numbers from 1 to N.
* The number of edges, M, is at most 60. Each edge has an integer length between 0 and 10^6 (inclusive).
* Every edge is directed from the vertex with the smaller ID to the vertex with the larger ID. That is, 1,2,...,N is one possible topological order of the vertices.
* There are exactly L different paths from Vertex 1 to Vertex N. The lengths of these paths are all different, and they are integers between 0 and L-1.
Here, the length of a path is the sum of the lengths of the edges contained in that path, and two paths are considered different when the sets of the edges contained in those paths are different.
Constraints
* 2 \leq L \leq 10^6
* L is an integer.
Input
Input is given from Standard Input in the following format:
L
Output
In the first line, print N and M, the number of the vertices and edges in your graph. In the i-th of the following M lines, print three integers u_i,v_i and w_i, representing the starting vertex, the ending vertex and the length of the i-th edge. If there are multiple solutions, any of them will be accepted.
Examples
Input
4
Output
8 10
1 2 0
2 3 0
3 4 0
1 5 0
2 6 0
3 7 0
4 8 0
5 6 1
6 7 1
7 8 1
Input
5
Output
5 7
1 2 0
2 3 1
3 4 0
4 5 0
2 4 0
1 3 3
3 5 1
Submitted Solution:
```
L = int(input())
Edges = []
n = 1
while 2**(n-1)-1 < L:
n += 1
n -= 1
for i in range(1, n):
Edges.append([i, i+1, 0])
Edges.append([i, i+1, 2**(i-1)])
remain = L - 2**(n-1)
for x in range(n-1, 0, -1):
if 2**(x-1) <= remain:
Edges.append([x, n, L-remain])
remain -= 2**(x-1)
print(n, len(Edges))
for u, v, w in Edges:
print(u, v, w)
``` | instruction | 0 | 25,411 | 13 | 50,822 |
Yes | output | 1 | 25,411 | 13 | 50,823 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer L. Construct a directed graph that satisfies the conditions below. The graph may contain multiple edges between the same pair of vertices. It can be proved that such a graph always exists.
* The number of vertices, N, is at most 20. The vertices are given ID numbers from 1 to N.
* The number of edges, M, is at most 60. Each edge has an integer length between 0 and 10^6 (inclusive).
* Every edge is directed from the vertex with the smaller ID to the vertex with the larger ID. That is, 1,2,...,N is one possible topological order of the vertices.
* There are exactly L different paths from Vertex 1 to Vertex N. The lengths of these paths are all different, and they are integers between 0 and L-1.
Here, the length of a path is the sum of the lengths of the edges contained in that path, and two paths are considered different when the sets of the edges contained in those paths are different.
Constraints
* 2 \leq L \leq 10^6
* L is an integer.
Input
Input is given from Standard Input in the following format:
L
Output
In the first line, print N and M, the number of the vertices and edges in your graph. In the i-th of the following M lines, print three integers u_i,v_i and w_i, representing the starting vertex, the ending vertex and the length of the i-th edge. If there are multiple solutions, any of them will be accepted.
Examples
Input
4
Output
8 10
1 2 0
2 3 0
3 4 0
1 5 0
2 6 0
3 7 0
4 8 0
5 6 1
6 7 1
7 8 1
Input
5
Output
5 7
1 2 0
2 3 1
3 4 0
4 5 0
2 4 0
1 3 3
3 5 1
Submitted Solution:
```
L = int(input())
r = 0
while 2 ** r <= L:
r += 1
E = []
for i in range(1, r):
E.append((i, i + 1, 0))
E.append((i, i + 1, 2 ** (i - 1)))
# 2**(r-1) ~ L-1 のPATHがない。
n = 2 ** (r - 1)
###
while True:
d = L - 1 - n + 1
if d <= 0:
break
zi = 0
while 2 ** (zi) <= d:
zi += 1
E.append((zi, r, n))
n = n + 2 ** (zi - 1)
print("{} {}".format(r, len(E)))
for e in E:
print("{} {} {}".format(e[0], e[1], e[2]))
``` | instruction | 0 | 25,412 | 13 | 50,824 |
Yes | output | 1 | 25,412 | 13 | 50,825 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer L. Construct a directed graph that satisfies the conditions below. The graph may contain multiple edges between the same pair of vertices. It can be proved that such a graph always exists.
* The number of vertices, N, is at most 20. The vertices are given ID numbers from 1 to N.
* The number of edges, M, is at most 60. Each edge has an integer length between 0 and 10^6 (inclusive).
* Every edge is directed from the vertex with the smaller ID to the vertex with the larger ID. That is, 1,2,...,N is one possible topological order of the vertices.
* There are exactly L different paths from Vertex 1 to Vertex N. The lengths of these paths are all different, and they are integers between 0 and L-1.
Here, the length of a path is the sum of the lengths of the edges contained in that path, and two paths are considered different when the sets of the edges contained in those paths are different.
Constraints
* 2 \leq L \leq 10^6
* L is an integer.
Input
Input is given from Standard Input in the following format:
L
Output
In the first line, print N and M, the number of the vertices and edges in your graph. In the i-th of the following M lines, print three integers u_i,v_i and w_i, representing the starting vertex, the ending vertex and the length of the i-th edge. If there are multiple solutions, any of them will be accepted.
Examples
Input
4
Output
8 10
1 2 0
2 3 0
3 4 0
1 5 0
2 6 0
3 7 0
4 8 0
5 6 1
6 7 1
7 8 1
Input
5
Output
5 7
1 2 0
2 3 1
3 4 0
4 5 0
2 4 0
1 3 3
3 5 1
Submitted Solution:
```
k=int(input())-1
if k==0:
print(2,1)
print(1,2,0)
else:
def f(x,n):
c=[]
while x>0:
c.append(x%n)
x=x//n
return c
io=0
for i in range(2,40):
if io==1:
break
else:
c=f(k,i)
d=2
p=int(c[0])+1
for j in range(1,len(c)):
h=int(c[j])
d+=j*h
p+=i*j*h+h
else:
if d<=20 and p<=60:
print(d,p)
m=i
io=1
break
po=2
q=f(k,m)
for n in range(0,q[0]):
print(1,d,n)
print(1,2,q[0])
for s in range(1,len(q)):
for i in range(0,q[s]):
print(po,po+s,m**s)
po+=s
g=2
for s in range(1,len(q)):
for t in range(0,q[s]):
for o in range(0,s-1):
for l in range(0,m):
print(g,g+1,l*m**o)
else:
g+=1
else:
for e in range(0,m):
print(g,d,e*m**(s-1))
g+=1
``` | instruction | 0 | 25,413 | 13 | 50,826 |
No | output | 1 | 25,413 | 13 | 50,827 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer L. Construct a directed graph that satisfies the conditions below. The graph may contain multiple edges between the same pair of vertices. It can be proved that such a graph always exists.
* The number of vertices, N, is at most 20. The vertices are given ID numbers from 1 to N.
* The number of edges, M, is at most 60. Each edge has an integer length between 0 and 10^6 (inclusive).
* Every edge is directed from the vertex with the smaller ID to the vertex with the larger ID. That is, 1,2,...,N is one possible topological order of the vertices.
* There are exactly L different paths from Vertex 1 to Vertex N. The lengths of these paths are all different, and they are integers between 0 and L-1.
Here, the length of a path is the sum of the lengths of the edges contained in that path, and two paths are considered different when the sets of the edges contained in those paths are different.
Constraints
* 2 \leq L \leq 10^6
* L is an integer.
Input
Input is given from Standard Input in the following format:
L
Output
In the first line, print N and M, the number of the vertices and edges in your graph. In the i-th of the following M lines, print three integers u_i,v_i and w_i, representing the starting vertex, the ending vertex and the length of the i-th edge. If there are multiple solutions, any of them will be accepted.
Examples
Input
4
Output
8 10
1 2 0
2 3 0
3 4 0
1 5 0
2 6 0
3 7 0
4 8 0
5 6 1
6 7 1
7 8 1
Input
5
Output
5 7
1 2 0
2 3 1
3 4 0
4 5 0
2 4 0
1 3 3
3 5 1
Submitted Solution:
```
def main():
L = int(input())-1
b = bin(L+1)[2:]
bl = len(b)
r = []
for i in range(bl-1):
r.append((i+1, i+2, 0))
r.append((i+1, i+2, 2**i))
if L == 2**(bl-1) - 1:
pr(r)
return
else:
print('aaa')
return
end = bl
num = 2**(bl-1)
b = bin(L-num)[2:]
while num <= L:
if num == L:
r.append((1, end, num))
break
for i, v in enumerate(reversed(b)):
if v == '0':
r.append((i+2, end, num))
num = num + 2**(i+1)
b = bin(L - num)[2:]
break
else:
r.append((len(b)+1, end, num))
break
pr(r)
def pr(r):
m = 0
for i in r:
m = max(m, i[1])
print(m, len(r))
for i in r:
print(i[0], i[1], i[2])
main()
``` | instruction | 0 | 25,414 | 13 | 50,828 |
No | output | 1 | 25,414 | 13 | 50,829 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer L. Construct a directed graph that satisfies the conditions below. The graph may contain multiple edges between the same pair of vertices. It can be proved that such a graph always exists.
* The number of vertices, N, is at most 20. The vertices are given ID numbers from 1 to N.
* The number of edges, M, is at most 60. Each edge has an integer length between 0 and 10^6 (inclusive).
* Every edge is directed from the vertex with the smaller ID to the vertex with the larger ID. That is, 1,2,...,N is one possible topological order of the vertices.
* There are exactly L different paths from Vertex 1 to Vertex N. The lengths of these paths are all different, and they are integers between 0 and L-1.
Here, the length of a path is the sum of the lengths of the edges contained in that path, and two paths are considered different when the sets of the edges contained in those paths are different.
Constraints
* 2 \leq L \leq 10^6
* L is an integer.
Input
Input is given from Standard Input in the following format:
L
Output
In the first line, print N and M, the number of the vertices and edges in your graph. In the i-th of the following M lines, print three integers u_i,v_i and w_i, representing the starting vertex, the ending vertex and the length of the i-th edge. If there are multiple solutions, any of them will be accepted.
Examples
Input
4
Output
8 10
1 2 0
2 3 0
3 4 0
1 5 0
2 6 0
3 7 0
4 8 0
5 6 1
6 7 1
7 8 1
Input
5
Output
5 7
1 2 0
2 3 1
3 4 0
4 5 0
2 4 0
1 3 3
3 5 1
Submitted Solution:
```
l = int(input())
l -= 1
to = [[] for _ in range(14)]
for i in range(1, 13):
to[i].append((i + 1, 0 * 3 ** (12 - i)))
to[i].append((i + 1, 1 * 3 ** (12 - i)))
to[i].append((i + 1, 2 * 3 ** (12 - i)))
d = []
l_upto = []
t = l
s = 0
for i in range(12):
d.append(t % 3)
s *= 3
s += t % 3
l_upto.append(s)
t //= 3
for i, t in enumerate(d):
for s in range(t + (i == 0)):
to[0].append((13 - i, l - l_upto[i] + 3 ** i * s))
print(14, sum(map(len, to)))
for i in range(len(to)):
for j, cost in to[i]:
print(i, j, cost)
``` | instruction | 0 | 25,415 | 13 | 50,830 |
No | output | 1 | 25,415 | 13 | 50,831 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer L. Construct a directed graph that satisfies the conditions below. The graph may contain multiple edges between the same pair of vertices. It can be proved that such a graph always exists.
* The number of vertices, N, is at most 20. The vertices are given ID numbers from 1 to N.
* The number of edges, M, is at most 60. Each edge has an integer length between 0 and 10^6 (inclusive).
* Every edge is directed from the vertex with the smaller ID to the vertex with the larger ID. That is, 1,2,...,N is one possible topological order of the vertices.
* There are exactly L different paths from Vertex 1 to Vertex N. The lengths of these paths are all different, and they are integers between 0 and L-1.
Here, the length of a path is the sum of the lengths of the edges contained in that path, and two paths are considered different when the sets of the edges contained in those paths are different.
Constraints
* 2 \leq L \leq 10^6
* L is an integer.
Input
Input is given from Standard Input in the following format:
L
Output
In the first line, print N and M, the number of the vertices and edges in your graph. In the i-th of the following M lines, print three integers u_i,v_i and w_i, representing the starting vertex, the ending vertex and the length of the i-th edge. If there are multiple solutions, any of them will be accepted.
Examples
Input
4
Output
8 10
1 2 0
2 3 0
3 4 0
1 5 0
2 6 0
3 7 0
4 8 0
5 6 1
6 7 1
7 8 1
Input
5
Output
5 7
1 2 0
2 3 1
3 4 0
4 5 0
2 4 0
1 3 3
3 5 1
Submitted Solution:
```
l = int(input())
bl = l.bit_length()
n = bl + 1
m = bl * 2
print(n, m)
for i in range(bl):
print(i+1, i+2, 0)
print(i+1, i+2, 2**i)
``` | instruction | 0 | 25,416 | 13 | 50,832 |
No | output | 1 | 25,416 | 13 | 50,833 |
Provide a correct Python 3 solution for this coding contest problem.
Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | instruction | 0 | 25,567 | 13 | 51,134 |
"Correct Solution:
```
import os
import sys
from collections import defaultdict
import heapq
if os.getenv("LOCAL"):
sys.stdin = open("_in.txt", "r")
sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
"""
最小費用流
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_6_B&lang=jp
"""
class MinCostFlow:
"""
最小費用流 ダイクストラ版
Primal Dual
"""
def __init__(self, graph=None, residual=None):
"""
:param list of (list of (int, int, int)) graph: (to, cap, cost) の隣接リスト
:param list of (list of (list of (int|list))) residual: (to, cap, cost, rev) の残余グラフ
"""
assert (graph and not residual) or (not graph and residual)
if graph:
self.graph = self.residual_graph(graph)
else:
self.graph = residual
@staticmethod
def residual_graph(graph):
"""
残余グラフ構築
:param list of (list of (int, int, int)) graph: (to, cap, cost) の隣接リスト
:rtype: list of (list of (list of (int|list)))
:return: (to, cap, cost, rev) の残余グラフ
"""
ret = [[] for _ in range(len(graph))]
for v in range(len(graph)):
for u, cap, cost in graph[v]:
rev = [v, 0, -cost]
edge = [u, cap, cost, rev]
rev.append(edge)
ret[v].append(edge)
ret[u].append(rev)
return ret
def solve(self, from_v, to_v, flow):
"""
:param int from_v:
:param int to_v:
:param int flow:
:rtype: int
"""
res = 0
h = [0] * len(self.graph)
prevv = [-1] * len(self.graph)
preve = [-1] * len(self.graph)
remains = flow
while remains > 0:
dist = [float('inf')] * len(self.graph)
dist[from_v] = 0
heap = [(0, from_v)]
# Dijkstra
while heap:
d, v = heapq.heappop(heap)
if d > dist[v]:
continue
for edge in self.graph[v]:
u, cap, cost, rev = edge
if cap > 0 and dist[v] + cost + h[v] - h[u] < dist[u]:
dist[u] = dist[v] + cost + h[v] - h[u]
prevv[u] = v
preve[u] = edge
heapq.heappush(heap, (dist[u], u))
if dist[to_v] == float('inf'):
# これ以上流せない
return -1
for i, d in enumerate(dist):
h[i] += d
# 最短路に流せる量
flow = remains
v = to_v
while v != from_v:
cap = preve[v][1]
flow = min(cap, flow)
v = prevv[v]
# 最短路に flow だけ流す
v = to_v
while v != from_v:
preve[v][1] -= flow
preve[v][3][1] += flow
v = prevv[v]
remains -= flow
res += flow * h[to_v]
return res
V, E, F = list(map(int, sys.stdin.readline().split()))
UVCD = [list(map(int, sys.stdin.readline().split())) for _ in range(E)]
graph = [[] for _ in range(V)]
for u, v, c, d in UVCD:
graph[u].append((v, c, d))
ans = MinCostFlow(graph=graph).solve(from_v=0, to_v=V - 1, flow=F)
print(ans)
``` | output | 1 | 25,567 | 13 | 51,135 |
Provide a correct Python 3 solution for this coding contest problem.
Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | instruction | 0 | 25,568 | 13 | 51,136 |
"Correct Solution:
```
import heapq
class MinCostFlow:
class Edge:
def __init__(self,to,cap,rev,cost):
self.to = to
self.cap = cap
self.rev = rev
self.cost = cost
def __init__(self,n,inf=1000000007):
self.n = n
self.inf = inf
self.e = [[] for _ in range(n)]
def add_edge(self, fr, to, cap, cost):
self.e[fr].append(self.Edge(to,cap,len(self.e[to]),cost))
self.e[to].append(self.Edge(fr,0,len(self.e[fr])-1,-cost))
def compute(self,source,sink,f):
res = 0
h = [0]*self.n
prevv = [0]*self.n
preve = [0]*self.n
while (f > 0):
pq = []
dist = [self.inf]*self.n
dist[source] = 0
heapq.heappush(pq,(0,source))
while pq:
cost, v = heapq.heappop(pq)
cost = -cost
if dist[v] < cost:continue
for i, edge in enumerate(self.e[v]):
if edge.cap > 0 and dist[v] - h[edge.to] < dist[edge.to] - edge.cost - h[v]:
dist[edge.to] = dist[v] + edge.cost + h[v] - h[edge.to]
prevv[edge.to] = v
preve[edge.to] = i
heapq.heappush(pq,(-dist[edge.to],edge.to))
if dist[sink] == self.inf:return -1
for v in range(self.n):
h[v] += dist[v]
d, v = f, sink
while v != source:
d = min(d,self.e[prevv[v]][preve[v]].cap)
v = prevv[v]
f -= d
res += d*h[sink]
v = sink
while v != source:
self.e[prevv[v]][preve[v]].cap -= d
self.e[v][self.e[prevv[v]][preve[v]].rev].cap += d
v = prevv[v]
return res
def main():
v,e,f = map(int,input().split())
MCF = MinCostFlow(v)
for _ in range(e):
a,b,c,d = map(int,input().split())
MCF.add_edge(a,b,c,d)
print(MCF.compute(0,v-1,f))
if __name__ == '__main__':
main()
``` | output | 1 | 25,568 | 13 | 51,137 |
Provide a correct Python 3 solution for this coding contest problem.
Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output | instruction | 0 | 25,570 | 13 | 51,140 |
"Correct Solution:
```
#!/usr/bin/env python3
# GRL_6_B: Minimum Cost Flow
WEIGHT_MAX = 10 ** 10
class Edge:
__slots__ = ('src', 'dest', 'capacity', 'flow', 'cost')
def __init__(self, v, w, capacity, cost=0):
self.src = v
self.dest = w
self.capacity = capacity
self.cost = cost
self.flow = 0
def other(self, v):
if v == self.src:
return self.dest
else:
return self.src
def residual_capacity(self, v):
if v == self.src:
return self.capacity - self.flow
else:
return self.flow
def cost_from(self, v):
if v == self.src:
return self.cost
else:
return -self.cost
def add_flow(self, v, f):
if v == self.src:
self.flow += f
else:
self.flow -= f
def __str__(self):
return "{} {} {} {} {}".format(self.src, self.dest, self.capacity,
self.cost, self.flow)
class Network:
def __init__(self, v):
self.v = v
self._edges = [[] for _ in range(v)]
def add(self, edge):
self._edges[edge.src].append(edge)
self._edges[edge.dest].append(edge)
def adj(self, v):
return self._edges[v]
def flow(self, v):
return sum(e.flow for e in self.adj(v) if e.src == v)
def cost(self):
cost = 0
for v in range(self.v):
for e in self.adj(v):
if e.src == v:
cost += e.flow * e.cost
return cost
def __str__(self):
s = ''
for v in range(self.v):
for e in self.adj(v):
s += "{} {}\n".format(v, e)
return s
def min_cost(network, s, t, f):
def augment_path():
def relax(edge, v):
w = edge.other(v)
c = edge.cost_from(v)
if e.residual_capacity(v) > 0 and dists[w] > dists[v] + c:
dists[w] = dists[v] + c
edge_to[w] = e
_nodes.append(w)
dists = [WEIGHT_MAX] * network.v
dists[s] = 0
edge_to = [None] * network.v
nodes = []
nodes.append(s)
for _ in range(network.v):
_nodes = []
for v in nodes:
for e in network.adj(v):
relax(e, v)
nodes = _nodes
if edge_to[t] is None:
return (0, [])
else:
v = t
e = edge_to[v]
cap = f
while e is not None:
v = e.other(v)
_cap = e.residual_capacity(v)
if cap > _cap:
cap = _cap
e = edge_to[v]
return (cap, edge_to)
while f > 0:
cap, path = augment_path()
if cap == 0:
break
f -= cap
v = t
e = path[t]
while e is not None:
v = e.other(v)
e.add_flow(v, cap)
e = path[v]
if f > 0:
return -1
else:
return network.cost()
def run():
v, e, f = [int(i) for i in input().split()]
net = Network(v)
s, t = 0, v-1
for _ in range(e):
v, w, c, d = [int(i) for i in input().split()]
net.add(Edge(v, w, c, d))
print(min_cost(net, s, t, f))
if __name__ == '__main__':
run()
``` | output | 1 | 25,570 | 13 | 51,141 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Examples
Input
4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1
Output
6
Input
Output
Submitted Solution:
```
import heapq as hp
class MinimumCostFlow():
def __init__(self, N, INF=10**18):
self.graph = [{} for _ in range(N)]
self.N = N
self.INF = INF
def add_edge(self, u, v, cap, cost, undirected=False):
# u -> v (maxflow, cost)
if cap == 0: return
if undirected:
self.graph[u][v] = [cap, cost]
self.graph[v][u] = [cap, -cost]
elif v in self.graph[u]:
self.graph[u][v] = [cap, cost]
else:
self.graph[u][v] = [cap, cost]
self.graph[v][u] = [0, -cost]
def dijkstra(self, start):
self.dist = [self.INF]*self.N # nearest distance
self.dist[start] = 0
self.que = [(0, start)]
while self.que:
d, v = hp.heappop(self.que)
if self.dist[v] < d: continue
for nv, (ncap, ncost) in self.graph[v].items():
if ncap > 0 and self.dist[nv] > self.dist[v] + ncost + self.H[v] - self.H[nv]:
self.dist[nv] = self.dist[v] + ncost + self.H[v] - self.H[nv]
self.prevv[nv] = v
hp.heappush(self.que, (self.dist[nv], nv))
def min_cost_flow(self, start, finish, flow):
self.res = 0
self.prevv = [-1]*self.N
self.H = [0]*self.N # potential
while flow > 0:
self.dijkstra(start)
if self.dist[finish] == self.INF: return -1 # cant run flow anymore
for i in range(self.N):
self.H[i] += self.dist[i]
d = flow
v = finish
while v != start:
d = min(d, self.graph[self.prevv[v]][v][0])
v = self.prevv[v]
flow -= d
self.res += d*self.H[finish]
v = finish
while v != start:
self.graph[self.prevv[v]][v][0] -= d
self.graph[v][self.prevv[v]][0] += d
v = self.prevv[v]
return self.res
if __name__ == "__main__":
import sys
input = sys.stdin.readline
V, E, F = map(int, input().split())
fl = MinimumCostFlow(V)
for _ in range(E):
u, v, c, d = map(int, input().split())
fl.add_edge(u, v, c, d)
print(fl.min_cost_flow(0, V-1, F))
``` | instruction | 0 | 25,573 | 13 | 51,146 |
Yes | output | 1 | 25,573 | 13 | 51,147 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one.
Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree.
After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node.
It can be shown that the process marks all nodes in the tree.
The final array a is the list of the nodes' labels in order of the time each node was marked.
Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.
The number of inversions in an array a is the number of pairs of indices (i, j) such that i < j and a_i > a_j. For example, the array [4, 1, 3, 2] contains 4 inversions: (1, 2), (1, 3), (1, 4), (3, 4).
Input
The first line contains a single integer n (2 ≤ n ≤ 200) — the number of nodes in the tree.
The next n - 1 lines each contains two integers x and y (1 ≤ x, y ≤ n; x ≠ y), denoting an edge between node x and y.
It's guaranteed that the given edges form a tree.
Output
Output the expected number of inversions in the generated array modulo 10^9+7.
Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not ≡ 0 \pmod{M}. Output the integer equal to p ⋅ q^{-1} mod M. In other words, output such an integer x that 0 ≤ x < M and x ⋅ q ≡ p \pmod{M}.
Examples
Input
3
1 2
1 3
Output
166666669
Input
6
2 1
2 3
6 1
1 4
2 5
Output
500000009
Input
5
1 2
1 3
1 4
2 5
Output
500000007
Note
This is the tree from the first sample:
<image>
For the first sample, the arrays are almost fixed. If node 2 is chosen initially, then the only possible array is [2, 1, 3] (1 inversion). If node 3 is chosen initially, then the only possible array is [3, 1, 2] (2 inversions). If node 1 is chosen initially, the arrays [1, 2, 3] (0 inversions) and [1, 3, 2] (1 inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is 1/3⋅ 1 + 1/3 ⋅ 2 + 1/3 ⋅ (1/2 ⋅ 0 + 1/2 ⋅ 1) = 7/6.
166666669 ⋅ 6 = 7 \pmod {10^9 + 7}, so the answer is 166666669.
This is the tree from the second sample:
<image>
This is the tree from the third sample:
<image> | instruction | 0 | 25,858 | 13 | 51,716 |
Tags: brute force, combinatorics, dp, graphs, math, probabilities, trees
Correct Solution:
```
def naiveSolve():
return
def floyd_warshall(n, edges):
dist = [[0 if i == j else float("inf") for i in range(n)] for j in range(n)]
for u, v, d in edges:
dist[u][v] = d
for k in range(n):
for i in range(n):
for j in range(n):
if dist[i][k] + dist[k][j] < dist[i][j]:
dist[i][j] = dist[i][k] + dist[k][j]
return dist
#(a/b)%MOD=((a%MOD)*pow(b,MOD-2,MOD))%MOD if MOD is prime, and a%b!=0
MOD=int(1e9+7)
def getNumDivDenMOD(num,den):
a,b=num,den
return ((a%MOD)*pow(b,MOD-2,MOD))%MOD
dp=[[0 for _ in range(201)] for __ in range(201)]
# dp[aCnts][bCnts]=number of ways
dp[0][0]+=1
for i in range(201):
for j in range(201):
if i-1>=0:
dp[i][j]+=dp[i-1][j]
dp[i][j]%=MOD
if j-1>=0:
dp[i][j]+=dp[i][j-1]
dp[i][j]%=MOD
dp2=[[0 for _ in range(201)] for __ in range(201)] # divide by pow(2,pathlen) to get actual probability
# dp2[aCnts][bCnts]=number of ways for a to reach first, replacing getProbabilityAFirst
for aCnts in range(201-1,-1,-1):
for bCnts in range(201):
if aCnts+1<201 and bCnts-1>=0:
toAdd=getNumDivDenMOD(dp[aCnts][bCnts-1],pow(2,aCnts+bCnts-1,MOD))
dp2[aCnts][bCnts]=dp2[aCnts+1][bCnts-1]+toAdd
dp2[aCnts][bCnts]%=MOD
def main():
n=int(input())
adj=[[] for _ in range(n+1)]
for _ in range(n-1):
u,v=readIntArr()
adj[u].append(v)
adj[v].append(u)
edges=[]
for u in range(1,n+1):
for v in adj[u]:
edges.append((u,v,1))
dist=floyd_warshall(n+1,edges)
ans=0
for root in range(1,n+1):
for b in range(1,n+1):
for a in range(b+1,n+1):
# find p(a first)
# aDepth is dist from a to lca
# bDepth is dist from b to lca
ab=dist[a][b]; A=dist[a][root]; B=dist[b][root]
aDepth=(ab+A-B)//2; bDepth=ab-aDepth
# total=aDepth+bDepth-1
# denominator=pow(2,total,MOD)
# p=getNumDivDenMOD(dp2[aDepth][bDepth],denominator)
p=dp2[aDepth][bDepth]
ans+=p
ans%=MOD
ans2=getNumDivDenMOD(ans,n)
print(ans2)
return
import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
# input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
# def readFloatArr():
# return [float(x) for x in input().split()]
def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m])
dv=defaultValFactory;da=dimensionArr
if len(da)==1:return [dv() for _ in range(da[0])]
else:return [makeArr(dv,da[1:]) for _ in range(da[0])]
def queryInteractive(a,b):
print('? {} {}'.format(a,b))
sys.stdout.flush()
return True if input()=='SI' else False
def answerInteractive(ans):
print('! {}'.format(ans))
sys.stdout.flush()
inf=float('inf')
MOD=10**9+7
# MOD=998244353
from math import gcd,floor,ceil
# from math import floor,ceil # for Python2
for _abc in range(1):
main()
``` | output | 1 | 25,858 | 13 | 51,717 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one.
Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree.
After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node.
It can be shown that the process marks all nodes in the tree.
The final array a is the list of the nodes' labels in order of the time each node was marked.
Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.
The number of inversions in an array a is the number of pairs of indices (i, j) such that i < j and a_i > a_j. For example, the array [4, 1, 3, 2] contains 4 inversions: (1, 2), (1, 3), (1, 4), (3, 4).
Input
The first line contains a single integer n (2 ≤ n ≤ 200) — the number of nodes in the tree.
The next n - 1 lines each contains two integers x and y (1 ≤ x, y ≤ n; x ≠ y), denoting an edge between node x and y.
It's guaranteed that the given edges form a tree.
Output
Output the expected number of inversions in the generated array modulo 10^9+7.
Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not ≡ 0 \pmod{M}. Output the integer equal to p ⋅ q^{-1} mod M. In other words, output such an integer x that 0 ≤ x < M and x ⋅ q ≡ p \pmod{M}.
Examples
Input
3
1 2
1 3
Output
166666669
Input
6
2 1
2 3
6 1
1 4
2 5
Output
500000009
Input
5
1 2
1 3
1 4
2 5
Output
500000007
Note
This is the tree from the first sample:
<image>
For the first sample, the arrays are almost fixed. If node 2 is chosen initially, then the only possible array is [2, 1, 3] (1 inversion). If node 3 is chosen initially, then the only possible array is [3, 1, 2] (2 inversions). If node 1 is chosen initially, the arrays [1, 2, 3] (0 inversions) and [1, 3, 2] (1 inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is 1/3⋅ 1 + 1/3 ⋅ 2 + 1/3 ⋅ (1/2 ⋅ 0 + 1/2 ⋅ 1) = 7/6.
166666669 ⋅ 6 = 7 \pmod {10^9 + 7}, so the answer is 166666669.
This is the tree from the second sample:
<image>
This is the tree from the third sample:
<image> | instruction | 0 | 25,859 | 13 | 51,718 |
Tags: brute force, combinatorics, dp, graphs, math, probabilities, trees
Correct Solution:
```
from collections import deque
MOD = 10 ** 9 + 7;N = 1000;fact = [0 for _ in range(N)];invfact = [0 for _ in range(N)];fact[0] = 1
for i in range(1, N):fact[i] = fact[i - 1] * i % MOD
invfact[N - 1] = pow(fact[N - 1], MOD - 2, MOD)
for i in range(N - 2, -1, -1):invfact[i] = invfact[i + 1] * (i + 1) % MOD
def nCk(n, k):return 0 if k < 0 or n < k else (fact[n] * invfact[k] % MOD) * invfact[n - k] % MOD
def nHk(n, k):return nCk(n + k - 1, k)
def main():
n = int(input())
edges = [[] for _ in range(n)]
for _ in range(n - 1):
x, y = map(int, input().split())
x -= 1
y -= 1
edges[x].append(y)
edges[y].append(x)
def cnt(i, j):
bef = [-1] * n
used = [False] * n
stack = [i]
while stack:
pos = stack.pop()
if pos == j:
break
for npos in edges[pos]:
if used[npos]:
continue
used[npos] = True
bef[npos] = pos
stack.append(npos)
c = 0
queue = deque()
queue.append((j, 0))
pos = j
used = [False] * n
used[pos] = True
while pos != i:
pos = bef[pos]
c += 1
queue.append((pos, c))
used[pos] = True
cnts = [1] * (c + 1)
C = c
while queue:
pos, c = queue.popleft()
for npos in edges[pos]:
if used[npos]: continue
used[npos] = True
cnts[c] += 1
queue.append((npos, c))
ret = 0
tot = 0
times = 1
inv = pow(pow(2, C - 1, MOD), MOD - 2, MOD)
for i, c in enumerate(cnts[:-1]):
ret += c * times
ret %= MOD
times -= nCk(C - 1, i) * inv
times %= MOD
return ret
ans = 0
for i in range(n):
for j in range(i + 1, n):
ans += cnt(i, j)
ans %= MOD
ans *= pow(n, MOD - 2, MOD)
print(ans % MOD)
for _ in range(1):
main()
``` | output | 1 | 25,859 | 13 | 51,719 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one.
Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree.
After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node.
It can be shown that the process marks all nodes in the tree.
The final array a is the list of the nodes' labels in order of the time each node was marked.
Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.
The number of inversions in an array a is the number of pairs of indices (i, j) such that i < j and a_i > a_j. For example, the array [4, 1, 3, 2] contains 4 inversions: (1, 2), (1, 3), (1, 4), (3, 4).
Input
The first line contains a single integer n (2 ≤ n ≤ 200) — the number of nodes in the tree.
The next n - 1 lines each contains two integers x and y (1 ≤ x, y ≤ n; x ≠ y), denoting an edge between node x and y.
It's guaranteed that the given edges form a tree.
Output
Output the expected number of inversions in the generated array modulo 10^9+7.
Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not ≡ 0 \pmod{M}. Output the integer equal to p ⋅ q^{-1} mod M. In other words, output such an integer x that 0 ≤ x < M and x ⋅ q ≡ p \pmod{M}.
Examples
Input
3
1 2
1 3
Output
166666669
Input
6
2 1
2 3
6 1
1 4
2 5
Output
500000009
Input
5
1 2
1 3
1 4
2 5
Output
500000007
Note
This is the tree from the first sample:
<image>
For the first sample, the arrays are almost fixed. If node 2 is chosen initially, then the only possible array is [2, 1, 3] (1 inversion). If node 3 is chosen initially, then the only possible array is [3, 1, 2] (2 inversions). If node 1 is chosen initially, the arrays [1, 2, 3] (0 inversions) and [1, 3, 2] (1 inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is 1/3⋅ 1 + 1/3 ⋅ 2 + 1/3 ⋅ (1/2 ⋅ 0 + 1/2 ⋅ 1) = 7/6.
166666669 ⋅ 6 = 7 \pmod {10^9 + 7}, so the answer is 166666669.
This is the tree from the second sample:
<image>
This is the tree from the third sample:
<image> | instruction | 0 | 25,860 | 13 | 51,720 |
Tags: brute force, combinatorics, dp, graphs, math, probabilities, trees
Correct Solution:
```
import bisect
import copy
import decimal
import fractions
import heapq
import itertools
import math
import random
import sys
from collections import Counter, deque,defaultdict
from functools import lru_cache,reduce
from heapq import heappush,heappop,heapify,heappushpop,_heappop_max,_heapify_max
def _heappush_max(heap,item):
heap.append(item)
heapq._siftdown_max(heap, 0, len(heap)-1)
def _heappushpop_max(heap, item):
if heap and item < heap[0]:
item, heap[0] = heap[0], item
heapq._siftup_max(heap, 0)
return item
from math import gcd as GCD
read=sys.stdin.read
readline=sys.stdin.readline
readlines=sys.stdin.readlines
def Extended_Euclid(n,m):
stack=[]
while m:
stack.append((n,m))
n,m=m,n%m
if n>=0:
x,y=1,0
else:
x,y=-1,0
for i in range(len(stack)-1,-1,-1):
n,m=stack[i]
x,y=y,x-(n//m)*y
return x,y
class MOD:
def __init__(self,mod):
self.mod=mod
def Pow(self,a,n):
a%=self.mod
if n>=0:
return pow(a,n,self.mod)
else:
assert math.gcd(a,self.mod)==1
x=Extended_Euclid(a,self.mod)[0]
return pow(x,-n,self.mod)
def Build_Fact(self,N):
assert N>=0
self.factorial=[1]
for i in range(1,N+1):
self.factorial.append((self.factorial[-1]*i)%self.mod)
self.factorial_inv=[None]*(N+1)
self.factorial_inv[-1]=self.Pow(self.factorial[-1],-1)
for i in range(N-1,-1,-1):
self.factorial_inv[i]=(self.factorial_inv[i+1]*(i+1))%self.mod
return self.factorial_inv
def Fact(self,N):
return self.factorial[N]
def Fact_Inv(self,N):
return self.factorial_inv[N]
def Comb(self,N,K):
if K<0 or K>N:
return 0
s=self.factorial[N]
s=(s*self.factorial_inv[K])%self.mod
s=(s*self.factorial_inv[N-K])%self.mod
return s
class Graph:
def __init__(self,V,edges=False,graph=False,directed=False,weighted=False):
self.V=V
self.directed=directed
self.weighted=weighted
if not graph:
self.edges=edges
self.graph=[[] for i in range(self.V)]
if weighted:
for i,j,d in self.edges:
self.graph[i].append((j,d))
if not self.directed:
self.graph[j].append((i,d))
else:
for i,j in self.edges:
self.graph[i].append(j)
if not self.directed:
self.graph[j].append(i)
else:
self.graph=graph
self.edges=[]
for i in range(self.V):
if self.weighted:
for j,d in self.graph[i]:
if self.directed or not self.directed and i<=j:
self.edges.append((i,j,d))
else:
for j in self.graph[i]:
if self.directed or not self.directed and i<=j:
self.edges.append((i,j))
def SS_BFS(self,s,bipartite_graph=False,linked_components=False,parents=False,unweighted_dist=False,weighted_dist=False):
seen=[False]*self.V
seen[s]=True
if linked_components:
lc=[s]
if parents:
ps=[None]*self.V
ps[s]=s
if unweighted_dist or bipartite_graph:
uwd=[float('inf')]*self.V
uwd[s]=0
if weighted_dist:
wd=[float('inf')]*self.V
wd[s]=0
queue=deque([s])
while queue:
x=queue.popleft()
for y in self.graph[x]:
if self.weighted:
y,d=y
if not seen[y]:
seen[y]=True
queue.append(y)
if linked_components:
lc.append(y)
if parents:
ps[y]=x
if unweighted_dist or bipartite_graph:
uwd[y]=uwd[x]+1
if weighted_dist:
wd[y]=wd[x]+d
if bipartite_graph:
bg=[[],[]]
for tpl in self.edges:
i,j=tpl[:2] if self.weighted else tpl
if type(uwd[i])==float or type(uwd[j])==float:
continue
if not uwd[i]%2^uwd[j]%2:
bg=False
break
else:
for x in range(self.V):
if type(uwd[x])==float:
continue
bg[uwd[x]%2].append(x)
tpl=()
if bipartite_graph:
tpl+=(bg,)
if linked_components:
tpl+=(lc,)
if parents:
tpl+=(ps,)
if unweighted_dist:
tpl+=(uwd,)
if weighted_dist:
tpl+=(wd,)
if len(tpl)==1:
tpl=tpl[0]
return tpl
def AP_BFS(self,bipartite_graph=False,linked_components=False,parents=False):
seen=[False]*self.V
if bipartite_graph:
bg=[None]*self.V
cnt=-1
if linked_components:
lc=[]
if parents:
ps=[None]*self.V
for s in range(self.V):
if seen[s]:
continue
seen[s]=True
if bipartite_graph:
cnt+=1
bg[s]=(cnt,s&2)
if linked_components:
lc.append([s])
if parents:
ps[s]=s
queue=deque([s])
while queue:
x=queue.popleft()
for y in self.graph[x]:
if self.weighted:
y,d=y
if not seen[y]:
seen[y]=True
queue.append(y)
if bipartite_graph:
bg[y]=(cnt,bg[x][1]^1)
if linked_components:
lc[-1].append(y)
if parents:
ps[y]=x
if bipartite_graph:
bg_=bg
bg=[[[],[]] for i in range(cnt+1)]
for tpl in self.edges:
i,j=tpl[:2] if self.weighted else tpl
if not bg_[i][1]^bg_[j][1]:
bg[bg_[i][0]]=False
for x in range(self.V):
if bg[bg_[x][0]]:
bg[bg_[x][0]][bg_[x][1]].append(x)
tpl=()
if bipartite_graph:
tpl+=(bg,)
if linked_components:
tpl+=(lc,)
if parents:
tpl+=(ps,)
if len(tpl)==1:
tpl=tpl[0]
return tpl
def SS_DFS(self,s,bipartite_graph=False,cycle_detection=False,directed_acyclic=False,euler_tour=False,linked_components=False,parents=False,postorder=False,preorder=False,topological_sort=False,unweighted_dist=False,weighted_dist=False):
seen=[False]*self.V
finished=[False]*self.V
if directed_acyclic or cycle_detection or topological_sort:
dag=True
if euler_tour:
et=[]
if linked_components:
lc=[]
if parents or cycle_detection:
ps=[None]*self.V
ps[s]=s
if postorder or topological_sort:
post=[]
if preorder:
pre=[]
if unweighted_dist or bipartite_graph:
uwd=[float('inf')]*self.V
uwd[s]=0
if weighted_dist:
wd=[float('inf')]*self.V
wd[s]=0
stack=[(s,0)] if self.weighted else [s]
while stack:
if self.weighted:
x,d=stack.pop()
else:
x=stack.pop()
if not seen[x]:
seen[x]=True
stack.append((x,d) if self.weighted else x)
if euler_tour:
et.append(x)
if linked_components:
lc.append(x)
if preorder:
pre.append(x)
for y in self.graph[x]:
if self.weighted:
y,d=y
if not seen[y]:
stack.append((y,d) if self.weighted else y)
if parents or cycle_detection:
ps[y]=x
if unweighted_dist or bipartite_graph:
uwd[y]=uwd[x]+1
if weighted_dist:
wd[y]=wd[x]+d
elif not finished[y]:
if (directed_acyclic or cycle_detection or topological_sort) and dag:
dag=False
if cycle_detection:
cd=(y,x)
elif not finished[x]:
finished[x]=True
if euler_tour:
et.append(~x)
if postorder or topological_sort:
post.append(x)
if bipartite_graph:
bg=[[],[]]
for tpl in self.edges:
i,j=tpl[:2] if self.weighted else tpl
if type(uwd[i])==float or type(uwd[j])==float:
continue
if not uwd[i]%2^uwd[j]%2:
bg=False
break
else:
for x in range(self.V):
if type(uwd[x])==float:
continue
bg[uwd[x]%2].append(x)
tpl=()
if bipartite_graph:
tpl+=(bg,)
if cycle_detection:
if dag:
cd=[]
else:
y,x=cd
cd=self.Route_Restoration(y,x,ps)
tpl+=(cd,)
if directed_acyclic:
tpl+=(dag,)
if euler_tour:
tpl+=(et,)
if linked_components:
tpl+=(lc,)
if parents:
tpl+=(ps,)
if postorder:
tpl+=(post,)
if preorder:
tpl+=(pre,)
if topological_sort:
if dag:
tp_sort=post[::-1]
else:
tp_sort=[]
tpl+=(tp_sort,)
if unweighted_dist:
tpl+=(uwd,)
if weighted_dist:
tpl+=(wd,)
if len(tpl)==1:
tpl=tpl[0]
return tpl
def AP_DFS(self,bipartite_graph=False,cycle_detection=False,directed_acyclic=False,euler_tour=False,linked_components=False,parents=False,postorder=False,preorder=False,topological_sort=False):
seen=[False]*self.V
finished=[False]*self.V
if bipartite_graph:
bg=[None]*self.V
cnt=-1
if directed_acyclic or cycle_detection or topological_sort:
dag=True
if euler_tour:
et=[]
if linked_components:
lc=[]
if parents or cycle_detection:
ps=[None]*self.V
if postorder or topological_sort:
post=[]
if preorder:
pre=[]
for s in range(self.V):
if seen[s]:
continue
if bipartite_graph:
cnt+=1
bg[s]=(cnt,s&2)
if linked_components:
lc.append([])
if parents:
ps[s]=s
stack=[(s,0)] if self.weighted else [s]
while stack:
if self.weighted:
x,d=stack.pop()
else:
x=stack.pop()
if not seen[x]:
seen[x]=True
stack.append((x,d) if self.weighted else x)
if euler_tour:
et.append(x)
if linked_components:
lc[-1].append(x)
if preorder:
pre.append(x)
for y in self.graph[x]:
if self.weighted:
y,d=y
if not seen[y]:
stack.append((y,d) if self.weighted else y)
if bipartite_graph:
bg[y]=(cnt,bg[x][1]^1)
if parents or cycle_detection:
ps[y]=x
elif not finished[y]:
if directed_acyclic and dag:
dag=False
if cycle_detection:
cd=(y,x)
elif not finished[x]:
finished[x]=True
if euler_tour:
et.append(~x)
if postorder or topological_sort:
post.append(x)
if bipartite_graph:
bg_=bg
bg=[[[],[]] for i in range(cnt+1)]
for tpl in self.edges:
i,j=tpl[:2] if self.weighted else tpl
if not bg_[i][1]^bg_[j][1]:
bg[bg_[i][0]]=False
for x in range(self.V):
if bg[bg_[x][0]]:
bg[bg_[x][0]][bg_[x][1]].append(x)
tpl=()
if bipartite_graph:
tpl+=(bg,)
if cycle_detection:
if dag:
cd=[]
else:
y,x=cd
cd=self.Route_Restoration(y,x,ps)
tpl+=(cd,)
if directed_acyclic:
tpl+=(dag,)
if euler_tour:
tpl+=(et,)
if linked_components:
tpl+=(lc,)
if parents:
tpl+=(ps,)
if postorder:
tpl+=(post,)
if preorder:
tpl+=(pre,)
if topological_sort:
if dag:
tp_sort=post[::-1]
else:
tp_sort=[]
tpl+=(tp_sort,)
if len(tpl)==1:
tpl=tpl[0]
return tpl
def Tree_Diameter(self,weighted=False):
def Farthest_Point(u):
dist=self.SS_BFS(u,weighted_dist=True) if self.weighted else self.SS_BFS(u,unweighted_dist=True)
fp=0
for i in range(self.V):
if dist[fp]<dist[i]:
fp=i
return fp,dist[fp]
u,d=Farthest_Point(0)
v,d=Farthest_Point(u)
return u,v,d
def SCC(self):
reverse_graph=[[] for i in range(self.V)]
for tpl in self.edges:
i,j=tpl[:2] if self.weighted else tpl
reverse_graph[j].append(i)
postorder=self.AP_DFS(postorder=True)
scc=[]
seen=[False]*self.V
for s in postorder[::-1]:
if seen[s]:
continue
queue=deque([s])
seen[s]=True
lst=[]
while queue:
x=queue.popleft()
lst.append(x)
for y in reverse_graph[x]:
if self.weighted:
y=y[0]
if not seen[y]:
seen[y]=True
queue.append(y)
scc.append(lst)
return scc
def Build_LCA(self,s):
self.euler_tour,self.parents,depth=self.SS_DFS(s,euler_tour=True,parents=True,unweighted_dist=True)
self.dfs_in_index=[None]*self.V
self.dfs_out_index=[None]*self.V
for i,x in enumerate(self.euler_tour):
if x>=0:
self.dfs_in_index[x]=i
else:
self.dfs_out_index[~x]=i
self.ST=Segment_Tree(2*self.V,lambda x,y:min(x,y),float('inf'))
lst=[None]*2*self.V
for i in range(2*self.V):
if self.euler_tour[i]>=0:
lst[i]=depth[self.euler_tour[i]]
else:
lst[i]=depth[self.parents[~self.euler_tour[i]]]
self.ST.Build(lst)
def LCA(self,a,b):
m=min(self.dfs_in_index[a],self.dfs_in_index[b])
M=max(self.dfs_in_index[a],self.dfs_in_index[b])
x=self.euler_tour[self.ST.Fold_Index(m,M+1)]
if x>=0:
return x
else:
return self.parents[~x]
def Dijkstra(self,s,route_restoration=False):
dist=[float('inf')]*self.V
dist[s]=0
hq=[(0,s)]
if route_restoration:
parents=[None]*self.V
parents[s]=s
while hq:
dx,x=heapq.heappop(hq)
if dist[x]<dx:
continue
for y,dy in self.graph[x]:
if dist[y]>dx+dy:
dist[y]=dx+dy
if route_restoration:
parents[y]=x
heapq.heappush(hq,(dist[y],y))
if route_restoration:
return dist,parents
else:
return dist
def Bellman_Ford(self,s,route_restoration=False):
dist=[float('inf')]*self.V
dist[s]=0
if route_restoration:
parents=[s]*self.V
for _ in range(self.V-1):
for i,j,d in self.edges:
if dist[j]>dist[i]+d:
dist[j]=dist[i]+d
if route_restoration:
parents[j]=i
if not self.directed and dist[i]>dist[j]+d:
dist[i]=dist[j]+d
if route_restoration:
parents[i]=j
negative_cycle=[]
for i,j,d in self.edges:
if dist[j]>dist[i]+d:
negative_cycle.append(j)
if not self.directed and dist[i]>dist[j]+d:
negative_cycle.append(i)
if negative_cycle:
is_negative_cycle=[False]*self.V
for i in negative_cycle:
if is_negative_cycle[i]:
continue
else:
queue=deque([i])
is_negative_cycle[i]=True
while queue:
x=queue.popleft()
for y,d in self.graph[x]:
if not is_negative_cycle[y]:
queue.append(y)
is_negative_cycle[y]=True
if route_restoration:
parents[y]=x
for i in range(self.V):
if is_negative_cycle[i]:
dist[i]=-float('inf')
if route_restoration:
return dist,parents
else:
return dist
def Warshall_Floyd(self,route_restoration=False):
dist=[[float('inf')]*self.V for i in range(self.V)]
for i in range(self.V):
dist[i][i]=0
if route_restoration:
parents=[[j for j in range(self.V)] for i in range(self.V)]
for i,j,d in self.edges:
if dist[i][j]>d:
dist[i][j]=d
if route_restoration:
parents[i][j]=i
if not self.directed and dist[j][i]>d:
dist[j][i]=d
if route_restoration:
parents[j][i]=j
for k in range(self.V):
for i in range(self.V):
for j in range(self.V):
if dist[i][j]>dist[i][k]+dist[k][j]:
dist[i][j]=dist[i][k]+dist[k][j]
if route_restoration:
parents[i][j]=parents[k][j]
for i in range(self.V):
if dist[i][i]<0:
for j in range(self.V):
if dist[i][j]!=float('inf'):
dist[i][j]=-float('inf')
if route_restoration:
return dist,parents
else:
return dist
def Route_Restoration(self,s,g,parents):
route=[g]
while s!=g and parents[g]!=g:
g=parents[g]
route.append(g)
route=route[::-1]
return route
def Kruskal(self):
UF=UnionFind(self.V)
sorted_edges=sorted(self.edges,key=lambda x:x[2])
minimum_spnning_tree=[]
for i,j,d in sorted_edges:
if not UF.Same(i,j):
UF.Union(i,j)
minimum_spnning_tree.append((i,j,d))
return minimum_spnning_tree
def Ford_Fulkerson(self,s,t):
max_flow=0
residual_graph=[defaultdict(int) for i in range(self.V)]
if self.weighted:
for i,j,d in self.edges:
if not d:
continue
residual_graph[i][j]+=d
if not self.directed:
residual_graph[j][i]+=d
else:
for i,j in self.edges:
residual_graph[i][j]+=1
if not self.directed:
residual_graph[j][i]+=1
while True:
parents=[None]*self.V
parents[s]=s
seen=[False]*self.V
seen[s]=True
queue=deque([s])
while queue:
x=queue.popleft()
for y in residual_graph[x].keys():
if not seen[y]:
seen[y]=True
queue.append(y)
parents[y]=x
if y==t:
tt=t
while tt!=s:
residual_graph[parents[tt]][tt]-=1
residual_graph[tt][parents[tt]]+=1
if not residual_graph[parents[tt]][tt]:
residual_graph[parents[tt]].pop(tt)
tt=parents[tt]
max_flow+=1
break
else:
continue
break
else:
break
return max_flow
def BFS(self,s):
seen=[False]*self.V
seen[s]=True
queue=deque([s])
while queue:
x=queue.popleft()
for y in self.graph[x]:
if self.weighted:
y,d=y
if not seen[y]:
seen[y]=True
queue.append(y)
return
def DFS(self,s):
seen=[False]*self.V
finished=[False]*self.V
stack=[(s,0)] if self.weighted else [s]
while stack:
if self.weighted:
x,d=stack.pop()
else:
x=stack.pop()
if not seen[x]:
seen[x]=True
stack.append((x,d) if self.weighted else x)
for y in self.graph[x]:
if self.weighted:
y,d=y
if not seen[y]:
stack.append((y,d) if self.weighted else y)
elif not finished[x]:
finished[x]=True
return
class Segment_Tree:
def __init__(self,N,f,e,lst=None):
self.f=f
self.e=e
self.N=N
if lst==None:
self.segment_tree=[self.e]*2*self.N
else:
assert len(lst)<=self.N
self.segment_tree=[self.e]*self.N+[x for x in lst]+[self.e]*(N-len(lst))
for i in range(self.N-1,0,-1):
self.segment_tree[i]=self.f(self.segment_tree[i<<1],self.segment_tree[i<<1|1])
def __getitem__(self,i):
if type(i)==int:
if -self.N<=i<0:
return self.segment_tree[i+self.N*2]
elif 0<=i<self.N:
return self.segment_tree[i+self.N]
else:
raise IndexError('list index out of range')
else:
a,b,c=i.start,i.stop,i.step
if a==None or a<-self.N:
a=self.N
elif self.N<=a:
a=self.N*2
elif a<0:
a+=self.N*2
else:
a+=self.N
if b==None or self.N<=b:
b=self.N*2
elif b<-self.N:
b=self.N
elif b<0:
b+=self.N*2
else:
b+=self.N
return self.segment_tree[slice(a,b,c)]
def __setitem__(self,i,x):
if -self.N<=i<0:
i+=self.N*2
elif 0<=i<self.N:
i+=self.N
else:
raise IndexError('list index out of range')
self.segment_tree[i]=x
while i>1:
i>>= 1
self.segment_tree[i]=self.f(self.segment_tree[i<<1],self.segment_tree[i<<1|1])
def Build(self,lst):
for i,x in enumerate(lst,self.N):
self.segment_tree[i]=x
for i in range(self.N-1,0,-1):
self.segment_tree[i]=self.f(self.segment_tree[i<<1],self.segment_tree[i<<1|1])
def Fold(self,L=None,R=None):
if L==None or L<-self.N:
L=self.N
elif self.N<=L:
L=self.N*2
elif L<0:
L+=self.N*2
else:
L+=self.N
if R==None or self.N<=R:
R=self.N*2
elif R<-self.N:
R=self.N
elif R<0:
R+=self.N*2
else:
R+=self.N
vL=self.e
vR=self.e
while L<R:
if L&1:
vL=self.f(vL,self.segment_tree[L])
L+=1
if R&1:
R-=1
vR=self.f(self.segment_tree[R],vR)
L>>=1
R>>=1
return self.f(vL,vR)
def Fold_Index(self,L=None,R=None):
if L==None or L<-self.N:
L=self.N
elif self.N<=L:
L=self.N*2
elif L<0:
L+=self.N*2
else:
L+=self.N
if R==None or self.N<=R:
R=self.N*2
elif R<-self.N:
R=self.N
elif R<0:
R+=self.N*2
else:
R+=self.N
if L==R:
return None
x=self.Fold(L-self.N,R-self.N)
while L<R:
if L&1:
if self.segment_tree[L]==x:
i=L
break
L+=1
if R&1:
R-=1
if self.segment_tree[R]==x:
i=R
break
L>>=1
R>>=1
while i<self.N:
if self.segment_tree[i]==self.segment_tree[i<<1]:
i<<=1
else:
i<<=1
i|=1
i-=self.N
return i
def __str__(self):
return '['+', '.join(map(str,self.segment_tree[self.N:]))+']'
N=int(readline())
mod=10**9+7
edges=[]
ans=0
for _ in range(N-1):
x,y=map(int,readline().split())
x-=1;y-=1
edges.append((x,y))
G=Graph(N,edges=edges)
MD=MOD(mod=mod)
MD.Build_Fact(1000)
pow_lst=[1]
for _ in range(1000):
pow_lst.append(pow_lst[-1]*500000004%mod)
@lru_cache(maxsize=None)
def f(a,b):
if a:
return (f(a-1,b)+pow_lst[b+a-1]*MD.Comb(b-2+a,a-1))%mod
return 0
for z in range(N):
parents,postorder,depth=G.SS_DFS(z,parents=True,postorder=True,unweighted_dist=True)
children=[[r] for r in range(N)]
for r in postorder:
for x in G.graph[r]:
if x==parents[r]:
continue
for y in children[x]:
children[r].append(y)
for x in children[r]:
if r>x:
ans+=1
for x in G.graph[r]:
if x==parents[r]:
continue
for y in G.graph[r]:
if y==parents[r]:
continue
if x!=y:
for xx in children[x]:
for yy in children[y]:
if xx<yy:
a,b=depth[xx]-depth[r],depth[yy]-depth[r]
ans+=f(a,b)
ans%=mod
ans*=MD.Pow(N,-1)
ans%=mod
print(ans)
``` | output | 1 | 25,860 | 13 | 51,721 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one.
Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree.
After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node.
It can be shown that the process marks all nodes in the tree.
The final array a is the list of the nodes' labels in order of the time each node was marked.
Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.
The number of inversions in an array a is the number of pairs of indices (i, j) such that i < j and a_i > a_j. For example, the array [4, 1, 3, 2] contains 4 inversions: (1, 2), (1, 3), (1, 4), (3, 4).
Input
The first line contains a single integer n (2 ≤ n ≤ 200) — the number of nodes in the tree.
The next n - 1 lines each contains two integers x and y (1 ≤ x, y ≤ n; x ≠ y), denoting an edge between node x and y.
It's guaranteed that the given edges form a tree.
Output
Output the expected number of inversions in the generated array modulo 10^9+7.
Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not ≡ 0 \pmod{M}. Output the integer equal to p ⋅ q^{-1} mod M. In other words, output such an integer x that 0 ≤ x < M and x ⋅ q ≡ p \pmod{M}.
Examples
Input
3
1 2
1 3
Output
166666669
Input
6
2 1
2 3
6 1
1 4
2 5
Output
500000009
Input
5
1 2
1 3
1 4
2 5
Output
500000007
Note
This is the tree from the first sample:
<image>
For the first sample, the arrays are almost fixed. If node 2 is chosen initially, then the only possible array is [2, 1, 3] (1 inversion). If node 3 is chosen initially, then the only possible array is [3, 1, 2] (2 inversions). If node 1 is chosen initially, the arrays [1, 2, 3] (0 inversions) and [1, 3, 2] (1 inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is 1/3⋅ 1 + 1/3 ⋅ 2 + 1/3 ⋅ (1/2 ⋅ 0 + 1/2 ⋅ 1) = 7/6.
166666669 ⋅ 6 = 7 \pmod {10^9 + 7}, so the answer is 166666669.
This is the tree from the second sample:
<image>
This is the tree from the third sample:
<image> | instruction | 0 | 25,861 | 13 | 51,722 |
Tags: brute force, combinatorics, dp, graphs, math, probabilities, trees
Correct Solution:
```
def naiveSolve():
return
MOD=int(1e9+7)
def getNumDivDenMOD(num,den): # return (a/b)%MOD
a,b=num,den
return ((a%MOD)*pow(b,MOD-2,MOD))%MOD
m=201
dp=[[0 for _ in range(m)] for __ in range(m)]
# dp[aDepth][bDepth]=p(reach a first)
for j in range(1,m):
dp[0][j]=1
for i in range(1,m):
for j in range(1,m):
dp[i][j]+=getNumDivDenMOD(dp[i-1][j]+dp[i][j-1],2)
dp[i][j]%=MOD
def main():
n=int(input())
adj=[[] for _ in range(n+1)]
for _ in range(n-1):
u,v=readIntArr()
adj[u].append(v)
adj[v].append(u)
ans=0
for root in range(1,n+1):
def eulerTour(node,p): # O(n)
depth[node]=depth[p]+1
up[node][0]=p
tin[node]=time[0]
time[0]+=1
for v in adj[node]: # adj[u]=[v1,v2,v3,...]
if v!=p:
eulerTour(v,node)
tout[node]=time[0]
time[0]+=1
depth=[0]*(n+1)
time=[0]
tin=[-1]*(n+1) # n is number of vertices
tout=[-1]*(n+1)
maxPow=0
while pow(2,maxPow)<n:
maxPow+=1
maxPow+=1
up=[[-1 for _ in range(maxPow)] for __ in range(n+1)]
eulerTour(root,-1)
for i in range(1,maxPow): # Build up in O(nlogn)
for u in range(1,n+1):
if up[u][i-1]==-1 or up[up[u][i-1]][i-1]==-1: # reached beyond root
continue
up[u][i]=up[up[u][i-1]][i-1]
def isAncestor(u,v): # True if u is ancestor of v
return tin[u]<=tin[v] and tout[u]>=tout[v]
def findLCA(u,v): # Find LCA in O(logn)
# traverse u to LCA
if not isAncestor(u,v):
u2=u
for i in range(maxPow-1,-1,-1):
if up[u2][i]!=-1 and not isAncestor(up[u2][i],v):
u2=up[u2][i]
# next level up is lca
lca=up[u2][0]
else:
lca=u
return lca
for b in range(1,n+1):
for a in range(b+1,n+1):
lca=findLCA(a,b)
aDepth=depth[a]-depth[lca]
bDepth=depth[b]-depth[lca]
p=dp[aDepth][bDepth]
ans+=p
ans%=MOD
ans=getNumDivDenMOD(ans,n)
print(ans)
return
import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
# input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
# def readFloatArr():
# return [float(x) for x in input().split()]
def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m])
dv=defaultValFactory;da=dimensionArr
if len(da)==1:return [dv() for _ in range(da[0])]
else:return [makeArr(dv,da[1:]) for _ in range(da[0])]
def queryInteractive(a,b):
print('? {} {}'.format(a,b))
sys.stdout.flush()
return True if input()=='SI' else False
def answerInteractive(ans):
print('! {}'.format(ans))
sys.stdout.flush()
inf=float('inf')
MOD=10**9+7
# MOD=998244353
from math import gcd,floor,ceil
# from math import floor,ceil # for Python2
for _abc in range(1):
main()
``` | output | 1 | 25,861 | 13 | 51,723 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one.
Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree.
After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node.
It can be shown that the process marks all nodes in the tree.
The final array a is the list of the nodes' labels in order of the time each node was marked.
Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.
The number of inversions in an array a is the number of pairs of indices (i, j) such that i < j and a_i > a_j. For example, the array [4, 1, 3, 2] contains 4 inversions: (1, 2), (1, 3), (1, 4), (3, 4).
Input
The first line contains a single integer n (2 ≤ n ≤ 200) — the number of nodes in the tree.
The next n - 1 lines each contains two integers x and y (1 ≤ x, y ≤ n; x ≠ y), denoting an edge between node x and y.
It's guaranteed that the given edges form a tree.
Output
Output the expected number of inversions in the generated array modulo 10^9+7.
Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not ≡ 0 \pmod{M}. Output the integer equal to p ⋅ q^{-1} mod M. In other words, output such an integer x that 0 ≤ x < M and x ⋅ q ≡ p \pmod{M}.
Examples
Input
3
1 2
1 3
Output
166666669
Input
6
2 1
2 3
6 1
1 4
2 5
Output
500000009
Input
5
1 2
1 3
1 4
2 5
Output
500000007
Note
This is the tree from the first sample:
<image>
For the first sample, the arrays are almost fixed. If node 2 is chosen initially, then the only possible array is [2, 1, 3] (1 inversion). If node 3 is chosen initially, then the only possible array is [3, 1, 2] (2 inversions). If node 1 is chosen initially, the arrays [1, 2, 3] (0 inversions) and [1, 3, 2] (1 inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is 1/3⋅ 1 + 1/3 ⋅ 2 + 1/3 ⋅ (1/2 ⋅ 0 + 1/2 ⋅ 1) = 7/6.
166666669 ⋅ 6 = 7 \pmod {10^9 + 7}, so the answer is 166666669.
This is the tree from the second sample:
<image>
This is the tree from the third sample:
<image> | instruction | 0 | 25,862 | 13 | 51,724 |
Tags: brute force, combinatorics, dp, graphs, math, probabilities, trees
Correct Solution:
```
def naiveSolve():
return
MOD=int(1e9+7)
def getNumDivDenMOD(num,den): # return (a/b)%MOD
a,b=num,den
return ((a%MOD)*pow(b,MOD-2,MOD))%MOD
m=201
dp=[[0 for _ in range(m)] for __ in range(m)]
# dp[aDepth][bDepth]=p(reach a first)
for j in range(1,m):
dp[0][j]=1
for i in range(1,m):
for j in range(1,m):
dp[i][j]+=getNumDivDenMOD(dp[i-1][j]+dp[i][j-1],2)
dp[i][j]%=MOD
def main():
n=int(input())
adj=[[] for _ in range(n+1)]
for _ in range(n-1):
u,v=readIntArr()
adj[u].append(v)
adj[v].append(u)
def floyd_warshall(n, edges):
dist = [[0 if i == j else float("inf") for i in range(n)] for j in range(n)]
# dist = [[float("inf") for i in range(n)] for j in range(n)] # if nodes are not directly connected to themselves
# pred = [[None] * n for _ in range(n)]
for u, v, d in edges:
dist[u][v] = d
# pred[u][v] = u
for k in range(n):
for i in range(n):
for j in range(n):
if dist[i][k] + dist[k][j] < dist[i][j]:
dist[i][j] = dist[i][k] + dist[k][j]
# pred[i][j] = pred[k][j]
return dist
# return dist, pred
edges=[]
for u in range(1,n+1):
for v in adj[u]:
edges.append((u,v,1))
dist=floyd_warshall(n+1,edges)
ans=0
for root in range(1,n+1):
# def eulerTour(node,p): # O(n)
# depth[node]=depth[p]+1
# up[node][0]=p
# tin[node]=time[0]
# time[0]+=1
# for v in adj[node]: # adj[u]=[v1,v2,v3,...]
# if v!=p:
# eulerTour(v,node)
# tout[node]=time[0]
# time[0]+=1
# time=[0]
# tin=[-1]*(n+1) # n is number of vertices
# tout=[-1]*(n+1)
# maxPow=0
# while pow(2,maxPow)<n:
# maxPow+=1
# maxPow+=1
# up=[[-1 for _ in range(maxPow)] for __ in range(n+1)]
# depth=[0]*(n+1)
# eulerTour(root,-1)
# for i in range(1,maxPow): # Build up in O(nlogn)
# for u in range(2,n+1):
# if up[u][i-1]==-1 or up[up[u][i-1]][i-1]==-1: # reached beyond root
# continue
# up[u][i]=up[up[u][i-1]][i-1]
# def isAncestor(u,v): # True if u is ancestor of v
# return tin[u]<=tin[v] and tout[u]>=tout[v]
# def findLCA(u,v): # Find LCA in O(logn)
# # traverse u to LCA
# if not isAncestor(u,v):
# u2=u
# for i in range(maxPow-1,-1,-1):
# if up[u2][i]!=-1 and not isAncestor(up[u2][i],v):
# u2=up[u2][i]
# # next level up is lca
# lca=up[u2][0]
# else:
# lca=u
# return lca
for b in range(1,n+1):
for a in range(b+1,n+1):
# lca=findLCA(a,b)
# aDepth=depth[a]-depth[lca]
# bDepth=depth[b]-depth[lca]
A=dist[root][a]
B=dist[root][b]
AB=dist[a][b]
bDepth=(AB-A+B)//2
aDepth=A-B+bDepth
p=dp[aDepth][bDepth]
ans+=p
ans%=MOD
ans=getNumDivDenMOD(ans,n)
print(ans)
return
import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
# input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
# def readFloatArr():
# return [float(x) for x in input().split()]
def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m])
dv=defaultValFactory;da=dimensionArr
if len(da)==1:return [dv() for _ in range(da[0])]
else:return [makeArr(dv,da[1:]) for _ in range(da[0])]
def queryInteractive(a,b):
print('? {} {}'.format(a,b))
sys.stdout.flush()
return True if input()=='SI' else False
def answerInteractive(ans):
print('! {}'.format(ans))
sys.stdout.flush()
inf=float('inf')
MOD=10**9+7
# MOD=998244353
from math import gcd,floor,ceil
# from math import floor,ceil # for Python2
for _abc in range(1):
main()
``` | output | 1 | 25,862 | 13 | 51,725 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one.
Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree.
After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node.
It can be shown that the process marks all nodes in the tree.
The final array a is the list of the nodes' labels in order of the time each node was marked.
Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.
The number of inversions in an array a is the number of pairs of indices (i, j) such that i < j and a_i > a_j. For example, the array [4, 1, 3, 2] contains 4 inversions: (1, 2), (1, 3), (1, 4), (3, 4).
Input
The first line contains a single integer n (2 ≤ n ≤ 200) — the number of nodes in the tree.
The next n - 1 lines each contains two integers x and y (1 ≤ x, y ≤ n; x ≠ y), denoting an edge between node x and y.
It's guaranteed that the given edges form a tree.
Output
Output the expected number of inversions in the generated array modulo 10^9+7.
Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not ≡ 0 \pmod{M}. Output the integer equal to p ⋅ q^{-1} mod M. In other words, output such an integer x that 0 ≤ x < M and x ⋅ q ≡ p \pmod{M}.
Examples
Input
3
1 2
1 3
Output
166666669
Input
6
2 1
2 3
6 1
1 4
2 5
Output
500000009
Input
5
1 2
1 3
1 4
2 5
Output
500000007
Note
This is the tree from the first sample:
<image>
For the first sample, the arrays are almost fixed. If node 2 is chosen initially, then the only possible array is [2, 1, 3] (1 inversion). If node 3 is chosen initially, then the only possible array is [3, 1, 2] (2 inversions). If node 1 is chosen initially, the arrays [1, 2, 3] (0 inversions) and [1, 3, 2] (1 inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is 1/3⋅ 1 + 1/3 ⋅ 2 + 1/3 ⋅ (1/2 ⋅ 0 + 1/2 ⋅ 1) = 7/6.
166666669 ⋅ 6 = 7 \pmod {10^9 + 7}, so the answer is 166666669.
This is the tree from the second sample:
<image>
This is the tree from the third sample:
<image> | instruction | 0 | 25,863 | 13 | 51,726 |
Tags: brute force, combinatorics, dp, graphs, math, probabilities, trees
Correct Solution:
```
from collections import deque
MOD = 10 ** 9 + 7;N = 1000;fact = [0 for _ in range(N)];invfact = [0 for _ in range(N)];fact[0] = 1
for i in range(1, N):fact[i] = fact[i - 1] * i % MOD
invfact[N - 1] = pow(fact[N - 1], MOD - 2, MOD)
for i in range(N - 2, -1, -1):invfact[i] = invfact[i + 1] * (i + 1) % MOD
def nCk(n, k):return 0 if k < 0 or n < k else (fact[n] * invfact[k] % MOD) * invfact[n - k] % MOD
def nHk(n, k):return nCk(n + k - 1, k)
def main():
n = int(input());edges = [[] for _ in range(n)]
for _ in range(n - 1):x, y = map(int, input().split());x -= 1;y -= 1;edges[x].append(y);edges[y].append(x)
def cnt(i, j):
bef = [-1] * n;used = [False] * n;stack = [i]
while stack:
pos = stack.pop()
if pos == j:break
for npos in edges[pos]:
if used[npos]:continue
used[npos] = True;bef[npos] = pos;stack.append(npos)
c = 0;queue = deque();queue.append((j, 0));pos = j;used = [False] * n;used[pos] = True
while pos != i:pos = bef[pos];c += 1;queue.append((pos, c));used[pos] = True
cnts = [1] * (c + 1);C = c
while queue:
pos, c = queue.popleft()
for npos in edges[pos]:
if used[npos]: continue
used[npos] = True;cnts[c] += 1;queue.append((npos, c))
ret = 0;tot = 0;times = 1;inv = pow(pow(2, C - 1, MOD), MOD - 2, MOD)
for i, c in enumerate(cnts[:-1]):ret += c * times;ret %= MOD;times -= nCk(C - 1, i) * inv;times %= MOD
return ret
ans = sum([cnt(i,j) for i in range(n) for j in range(i + 1, n)]) % MOD;ans *= pow(n, MOD - 2, MOD);print(ans % MOD)
main()
``` | output | 1 | 25,863 | 13 | 51,727 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one.
Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree.
After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node.
It can be shown that the process marks all nodes in the tree.
The final array a is the list of the nodes' labels in order of the time each node was marked.
Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.
The number of inversions in an array a is the number of pairs of indices (i, j) such that i < j and a_i > a_j. For example, the array [4, 1, 3, 2] contains 4 inversions: (1, 2), (1, 3), (1, 4), (3, 4).
Input
The first line contains a single integer n (2 ≤ n ≤ 200) — the number of nodes in the tree.
The next n - 1 lines each contains two integers x and y (1 ≤ x, y ≤ n; x ≠ y), denoting an edge between node x and y.
It's guaranteed that the given edges form a tree.
Output
Output the expected number of inversions in the generated array modulo 10^9+7.
Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not ≡ 0 \pmod{M}. Output the integer equal to p ⋅ q^{-1} mod M. In other words, output such an integer x that 0 ≤ x < M and x ⋅ q ≡ p \pmod{M}.
Examples
Input
3
1 2
1 3
Output
166666669
Input
6
2 1
2 3
6 1
1 4
2 5
Output
500000009
Input
5
1 2
1 3
1 4
2 5
Output
500000007
Note
This is the tree from the first sample:
<image>
For the first sample, the arrays are almost fixed. If node 2 is chosen initially, then the only possible array is [2, 1, 3] (1 inversion). If node 3 is chosen initially, then the only possible array is [3, 1, 2] (2 inversions). If node 1 is chosen initially, the arrays [1, 2, 3] (0 inversions) and [1, 3, 2] (1 inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is 1/3⋅ 1 + 1/3 ⋅ 2 + 1/3 ⋅ (1/2 ⋅ 0 + 1/2 ⋅ 1) = 7/6.
166666669 ⋅ 6 = 7 \pmod {10^9 + 7}, so the answer is 166666669.
This is the tree from the second sample:
<image>
This is the tree from the third sample:
<image> | instruction | 0 | 25,864 | 13 | 51,728 |
Tags: brute force, combinatorics, dp, graphs, math, probabilities, trees
Correct Solution:
```
from functools import lru_cache
from collections import deque
M = 10 ** 9 + 7
def inv(x):
return pow(x, M - 2, M)
@lru_cache(None)
def dp(u, v):
# u before v
if u == 0:
return 0
if v == 0:
return 1
return (dp(u - 1, v) * inv(2) + dp(u, v - 1) * inv(2)) % M
def main():
n = int(input())
graph = [[] for i in range(n + 1)]
ans = 0
for _ in range(n - 1):
u, v = [int(word) for word in input().split()]
graph[u].append(v)
graph[v].append(u)
link = [[-1 for j in range(n + 1)] for i in range(n + 1)]
for i in range(1, n + 1):
link[i][i] = 0
q = deque()
q.append(i)
while len(q) != 0:
u = q.popleft()
for v in graph[u]:
if link[i][v] >= 0:
continue
link[i][v] = link[i][u] + 1
q.append(v)
ans = 0
for start in range(1, n + 1):
for u in range(1, n + 1):
for v in range(u + 1, n + 1):
lca = (link[start][u] + link[start][v] - link[u][v]) // 2
ans += dp(link[start][u] - lca, link[start][v] - lca)
ans %= M
ans *= inv(n)
ans %= M
print(ans)
if __name__ == "__main__":
main()
``` | output | 1 | 25,864 | 13 | 51,729 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one.
Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree.
After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node.
It can be shown that the process marks all nodes in the tree.
The final array a is the list of the nodes' labels in order of the time each node was marked.
Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.
The number of inversions in an array a is the number of pairs of indices (i, j) such that i < j and a_i > a_j. For example, the array [4, 1, 3, 2] contains 4 inversions: (1, 2), (1, 3), (1, 4), (3, 4).
Input
The first line contains a single integer n (2 ≤ n ≤ 200) — the number of nodes in the tree.
The next n - 1 lines each contains two integers x and y (1 ≤ x, y ≤ n; x ≠ y), denoting an edge between node x and y.
It's guaranteed that the given edges form a tree.
Output
Output the expected number of inversions in the generated array modulo 10^9+7.
Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not ≡ 0 \pmod{M}. Output the integer equal to p ⋅ q^{-1} mod M. In other words, output such an integer x that 0 ≤ x < M and x ⋅ q ≡ p \pmod{M}.
Examples
Input
3
1 2
1 3
Output
166666669
Input
6
2 1
2 3
6 1
1 4
2 5
Output
500000009
Input
5
1 2
1 3
1 4
2 5
Output
500000007
Note
This is the tree from the first sample:
<image>
For the first sample, the arrays are almost fixed. If node 2 is chosen initially, then the only possible array is [2, 1, 3] (1 inversion). If node 3 is chosen initially, then the only possible array is [3, 1, 2] (2 inversions). If node 1 is chosen initially, the arrays [1, 2, 3] (0 inversions) and [1, 3, 2] (1 inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is 1/3⋅ 1 + 1/3 ⋅ 2 + 1/3 ⋅ (1/2 ⋅ 0 + 1/2 ⋅ 1) = 7/6.
166666669 ⋅ 6 = 7 \pmod {10^9 + 7}, so the answer is 166666669.
This is the tree from the second sample:
<image>
This is the tree from the third sample:
<image> | instruction | 0 | 25,865 | 13 | 51,730 |
Tags: brute force, combinatorics, dp, graphs, math, probabilities, trees
Correct Solution:
```
from functools import lru_cache
M = 10 ** 9 + 7
@lru_cache(5)
def inv(x):
return pow(x, M - 2, M)
@lru_cache(None)
def dp(u, v):
# u before v
if u == 0:
return 0
if v == 0:
return 1
return (dp(u - 1, v) * inv(2) + dp(u, v - 1) * inv(2)) % M
def main():
n = int(input())
link = [[float('inf') for j in range(n + 1)] for i in range(n + 1)]
for _ in range(n - 1):
u, v = [int(word) for word in input().split()]
link[u][v] = 1
link[v][u] = 1
for w in range(1, n + 1):
for u in range(1, n + 1):
for v in range(1, n + 1):
link[u][v] = min(link[u][v], link[u][w] + link[w][v])
ans = 0
for start in range(1, n + 1):
for u in range(1, n + 1):
for v in range(u + 1, n + 1):
lca = (link[start][u] + link[start][v] - link[u][v]) // 2
ans += dp(link[start][u] - lca, link[start][v] - lca)
ans %= M
ans *= inv(n)
ans %= M
print(ans)
if __name__ == "__main__":
main()
``` | output | 1 | 25,865 | 13 | 51,731 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one.
Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree.
After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node.
It can be shown that the process marks all nodes in the tree.
The final array a is the list of the nodes' labels in order of the time each node was marked.
Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.
The number of inversions in an array a is the number of pairs of indices (i, j) such that i < j and a_i > a_j. For example, the array [4, 1, 3, 2] contains 4 inversions: (1, 2), (1, 3), (1, 4), (3, 4).
Input
The first line contains a single integer n (2 ≤ n ≤ 200) — the number of nodes in the tree.
The next n - 1 lines each contains two integers x and y (1 ≤ x, y ≤ n; x ≠ y), denoting an edge between node x and y.
It's guaranteed that the given edges form a tree.
Output
Output the expected number of inversions in the generated array modulo 10^9+7.
Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not ≡ 0 \pmod{M}. Output the integer equal to p ⋅ q^{-1} mod M. In other words, output such an integer x that 0 ≤ x < M and x ⋅ q ≡ p \pmod{M}.
Examples
Input
3
1 2
1 3
Output
166666669
Input
6
2 1
2 3
6 1
1 4
2 5
Output
500000009
Input
5
1 2
1 3
1 4
2 5
Output
500000007
Note
This is the tree from the first sample:
<image>
For the first sample, the arrays are almost fixed. If node 2 is chosen initially, then the only possible array is [2, 1, 3] (1 inversion). If node 3 is chosen initially, then the only possible array is [3, 1, 2] (2 inversions). If node 1 is chosen initially, the arrays [1, 2, 3] (0 inversions) and [1, 3, 2] (1 inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is 1/3⋅ 1 + 1/3 ⋅ 2 + 1/3 ⋅ (1/2 ⋅ 0 + 1/2 ⋅ 1) = 7/6.
166666669 ⋅ 6 = 7 \pmod {10^9 + 7}, so the answer is 166666669.
This is the tree from the second sample:
<image>
This is the tree from the third sample:
<image>
Submitted Solution:
```
from sys import stdin, stdout
from collections import deque
from math import gcd
N = 1000000007
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def modinv(a, m=N):
g, x, y = egcd(a, m)
if g != 1:
raise Exception('modular inverse does not exist')
else:
return x % m
n = int(stdin.readline())
n_inv = modinv(n)
two_inv = modinv(2)
probs = [[0]*n for i in range(n)]
probs[1][1] = two_inv
for l in range(2,n):
probs[l][1] = (two_inv + two_inv*probs[l-1][1])%N
for r in range(2,n):
probs[1][r] = (two_inv*probs[1][r-1])%N
for l in range(2,n):
for r in range(2,n):
probs[l][r] = (two_inv*probs[l-1][r] + two_inv*probs[l][r-1])%N
edges = {i:[] for i in range(1,n+1)}
for _ in range(n-1):
v, w = [int(x) for x in stdin.readline().split()]
edges[v].append(w)
edges[w].append(v)
answer = 0
subtree_size = [0]*(n+1)
root = [0]*(n+1)
parent = [0]*(n+1)
for i in range(1, n+1):
subtree_size[i] = {v:0 for v in edges[i]}
root[i] = [-1]*(n+1)
parent[i] = [-1]*(n+1)
q = deque()
for v in edges[i]:
subtree_size[i][v] += 1
root[i][v] = v
for w in edges[v]:
if w != i:
parent[i][w] = v
q.append(w)
while len(q) > 0:
v = q.popleft()
root[i][v] = root[i][parent[i][v]]
subtree_size[i][root[i][v]] += 1
for w in edges[v]:
if w != parent[i][v]:
parent[i][w] = v
q.append(w)
for i in range(1,n):
for j in range(i+1,n+1):
n2 = 1
for v in edges[j]:
if v != root[j][i]:
n2 += subtree_size[j][v]
answer = (answer + n2*n_inv)%N
path = [j]
while path[-1] != root[i][j]:
path.append(parent[i][path[-1]])
path.append(i)
for r in range(1,len(path)-1):
l = len(path)-1 - r
size = 1
for v in edges[path[r]]:
if v != path[r-1] and v!= path[r+1]:
size += subtree_size[path[r]][v]
answer = (answer + size*n_inv*probs[l][r])%N
stdout.write(str(answer)+'\n')
``` | instruction | 0 | 25,866 | 13 | 51,732 |
Yes | output | 1 | 25,866 | 13 | 51,733 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one.
Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree.
After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node.
It can be shown that the process marks all nodes in the tree.
The final array a is the list of the nodes' labels in order of the time each node was marked.
Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.
The number of inversions in an array a is the number of pairs of indices (i, j) such that i < j and a_i > a_j. For example, the array [4, 1, 3, 2] contains 4 inversions: (1, 2), (1, 3), (1, 4), (3, 4).
Input
The first line contains a single integer n (2 ≤ n ≤ 200) — the number of nodes in the tree.
The next n - 1 lines each contains two integers x and y (1 ≤ x, y ≤ n; x ≠ y), denoting an edge between node x and y.
It's guaranteed that the given edges form a tree.
Output
Output the expected number of inversions in the generated array modulo 10^9+7.
Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not ≡ 0 \pmod{M}. Output the integer equal to p ⋅ q^{-1} mod M. In other words, output such an integer x that 0 ≤ x < M and x ⋅ q ≡ p \pmod{M}.
Examples
Input
3
1 2
1 3
Output
166666669
Input
6
2 1
2 3
6 1
1 4
2 5
Output
500000009
Input
5
1 2
1 3
1 4
2 5
Output
500000007
Note
This is the tree from the first sample:
<image>
For the first sample, the arrays are almost fixed. If node 2 is chosen initially, then the only possible array is [2, 1, 3] (1 inversion). If node 3 is chosen initially, then the only possible array is [3, 1, 2] (2 inversions). If node 1 is chosen initially, the arrays [1, 2, 3] (0 inversions) and [1, 3, 2] (1 inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is 1/3⋅ 1 + 1/3 ⋅ 2 + 1/3 ⋅ (1/2 ⋅ 0 + 1/2 ⋅ 1) = 7/6.
166666669 ⋅ 6 = 7 \pmod {10^9 + 7}, so the answer is 166666669.
This is the tree from the second sample:
<image>
This is the tree from the third sample:
<image>
Submitted Solution:
```
import sys
input = sys.stdin.readline
from collections import deque
MOD = 10 ** 9 + 7
N = 1000
fact = [0 for _ in range(N)]
invfact = [0 for _ in range(N)]
fact[0] = 1
for i in range(1, N):fact[i] = fact[i - 1] * i % MOD
invfact[N - 1] = pow(fact[N - 1], MOD - 2, MOD)
for i in range(N - 2, -1, -1):invfact[i] = invfact[i + 1] * (i + 1) % MOD
def nCk(n, k):
return 0 if k < 0 or n < k else (fact[n] * invfact[k] % MOD) * invfact[n - k] % MOD
def nHk(n, k):
return nCk(n + k - 1, k)
def main():
n = int(input())
edges = [[] for _ in range(n)]
for _ in range(n - 1):
x, y = map(int, input().split())
x -= 1
y -= 1
edges[x].append(y)
edges[y].append(x)
def cnt(i, j):
bef = [-1] * n
used = [False] * n
stack = [i]
while stack:
pos = stack.pop()
if pos == j:
break
for npos in edges[pos]:
if used[npos]:
continue
used[npos] = True
bef[npos] = pos
stack.append(npos)
c = 0
queue = deque()
queue.append((j, 0))
pos = j
used = [False] * n
used[pos] = True
while pos != i:
pos = bef[pos]
c += 1
queue.append((pos, c))
used[pos] = True
cnts = [1] * (c + 1)
C = c
while queue:
pos, c = queue.popleft()
for npos in edges[pos]:
if used[npos]: continue
used[npos] = True
cnts[c] += 1
queue.append((npos, c))
ret = 0
tot = 0
times = 1
inv = pow(pow(2, C - 1, MOD), MOD - 2, MOD)
for i, c in enumerate(cnts[:-1]):
ret += c * times
ret %= MOD
times -= nCk(C - 1, i) * inv
times %= MOD
return ret
ans = 0
for i in range(n):
for j in range(i + 1, n):
ans += cnt(i, j)
ans %= MOD
ans *= pow(n, MOD - 2, MOD)
print(ans % MOD)
for _ in range(1):
main()
``` | instruction | 0 | 25,867 | 13 | 51,734 |
Yes | output | 1 | 25,867 | 13 | 51,735 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one.
Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree.
After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node.
It can be shown that the process marks all nodes in the tree.
The final array a is the list of the nodes' labels in order of the time each node was marked.
Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.
The number of inversions in an array a is the number of pairs of indices (i, j) such that i < j and a_i > a_j. For example, the array [4, 1, 3, 2] contains 4 inversions: (1, 2), (1, 3), (1, 4), (3, 4).
Input
The first line contains a single integer n (2 ≤ n ≤ 200) — the number of nodes in the tree.
The next n - 1 lines each contains two integers x and y (1 ≤ x, y ≤ n; x ≠ y), denoting an edge between node x and y.
It's guaranteed that the given edges form a tree.
Output
Output the expected number of inversions in the generated array modulo 10^9+7.
Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not ≡ 0 \pmod{M}. Output the integer equal to p ⋅ q^{-1} mod M. In other words, output such an integer x that 0 ≤ x < M and x ⋅ q ≡ p \pmod{M}.
Examples
Input
3
1 2
1 3
Output
166666669
Input
6
2 1
2 3
6 1
1 4
2 5
Output
500000009
Input
5
1 2
1 3
1 4
2 5
Output
500000007
Note
This is the tree from the first sample:
<image>
For the first sample, the arrays are almost fixed. If node 2 is chosen initially, then the only possible array is [2, 1, 3] (1 inversion). If node 3 is chosen initially, then the only possible array is [3, 1, 2] (2 inversions). If node 1 is chosen initially, the arrays [1, 2, 3] (0 inversions) and [1, 3, 2] (1 inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is 1/3⋅ 1 + 1/3 ⋅ 2 + 1/3 ⋅ (1/2 ⋅ 0 + 1/2 ⋅ 1) = 7/6.
166666669 ⋅ 6 = 7 \pmod {10^9 + 7}, so the answer is 166666669.
This is the tree from the second sample:
<image>
This is the tree from the third sample:
<image>
Submitted Solution:
```
M = 10**9 + 7
n = int(input())
G = [[] for i in range(n)]
for i in range(n - 1):
x, y = map(int, input().split())
G[x - 1].append(y - 1)
G[y - 1].append(x - 1)
answer = 0
def dfs(i, entered, left, depths, descendents, time, depth):
assert(entered[i] == -1)
entered[i] = time
depths[i] = depth
time += 1
descendents[i] = 1
for x in G[i]:
if entered[x] == -1:
time = dfs(x, entered, left, depths, descendents,
time, depth + 1)
descendents[i] += descendents[x]
time += 1
left[i] = time
return time
L = [None for i in range(2 * n + 1)]
def inverse(x):
if L[x] == None:
L[x] = pow(x, M - 2, M)
return L[x]
distances = [[None for i in range(n + 1)] for i in range(n + 1)]
def init_distances():
for i in range(n + 1):
distances[i][0] = 1
distances[0][i] = 0
for i in range(1, n + 1):
for j in range(1, n + 1):
distances[i][j] = (inverse(2) * (
distances[i - 1][j - 1] + distances[i - 1][j])) % M
def get_dist_probability(d_v, d_v12):
return distances[d_v12][d_v]
init_distances()
'''
print(get_dist_probability(0, 1))
print(get_dist_probability(1, 1))
print(get_dist_probability(1, 4))
print(get_dist_probability(1, 3))
print(get_dist_probability(1, 2))
'''
for v1 in range(n):
for v2 in range(v1 + 1, n):
entered = [-1 for i in range(n)]
left = [-1 for i in range(n)]
depths = [-1 for i in range(n)]
descendents = [-1 for i in range(n)]
dfs(v1, entered, left, depths, descendents, 0, 0)
# entered after v2, left before v2 = v2's side
# entered at or before v2, left at or after v2 = in between
# rest = v1's side
prob_times_2n = 0
path = []
for i in range(n):
if entered[i] <= entered[v2] and left[i] >= left[v2]:
path.append((depths[i], i))
path.sort()
for (index, (_, i)) in enumerate(path):
real_descendents = descendents[i]
if index != len(path) - 1:
real_descendents -= descendents[path[index + 1][1]]
dist_to_v1 = depths[i]
dist_to_v2 = depths[v2] - depths[i]
dist_probability = get_dist_probability(dist_to_v2,
dist_to_v1 + dist_to_v2)
answer = (answer + dist_probability *
real_descendents *
inverse(n)) % M
print(answer)
``` | instruction | 0 | 25,868 | 13 | 51,736 |
Yes | output | 1 | 25,868 | 13 | 51,737 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one.
Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree.
After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node.
It can be shown that the process marks all nodes in the tree.
The final array a is the list of the nodes' labels in order of the time each node was marked.
Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.
The number of inversions in an array a is the number of pairs of indices (i, j) such that i < j and a_i > a_j. For example, the array [4, 1, 3, 2] contains 4 inversions: (1, 2), (1, 3), (1, 4), (3, 4).
Input
The first line contains a single integer n (2 ≤ n ≤ 200) — the number of nodes in the tree.
The next n - 1 lines each contains two integers x and y (1 ≤ x, y ≤ n; x ≠ y), denoting an edge between node x and y.
It's guaranteed that the given edges form a tree.
Output
Output the expected number of inversions in the generated array modulo 10^9+7.
Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not ≡ 0 \pmod{M}. Output the integer equal to p ⋅ q^{-1} mod M. In other words, output such an integer x that 0 ≤ x < M and x ⋅ q ≡ p \pmod{M}.
Examples
Input
3
1 2
1 3
Output
166666669
Input
6
2 1
2 3
6 1
1 4
2 5
Output
500000009
Input
5
1 2
1 3
1 4
2 5
Output
500000007
Note
This is the tree from the first sample:
<image>
For the first sample, the arrays are almost fixed. If node 2 is chosen initially, then the only possible array is [2, 1, 3] (1 inversion). If node 3 is chosen initially, then the only possible array is [3, 1, 2] (2 inversions). If node 1 is chosen initially, the arrays [1, 2, 3] (0 inversions) and [1, 3, 2] (1 inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is 1/3⋅ 1 + 1/3 ⋅ 2 + 1/3 ⋅ (1/2 ⋅ 0 + 1/2 ⋅ 1) = 7/6.
166666669 ⋅ 6 = 7 \pmod {10^9 + 7}, so the answer is 166666669.
This is the tree from the second sample:
<image>
This is the tree from the third sample:
<image>
Submitted Solution:
```
from functools import lru_cache
from collections import deque
M = 10 ** 9 + 7
def inv(x):
return pow(x, M - 2, M)
@lru_cache(None)
def dp(u, v):
# u before v
if u == 0:
return 0
if v == 0:
return 1
return (dp(u - 1, v) * inv(2) + dp(u, v - 1) * inv(2)) % M
def calc(n, link, start):
res = 0
for u in range(1, n + 1):
for v in range(u + 1, n + 1):
lca = (link[start][u] + link[start][v] - link[u][v]) // 2
res += dp(link[start][u] - lca, link[start][v] - lca)
res %= M
return res
def main():
n = int(input())
graph = [[] for i in range(n + 1)]
ans = 0
for _ in range(n - 1):
u, v = [int(word) for word in input().split()]
graph[u].append(v)
graph[v].append(u)
link = [[-1 for j in range(n + 1)] for i in range(n + 1)]
for i in range(1, n + 1):
link[i][i] = 0
q = deque()
q.append(i)
while len(q) != 0:
u = q.popleft()
for v in graph[u]:
if link[i][v] >= 0:
continue
link[i][v] = link[i][u] + 1
q.append(v)
for root in range(1, n + 1):
ans += calc(n, link, start=root)
ans %= M
ans *= inv(n)
ans %= M
print(ans)
if __name__ == "__main__":
main()
``` | instruction | 0 | 25,869 | 13 | 51,738 |
Yes | output | 1 | 25,869 | 13 | 51,739 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one.
Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree.
After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node.
It can be shown that the process marks all nodes in the tree.
The final array a is the list of the nodes' labels in order of the time each node was marked.
Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.
The number of inversions in an array a is the number of pairs of indices (i, j) such that i < j and a_i > a_j. For example, the array [4, 1, 3, 2] contains 4 inversions: (1, 2), (1, 3), (1, 4), (3, 4).
Input
The first line contains a single integer n (2 ≤ n ≤ 200) — the number of nodes in the tree.
The next n - 1 lines each contains two integers x and y (1 ≤ x, y ≤ n; x ≠ y), denoting an edge between node x and y.
It's guaranteed that the given edges form a tree.
Output
Output the expected number of inversions in the generated array modulo 10^9+7.
Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not ≡ 0 \pmod{M}. Output the integer equal to p ⋅ q^{-1} mod M. In other words, output such an integer x that 0 ≤ x < M and x ⋅ q ≡ p \pmod{M}.
Examples
Input
3
1 2
1 3
Output
166666669
Input
6
2 1
2 3
6 1
1 4
2 5
Output
500000009
Input
5
1 2
1 3
1 4
2 5
Output
500000007
Note
This is the tree from the first sample:
<image>
For the first sample, the arrays are almost fixed. If node 2 is chosen initially, then the only possible array is [2, 1, 3] (1 inversion). If node 3 is chosen initially, then the only possible array is [3, 1, 2] (2 inversions). If node 1 is chosen initially, the arrays [1, 2, 3] (0 inversions) and [1, 3, 2] (1 inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is 1/3⋅ 1 + 1/3 ⋅ 2 + 1/3 ⋅ (1/2 ⋅ 0 + 1/2 ⋅ 1) = 7/6.
166666669 ⋅ 6 = 7 \pmod {10^9 + 7}, so the answer is 166666669.
This is the tree from the second sample:
<image>
This is the tree from the third sample:
<image>
Submitted Solution:
```
def naiveSolve():
return
MOD=int(1e9+7)
def getNumDivDenMOD(num,den): # return (a/b)%MOD
a,b=num,den
return ((a%MOD)*pow(b,MOD-2,MOD))%MOD
m=201
dp=[[0 for _ in range(m)] for __ in range(m)]
# dp[aDepth][bDepth]=p(reach a first)
for j in range(1,m):
dp[0][j]=1
for i in range(1,m):
for j in range(1,m):
dp[i][j]+=getNumDivDenMOD(dp[i-1][j],2)
dp[i][j]%=MOD
dp[i][j]+=getNumDivDenMOD(dp[i][j-1],2)
dp[i][j]%=MOD
def main():
n=int(input())
adj=[[] for _ in range(n+1)]
for _ in range(n-1):
u,v=readIntArr()
adj[u].append(v)
adj[v].append(u)
ans=0
for root in range(1,n+1):
def eulerTour(node,p): # O(n)
depth[node]=depth[p]+1
up[node][0]=p
tin[node]=time[0]
time[0]+=1
for v in adj[node]: # adj[u]=[v1,v2,v3,...]
if v!=p:
eulerTour(v,node)
tout[node]=time[0]
time[0]+=1
time=[0]
tin=[-1]*(n+1) # n is number of vertices
tout=[-1]*(n+1)
maxPow=0
while pow(2,maxPow)<n:
maxPow+=1
maxPow+=1
up=[[-1 for _ in range(maxPow)] for __ in range(n+1)]
depth=[0]*(n+1)
eulerTour(root,-1)
for i in range(1,maxPow): # Build up in O(nlogn)
for u in range(2,n+1):
if up[u][i-1]==-1 or up[up[u][i-1]][i-1]==-1: # reached beyond root
continue
up[u][i]=up[up[u][i-1]][i-1]
def isAncestor(u,v): # True if u is ancestor of v
return tin[u]<=tin[v] and tout[u]>=tout[v]
def findLCA(u,v): # Find LCA in O(logn)
# traverse u to LCA
if not isAncestor(u,v):
u2=u
for i in range(maxPow-1,-1,-1):
if up[u2][i]!=-1 and not isAncestor(up[u2][i],v):
u2=up[u2][i]
# next level up is lca
lca=up[u2][0]
else:
lca=u
return lca
for b in range(1,n+1):
for a in range(b+1,n+1):
lca=findLCA(a,b)
aDepth=depth[a]-depth[lca]
bDepth=depth[b]-depth[lca]
p=dp[aDepth][bDepth]
ans+=p
ans%=MOD
ans=getNumDivDenMOD(ans,n)
print(ans)
return
import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
# input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
# def readFloatArr():
# return [float(x) for x in input().split()]
def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m])
dv=defaultValFactory;da=dimensionArr
if len(da)==1:return [dv() for _ in range(da[0])]
else:return [makeArr(dv,da[1:]) for _ in range(da[0])]
def queryInteractive(a,b):
print('? {} {}'.format(a,b))
sys.stdout.flush()
return True if input()=='SI' else False
def answerInteractive(ans):
print('! {}'.format(ans))
sys.stdout.flush()
inf=float('inf')
MOD=10**9+7
# MOD=998244353
from math import gcd,floor,ceil
# from math import floor,ceil # for Python2
for _abc in range(1):
main()
``` | instruction | 0 | 25,870 | 13 | 51,740 |
No | output | 1 | 25,870 | 13 | 51,741 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one.
Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree.
After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node.
It can be shown that the process marks all nodes in the tree.
The final array a is the list of the nodes' labels in order of the time each node was marked.
Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.
The number of inversions in an array a is the number of pairs of indices (i, j) such that i < j and a_i > a_j. For example, the array [4, 1, 3, 2] contains 4 inversions: (1, 2), (1, 3), (1, 4), (3, 4).
Input
The first line contains a single integer n (2 ≤ n ≤ 200) — the number of nodes in the tree.
The next n - 1 lines each contains two integers x and y (1 ≤ x, y ≤ n; x ≠ y), denoting an edge between node x and y.
It's guaranteed that the given edges form a tree.
Output
Output the expected number of inversions in the generated array modulo 10^9+7.
Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not ≡ 0 \pmod{M}. Output the integer equal to p ⋅ q^{-1} mod M. In other words, output such an integer x that 0 ≤ x < M and x ⋅ q ≡ p \pmod{M}.
Examples
Input
3
1 2
1 3
Output
166666669
Input
6
2 1
2 3
6 1
1 4
2 5
Output
500000009
Input
5
1 2
1 3
1 4
2 5
Output
500000007
Note
This is the tree from the first sample:
<image>
For the first sample, the arrays are almost fixed. If node 2 is chosen initially, then the only possible array is [2, 1, 3] (1 inversion). If node 3 is chosen initially, then the only possible array is [3, 1, 2] (2 inversions). If node 1 is chosen initially, the arrays [1, 2, 3] (0 inversions) and [1, 3, 2] (1 inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is 1/3⋅ 1 + 1/3 ⋅ 2 + 1/3 ⋅ (1/2 ⋅ 0 + 1/2 ⋅ 1) = 7/6.
166666669 ⋅ 6 = 7 \pmod {10^9 + 7}, so the answer is 166666669.
This is the tree from the second sample:
<image>
This is the tree from the third sample:
<image>
Submitted Solution:
```
def naiveSolve():
return
MOD=int(1e9+7)
def getNumDivDenMOD(num,den): # return (a/b)%MOD
a,b=num,den
return ((a%MOD)*pow(b,MOD-2,MOD))%MOD
m=201
dp=[[0 for _ in range(m)] for __ in range(m)]
# dp[aDepth][bDepth]=p(reach a first)
for j in range(1,m):
dp[0][j]=1
for i in range(1,m):
for j in range(1,m):
dp[i][j]+=getNumDivDenMOD(dp[i-1][j]+dp[i][j-1],2)
dp[i][j]%=MOD
def main():
n=int(input())
adj=[[] for _ in range(n+1)]
for _ in range(n-1):
u,v=readIntArr()
adj[u].append(v)
adj[v].append(u)
ans=0
for root in range(1,n+1):
def eulerTour(node,p): # O(n)
depth[node]=depth[p]+1
up[node][0]=p
tin[node]=time[0]
time[0]+=1
for v in adj[node]: # adj[u]=[v1,v2,v3,...]
if v!=p:
eulerTour(v,node)
tout[node]=time[0]
time[0]+=1
time=[0]
tin=[-1]*(n+1) # n is number of vertices
tout=[-1]*(n+1)
maxPow=0
while pow(2,maxPow)<n:
maxPow+=1
maxPow+=1
up=[[-1 for _ in range(maxPow)] for __ in range(n+1)]
depth=[0]*(n+1)
eulerTour(root,-1)
for i in range(1,maxPow): # Build up in O(nlogn)
for u in range(2,n+1):
if up[u][i-1]==-1 or up[up[u][i-1]][i-1]==-1: # reached beyond root
continue
up[u][i]=up[up[u][i-1]][i-1]
def isAncestor(u,v): # True if u is ancestor of v
return tin[u]<=tin[v] and tout[u]>=tout[v]
def findLCA(u,v): # Find LCA in O(logn)
# traverse u to LCA
if not isAncestor(u,v):
u2=u
for i in range(maxPow-1,-1,-1):
if up[u2][i]!=-1 and not isAncestor(up[u2][i],v):
u2=up[u2][i]
# next level up is lca
lca=up[u2][0]
else:
lca=u
return lca
for b in range(1,n+1):
for a in range(b+1,n+1):
lca=findLCA(a,b)
aDepth=depth[a]-depth[lca]
bDepth=depth[b]-depth[lca]
p=dp[aDepth][bDepth]
ans+=p
ans%=MOD
ans=getNumDivDenMOD(ans,n)
print(ans)
return
import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
# input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
# def readFloatArr():
# return [float(x) for x in input().split()]
def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m])
dv=defaultValFactory;da=dimensionArr
if len(da)==1:return [dv() for _ in range(da[0])]
else:return [makeArr(dv,da[1:]) for _ in range(da[0])]
def queryInteractive(a,b):
print('? {} {}'.format(a,b))
sys.stdout.flush()
return True if input()=='SI' else False
def answerInteractive(ans):
print('! {}'.format(ans))
sys.stdout.flush()
inf=float('inf')
MOD=10**9+7
# MOD=998244353
from math import gcd,floor,ceil
# from math import floor,ceil # for Python2
for _abc in range(1):
main()
``` | instruction | 0 | 25,871 | 13 | 51,742 |
No | output | 1 | 25,871 | 13 | 51,743 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a tree with N vertices numbered 1, 2, ..., N. The i-th edge connects Vertex a_i and Vertex b_i. You are also given a string S of length N consisting of `0` and `1`. The i-th character of S represents the number of pieces placed on Vertex i.
Snuke will perform the following operation some number of times:
* Choose two pieces the distance between which is at least 2, and bring these pieces closer to each other by 1. More formally, choose two vertices u and v, each with one or more pieces, and consider the shortest path between them. Here the path must contain at least two edges. Then, move one piece from u to its adjacent vertex on the path, and move one piece from v to its adjacent vertex on the path.
By repeating this operation, Snuke wants to have all the pieces on the same vertex. Is this possible? If the answer is yes, also find the minimum number of operations required to achieve it.
Constraints
* 2 \leq N \leq 2000
* |S| = N
* S consists of `0` and `1`, and contains at least one `1`.
* 1 \leq a_i, b_i \leq N(a_i \neq b_i)
* The edges (a_1, b_1), (a_2, b_2), ..., (a_{N - 1}, b_{N - 1}) forms a tree.
Input
Input is given from Standard Input in the following format:
N
S
a_1 b_1
a_2 b_2
:
a_{N - 1} b_{N - 1}
Output
If it is impossible to have all the pieces on the same vertex, print `-1`. If it is possible, print the minimum number of operations required.
Examples
Input
7
0010101
1 2
2 3
1 4
4 5
1 6
6 7
Output
3
Input
7
0010110
1 2
2 3
1 4
4 5
1 6
6 7
Output
-1
Input
2
01
1 2
Output
0 | instruction | 0 | 26,277 | 13 | 52,554 |
"Correct Solution:
```
import sys
sys.setrecursionlimit(10000)
input = sys.stdin.readline
def f(v, vs):
kminmax = 0
r = 0
rkoma = 0
fff = 0
ffmx = 0
for u in d[v]:
if u in vs:
continue
vs.add(u)
k1, koma, ff = f(u, vs)
if k1 > kminmax:
kminmax = k1
ffmx = ff
kminmax = max(kminmax, k1)
rkoma += koma
fff += ff
if kminmax > fff - ffmx:
r1 = kminmax+ffmx-fff
else:
r1 = fff % 2
rkoma += km[v]
# print(v, r1 + rkoma, rkoma, fff + rkoma)
return r1 + rkoma, rkoma, fff + rkoma
N = int(input())
km = [0] + [int(i) for i in str(input().strip())]
d = [set() for _ in range(N+1)]
for _ in range(N-1):
x, y = map(int, input().split())
d[x].add(y)
d[y].add(x)
r = 10**10
#print(f(4, {4}))
for i in range(N):
a, c, fff = f(i+1, {i+1})
# print(i, a, c)
if a == c:
r = min(r, (fff-c)//2)
print(r if r != 10**10 else -1)
``` | output | 1 | 26,277 | 13 | 52,555 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a tree with N vertices numbered 1, 2, ..., N. The i-th edge connects Vertex a_i and Vertex b_i. You are also given a string S of length N consisting of `0` and `1`. The i-th character of S represents the number of pieces placed on Vertex i.
Snuke will perform the following operation some number of times:
* Choose two pieces the distance between which is at least 2, and bring these pieces closer to each other by 1. More formally, choose two vertices u and v, each with one or more pieces, and consider the shortest path between them. Here the path must contain at least two edges. Then, move one piece from u to its adjacent vertex on the path, and move one piece from v to its adjacent vertex on the path.
By repeating this operation, Snuke wants to have all the pieces on the same vertex. Is this possible? If the answer is yes, also find the minimum number of operations required to achieve it.
Constraints
* 2 \leq N \leq 2000
* |S| = N
* S consists of `0` and `1`, and contains at least one `1`.
* 1 \leq a_i, b_i \leq N(a_i \neq b_i)
* The edges (a_1, b_1), (a_2, b_2), ..., (a_{N - 1}, b_{N - 1}) forms a tree.
Input
Input is given from Standard Input in the following format:
N
S
a_1 b_1
a_2 b_2
:
a_{N - 1} b_{N - 1}
Output
If it is impossible to have all the pieces on the same vertex, print `-1`. If it is possible, print the minimum number of operations required.
Examples
Input
7
0010101
1 2
2 3
1 4
4 5
1 6
6 7
Output
3
Input
7
0010110
1 2
2 3
1 4
4 5
1 6
6 7
Output
-1
Input
2
01
1 2
Output
0 | instruction | 0 | 26,278 | 13 | 52,556 |
"Correct Solution:
```
import sys
from heapq import nlargest
sys.setrecursionlimit(10000)
def first_dfs(v, p, stones, dists, costs):
stone = s[v]
dist = 0
cost = 0
children_dists = []
for u in links[v]:
if u == p:
continue
us, ud, uc = first_dfs(u, v, stones, dists, costs)
stone += us
dist += us + ud
cost += uc
children_dists.append((us + ud, uc))
# print(v, p, stone, dist, cost, children_dists)
if len(children_dists) > 1:
md, mc = max(children_dists)
if dist - md < md - mc * 2:
cost = dist - md + mc
else:
cost = dist // 2
# print(v, p, md, hd, dist, cost)
stones[v] = stone
dists[v] = dist
costs[v] = cost
return stone, dist, cost
def second_dfs(v, p, pd, pc):
children_dists = []
dist = 0
for u in links[v]:
if u == p:
dist += pd
children_dists.append((pd, pc))
continue
ud = stones[u] + dists[u]
uc = costs[u]
dist += ud
children_dists.append((ud, uc))
# print(v, p, pd, pc, dist, children_dists)
# only when source and leaf node
if len(children_dists) == 1:
u = next(iter(links[v]))
return second_dfs(u, v, s[v], 0)
(md1, mc1), (md2, mc2) = nlargest(2, children_dists)
ret = INF
hd, m = divmod(dist, 2)
# print(' ', hd, m, md1, mc1, dist - md1, md1 - mc1 * 2)
if m == 0 and dist - md1 >= md1 - mc1 * 2:
ret = min(ret, hd)
for u in links[v]:
if u == p:
continue
us = stones[u]
ud = dists[u]
uc = costs[u]
# dist=0 node cannot be a center
if ud == 0:
continue
usd = us + ud
if usd == md1 and uc == mc1:
md, mc = md2, mc2
else:
md, mc = md1, mc1
td = dist - usd
if td - md < md - mc * 2:
vc = td - md + mc
else:
vc = td // 2
result = second_dfs(u, v, td + (all_stones - us), vc)
ret = min(ret, result)
return ret
n = int(input())
s = list(map(int, input()))
links = [set() for _ in [0] * n]
for line in sys.stdin:
a, b = map(int, line.split())
a -= 1
b -= 1
links[a].add(b)
links[b].add(a)
all_stones = sum(s)
if all_stones == 1:
print(0)
exit()
stones = [0] * n # 1を根とした木の、頂点vの部分木以下(自身含む)にある石の数
dists = [0] * n # 頂点vの部分木以下にある石 x それぞれのvとの距離 の和
costs = [0] * n # 頂点v以下の石同士で、最大限頂点vに近づけておくためにできる操作の数
first_dfs(0, -1, stones, dists, costs)
# print(stones)
# print(dists)
# print(costs)
INF = 10 ** 10
ret = second_dfs(0, -1, 0, 0)
print(-1 if ret == INF else ret)
``` | output | 1 | 26,278 | 13 | 52,557 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a tree with N vertices numbered 1, 2, ..., N. The i-th edge connects Vertex a_i and Vertex b_i. You are also given a string S of length N consisting of `0` and `1`. The i-th character of S represents the number of pieces placed on Vertex i.
Snuke will perform the following operation some number of times:
* Choose two pieces the distance between which is at least 2, and bring these pieces closer to each other by 1. More formally, choose two vertices u and v, each with one or more pieces, and consider the shortest path between them. Here the path must contain at least two edges. Then, move one piece from u to its adjacent vertex on the path, and move one piece from v to its adjacent vertex on the path.
By repeating this operation, Snuke wants to have all the pieces on the same vertex. Is this possible? If the answer is yes, also find the minimum number of operations required to achieve it.
Constraints
* 2 \leq N \leq 2000
* |S| = N
* S consists of `0` and `1`, and contains at least one `1`.
* 1 \leq a_i, b_i \leq N(a_i \neq b_i)
* The edges (a_1, b_1), (a_2, b_2), ..., (a_{N - 1}, b_{N - 1}) forms a tree.
Input
Input is given from Standard Input in the following format:
N
S
a_1 b_1
a_2 b_2
:
a_{N - 1} b_{N - 1}
Output
If it is impossible to have all the pieces on the same vertex, print `-1`. If it is possible, print the minimum number of operations required.
Examples
Input
7
0010101
1 2
2 3
1 4
4 5
1 6
6 7
Output
3
Input
7
0010110
1 2
2 3
1 4
4 5
1 6
6 7
Output
-1
Input
2
01
1 2
Output
0 | instruction | 0 | 26,279 | 13 | 52,558 |
"Correct Solution:
```
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10000000)
n=int(input())
s=list(map(int,list(input()[:-1])))
edge=[[]for _ in range(n)]
for _ in range(n-1):
a,b=map(int,input().split())
a-=1
b-=1
edge[a].append(b)
edge[b].append(a)
def f(lrc):
l1,r1,c1,x1=lrc[0]
for l2,r2,c2,x2 in lrc[1:]:
l1,r1=max(max(l1,l2)-min(r1,r2),0),r1+r2
if r1%2!=l1%2:l1+=1
c1+=c2
x1+=x2
return [l1,r1,c1,x1]
def dfs(root,node):
lrcx=[]
for mode in edge[node]:
if root!=mode:
lrcx.append(dfs(node,mode))
if len(lrcx)==0:
return [s[node]]*4
l,r,c,x=f(lrcx)
c+=s[node]
return [l+c,r+c,c,x+c]
anss=[]
for i in range(n):
l,r,c,x=dfs(-1,i)
if l==c:
anss.append(x-c)
if len(anss)==0:print(-1)
else:print(min(anss)//2)
``` | output | 1 | 26,279 | 13 | 52,559 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a tree with N vertices numbered 1, 2, ..., N. The i-th edge connects Vertex a_i and Vertex b_i. You are also given a string S of length N consisting of `0` and `1`. The i-th character of S represents the number of pieces placed on Vertex i.
Snuke will perform the following operation some number of times:
* Choose two pieces the distance between which is at least 2, and bring these pieces closer to each other by 1. More formally, choose two vertices u and v, each with one or more pieces, and consider the shortest path between them. Here the path must contain at least two edges. Then, move one piece from u to its adjacent vertex on the path, and move one piece from v to its adjacent vertex on the path.
By repeating this operation, Snuke wants to have all the pieces on the same vertex. Is this possible? If the answer is yes, also find the minimum number of operations required to achieve it.
Constraints
* 2 \leq N \leq 2000
* |S| = N
* S consists of `0` and `1`, and contains at least one `1`.
* 1 \leq a_i, b_i \leq N(a_i \neq b_i)
* The edges (a_1, b_1), (a_2, b_2), ..., (a_{N - 1}, b_{N - 1}) forms a tree.
Input
Input is given from Standard Input in the following format:
N
S
a_1 b_1
a_2 b_2
:
a_{N - 1} b_{N - 1}
Output
If it is impossible to have all the pieces on the same vertex, print `-1`. If it is possible, print the minimum number of operations required.
Examples
Input
7
0010101
1 2
2 3
1 4
4 5
1 6
6 7
Output
3
Input
7
0010110
1 2
2 3
1 4
4 5
1 6
6 7
Output
-1
Input
2
01
1 2
Output
0 | instruction | 0 | 26,280 | 13 | 52,560 |
"Correct Solution:
```
from collections import deque
N=int(input())
S=input()
edge=[[] for i in range(N)]
for i in range(N-1):
a,b=map(int,input().split())
edge[a-1].append(b-1)
edge[b-1].append(a-1)
depth=[0]*N
num=[0]*N
sd=[0]*N
a=10**18
for i in range(N):
depth=[0]*N
num=[0]*N
sd=[0]*N
parent=[-1]*N
que=deque([(i,-1)])
ans=[i]
while que:
v,pv=que.popleft()
for nv in edge[v]:
if nv!=pv:
depth[nv]=depth[v]+1
parent[nv]=v
que.append((nv,v))
ans.append(nv)
ans=ans[::-1]
#print(depth)
for v in ans:
res=depth[v]*(S[v]=="1")
n=int(S[v])
for nv in edge[v]:
if nv!=parent[v]:
res+=sd[nv]
n+=num[nv]
sd[v],num[v]=res,n
res=[0]*N
for v in ans:
hosei=depth[v]
s=sd[v]-num[v]*hosei
if s%2==0:
check=0
node=-1
for nv in edge[v]:
if nv!=parent[v]:
if sd[nv]-num[nv]*hosei>s//2:
check=sd[nv]-num[nv]*hosei
node=nv
if not check:
res[v]=s//2
else:
minus=res[node]
if check-2*minus<=s-check:
res[v]=s//2
else:
res[v]=s-check+minus
else:
check=0
node=-1
k=s//2
for nv in edge[v]:
if nv!=parent[v]:
if sd[nv]-num[nv]*hosei>k+1:
check=sd[nv]-num[nv]*hosei
node=nv
if not check:
res[v]=k
else:
minus=res[node]
if check-2*minus<=s-check:
res[v]=k
else:
res[v]=s-check+minus
test=res[i]
#print(i,test,sd[i],sd)
if 2*test==sd[i]:
a=min(a,test)
if a==10**18:
print(-1)
else:
print(a)
``` | output | 1 | 26,280 | 13 | 52,561 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a tree with N vertices numbered 1, 2, ..., N. The i-th edge connects Vertex a_i and Vertex b_i. You are also given a string S of length N consisting of `0` and `1`. The i-th character of S represents the number of pieces placed on Vertex i.
Snuke will perform the following operation some number of times:
* Choose two pieces the distance between which is at least 2, and bring these pieces closer to each other by 1. More formally, choose two vertices u and v, each with one or more pieces, and consider the shortest path between them. Here the path must contain at least two edges. Then, move one piece from u to its adjacent vertex on the path, and move one piece from v to its adjacent vertex on the path.
By repeating this operation, Snuke wants to have all the pieces on the same vertex. Is this possible? If the answer is yes, also find the minimum number of operations required to achieve it.
Constraints
* 2 \leq N \leq 2000
* |S| = N
* S consists of `0` and `1`, and contains at least one `1`.
* 1 \leq a_i, b_i \leq N(a_i \neq b_i)
* The edges (a_1, b_1), (a_2, b_2), ..., (a_{N - 1}, b_{N - 1}) forms a tree.
Input
Input is given from Standard Input in the following format:
N
S
a_1 b_1
a_2 b_2
:
a_{N - 1} b_{N - 1}
Output
If it is impossible to have all the pieces on the same vertex, print `-1`. If it is possible, print the minimum number of operations required.
Examples
Input
7
0010101
1 2
2 3
1 4
4 5
1 6
6 7
Output
3
Input
7
0010110
1 2
2 3
1 4
4 5
1 6
6 7
Output
-1
Input
2
01
1 2
Output
0 | instruction | 0 | 26,281 | 13 | 52,562 |
"Correct Solution:
```
import sys
readline = sys.stdin.readline
def parorder(Edge, p):
N = len(Edge)
dist = [None]*N
dist[p] = 0
par = [0]*N
par[p] = -1
stack = [p]
order = []
visited = set([p])
ast = stack.append
apo = order.append
while stack:
vn = stack.pop()
apo(vn)
for vf in Edge[vn]:
if vf in visited:
continue
visited.add(vf)
par[vf] = vn
dist[vf] = 1+dist[vn]
ast(vf)
return par, order, dist
def getcld(p):
res = [[] for _ in range(len(p))]
for i, v in enumerate(p[1:], 1):
res[v].append(i)
return res
N = int(readline())
S = list(map(int, readline().strip()))
Edge = [[] for _ in range(N)]
for _ in range(N-1):
a, b = map(int, readline().split())
a -= 1
b -= 1
Edge[a].append(b)
Edge[b].append(a)
INF = 10**9+7
ans = INF
for root in range(N):
P, L, dist = parorder(Edge, root)
K = sum(dist[i] for i in range(N) if S[i])
if K&1:
continue
if ans <= K//2:
continue
size = S[:]
cr = []
for l in L[:0:-1]:
p = P[l]
size[p] += size[l]
dp = [0]*N
for l in L[:0:-1]:
p = P[l]
dp[p] += size[l] + dp[l]
if p == root:
cr.append((size[l] + dp[l], l))
if cr:
cm = -1
cs = 0
midx = None
for sz, idx in cr:
if cm < sz:
cm = sz
midx = idx
cs += sz
if 2*cm > cs:
candi = [[] for _ in range(N)]
cnt = None
for l in L[:0:-1]:
p = P[l]
res = 0
if candi[l]:
cis = sum(candi[l])
cim = max(candi[l])
if 2*cim > cis:
res = 2*cim-cis
else:
res = 1&cis
if l == midx:
cnt = res + size[l]
break
candi[p].append(res+size[l])
if cs-cm < cnt:
continue
ans = K//2
if ans == INF:
ans = -1
print(ans)
``` | output | 1 | 26,281 | 13 | 52,563 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a tree with N vertices numbered 1, 2, ..., N. The i-th edge connects Vertex a_i and Vertex b_i. You are also given a string S of length N consisting of `0` and `1`. The i-th character of S represents the number of pieces placed on Vertex i.
Snuke will perform the following operation some number of times:
* Choose two pieces the distance between which is at least 2, and bring these pieces closer to each other by 1. More formally, choose two vertices u and v, each with one or more pieces, and consider the shortest path between them. Here the path must contain at least two edges. Then, move one piece from u to its adjacent vertex on the path, and move one piece from v to its adjacent vertex on the path.
By repeating this operation, Snuke wants to have all the pieces on the same vertex. Is this possible? If the answer is yes, also find the minimum number of operations required to achieve it.
Constraints
* 2 \leq N \leq 2000
* |S| = N
* S consists of `0` and `1`, and contains at least one `1`.
* 1 \leq a_i, b_i \leq N(a_i \neq b_i)
* The edges (a_1, b_1), (a_2, b_2), ..., (a_{N - 1}, b_{N - 1}) forms a tree.
Input
Input is given from Standard Input in the following format:
N
S
a_1 b_1
a_2 b_2
:
a_{N - 1} b_{N - 1}
Output
If it is impossible to have all the pieces on the same vertex, print `-1`. If it is possible, print the minimum number of operations required.
Examples
Input
7
0010101
1 2
2 3
1 4
4 5
1 6
6 7
Output
3
Input
7
0010110
1 2
2 3
1 4
4 5
1 6
6 7
Output
-1
Input
2
01
1 2
Output
0 | instruction | 0 | 26,282 | 13 | 52,564 |
"Correct Solution:
```
import sys
from collections import deque
input = sys.stdin.readline
sys.setrecursionlimit(2000)
N = int(input())
for K in range(12) :
if 2 ** K >= N :
break
S = input()
path = [[] for _ in range(N)]
for _ in range(N-1) :
a, b = map(int, input().split())
path[a-1].append(b-1)
path[b-1].append(a-1)
def dfs(parent, current, dp) :
max_dp = 0
for i in path[current] :
if i == parent :
continue
dp_ = [0] * 3
dfs(current, i, dp_)
dp[0] += dp_[0]
dp[1] += dp_[1]
max_dp = max(max_dp, dp_[1]+dp_[2])
if max_dp > dp[1] :
dp[2] = max_dp - dp[1]
else :
dp[2] = dp[1] % 2
if parent == -1 :
return dp
else :
if S[current] == '1' :
dp[0] += 1
dp[1] += dp[0]
dp[2] += dp[0]
ret = 10 ** 10
for root in range(N) :
dp = dfs(-1, root, [0] * 3)
if dp[2] == 0 :
ret = min(ret, dp[1] // 2)
if ret == 10 ** 10 :
print(-1)
else :
print(ret)
``` | output | 1 | 26,282 | 13 | 52,565 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a tree with N vertices numbered 1, 2, ..., N. The i-th edge connects Vertex a_i and Vertex b_i. You are also given a string S of length N consisting of `0` and `1`. The i-th character of S represents the number of pieces placed on Vertex i.
Snuke will perform the following operation some number of times:
* Choose two pieces the distance between which is at least 2, and bring these pieces closer to each other by 1. More formally, choose two vertices u and v, each with one or more pieces, and consider the shortest path between them. Here the path must contain at least two edges. Then, move one piece from u to its adjacent vertex on the path, and move one piece from v to its adjacent vertex on the path.
By repeating this operation, Snuke wants to have all the pieces on the same vertex. Is this possible? If the answer is yes, also find the minimum number of operations required to achieve it.
Constraints
* 2 \leq N \leq 2000
* |S| = N
* S consists of `0` and `1`, and contains at least one `1`.
* 1 \leq a_i, b_i \leq N(a_i \neq b_i)
* The edges (a_1, b_1), (a_2, b_2), ..., (a_{N - 1}, b_{N - 1}) forms a tree.
Input
Input is given from Standard Input in the following format:
N
S
a_1 b_1
a_2 b_2
:
a_{N - 1} b_{N - 1}
Output
If it is impossible to have all the pieces on the same vertex, print `-1`. If it is possible, print the minimum number of operations required.
Examples
Input
7
0010101
1 2
2 3
1 4
4 5
1 6
6 7
Output
3
Input
7
0010110
1 2
2 3
1 4
4 5
1 6
6 7
Output
-1
Input
2
01
1 2
Output
0 | instruction | 0 | 26,283 | 13 | 52,566 |
"Correct Solution:
```
from collections import deque
n=int(input())
S=list(input())
G=[[] for i in range(n)]
for i in range(n-1):
a,b=map(int,input().split())
G[a-1].append(b-1)
G[b-1].append(a-1)
ans=10**10
AAA=10**10
for i in range(n):#根
D=deque([i])
A=[i]
V=[0]*n
V[i]=1
C=[[] for i in range(n)]
while len(D)>0:
x=D[0]
D.popleft()
for j in range(len(G[x])):
if V[G[x][j]]==0:
V[G[x][j]]=1
D.append(G[x][j])
A.append(G[x][j])
C[x].append(G[x][j])
A=A[::-1]
Ans=[[0]*3 for i in range(n)]
for v in A:
if len(C[v])==1:
vc=C[v][0]
Ans[v]=[Ans[vc][0],Ans[vc][1]+Ans[vc][2],Ans[vc][2]]
elif len(C[v])!=0:
L=[]
LL=[]
cc=0
s=0
M=0
MM=0
for vc in C[v]:
m=Ans[vc][1]+Ans[vc][2]
if m>M:
M=m
MM=Ans[vc][0]
L.append(Ans[vc][1]+Ans[vc][2])
LL.append(2*Ans[vc][0]+Ans[vc][1]+Ans[vc][2])
cc=cc+Ans[vc][2]
s=s+Ans[vc][0]
if sum(LL)-M-2*MM>=M:
ss=sum(L)//2
else:
ss=sum(LL)-M-2*MM-s+MM
Ans[v]=[s+ss,sum(L)-2*ss,cc]
if S[v]=="1":
Ans[v][2]+=1
if Ans[i][1]==0:
if Ans[i][0]<ans:
ans=Ans[i][0]
if ans==10**10:
print(-1)
else:
print(ans)
``` | output | 1 | 26,283 | 13 | 52,567 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a tree with N vertices numbered 1, 2, ..., N. The i-th edge connects Vertex a_i and Vertex b_i. You are also given a string S of length N consisting of `0` and `1`. The i-th character of S represents the number of pieces placed on Vertex i.
Snuke will perform the following operation some number of times:
* Choose two pieces the distance between which is at least 2, and bring these pieces closer to each other by 1. More formally, choose two vertices u and v, each with one or more pieces, and consider the shortest path between them. Here the path must contain at least two edges. Then, move one piece from u to its adjacent vertex on the path, and move one piece from v to its adjacent vertex on the path.
By repeating this operation, Snuke wants to have all the pieces on the same vertex. Is this possible? If the answer is yes, also find the minimum number of operations required to achieve it.
Constraints
* 2 \leq N \leq 2000
* |S| = N
* S consists of `0` and `1`, and contains at least one `1`.
* 1 \leq a_i, b_i \leq N(a_i \neq b_i)
* The edges (a_1, b_1), (a_2, b_2), ..., (a_{N - 1}, b_{N - 1}) forms a tree.
Input
Input is given from Standard Input in the following format:
N
S
a_1 b_1
a_2 b_2
:
a_{N - 1} b_{N - 1}
Output
If it is impossible to have all the pieces on the same vertex, print `-1`. If it is possible, print the minimum number of operations required.
Examples
Input
7
0010101
1 2
2 3
1 4
4 5
1 6
6 7
Output
3
Input
7
0010110
1 2
2 3
1 4
4 5
1 6
6 7
Output
-1
Input
2
01
1 2
Output
0 | instruction | 0 | 26,284 | 13 | 52,568 |
"Correct Solution:
```
import sys
input = sys.stdin.readline
n = int(input())
s = "Q"+input()
ab = [list(map(int,input().split())) for i in range(n-1)]
graph = [[] for i in range(n+1)]
deg = [0 for i in range(n+1)]
for a,b in ab:
graph[a].append(b)
graph[b].append(a)
deg[a] += 1
deg[b] += 1
leaf = set()
for i in range(1,n+1):
if deg[i] == 1:
leaf.add(i)
if s.count("1") == 1:
print(0)
exit()
ans = 10**18
for root in range(1,n+1):
degr = deg[:]
degr[root] += 1
if root in leaf:
continue
stack = list(leaf)
dpn = [[] for i in range(n+1)]
dpmn = [[] for i in range(n+1)]
dpmx = [[] for i in range(n+1)]
info = [[0,0,0] for i in range(n+1)]
for i in leaf:
if s[i] == "1":
info[i][0] += 1
vis = set(i for i in leaf)
anstmp = 0
while stack:
x = stack.pop()
if dpn[x]:
if len(dpn[x]) == 1:
num = dpn[x][0]
info[x] = [num,dpmn[x][0]+num,dpmx[x][0]+num]
if s[x] == "1":
info[x][0] += 1
else:
info[x][0] = sum(dpn[x])
info[x][2] = sum(dpmx[x])+info[x][0]
mxv = -1
mxind = -1
for i in range(len(dpmn[x])):
if mxv < dpmn[x][i]+dpn[x][i]:
mxv = dpmn[x][i]+dpn[x][i]
mxind = i
cnst = mxv-info[x][2]+dpmx[x][mxind]+dpn[x][mxind]
info[x][1] = max(0,cnst%2,cnst)
if s[x] == "1":
info[x][0] += 1
for y in graph[x]:
if y not in vis:
dpn[y].append(info[x][0])
dpmn[y].append(info[x][1])
dpmx[y].append(info[x][2])
degr[y] -= 1
if degr[y] == 1:
vis.add(y)
stack.append(y)
if info[root][1] == 0:
ans = min(ans,info[root][2]//2)
if ans == 10**18:
print(-1)
else:
print(ans)
``` | output | 1 | 26,284 | 13 | 52,569 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree with N vertices numbered 1, 2, ..., N. The i-th edge connects Vertex a_i and Vertex b_i. You are also given a string S of length N consisting of `0` and `1`. The i-th character of S represents the number of pieces placed on Vertex i.
Snuke will perform the following operation some number of times:
* Choose two pieces the distance between which is at least 2, and bring these pieces closer to each other by 1. More formally, choose two vertices u and v, each with one or more pieces, and consider the shortest path between them. Here the path must contain at least two edges. Then, move one piece from u to its adjacent vertex on the path, and move one piece from v to its adjacent vertex on the path.
By repeating this operation, Snuke wants to have all the pieces on the same vertex. Is this possible? If the answer is yes, also find the minimum number of operations required to achieve it.
Constraints
* 2 \leq N \leq 2000
* |S| = N
* S consists of `0` and `1`, and contains at least one `1`.
* 1 \leq a_i, b_i \leq N(a_i \neq b_i)
* The edges (a_1, b_1), (a_2, b_2), ..., (a_{N - 1}, b_{N - 1}) forms a tree.
Input
Input is given from Standard Input in the following format:
N
S
a_1 b_1
a_2 b_2
:
a_{N - 1} b_{N - 1}
Output
If it is impossible to have all the pieces on the same vertex, print `-1`. If it is possible, print the minimum number of operations required.
Examples
Input
7
0010101
1 2
2 3
1 4
4 5
1 6
6 7
Output
3
Input
7
0010110
1 2
2 3
1 4
4 5
1 6
6 7
Output
-1
Input
2
01
1 2
Output
0
Submitted Solution:
```
import sys;sys.setrecursionlimit(9**9);n=int(input());s=list(map(int,list(input())));e=[[]for _ in[0]*n]
for _ in[0]*(n-1):a,b=map(int,input().split());e[a-1].append(b-1);e[b-1].append(a-1)
def f(a):
l,r,c=a[0]
for u,v,d in a[1:]:l,r=max(max(l,u)-min(r,v),(l^u)&1),r+v;c+=d
return[l,r,c]
def dfs(o,u):
if(o!=u)&(len(e[u])==1):return[s[u]]*3
l,r,c=f([dfs(u,v)for v in e[u]if o-v]);c+=s[u];return[l+c,r+c,c]
a=[r-c for l,r,c in[dfs(i,i)for i in range(n)]if l==c];print(min(a)//2if a else-1)
``` | instruction | 0 | 26,285 | 13 | 52,570 |
Yes | output | 1 | 26,285 | 13 | 52,571 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree with N vertices numbered 1, 2, ..., N. The i-th edge connects Vertex a_i and Vertex b_i. You are also given a string S of length N consisting of `0` and `1`. The i-th character of S represents the number of pieces placed on Vertex i.
Snuke will perform the following operation some number of times:
* Choose two pieces the distance between which is at least 2, and bring these pieces closer to each other by 1. More formally, choose two vertices u and v, each with one or more pieces, and consider the shortest path between them. Here the path must contain at least two edges. Then, move one piece from u to its adjacent vertex on the path, and move one piece from v to its adjacent vertex on the path.
By repeating this operation, Snuke wants to have all the pieces on the same vertex. Is this possible? If the answer is yes, also find the minimum number of operations required to achieve it.
Constraints
* 2 \leq N \leq 2000
* |S| = N
* S consists of `0` and `1`, and contains at least one `1`.
* 1 \leq a_i, b_i \leq N(a_i \neq b_i)
* The edges (a_1, b_1), (a_2, b_2), ..., (a_{N - 1}, b_{N - 1}) forms a tree.
Input
Input is given from Standard Input in the following format:
N
S
a_1 b_1
a_2 b_2
:
a_{N - 1} b_{N - 1}
Output
If it is impossible to have all the pieces on the same vertex, print `-1`. If it is possible, print the minimum number of operations required.
Examples
Input
7
0010101
1 2
2 3
1 4
4 5
1 6
6 7
Output
3
Input
7
0010110
1 2
2 3
1 4
4 5
1 6
6 7
Output
-1
Input
2
01
1 2
Output
0
Submitted Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
import random
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def pe(s): return print(str(s), file=sys.stderr)
def main():
n = I()
s = S()
aa = [LI_() for _ in range(n-1)]
e = collections.defaultdict(set)
for a,b in aa:
e[a].add(b)
e[b].add(a)
sa = []
for i in range(n):
if s[i] == '1':
sa.append(i)
if len(sa) <= 1:
return 0
m = {}
def f(i,p):
k = (i,p)
if k in m:
return m[k]
t = 0
if s[i] == '1':
t = 1
h = []
tk = 0
tc = 0
for c in e[i]:
if c == p:
continue
r = f(c,i)
if r[0] < 1:
continue
tc += r[0]
tk += r[0] + r[1]
h.append([r[0]+r[1],r[2]])
if p == -1:
return h
mk = 0
mv = 0
for u,v in h:
if mk < u:
mk = u
mv = v
if mk > tk - mk:
kk = tk - mk
mk -= kk
kk += min(mv//2,mk)
m[k] = (tc+t,tk,kk*2)
else:
m[k] = (tc+t,tk,tk//2*2)
return m[k]
r = inf
for i in range(n):
t = f(i,-1)
tk = 0
mk = 0
for u,v in t:
tk += u
if tk % 2 == 1:
continue
ff = 1
for u,v in t:
kk = u-v
nk = tk - u
if kk > nk:
ff = 0
# print(i,ff,tk,mk,t)
if ff == 0:
continue
if tk // 2 < mk:
continue
v = tk // 2
if r > v:
r = v
if r == inf:
return -1
return r
print(main())
``` | instruction | 0 | 26,286 | 13 | 52,572 |
Yes | output | 1 | 26,286 | 13 | 52,573 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree with N vertices numbered 1, 2, ..., N. The i-th edge connects Vertex a_i and Vertex b_i. You are also given a string S of length N consisting of `0` and `1`. The i-th character of S represents the number of pieces placed on Vertex i.
Snuke will perform the following operation some number of times:
* Choose two pieces the distance between which is at least 2, and bring these pieces closer to each other by 1. More formally, choose two vertices u and v, each with one or more pieces, and consider the shortest path between them. Here the path must contain at least two edges. Then, move one piece from u to its adjacent vertex on the path, and move one piece from v to its adjacent vertex on the path.
By repeating this operation, Snuke wants to have all the pieces on the same vertex. Is this possible? If the answer is yes, also find the minimum number of operations required to achieve it.
Constraints
* 2 \leq N \leq 2000
* |S| = N
* S consists of `0` and `1`, and contains at least one `1`.
* 1 \leq a_i, b_i \leq N(a_i \neq b_i)
* The edges (a_1, b_1), (a_2, b_2), ..., (a_{N - 1}, b_{N - 1}) forms a tree.
Input
Input is given from Standard Input in the following format:
N
S
a_1 b_1
a_2 b_2
:
a_{N - 1} b_{N - 1}
Output
If it is impossible to have all the pieces on the same vertex, print `-1`. If it is possible, print the minimum number of operations required.
Examples
Input
7
0010101
1 2
2 3
1 4
4 5
1 6
6 7
Output
3
Input
7
0010110
1 2
2 3
1 4
4 5
1 6
6 7
Output
-1
Input
2
01
1 2
Output
0
Submitted Solution:
```
import sys
sys.setrecursionlimit(10000)
input = sys.stdin.readline
def f(v, vs):
kminmax = rkoma = fff = ffmx = 0
for u in d[v]:
if u in vs:
continue
vs.add(u)
k1, koma, ff = f(u, vs)
if k1 > kminmax:
kminmax, ffmx = k1, ff
rkoma += koma
fff += ff
r1 = kminmax+ffmx-fff if kminmax > fff - ffmx else fff % 2
rkoma += km[v]
return r1+rkoma, rkoma, fff+rkoma
N = int(input())
km = [0] + [int(i) for i in str(input().strip())]
d = [set() for _ in range(N+1)]
for _ in range(N-1):
x, y = map(int, input().split())
d[x].add(y)
d[y].add(x)
r = 10**10
for i in range(N):
a, c, fff = f(i+1, {i+1})
if a == c:
r = min((fff-c)//2, r)
print(r if r != 10**10 else -1)
``` | instruction | 0 | 26,287 | 13 | 52,574 |
Yes | output | 1 | 26,287 | 13 | 52,575 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.