message stringlengths 2 49.9k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 446 108k | cluster float64 13 13 | __index_level_0__ int64 892 217k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph.
Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| ≥ wi + wj.
Find the size of the maximum clique in such graph.
Input
The first line contains the integer n (1 ≤ n ≤ 200 000) — the number of points.
Each of the next n lines contains two numbers xi, wi (0 ≤ xi ≤ 109, 1 ≤ wi ≤ 109) — the coordinate and the weight of a point. All xi are different.
Output
Print a single number — the number of vertexes in the maximum clique of the given graph.
Examples
Input
4
2 3
3 1
6 1
0 2
Output
3
Note
If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars!
The picture for the sample test.
<image> | instruction | 0 | 75,452 | 13 | 150,904 |
Tags: data structures, dp, greedy, implementation, sortings
Correct Solution:
```
N = int(input())
pairs = []
for i in range(N):
x, w = map(int, input().split())
pairs.append((x, w))
sorted_pairs = sorted(pairs, key=lambda x: x[0])
stack = []
stack.append(sorted_pairs[0])
for x, w in sorted_pairs[1:N]:
right_x, right_w = stack[-1]
if right_x + right_w <= x - w:
stack.append((x, w))
else:
if x + w < right_x + right_w:
stack[-1] = (x, w)
print(len(stack))
``` | output | 1 | 75,452 | 13 | 150,905 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph.
Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| ≥ wi + wj.
Find the size of the maximum clique in such graph.
Input
The first line contains the integer n (1 ≤ n ≤ 200 000) — the number of points.
Each of the next n lines contains two numbers xi, wi (0 ≤ xi ≤ 109, 1 ≤ wi ≤ 109) — the coordinate and the weight of a point. All xi are different.
Output
Print a single number — the number of vertexes in the maximum clique of the given graph.
Examples
Input
4
2 3
3 1
6 1
0 2
Output
3
Note
If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars!
The picture for the sample test.
<image> | instruction | 0 | 75,453 | 13 | 150,906 |
Tags: data structures, dp, greedy, implementation, sortings
Correct Solution:
```
n = int(input())
S=[]
for _ in range(n):
x,w = list(map(int,input().split()))
S.append((x,w))
S = sorted(S,key=lambda kv:kv[0]+kv[1])
m=1
last=S[0]
for kv in S[1:]:
if abs(kv[0]-last[0]) >= kv[1]+last[1]:
m+=1
last=kv
print(m)
``` | output | 1 | 75,453 | 13 | 150,907 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph.
Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| ≥ wi + wj.
Find the size of the maximum clique in such graph.
Input
The first line contains the integer n (1 ≤ n ≤ 200 000) — the number of points.
Each of the next n lines contains two numbers xi, wi (0 ≤ xi ≤ 109, 1 ≤ wi ≤ 109) — the coordinate and the weight of a point. All xi are different.
Output
Print a single number — the number of vertexes in the maximum clique of the given graph.
Examples
Input
4
2 3
3 1
6 1
0 2
Output
3
Note
If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars!
The picture for the sample test.
<image> | instruction | 0 | 75,454 | 13 | 150,908 |
Tags: data structures, dp, greedy, implementation, sortings
Correct Solution:
```
def on(l1, l2):
return(abs(l1[0]-l2[0])>=l1[1]+l2[1])
n = int(input())
inf = []
for i in range(n):
a,b = map(int,input().split())
inf.append([a+b,a-b])
inf.sort()
res = 1
last = 0
for i in range(1,n):
if inf[i][1] >= inf[last][0]:
res+=1
last = i
print(res)
``` | output | 1 | 75,454 | 13 | 150,909 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph.
Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| ≥ wi + wj.
Find the size of the maximum clique in such graph.
Input
The first line contains the integer n (1 ≤ n ≤ 200 000) — the number of points.
Each of the next n lines contains two numbers xi, wi (0 ≤ xi ≤ 109, 1 ≤ wi ≤ 109) — the coordinate and the weight of a point. All xi are different.
Output
Print a single number — the number of vertexes in the maximum clique of the given graph.
Examples
Input
4
2 3
3 1
6 1
0 2
Output
3
Note
If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars!
The picture for the sample test.
<image> | instruction | 0 | 75,455 | 13 | 150,910 |
Tags: data structures, dp, greedy, implementation, sortings
Correct Solution:
```
from sys import stdin
from sys import stdout
from collections import defaultdict
n=int(stdin.readline())
a=[map(int,stdin.readline().split(),(10,10)) for i in range(n)]
v=defaultdict(list)
for i,e in enumerate(a,1):
q,f=e
v[q-f].append(i)
v[q+f-1].append(-i)
sa=set()
rez=0
for j in sorted(v.keys()):
for d in v[j]:
if d>0:
sa.add(d)
for d in v[j]:
if -d in sa:
sa.clear()
rez+=1
stdout.write(str(rez))
``` | output | 1 | 75,455 | 13 | 150,911 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph.
Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| ≥ wi + wj.
Find the size of the maximum clique in such graph.
Input
The first line contains the integer n (1 ≤ n ≤ 200 000) — the number of points.
Each of the next n lines contains two numbers xi, wi (0 ≤ xi ≤ 109, 1 ≤ wi ≤ 109) — the coordinate and the weight of a point. All xi are different.
Output
Print a single number — the number of vertexes in the maximum clique of the given graph.
Examples
Input
4
2 3
3 1
6 1
0 2
Output
3
Note
If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars!
The picture for the sample test.
<image> | instruction | 0 | 75,456 | 13 | 150,912 |
Tags: data structures, dp, greedy, implementation, sortings
Correct Solution:
```
def main():
from bisect import bisect_right as br
n = int(input())
ab = [list(map(int, input().split())) for _ in [0]*n]
ab.sort()
ans = [-10**20]
l = 1
for a, b in ab:
c = br(ans, a-b)
d = a+b
if c == br(ans, d):
if c == l:
ans.append(d)
l += 1
else:
ans[c] = d
print(len(ans)-1)
main()
``` | output | 1 | 75,456 | 13 | 150,913 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph.
Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| ≥ wi + wj.
Find the size of the maximum clique in such graph.
Input
The first line contains the integer n (1 ≤ n ≤ 200 000) — the number of points.
Each of the next n lines contains two numbers xi, wi (0 ≤ xi ≤ 109, 1 ≤ wi ≤ 109) — the coordinate and the weight of a point. All xi are different.
Output
Print a single number — the number of vertexes in the maximum clique of the given graph.
Examples
Input
4
2 3
3 1
6 1
0 2
Output
3
Note
If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars!
The picture for the sample test.
<image> | instruction | 0 | 75,457 | 13 | 150,914 |
Tags: data structures, dp, greedy, implementation, sortings
Correct Solution:
```
R = lambda: list(map(int,input().split()))
n = int(input())
a = []
for _ in range(n):
a.append(R())
a.sort(key=lambda x:(x[0]+x[1]))
j = 0; ans = 1
for i in range(1,n):
if a[j][0]+a[j][1]<=a[i][0]-a[i][1]:
ans += 1
j = i
print(ans)
``` | output | 1 | 75,457 | 13 | 150,915 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph.
Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| ≥ wi + wj.
Find the size of the maximum clique in such graph.
Input
The first line contains the integer n (1 ≤ n ≤ 200 000) — the number of points.
Each of the next n lines contains two numbers xi, wi (0 ≤ xi ≤ 109, 1 ≤ wi ≤ 109) — the coordinate and the weight of a point. All xi are different.
Output
Print a single number — the number of vertexes in the maximum clique of the given graph.
Examples
Input
4
2 3
3 1
6 1
0 2
Output
3
Note
If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars!
The picture for the sample test.
<image> | instruction | 0 | 75,458 | 13 | 150,916 |
Tags: data structures, dp, greedy, implementation, sortings
Correct Solution:
```
#!/usr/bin/env python
# coding=utf-8
n = int(input())
l = []
for i in range(n):
x, y = map(int, input().split())
l += [(x + y, x - y)]
l.sort()
r = -2000000000
a = 0
for u in l:
if u[1] >= r:
a += 1
r = u[0]
print(a)
``` | output | 1 | 75,458 | 13 | 150,917 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph.
Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| ≥ wi + wj.
Find the size of the maximum clique in such graph.
Input
The first line contains the integer n (1 ≤ n ≤ 200 000) — the number of points.
Each of the next n lines contains two numbers xi, wi (0 ≤ xi ≤ 109, 1 ≤ wi ≤ 109) — the coordinate and the weight of a point. All xi are different.
Output
Print a single number — the number of vertexes in the maximum clique of the given graph.
Examples
Input
4
2 3
3 1
6 1
0 2
Output
3
Note
If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars!
The picture for the sample test.
<image> | instruction | 0 | 75,459 | 13 | 150,918 |
Tags: data structures, dp, greedy, implementation, sortings
Correct Solution:
```
import sys
n = int(input())
ranges = []
for xw in sys.stdin:
x, w = map(int, xw.split())
ranges.append((x + w, x - w))
ranges.sort()
result = 0
end = - float('inf')
for e, b in ranges:
if b >= end:
result += 1
end = e
print(result)
``` | output | 1 | 75,459 | 13 | 150,919 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph.
Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| ≥ wi + wj.
Find the size of the maximum clique in such graph.
Input
The first line contains the integer n (1 ≤ n ≤ 200 000) — the number of points.
Each of the next n lines contains two numbers xi, wi (0 ≤ xi ≤ 109, 1 ≤ wi ≤ 109) — the coordinate and the weight of a point. All xi are different.
Output
Print a single number — the number of vertexes in the maximum clique of the given graph.
Examples
Input
4
2 3
3 1
6 1
0 2
Output
3
Note
If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars!
The picture for the sample test.
<image>
Submitted Solution:
```
def read_data():
n = int(input())
ranges = []
buffer = [input() for i in range(n)]
for xw in buffer:
x, w = map(int, xw.split())
ranges.append((x + w, x - w))
return n, ranges
def solve(n, ranges):
ranges.sort()
n = 0
end = - float('inf')
for e, b in ranges:
if b >= end:
n += 1
end = e
return n
n, ranges = read_data()
print(solve(n, ranges))
``` | instruction | 0 | 75,460 | 13 | 150,920 |
Yes | output | 1 | 75,460 | 13 | 150,921 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph.
Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| ≥ wi + wj.
Find the size of the maximum clique in such graph.
Input
The first line contains the integer n (1 ≤ n ≤ 200 000) — the number of points.
Each of the next n lines contains two numbers xi, wi (0 ≤ xi ≤ 109, 1 ≤ wi ≤ 109) — the coordinate and the weight of a point. All xi are different.
Output
Print a single number — the number of vertexes in the maximum clique of the given graph.
Examples
Input
4
2 3
3 1
6 1
0 2
Output
3
Note
If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars!
The picture for the sample test.
<image>
Submitted Solution:
```
n = int(input())
X = []
W = {}
big = -1
for _ in range(n):
x,w = list(map(int,input().split()))
X.append(x)
W[x] = w
big = max(big,x)
dp = {}
X=sorted(X)
for i,xi in enumerate(X):
m = 1
for j in range(i - 1,-1,-1):
xj=X[j]
if xi - xj >= W[xi] + W[xj]:
m = max(m,1 + dp[xj])
break
dp[xi] = m
print(dp[max(dp)])
``` | instruction | 0 | 75,461 | 13 | 150,922 |
No | output | 1 | 75,461 | 13 | 150,923 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph.
Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| ≥ wi + wj.
Find the size of the maximum clique in such graph.
Input
The first line contains the integer n (1 ≤ n ≤ 200 000) — the number of points.
Each of the next n lines contains two numbers xi, wi (0 ≤ xi ≤ 109, 1 ≤ wi ≤ 109) — the coordinate and the weight of a point. All xi are different.
Output
Print a single number — the number of vertexes in the maximum clique of the given graph.
Examples
Input
4
2 3
3 1
6 1
0 2
Output
3
Note
If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars!
The picture for the sample test.
<image>
Submitted Solution:
```
n = int(input())
X = []
W = {}
big = -1
for _ in range(n):
x,w = list(map(int,input().split()))
X.append(x)
W[x] = w
big = max(big,x)
dp = {}
X=sorted(X)
for i,xi in enumerate(X):
m = 1
for j in range(i - 1,-1,-1):
xj=X[j]
if xi - xj >= W[xi] + W[xj]:
m = max(m,1 + dp[xj])
dp[xi] = m
print(max(dp))
``` | instruction | 0 | 75,462 | 13 | 150,924 |
No | output | 1 | 75,462 | 13 | 150,925 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph.
Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| ≥ wi + wj.
Find the size of the maximum clique in such graph.
Input
The first line contains the integer n (1 ≤ n ≤ 200 000) — the number of points.
Each of the next n lines contains two numbers xi, wi (0 ≤ xi ≤ 109, 1 ≤ wi ≤ 109) — the coordinate and the weight of a point. All xi are different.
Output
Print a single number — the number of vertexes in the maximum clique of the given graph.
Examples
Input
4
2 3
3 1
6 1
0 2
Output
3
Note
If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars!
The picture for the sample test.
<image>
Submitted Solution:
```
def on(l1, l2):
return(abs(l1[0]-l2[0])>=l1[1]+l2[1])
n = int(input())
inf = []
for i in range(n):
a,b = map(int,input().split())
inf.append([a+b,a-b])
inf.sort()
res = 1
for i in range(1,n):
if inf[i][1] >= inf[i-1][0]:res+=1
print(res)
``` | instruction | 0 | 75,463 | 13 | 150,926 |
No | output | 1 | 75,463 | 13 | 150,927 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph.
Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| ≥ wi + wj.
Find the size of the maximum clique in such graph.
Input
The first line contains the integer n (1 ≤ n ≤ 200 000) — the number of points.
Each of the next n lines contains two numbers xi, wi (0 ≤ xi ≤ 109, 1 ≤ wi ≤ 109) — the coordinate and the weight of a point. All xi are different.
Output
Print a single number — the number of vertexes in the maximum clique of the given graph.
Examples
Input
4
2 3
3 1
6 1
0 2
Output
3
Note
If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars!
The picture for the sample test.
<image>
Submitted Solution:
```
n = int(input())
S=[]
for _ in range(n):
x,w = list(map(int,input().split()))
S.append((x,w))
S = sorted(S,key=lambda kv:kv[0]+kv[1])
m=1
last=S[0]
for kv in S[1:]:
if abs(kv[0]-last[0]) >= abs(kv[1]-last[1]):
m+=1
last=kv
print(m)
``` | instruction | 0 | 75,464 | 13 | 150,928 |
No | output | 1 | 75,464 | 13 | 150,929 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected bipartite graph without multiple edges. You should paint the edges of graph to minimal number of colours, so that no two adjacent edges have the same colour.
Input
The first line contains three integers a, b, m (1 ≤ a, b ≤ 1000, 0 ≤ m ≤ 105), a is the size of the first part, b is the size of the second part, m is the number of edges in the graph.
Each of the next m lines contains two integers x, y (1 ≤ x ≤ a, 1 ≤ y ≤ b), where x is the number of the vertex in the first part and y is the number of the vertex in the second part. It is guaranteed that there are no multiple edges.
Output
In the first line print integer c — the minimal number of colours. The second line should contain m integers from 1 to c — the colours of the edges (in the order they appear in the input).
If there are several solutions, you can print any one of them.
Examples
Input
4 3 5
1 2
2 2
3 2
4 1
4 3
Output
3
1 2 3 1 2
Submitted Solution:
```
a, b, m = list(map(int, input().split()))
n = a + b
g_list = [[] for i in range(n)]
g_matrix = [[[-1] for i in range(n)] for j in range(n)]
order_edges = [None] * m
for i in range(m):
x, y = list(map(int, input().split()))
x = x - 1
y = a + y - 1
order_edges[i] = (x, y)
g_list[x].append(y)
g_list[y].append(x)
g_matrix[x][y] = g_matrix[y][x] = 0
delta = 0
for i in g_list:
if len(i) > delta:
delta = len(i)
edges_color = [set() for i in range(n)]
all_colors = set(range(1, delta + 1))
def check_color_dif(x, y):
c1 = all_colors.difference(edges_color[x])
c2 = all_colors.difference(edges_color[y])
c = c1.intersection(c2)
if len(c) > 0:
c1 = next(iter(c))
return c1, c1
c1 = edges_color[x].difference(edges_color[y])
c2 = edges_color[y].difference(edges_color[x])
return next(iter(c1)), next(iter(c2))
def find_alternative_path(current, next, vertex, visited):
for adj in g_list[vertex]:
if g_matrix[vertex][adj] == current:
try:
visited[vertex, adj]
except KeyError:
g_matrix[vertex][adj] = next
g_matrix[adj][vertex] = next
edges_color[vertex].remove(current)
edges_color[vertex].add(next)
edges_color[adj].add(next)
edges_color[adj].remove(current)
visited[vertex, adj] = True
visited[adj, vertex] = True
find_alternative_path(next, current, adj, visited)
return
color = delta
for edge in order_edges:
x, y = edge
g_matrix[x][y] = color
g_matrix[y][x] = color
edges_color[x].add(color)
edges_color[y].add(color)
color -= 1
if color == 0:
break
for edge in order_edges:
x, y = edge
if g_matrix[x][y] == 0:
beta, alpha = check_color_dif(x, y)
if alpha == beta:
g_matrix[x][y] = alpha
g_matrix[y][x] = alpha
edges_color[x].add(alpha)
edges_color[y].add(alpha)
else:
visited = {}
find_alternative_path(beta, alpha, x, visited)
g_matrix[x][y] = beta
g_matrix[y][x] = beta
edges_color[y].add(beta)
edges_color[x].add(beta)
print(delta)
for edge in order_edges:
x, y = edge
print(g_matrix[x][y], end=' ')
``` | instruction | 0 | 75,496 | 13 | 150,992 |
No | output | 1 | 75,496 | 13 | 150,993 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected bipartite graph without multiple edges. You should paint the edges of graph to minimal number of colours, so that no two adjacent edges have the same colour.
Input
The first line contains three integers a, b, m (1 ≤ a, b ≤ 1000, 0 ≤ m ≤ 105), a is the size of the first part, b is the size of the second part, m is the number of edges in the graph.
Each of the next m lines contains two integers x, y (1 ≤ x ≤ a, 1 ≤ y ≤ b), where x is the number of the vertex in the first part and y is the number of the vertex in the second part. It is guaranteed that there are no multiple edges.
Output
In the first line print integer c — the minimal number of colours. The second line should contain m integers from 1 to c — the colours of the edges (in the order they appear in the input).
If there are several solutions, you can print any one of them.
Examples
Input
4 3 5
1 2
2 2
3 2
4 1
4 3
Output
3
1 2 3 1 2
Submitted Solution:
```
import sys
from collections import defaultdict as dd
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 6)
a, b, m = map(int, input().split())
if m == 0:
print(0)
print()
exit(0)
e = dd(list)
for i in range(m):
u, v = map(int, input().split())
e[u].append((a + v, i))
e[a + v].append((u, i))
n = a + b
res = [0] * m
def dfs(x):
global res
c = 1
vis = set()
for y, i in e[x]: vis.add(res[i])
for y, i in e[x]:
if res[i] > 0: continue
while c in vis: c += 1
res[i] = c
vis.add(c)
dfs(y)
for x in range(1, n + 1): dfs(x)
print(max(res))
print(*res)
``` | instruction | 0 | 75,497 | 13 | 150,994 |
No | output | 1 | 75,497 | 13 | 150,995 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected bipartite graph without multiple edges. You should paint the edges of graph to minimal number of colours, so that no two adjacent edges have the same colour.
Input
The first line contains three integers a, b, m (1 ≤ a, b ≤ 1000, 0 ≤ m ≤ 105), a is the size of the first part, b is the size of the second part, m is the number of edges in the graph.
Each of the next m lines contains two integers x, y (1 ≤ x ≤ a, 1 ≤ y ≤ b), where x is the number of the vertex in the first part and y is the number of the vertex in the second part. It is guaranteed that there are no multiple edges.
Output
In the first line print integer c — the minimal number of colours. The second line should contain m integers from 1 to c — the colours of the edges (in the order they appear in the input).
If there are several solutions, you can print any one of them.
Examples
Input
4 3 5
1 2
2 2
3 2
4 1
4 3
Output
3
1 2 3 1 2
Submitted Solution:
```
a, b, m = [int(x) for x in input().split()]
n = a + b
graph = [[] for i in range(n+1)]
edges = [(0,0) for i in range(m)]
edge_color = [0 for i in range(m)]
vertice_colors = [[False for i in range(2001)] for j in range(2001)]
edge_index = [[0 for i in range(2010)] for j in range(2010)]
for i in range(m):
x, y = [int(i) for i in input().split()]
graph[x].append(y+a)
graph[y+a].append(x)
edges[i] = (x, y+a)
edge_index[x][y+a] = i
edge_index[y+a][x] = i
delta = max([len(i) for i in graph])
print(delta)
for i in range(m):
v = edges[i][0]
w = edges[i][1]
for j in range(1,delta+1):
if not vertice_colors[v][j] or not vertice_colors[w][j]:
vertice_colors[v][j] = True
vertice_colors[w][j] = True
edge_color[i] = j
break
if not edge_color[i]:
c1 = 0
c2 = 0
for j in range(1,delta+1) and (not c1 or not c2):
if vertice_colors[v][j] and not vertice_colors[w][j]:
c1 = j
elif not vertice_colors[v][j] and not vertice_colors[w][j]:
c2 = j
vertice_colors[v][c2] = True
vertice_colors[w][c1] = True
_c1 = c1
_c2 = c2
path = []
path.append((v,w))
while True:
u = 0
for j in range(len(graph[w])):
aux = graph[w][j]
if edge_color[edge_index[w][aux]] == _c2:
u = aux
break
if u > 0:
path.append((w,u))
else:
break
_c1 += _c2
_c2 = _c1 - _c2
_c1 = _c1 - _c2
w = u
vertice_colors[path[-1][1]][_c2] = True
vertice_colors[path[-1][1]][_c1] = False
for edge in path:
edge_color[edge_index[edge[0]][edge[1]]]
c1 += c2
c2 = c1 - c2
c1 = c1 - c2
for color in edge_color:
print(color)
print(" ")
print("\n")
``` | instruction | 0 | 75,498 | 13 | 150,996 |
No | output | 1 | 75,498 | 13 | 150,997 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected bipartite graph without multiple edges. You should paint the edges of graph to minimal number of colours, so that no two adjacent edges have the same colour.
Input
The first line contains three integers a, b, m (1 ≤ a, b ≤ 1000, 0 ≤ m ≤ 105), a is the size of the first part, b is the size of the second part, m is the number of edges in the graph.
Each of the next m lines contains two integers x, y (1 ≤ x ≤ a, 1 ≤ y ≤ b), where x is the number of the vertex in the first part and y is the number of the vertex in the second part. It is guaranteed that there are no multiple edges.
Output
In the first line print integer c — the minimal number of colours. The second line should contain m integers from 1 to c — the colours of the edges (in the order they appear in the input).
If there are several solutions, you can print any one of them.
Examples
Input
4 3 5
1 2
2 2
3 2
4 1
4 3
Output
3
1 2 3 1 2
Submitted Solution:
```
import sys
from time import time
input = sys.stdin.buffer.readline
t1 = time()
a, b, m = [int(x) for x in input().split()]
n = a + b
graph = [[] for i in range(n+1)]
edges = [(0,0) for i in range(m)]
edge_color = [0 for i in range(m)]
vertice_colors = [[False for i in range(2001)] for j in range(2001)]
edge_index = [[0 for i in range(2010)] for j in range(2010)]
for i in range(m):
x, y = [int(k) for k in input().split()]
graph[x].append(y+a)
graph[y+a].append(x)
edges[i] = (x, y+a)
edge_index[x][y+a] = i
edge_index[y+a][x] = i
delta = max([len(k) for k in graph])
print(delta)
for i in range(m):
v = edges[i][0]
w = edges[i][1]
for j in range(1,delta+1):
if not vertice_colors[v][j] and not vertice_colors[w][j]:
vertice_colors[v][j] = True
vertice_colors[w][j] = True
edge_color[i] = j
break
if edge_color[i] == 0:
c1 = 0
c2 = 0
for j in range(1,delta+1) :
if c1 != 0 and c2 != 0:
break
if vertice_colors[v][j] and not vertice_colors[w][j]:
c1 = j
elif not vertice_colors[v][j] and vertice_colors[w][j]:
c2 = j
vertice_colors[v][c2] = True
vertice_colors[w][c1] = True
_c1 = c1
_c2 = c2
path = []
path.append((v,w))
while True:
u = 0
for j in range(len(graph[w])):
aux = graph[w][j]
if edge_color[edge_index[w][aux]] == _c2:
u = aux
break
if u > 0:
path.append((w,u))
else:
break
_c1, _c2 = _c2, _c1
w = u
vertice_colors[path[-1][1]][_c2] = True
vertice_colors[path[-1][1]][_c1] = False
for edge in path:
edge_color[edge_index[edge[0]][edge[1]]] = c2
c1, c2 = c2, c1
for color in edge_color:
print(color, end = " ")
print()
t2=time()
print(t2-t1)
``` | instruction | 0 | 75,499 | 13 | 150,998 |
No | output | 1 | 75,499 | 13 | 150,999 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bob has a simple undirected connected graph (without self-loops and multiple edges). He wants to learn whether his graph is bipartite (that is, you can paint all vertices of the graph into two colors so that there is no edge connecting two vertices of the same color) or not. As he is not very good at programming, he asked Alice for help. He does not want to disclose his graph to Alice, but he agreed that Alice can ask him some questions about the graph.
The only question that Alice can ask is the following: she sends s — a subset of vertices of the original graph. Bob answers with the number of edges that have both endpoints in s. Since he doesn't want Alice to learn too much about the graph, he allows her to ask no more than 20000 questions. Furthermore, he suspects that Alice might introduce false messages to their communication channel, so when Alice finally tells him whether the graph is bipartite or not, she also needs to provide a proof — either the partitions themselves or a cycle of odd length.
Your task is to help Alice to construct the queries, find whether the graph is bipartite.
Input
The first line contains a single integer n (1 ≤ n ≤ 600) — the number of vertices in Bob's graph.
Interaction
First, read an integer n (1≤ n≤ 600) — the number of vertices in Bob's graph.
To make a query, print two lines. First of which should be in the format "? k" (1 ≤ k ≤ n), where k is the size of the set to be queried. The second line should contain k space separated distinct integers s_1, s_2, ..., s_k (1 ≤ s_i ≤ n) — the vertices of the queried set.
After each query read a single integer m (0 ≤ m ≤ (n(n-1))/(2)) — the number of edges between the vertices of the set \\{s_i\}.
You are not allowed to ask more than 20000 queries.
If m = -1, it means that you asked more queries than allowed, or asked an invalid query. Your program should immediately terminate (for example, by calling exit(0)). You will receive Wrong Answer; it means that you asked more queries than allowed, or asked an invalid query. If you ignore this, you can get other verdicts since your program will continue to read from a closed stream.
After printing a query do not forget to print end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
When you know the answer, you need to print it.
The format of the answer depends on whether the graph is bipartite or not.
If the graph is bipartite, print two lines. The first should contain the letter "Y" (short for "YES") followed by a space, and then a single integer s (0 ≤ s ≤ n) — the number of vertices in one of the partitions. Second line should contain s integers a_1, a_2, ..., a_s — vertices belonging to the first partition. All a_i must be distinct, and all edges in the main graph must have exactly one endpoint in the set \\{a_i\}.
If the graph is not bipartite, print two lines. The first should contain the letter "N" (short for "NO") followed by a space, and then a single integer l (3 ≤ l ≤ n) — the length of one simple cycle of odd length. Second line should contain l integers c_1, c_2, ..., c_l — the vertices along the cycle. It must hold that for all 1 ≤ i ≤ l, there is an edge \\{c_i, c_{(i mod l)+1}\} in the main graph, and all c_i are distinct.
If there are multiple possible answers, you may print any of them.
Hacks format For hacks, use the following format:
The first line contains two integers n and m~(1 ≤ n ≤ 600, 0 ≤ m ≤ (n(n-1))/(2)) — the number of vertices and edges of the graph, respectively.
Each of the next m lines contains two integers u_i and v_i~(1 ≤ u_i, v_i ≤ n) mean that there is an edge between u_i and v_i. There must not be any multiple edges, no loops, and the graph must be connected.
For example, you need to use this test to get the first sample:
4 4
4 1
1 3
3 2
2 4
Examples
Input
4
4
0
1
1
1
0
Output
? 4
1 2 3 4
? 2
1 2
? 2
1 3
? 2
1 4
? 2
2 4
? 2
3 4
Y 2
1 2
Input
4
4
3
Output
? 4
1 4 2 3
? 3
1 2 4
N 3
2 1 4
Note
In the first case, Alice learns that there are 4 edges in the whole graph. Over the course of the next three queries, she learns that vertex 1 has two neighbors: 3 and 4. She then learns that while vertex 2 is adjacent to 4, the vertex 3 isn't adjacent to 4. There is only one option for the remaining edge, and that is (2, 3). This means that the graph is a cycle on four vertices, with (1, 2) being one partition and (3, 4) being the second. Here, it would be also valid to output "3 4" on the second line.
In the second case, we also have a graph on four vertices and four edges. In the second query, Alice learns that there are three edges among vertices (1, 2, 4). The only way this could possibly happen is that those form a triangle. As the triangle is not bipartite, Alice can report it as a proof. Notice that she does not learn where the fourth edge is, but she is able to answer Bob correctly anyway.
Submitted Solution:
```
from sys import stdout
def Ask(S1, S2, L, R):
size = 0 if S2 is None else len(S2)
if size == 0 and R - L < 2:
return 0
question = []
for i in range(L, R):
question.append(str(S1[i] + 1))
for i in range(size):
question.append(str(S2[i] + 1))
stdout.write("? " + str(size + R - L) + "\n" + " ".join(question) + "\n")
stdout.flush()
answer = int(input())
if answer == -1:
exit()
return answer
def Binary_Search(S, check):
L = 0
R = len(S)
while R - L > 1:
middle = L + (R - L) // 2
if check(S, L, middle):
R = middle
else:
L = middle
return S[L]
def Spanning_Build(v, S, father, set, sets):
sets[v] = set
S.remove(v)
D = [v]
while len(S) > 0 and Ask(S, D, 0, len(S)) != Ask(S, None, 0, len(S)):
w = Binary_Search(S, lambda S_i, i, j: Ask(S_i, D, i, j) != Ask(S_i, None, i, j))
father[w] = v
Spanning_Build(w, S, father, not set, sets)
def Found_Edge(B):
L = 0
R = len(B)
while R - L > 2:
middle = L + (R - L) // 2
if Ask(B, None, L, middle):
R = middle
elif Ask(B, None, middle, R):
L = middle
else:
B_1 = B[L: middle]
B_2 = B[middle: R]
v = Binary_Search(B_1, lambda B_1i, i, j: Ask(B_1i, B_2, i, j) != 0)
D = [v]
w = Binary_Search(B_2, lambda B_2i, i, j: Ask(B_2i, D, i, j) != 0)
return v, w
return B[L], B[L + 1]
def Odd_Cycle(v, w, father):
mark = [False for _ in range(len(father))]
x = v
while x != -1:
mark[x] = True
x = father[x]
x = w
while not mark[x]:
x = father[x]
first_middle = []
second_middle = []
while w != x:
first_middle.append(str(w + 1))
w = father[w]
first_middle.append(str(x + 1))
while v != x:
second_middle.append(str(v + 1))
v = father[v]
stdout.write("N " + str(len(first_middle) + len(second_middle)) + "\n" + " ".join(first_middle)
+ " ".join(reversed(second_middle)) + "\n")
stdout.flush()
n = int(input())
father = [-1 for _ in range(n)]
sets = [False for _ in range(n)]
S = [i for i in range(n)]
Spanning_Build(0, S, father, True, sets)
B = []
N = []
for i in range(n):
if sets[i]:
B.append(i)
else:
N.append(i)
if Ask(B, None, 0, len(B)) != 0:
v, w = Found_Edge(B)
Odd_Cycle(v, w, father)
elif Ask(N, None, 0, len(N)) != 0:
v, w = Found_Edge(N)
Odd_Cycle(v, w, father)
else:
B = [str(v + 1) for v in B]
stdout.write("Y " + str(len(B)) + "\n" + " ".join(B) + "\n")
stdout.flush()
``` | instruction | 0 | 75,890 | 13 | 151,780 |
No | output | 1 | 75,890 | 13 | 151,781 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bob has a simple undirected connected graph (without self-loops and multiple edges). He wants to learn whether his graph is bipartite (that is, you can paint all vertices of the graph into two colors so that there is no edge connecting two vertices of the same color) or not. As he is not very good at programming, he asked Alice for help. He does not want to disclose his graph to Alice, but he agreed that Alice can ask him some questions about the graph.
The only question that Alice can ask is the following: she sends s — a subset of vertices of the original graph. Bob answers with the number of edges that have both endpoints in s. Since he doesn't want Alice to learn too much about the graph, he allows her to ask no more than 20000 questions. Furthermore, he suspects that Alice might introduce false messages to their communication channel, so when Alice finally tells him whether the graph is bipartite or not, she also needs to provide a proof — either the partitions themselves or a cycle of odd length.
Your task is to help Alice to construct the queries, find whether the graph is bipartite.
Input
The first line contains a single integer n (1 ≤ n ≤ 600) — the number of vertices in Bob's graph.
Interaction
First, read an integer n (1≤ n≤ 600) — the number of vertices in Bob's graph.
To make a query, print two lines. First of which should be in the format "? k" (1 ≤ k ≤ n), where k is the size of the set to be queried. The second line should contain k space separated distinct integers s_1, s_2, ..., s_k (1 ≤ s_i ≤ n) — the vertices of the queried set.
After each query read a single integer m (0 ≤ m ≤ (n(n-1))/(2)) — the number of edges between the vertices of the set \\{s_i\}.
You are not allowed to ask more than 20000 queries.
If m = -1, it means that you asked more queries than allowed, or asked an invalid query. Your program should immediately terminate (for example, by calling exit(0)). You will receive Wrong Answer; it means that you asked more queries than allowed, or asked an invalid query. If you ignore this, you can get other verdicts since your program will continue to read from a closed stream.
After printing a query do not forget to print end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
When you know the answer, you need to print it.
The format of the answer depends on whether the graph is bipartite or not.
If the graph is bipartite, print two lines. The first should contain the letter "Y" (short for "YES") followed by a space, and then a single integer s (0 ≤ s ≤ n) — the number of vertices in one of the partitions. Second line should contain s integers a_1, a_2, ..., a_s — vertices belonging to the first partition. All a_i must be distinct, and all edges in the main graph must have exactly one endpoint in the set \\{a_i\}.
If the graph is not bipartite, print two lines. The first should contain the letter "N" (short for "NO") followed by a space, and then a single integer l (3 ≤ l ≤ n) — the length of one simple cycle of odd length. Second line should contain l integers c_1, c_2, ..., c_l — the vertices along the cycle. It must hold that for all 1 ≤ i ≤ l, there is an edge \\{c_i, c_{(i mod l)+1}\} in the main graph, and all c_i are distinct.
If there are multiple possible answers, you may print any of them.
Hacks format For hacks, use the following format:
The first line contains two integers n and m~(1 ≤ n ≤ 600, 0 ≤ m ≤ (n(n-1))/(2)) — the number of vertices and edges of the graph, respectively.
Each of the next m lines contains two integers u_i and v_i~(1 ≤ u_i, v_i ≤ n) mean that there is an edge between u_i and v_i. There must not be any multiple edges, no loops, and the graph must be connected.
For example, you need to use this test to get the first sample:
4 4
4 1
1 3
3 2
2 4
Examples
Input
4
4
0
1
1
1
0
Output
? 4
1 2 3 4
? 2
1 2
? 2
1 3
? 2
1 4
? 2
2 4
? 2
3 4
Y 2
1 2
Input
4
4
3
Output
? 4
1 4 2 3
? 3
1 2 4
N 3
2 1 4
Note
In the first case, Alice learns that there are 4 edges in the whole graph. Over the course of the next three queries, she learns that vertex 1 has two neighbors: 3 and 4. She then learns that while vertex 2 is adjacent to 4, the vertex 3 isn't adjacent to 4. There is only one option for the remaining edge, and that is (2, 3). This means that the graph is a cycle on four vertices, with (1, 2) being one partition and (3, 4) being the second. Here, it would be also valid to output "3 4" on the second line.
In the second case, we also have a graph on four vertices and four edges. In the second query, Alice learns that there are three edges among vertices (1, 2, 4). The only way this could possibly happen is that those form a triangle. As the triangle is not bipartite, Alice can report it as a proof. Notice that she does not learn where the fourth edge is, but she is able to answer Bob correctly anyway.
Submitted Solution:
```
from sys import stdout
def Ask(S1, S2, L, R):
size = 0 if S2 is None else len(S2)
if size == 0 and R - L < 2:
return 0
question = []
for i in range(L, R):
question.append(str(S1[i] + 1))
for i in range(size):
question.append(str(S2[i] + 1))
stdout.write("? " + str(size + R - L) + "\n" + " ".join(question) + "\n")
stdout.flush()
answer = int(input())
if answer == -1:
exit()
return answer
def Binary_Search(S, check):
L = 0
R = len(S)
while R - L > 1:
middle = L + (R - L) // 2
if check(S, L, middle):
R = middle
else:
L = middle
return S[L]
def Spanning_Build(v, S, father, set, sets):
sets[v] = set
S.remove(v)
D = [v]
while len(S) > 0 and Ask(S, D, 0, len(S)) != Ask(S, None, 0, len(S)):
w = Binary_Search(S, lambda S_i, i, j: Ask(S_i, D, i, j) != Ask(S_i, None, i, j))
father[w] = v
Spanning_Build(w, S, father, not set, sets)
def Found_Edge(B):
L = 0
R = len(B)
while R - L > 2:
middle = L + (R - L) // 2
if Ask(B, None, L, middle):
R = middle
elif Ask(B, None, middle, R):
L = middle
else:
B_1 = B[L: middle]
B_2 = B[middle: R]
v = Binary_Search(B_1, lambda B_1i, i, j: Ask(B_1i, B_2, i, j) != 0)
D = [v]
w = Binary_Search(B_2, lambda B_2i, i, j: Ask(B_2i, D, i, j) != 0)
return v, w
return B[L], B[L + 1]
def Odd_Cycle(v, w, father):
mark = [False for _ in range(len(father))]
x = v
while x != -1:
mark[x] = True
x = father[x]
x = w
while not mark[x]:
x = father[x]
first_middle = []
second_middle = []
while w != x:
first_middle.append(str(w + 1))
w = father[w]
first_middle.append(str(x + 1))
while v != x:
second_middle.append(str(v + 1))
v = father[v]
stdout.write("N " + str(len(first_middle) + len(second_middle)) + "\n" +
(" ".join(first_middle) if len(first_middle) > 0 else "") +
(" ".join(reversed(second_middle)) if len(second_middle) > 0 else "") + "\n")
stdout.flush()
n = int(input())
father = [-1 for _ in range(n)]
sets = [False for _ in range(n)]
S = [i for i in range(n)]
Spanning_Build(0, S, father, True, sets)
B = []
N = []
for i in range(n):
if sets[i]:
B.append(i)
else:
N.append(i)
if Ask(B, None, 0, len(B)) != 0:
v, w = Found_Edge(B)
Odd_Cycle(v, w, father)
elif Ask(N, None, 0, len(N)) != 0:
v, w = Found_Edge(N)
Odd_Cycle(v, w, father)
else:
B = [str(v + 1) for v in B]
stdout.write("Y " + str(len(B)) + "\n" + " ".join(B) + "\n")
stdout.flush()
``` | instruction | 0 | 75,891 | 13 | 151,782 |
No | output | 1 | 75,891 | 13 | 151,783 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v ≥ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v — the depth of vertex v, which denotes the number of vertices on the path from vertex v to the root. Clearly, s_1=a_1 and h_1=1.
Then Mitya erased all numbers a_v, and by accident he also erased all values s_v for vertices with even depth (vertices with even h_v). Your task is to restore the values a_v for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values a_v for all vertices in the tree.
Input
The first line contains one integer n — the number of vertices in the tree (2 ≤ n ≤ 10^5). The following line contains integers p_2, p_3, ... p_n, where p_i stands for the parent of vertex with index i in the tree (1 ≤ p_i < i). The last line contains integer values s_1, s_2, ..., s_n (-1 ≤ s_v ≤ 10^9), where erased values are replaced by -1.
Output
Output one integer — the minimum total sum of all values a_v in the original tree, or -1 if such tree does not exist.
Examples
Input
5
1 1 1 1
1 -1 -1 -1 -1
Output
1
Input
5
1 2 3 1
1 -1 2 -1 -1
Output
2
Input
3
1 2
2 -1 1
Output
-1 | instruction | 0 | 75,901 | 13 | 151,802 |
Tags: constructive algorithms, dfs and similar, greedy, trees
Correct Solution:
```
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
n=int(input())
parents=['None']+list(map(int, input().rstrip().split()))
weights=list(map(int, input().rstrip().split()))
# In[102]:
# In[113]:
children = [[] for i in range(0,n)]
# In[104]:
#weightsum = dict(zip(seq, weights))
# In[114]:
weightvalue =[0]*n
weightvalue[0]=weights[0]
# In[115]:
#print(parents, children)
for i in range(1,n):
k=parents[i]
children[k-1].append(i+1)
# In[116]:
# In[119]:
check=0
for i in range(1,n):
if weights[i]==-1:
if not children[i]==[]:
childweights=[]
for c in children[i]:
childweights.append(weights[c-1])
m=min(childweights)
else:
m=weights[parents[i]-1]
if m<weights[parents[i]-1]:
check=-1
else:
weightvalue[i]=m-weights[parents[i]-1]
weights[i]=weights[parents[i]-1]+weightvalue[i]
#print(m,weights[i], weightvalue[i])
else:
if weights[i]-weights[parents[i]-1]<0:
check=-1
else:
weightvalue[i]=weights[i]-weights[parents[i]-1]
#print(weights, weightvalue)
if check==-1:
print(-1)
else:
print(sum(weightvalue))
# In[ ]:
``` | output | 1 | 75,901 | 13 | 151,803 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v ≥ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v — the depth of vertex v, which denotes the number of vertices on the path from vertex v to the root. Clearly, s_1=a_1 and h_1=1.
Then Mitya erased all numbers a_v, and by accident he also erased all values s_v for vertices with even depth (vertices with even h_v). Your task is to restore the values a_v for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values a_v for all vertices in the tree.
Input
The first line contains one integer n — the number of vertices in the tree (2 ≤ n ≤ 10^5). The following line contains integers p_2, p_3, ... p_n, where p_i stands for the parent of vertex with index i in the tree (1 ≤ p_i < i). The last line contains integer values s_1, s_2, ..., s_n (-1 ≤ s_v ≤ 10^9), where erased values are replaced by -1.
Output
Output one integer — the minimum total sum of all values a_v in the original tree, or -1 if such tree does not exist.
Examples
Input
5
1 1 1 1
1 -1 -1 -1 -1
Output
1
Input
5
1 2 3 1
1 -1 2 -1 -1
Output
2
Input
3
1 2
2 -1 1
Output
-1 | instruction | 0 | 75,902 | 13 | 151,804 |
Tags: constructive algorithms, dfs and similar, greedy, trees
Correct Solution:
```
n = int(input())
p = list(map(int, input().split()))
p = [-1] + [i - 1 for i in p]
s = list(map(int, input().split()))
g = {}
for i in range(n):
g[i] = []
for i in range(1, len(p)):
g[p[i]].append(i)
d = {}
md = 1
q = [(0, 1)]
while len(q) > 0:
v = q[0]
del q[0]
nd = v[1] + 1
if nd not in d:
d[nd] = []
for nv in g[v[0]]:
q.append((nv, nd))
d[nd].append(nv)
md = max(md, nd)
sh = [0 for i in range(n)]
a = [0 for i in range(n)]
a[0] = s[0]
for dp in range(md, 0, -1):
if dp % 2 == 0 or dp == 1:
continue
dc = {}
for v in d[dp]:
sv = s[v]
gp = p[p[v]]
gpv = s[gp]
if sv < gpv:
print(-1)
exit()
a[v] = sv - gpv
pr = p[v]
if pr not in dc:
dc[pr] = 10**15
dc[pr] = min(dc[pr], a[v])
for v in d[dp]:
pr = p[v]
a[v] -= dc[pr]
for pr in dc:
a[pr] = dc[pr]
print(sum(a))
``` | output | 1 | 75,902 | 13 | 151,805 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v ≥ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v — the depth of vertex v, which denotes the number of vertices on the path from vertex v to the root. Clearly, s_1=a_1 and h_1=1.
Then Mitya erased all numbers a_v, and by accident he also erased all values s_v for vertices with even depth (vertices with even h_v). Your task is to restore the values a_v for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values a_v for all vertices in the tree.
Input
The first line contains one integer n — the number of vertices in the tree (2 ≤ n ≤ 10^5). The following line contains integers p_2, p_3, ... p_n, where p_i stands for the parent of vertex with index i in the tree (1 ≤ p_i < i). The last line contains integer values s_1, s_2, ..., s_n (-1 ≤ s_v ≤ 10^9), where erased values are replaced by -1.
Output
Output one integer — the minimum total sum of all values a_v in the original tree, or -1 if such tree does not exist.
Examples
Input
5
1 1 1 1
1 -1 -1 -1 -1
Output
1
Input
5
1 2 3 1
1 -1 2 -1 -1
Output
2
Input
3
1 2
2 -1 1
Output
-1 | instruction | 0 | 75,903 | 13 | 151,806 |
Tags: constructive algorithms, dfs and similar, greedy, trees
Correct Solution:
```
n = int(input())
p = [0, 0] + list(map(int, input().split()))
s = [0] + list(map(int, input().split()))
for i in range(2,n+1):
if s[i]!=-1 and (s[p[i]]==-1 or s[p[i]]>s[i]):
s[p[i]]=s[i]
a=s[::]
for i in range(2,n+1):
if s[i]!=-1:
c = s[i]-s[p[i]]
if c<0:
print(-1)
exit()
a[i]=c
else:
a[i]=0
print(sum(a))
``` | output | 1 | 75,903 | 13 | 151,807 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v ≥ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v — the depth of vertex v, which denotes the number of vertices on the path from vertex v to the root. Clearly, s_1=a_1 and h_1=1.
Then Mitya erased all numbers a_v, and by accident he also erased all values s_v for vertices with even depth (vertices with even h_v). Your task is to restore the values a_v for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values a_v for all vertices in the tree.
Input
The first line contains one integer n — the number of vertices in the tree (2 ≤ n ≤ 10^5). The following line contains integers p_2, p_3, ... p_n, where p_i stands for the parent of vertex with index i in the tree (1 ≤ p_i < i). The last line contains integer values s_1, s_2, ..., s_n (-1 ≤ s_v ≤ 10^9), where erased values are replaced by -1.
Output
Output one integer — the minimum total sum of all values a_v in the original tree, or -1 if such tree does not exist.
Examples
Input
5
1 1 1 1
1 -1 -1 -1 -1
Output
1
Input
5
1 2 3 1
1 -1 2 -1 -1
Output
2
Input
3
1 2
2 -1 1
Output
-1 | instruction | 0 | 75,904 | 13 | 151,808 |
Tags: constructive algorithms, dfs and similar, greedy, trees
Correct Solution:
```
import sys
input = sys.stdin.readline
n=int(input())
P=[0,0]+list(map(int,input().split()))
S=[0]+list(map(int,input().split()))
SONS=[[] for i in range(n+1)]
for i in range(n+1):
SONS[P[i]].append(i)
from collections import deque
height=0
SCORE=[0]*(n+1)
SCORESUM=[0]*(n+1)
SCORE[1]=S[1]
SCORESUM[1]=S[1]
QUE = deque(SONS[1])
while QUE:
x=QUE.pop()
#print(x,QUE,SCORE,SCORESUM)
if S[x]>=0:
SCORE[x]=S[x]-SCORESUM[P[x]]
SCORESUM[x]=S[x]
for to in SONS[x]:
QUE.append(to)
continue
elif S[x]==-1:
MINSCORE=float("inf")
for to in SONS[x]:
QUE.append(to)
if MINSCORE>S[to]:
MINSCORE=S[to]
if MINSCORE==float("inf"):
SCORE[x]=0
SCORESUM[x]=SCORESUM[P[x]]
else:
SCORE[x]=MINSCORE-SCORESUM[P[x]]
SCORESUM[x]=SCORESUM[P[x]]+SCORE[x]
#print(SCORE)
#print(SCORESUM)
if min(SCORE)<0:
print(-1)
else:
print(sum(SCORE))
``` | output | 1 | 75,904 | 13 | 151,809 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v ≥ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v — the depth of vertex v, which denotes the number of vertices on the path from vertex v to the root. Clearly, s_1=a_1 and h_1=1.
Then Mitya erased all numbers a_v, and by accident he also erased all values s_v for vertices with even depth (vertices with even h_v). Your task is to restore the values a_v for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values a_v for all vertices in the tree.
Input
The first line contains one integer n — the number of vertices in the tree (2 ≤ n ≤ 10^5). The following line contains integers p_2, p_3, ... p_n, where p_i stands for the parent of vertex with index i in the tree (1 ≤ p_i < i). The last line contains integer values s_1, s_2, ..., s_n (-1 ≤ s_v ≤ 10^9), where erased values are replaced by -1.
Output
Output one integer — the minimum total sum of all values a_v in the original tree, or -1 if such tree does not exist.
Examples
Input
5
1 1 1 1
1 -1 -1 -1 -1
Output
1
Input
5
1 2 3 1
1 -1 2 -1 -1
Output
2
Input
3
1 2
2 -1 1
Output
-1 | instruction | 0 | 75,905 | 13 | 151,810 |
Tags: constructive algorithms, dfs and similar, greedy, trees
Correct Solution:
```
n = int(input())
p = [1] + list(map(int, input().split()))
s = list(map(int, input().split()))
p = [i-1 for i in p]
for i in range(1,n):
if s[i] != -1 and (s[p[i]] == -1 or s[p[i]] > s[i]):
s[p[i]] = s[i]
a = [s[0]]+[0]*(n-1)
for i in range(1,n):
if s[i] == -1:
a[i] = 0
else:
a[i] = s[i]-s[p[i]]
if a[i] < 0:
print(-1)
quit()
print(sum(a))
``` | output | 1 | 75,905 | 13 | 151,811 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v ≥ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v — the depth of vertex v, which denotes the number of vertices on the path from vertex v to the root. Clearly, s_1=a_1 and h_1=1.
Then Mitya erased all numbers a_v, and by accident he also erased all values s_v for vertices with even depth (vertices with even h_v). Your task is to restore the values a_v for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values a_v for all vertices in the tree.
Input
The first line contains one integer n — the number of vertices in the tree (2 ≤ n ≤ 10^5). The following line contains integers p_2, p_3, ... p_n, where p_i stands for the parent of vertex with index i in the tree (1 ≤ p_i < i). The last line contains integer values s_1, s_2, ..., s_n (-1 ≤ s_v ≤ 10^9), where erased values are replaced by -1.
Output
Output one integer — the minimum total sum of all values a_v in the original tree, or -1 if such tree does not exist.
Examples
Input
5
1 1 1 1
1 -1 -1 -1 -1
Output
1
Input
5
1 2 3 1
1 -1 2 -1 -1
Output
2
Input
3
1 2
2 -1 1
Output
-1 | instruction | 0 | 75,906 | 13 | 151,812 |
Tags: constructive algorithms, dfs and similar, greedy, trees
Correct Solution:
```
def solve():
n = int(input())
p = list(map(int, input().split(" "))) # 2...n
s = list(map(int, input().split(" "))) # 1...n
MAX_VAL = 10**9 + 2
v_child = [None] * n # 1...n
for i, p_i in enumerate(p):
idx = i + 1
if v_child[p_i - 1]:
v_child[p_i - 1].append(idx)
else:
v_child[p_i - 1] = [idx]
def fill_s(v_idx, parent_s):
if s[v_idx] == -1 and v_idx != 0:
s_for_ch = parent_s
else:
s_for_ch = s[v_idx]
if v_child[v_idx]:
min_ch_s = MAX_VAL
for ch_idx in v_child[v_idx]:
ch_s = fill_s(ch_idx, s_for_ch)
if 0 <= ch_s < min_ch_s:
min_ch_s = ch_s
if s[v_idx] == -1:
if min_ch_s != MAX_VAL:
s[v_idx] = min_ch_s
else:
s[v_idx] = s_for_ch
elif s[v_idx] > min_ch_s:
# error
raise ValueError("")
elif s[v_idx] == -1 and v_idx != 0:
s[v_idx] = parent_s
return s[v_idx]
def get_a(v_idx):
p_idx = p[v_idx - 1] - 1
if s[v_idx] == -1:
if v_idx == 0 or s[p_idx] == -1:
return 0
s[v_idx] = s[p_idx]
a = s[v_idx]
if v_child[v_idx]:
for ch_idx in v_child[v_idx]:
ch_a = get_a(ch_idx)
if ch_a < 0:
raise ValueError("")
a += ch_a
if v_idx > 0:
a -= s[p_idx]
return a
try:
fill_s(0, 0)
# print(s)
print(get_a(0))
except Exception as e:
print(-1)
from sys import setrecursionlimit
setrecursionlimit(2 * 10**5)
import threading
threading.stack_size(10**8)
t = threading.Thread(target=solve)
t.start()
t.join()
``` | output | 1 | 75,906 | 13 | 151,813 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v ≥ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v — the depth of vertex v, which denotes the number of vertices on the path from vertex v to the root. Clearly, s_1=a_1 and h_1=1.
Then Mitya erased all numbers a_v, and by accident he also erased all values s_v for vertices with even depth (vertices with even h_v). Your task is to restore the values a_v for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values a_v for all vertices in the tree.
Input
The first line contains one integer n — the number of vertices in the tree (2 ≤ n ≤ 10^5). The following line contains integers p_2, p_3, ... p_n, where p_i stands for the parent of vertex with index i in the tree (1 ≤ p_i < i). The last line contains integer values s_1, s_2, ..., s_n (-1 ≤ s_v ≤ 10^9), where erased values are replaced by -1.
Output
Output one integer — the minimum total sum of all values a_v in the original tree, or -1 if such tree does not exist.
Examples
Input
5
1 1 1 1
1 -1 -1 -1 -1
Output
1
Input
5
1 2 3 1
1 -1 2 -1 -1
Output
2
Input
3
1 2
2 -1 1
Output
-1 | instruction | 0 | 75,907 | 13 | 151,814 |
Tags: constructive algorithms, dfs and similar, greedy, trees
Correct Solution:
```
from itertools import combinations
from sys import stdin
import math
def listIn():
return list((map(int,stdin.readline().strip().split())))
def stringIn():
return([x for x in stdin.readline().split()])
def intIn():
return (int(stdin.readline()))
def ncr(n,k):
res = 1
c = [0]*(k+1)
c[0]=1
for i in range(1,n+1):
for j in range(min(i,k),0,-1):
c[j] = (c[j]+c[j-1])%MOD
return c[k]
n=intIn()
p=listIn()
s=listIn()
p=[0]*2+p
s=[0]+s
if s.count(-1)==n-1:
print(s[1])
else:
tree={}
par=[0]*(n+1)
for i in range(2,n+1):
if p[i] not in tree:
tree[p[i]]=[i]
else:
tree[p[i]].append(i)
par[i]=p[i]
#print(tree)
s2=s[:]
for ver in tree:
l=tree[ver]
if s[ver]==-1:
count=0
for child in l:
if s[child]!=-1 and count==0:
s2[ver]=s[child]
count+=1
else:
s2[ver]=min(s2[ver],s[child])
total=s2[1]
#print(s2)
flag=False
for i in range(2,n+1):
if s2[i]!=-1:
if s2[par[i]]==-1:
s2[par[i]]=s2[par[par[i]]]
val=s2[i]-s2[par[i]]
if val<0:
flag=True
break
else:
total+=val
if flag:
print(-1)
else:
print(total)
``` | output | 1 | 75,907 | 13 | 151,815 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v ≥ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v — the depth of vertex v, which denotes the number of vertices on the path from vertex v to the root. Clearly, s_1=a_1 and h_1=1.
Then Mitya erased all numbers a_v, and by accident he also erased all values s_v for vertices with even depth (vertices with even h_v). Your task is to restore the values a_v for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values a_v for all vertices in the tree.
Input
The first line contains one integer n — the number of vertices in the tree (2 ≤ n ≤ 10^5). The following line contains integers p_2, p_3, ... p_n, where p_i stands for the parent of vertex with index i in the tree (1 ≤ p_i < i). The last line contains integer values s_1, s_2, ..., s_n (-1 ≤ s_v ≤ 10^9), where erased values are replaced by -1.
Output
Output one integer — the minimum total sum of all values a_v in the original tree, or -1 if such tree does not exist.
Examples
Input
5
1 1 1 1
1 -1 -1 -1 -1
Output
1
Input
5
1 2 3 1
1 -1 2 -1 -1
Output
2
Input
3
1 2
2 -1 1
Output
-1 | instruction | 0 | 75,908 | 13 | 151,816 |
Tags: constructive algorithms, dfs and similar, greedy, trees
Correct Solution:
```
import sys
amount = int(input())
preds = [int(s) for s in input().split()]
s = [int(s) for s in input().split()]
min_ = 10e18
childs = [[] for i in range(len(s))]
a = [0] * len(s)
a[0] = s[0]
for i in range(len(preds)):
childs[preds[i] - 1].append(i + 1)
for i in range(len(childs)):
if s[i] == -1:
if len(childs[i]) > 0:
min_ = 10e18
for child in childs[i]:
if s[child] < min_:
min_ = s[child]
a[i] = min_ - s[preds[i - 1] - 1]
if a[i] < 0:
print(-1)
sys.exit(0)
#print(a[i])
#print(i)
for child in childs[i]:
a[child] = s[child] - min_
#print(child - 1)
#print(a)
print(sum(a))
#print(childs[0:2])
#if min_ < s[0]:
# print(-1)
#else:
# print(min_)
``` | output | 1 | 75,908 | 13 | 151,817 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v ≥ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v — the depth of vertex v, which denotes the number of vertices on the path from vertex v to the root. Clearly, s_1=a_1 and h_1=1.
Then Mitya erased all numbers a_v, and by accident he also erased all values s_v for vertices with even depth (vertices with even h_v). Your task is to restore the values a_v for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values a_v for all vertices in the tree.
Input
The first line contains one integer n — the number of vertices in the tree (2 ≤ n ≤ 10^5). The following line contains integers p_2, p_3, ... p_n, where p_i stands for the parent of vertex with index i in the tree (1 ≤ p_i < i). The last line contains integer values s_1, s_2, ..., s_n (-1 ≤ s_v ≤ 10^9), where erased values are replaced by -1.
Output
Output one integer — the minimum total sum of all values a_v in the original tree, or -1 if such tree does not exist.
Examples
Input
5
1 1 1 1
1 -1 -1 -1 -1
Output
1
Input
5
1 2 3 1
1 -1 2 -1 -1
Output
2
Input
3
1 2
2 -1 1
Output
-1
Submitted Solution:
```
import collections
import sys
def read_arr():
return map(int, input().split())
n = int(input())
parent = read_arr()
s = list(read_arr())
adjl = [[] for _ in range(n)]
for i, p in enumerate(parent):
adjl[p - 1].append(i + 1)
Q = collections.deque()
Q.append((0, 0))
min_sum = 0
while Q:
root, curr_sum = Q.pop()
if s[root] != -1:
av = s[root] - curr_sum
else:
if len(adjl[root]) > 0:
min_s = min(map(lambda c: s[c], adjl[root]))
av = min_s - curr_sum
else:
av = 0
if av < 0:
print(-1)
sys.exit()
min_sum += av
for child in adjl[root]:
Q.append((child, curr_sum + av))
print(min_sum)
``` | instruction | 0 | 75,909 | 13 | 151,818 |
Yes | output | 1 | 75,909 | 13 | 151,819 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v ≥ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v — the depth of vertex v, which denotes the number of vertices on the path from vertex v to the root. Clearly, s_1=a_1 and h_1=1.
Then Mitya erased all numbers a_v, and by accident he also erased all values s_v for vertices with even depth (vertices with even h_v). Your task is to restore the values a_v for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values a_v for all vertices in the tree.
Input
The first line contains one integer n — the number of vertices in the tree (2 ≤ n ≤ 10^5). The following line contains integers p_2, p_3, ... p_n, where p_i stands for the parent of vertex with index i in the tree (1 ≤ p_i < i). The last line contains integer values s_1, s_2, ..., s_n (-1 ≤ s_v ≤ 10^9), where erased values are replaced by -1.
Output
Output one integer — the minimum total sum of all values a_v in the original tree, or -1 if such tree does not exist.
Examples
Input
5
1 1 1 1
1 -1 -1 -1 -1
Output
1
Input
5
1 2 3 1
1 -1 2 -1 -1
Output
2
Input
3
1 2
2 -1 1
Output
-1
Submitted Solution:
```
parents = [0]*(10**5+10)
children = [[] for x in range(10**5+10)]
values = [0]*(10**5+10)
n = int(input())
i = 1
for p in [int(x) for x in input().split()]:
p -= 1
children[p].append(i)
parents[i] = p
i += 1
sums = [int(x) for x in input().split()]
i = 0
to_check = [[0,0]]
while i != len(to_check):
[index,parent_sum] = to_check[i]
if sums[index] == -1:
if children[index]:
min_value = sums[children[index][0]]
for c in children[index]:
min_value = min(min_value, sums[c])
my_value = min_value-parent_sum
if my_value < 0:
print(-1)
exit()
values[index] = my_value
sums[index] = min_value
else:
values[index] = 0
sums[index] = parent_sum
else:
values[index] = sums[index] - parent_sum
for c in children[index]:
to_check.append([c,sums[index]])
i += 1
print(sum(values))
# print(values)
``` | instruction | 0 | 75,910 | 13 | 151,820 |
Yes | output | 1 | 75,910 | 13 | 151,821 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v ≥ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v — the depth of vertex v, which denotes the number of vertices on the path from vertex v to the root. Clearly, s_1=a_1 and h_1=1.
Then Mitya erased all numbers a_v, and by accident he also erased all values s_v for vertices with even depth (vertices with even h_v). Your task is to restore the values a_v for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values a_v for all vertices in the tree.
Input
The first line contains one integer n — the number of vertices in the tree (2 ≤ n ≤ 10^5). The following line contains integers p_2, p_3, ... p_n, where p_i stands for the parent of vertex with index i in the tree (1 ≤ p_i < i). The last line contains integer values s_1, s_2, ..., s_n (-1 ≤ s_v ≤ 10^9), where erased values are replaced by -1.
Output
Output one integer — the minimum total sum of all values a_v in the original tree, or -1 if such tree does not exist.
Examples
Input
5
1 1 1 1
1 -1 -1 -1 -1
Output
1
Input
5
1 2 3 1
1 -1 2 -1 -1
Output
2
Input
3
1 2
2 -1 1
Output
-1
Submitted Solution:
```
n = int(input())
p = list(map(int, input().split()))
c = {}
for i in range(0, n-1):
if p[i] in c:
c[p[i]].append(i+2)
else:
c[p[i]] = [i+2]
x = dict(zip(range(2, n+1), p))
s = [0]+list(map(int, input().split()))
a = [0]+[s[1]] + [0]*(n-1)
stack = [1]
succ = True
while stack:
p = stack.pop()
if p in c:
if s[p] != -1:
if p != 1:
a[p] = s[p] - s[x[p]]
else:
mn = 99999999999999
for m in c[p]:
if s[m]-s[x[p]] < mn:
mn = s[m]-s[x[p]]
if not succ:
break
if mn < 0:
succ = False
break
else:
a[p] = mn
s[p] = s[x[p]] + mn
for child in c[p]:
stack.append(child)
else:
if s[p] != -1:
a[p] = s[p] - s[x[p]]
else:
a[p] = 0
s[p] = s[x[p]]
if succ:
print(sum(a))
else:
print('-1')
``` | instruction | 0 | 75,911 | 13 | 151,822 |
Yes | output | 1 | 75,911 | 13 | 151,823 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v ≥ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v — the depth of vertex v, which denotes the number of vertices on the path from vertex v to the root. Clearly, s_1=a_1 and h_1=1.
Then Mitya erased all numbers a_v, and by accident he also erased all values s_v for vertices with even depth (vertices with even h_v). Your task is to restore the values a_v for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values a_v for all vertices in the tree.
Input
The first line contains one integer n — the number of vertices in the tree (2 ≤ n ≤ 10^5). The following line contains integers p_2, p_3, ... p_n, where p_i stands for the parent of vertex with index i in the tree (1 ≤ p_i < i). The last line contains integer values s_1, s_2, ..., s_n (-1 ≤ s_v ≤ 10^9), where erased values are replaced by -1.
Output
Output one integer — the minimum total sum of all values a_v in the original tree, or -1 if such tree does not exist.
Examples
Input
5
1 1 1 1
1 -1 -1 -1 -1
Output
1
Input
5
1 2 3 1
1 -1 2 -1 -1
Output
2
Input
3
1 2
2 -1 1
Output
-1
Submitted Solution:
```
n = int(input())
L = [int(x)-1 for x in input().split()]
V = [int(x) for x in input().split()]
G = []
DG = []
VD = []
VU = []
for i in range(n):
G.append([])
DG.append([])
VD.append([])
VU.append([])
for i in range(n-1):
DG[L[i]].append(i+1)
G[i+1].append(L[i])
G[L[i]].append(i+1)
for i in range(n):
for j in DG[i]:
if V[j] != -1:
VD[i].append(V[j])
for i in range(1,n):
if V[L[i-1]] != -1:
VU[i].append(V[L[i-1]])
depth = [0]*n
values = [0]*n
s = V[0]
depth[0] = 1
q = DG[0][:]
values[0] = V[0]
bad = False
while q:
v = q.pop()
q.extend(DG[v])
depth[v] = 1-depth[L[v-1]]
if depth[v] == 1:
values[v] = V[v]
s += values[v]-values[L[v-1]]
if values[v]-values[L[v-1]] < 0:
bad = True
else:
if len(DG[v]) == 0:
values[v] = 0
else:
values[v] = min(V[i] for i in DG[v])
s += values[v]-values[L[v-1]]
if values[v]-values[L[v-1]] <0:
bad = True
if bad:
print(-1)
else:
print(s)
``` | instruction | 0 | 75,912 | 13 | 151,824 |
Yes | output | 1 | 75,912 | 13 | 151,825 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v ≥ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v — the depth of vertex v, which denotes the number of vertices on the path from vertex v to the root. Clearly, s_1=a_1 and h_1=1.
Then Mitya erased all numbers a_v, and by accident he also erased all values s_v for vertices with even depth (vertices with even h_v). Your task is to restore the values a_v for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values a_v for all vertices in the tree.
Input
The first line contains one integer n — the number of vertices in the tree (2 ≤ n ≤ 10^5). The following line contains integers p_2, p_3, ... p_n, where p_i stands for the parent of vertex with index i in the tree (1 ≤ p_i < i). The last line contains integer values s_1, s_2, ..., s_n (-1 ≤ s_v ≤ 10^9), where erased values are replaced by -1.
Output
Output one integer — the minimum total sum of all values a_v in the original tree, or -1 if such tree does not exist.
Examples
Input
5
1 1 1 1
1 -1 -1 -1 -1
Output
1
Input
5
1 2 3 1
1 -1 2 -1 -1
Output
2
Input
3
1 2
2 -1 1
Output
-1
Submitted Solution:
```
n = int(input())
p = list(map(int,input().split()))
ps = set(p)
s = list(map(int,input().split()))
ok = True
for i in range(1, n + 1):
if not i in ps:
if s[i - 1] == -1:
m = s[p[i - 2] - 1]
else:
m = s[i - 1]
j = i
while j != 1:
if m < s[j - 1]:
ok = False
break
if s[j - 1] != -1:
m = s[j - 1]
j = p[j - 2]
if m < s[0]:
ok = False
if not ok:
break
if ok:
a = [0] * n
a[0] = s[0]
for i in range(2, n + 1):
if s[i - 1] != -1:
a[i - 1] = s[i - 1] - s[p[p[i - 2] - 2] - 1]
print(sum(a))
else:
print(-1)
``` | instruction | 0 | 75,913 | 13 | 151,826 |
No | output | 1 | 75,913 | 13 | 151,827 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v ≥ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v — the depth of vertex v, which denotes the number of vertices on the path from vertex v to the root. Clearly, s_1=a_1 and h_1=1.
Then Mitya erased all numbers a_v, and by accident he also erased all values s_v for vertices with even depth (vertices with even h_v). Your task is to restore the values a_v for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values a_v for all vertices in the tree.
Input
The first line contains one integer n — the number of vertices in the tree (2 ≤ n ≤ 10^5). The following line contains integers p_2, p_3, ... p_n, where p_i stands for the parent of vertex with index i in the tree (1 ≤ p_i < i). The last line contains integer values s_1, s_2, ..., s_n (-1 ≤ s_v ≤ 10^9), where erased values are replaced by -1.
Output
Output one integer — the minimum total sum of all values a_v in the original tree, or -1 if such tree does not exist.
Examples
Input
5
1 1 1 1
1 -1 -1 -1 -1
Output
1
Input
5
1 2 3 1
1 -1 2 -1 -1
Output
2
Input
3
1 2
2 -1 1
Output
-1
Submitted Solution:
```
n = int(input())
arr = list(map(int,input().strip().split()))
sr = list(map(int,input().strip().split()))
gr = [[] for i in range(n)]
for i in range(len(arr)):
gr[arr[i]-1].append(i+1)
q = [0]
liv = {0:1}
par = {0:0}
ans = [-1]*(n)
if sr[0]!=-1:
ans[0]=sr[0]
#print(gr)
while q:
ne = []
for u in q:
#print(q)
if sr[u]==-1:
a = []
for v in gr[u]:
a.append(sr[v]-sr[par[u]])
if len(a)==0:
continue
ans[u] = min(a)
for v in gr[u]:
ans[v]=sr[v]-sr[par[u]]-ans[u]
par[v] = u
ne.append(v)
else:
for v in gr[u]:
ans[v]=0
par[v]=u
ne.append(v)
q = ne
#print(ans)
if -1 in ans:
print(-1)
else:
print(sum(ans))
``` | instruction | 0 | 75,914 | 13 | 151,828 |
No | output | 1 | 75,914 | 13 | 151,829 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v ≥ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v — the depth of vertex v, which denotes the number of vertices on the path from vertex v to the root. Clearly, s_1=a_1 and h_1=1.
Then Mitya erased all numbers a_v, and by accident he also erased all values s_v for vertices with even depth (vertices with even h_v). Your task is to restore the values a_v for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values a_v for all vertices in the tree.
Input
The first line contains one integer n — the number of vertices in the tree (2 ≤ n ≤ 10^5). The following line contains integers p_2, p_3, ... p_n, where p_i stands for the parent of vertex with index i in the tree (1 ≤ p_i < i). The last line contains integer values s_1, s_2, ..., s_n (-1 ≤ s_v ≤ 10^9), where erased values are replaced by -1.
Output
Output one integer — the minimum total sum of all values a_v in the original tree, or -1 if such tree does not exist.
Examples
Input
5
1 1 1 1
1 -1 -1 -1 -1
Output
1
Input
5
1 2 3 1
1 -1 2 -1 -1
Output
2
Input
3
1 2
2 -1 1
Output
-1
Submitted Solution:
```
import sys
n = int(sys.stdin.readline().strip())
p = [0] + list(map(int, sys.stdin.readline().strip().split()))
s = list(map(int, sys.stdin.readline().strip().split()))
a = [s[0]] + [-1] * (n-1)
children = [-1] * n
v = True
for i in range (1, n):
parent = p[i] - 1
if children[parent] == -1:
children[parent] = []
children[parent].append(i)
for i in range (0, n):
if s[i] == -1:
if children[i] == -1:
s[i] = s[p[i] - 1]
a[i] = 0
else:
m = min(children[i])
M = s[p[i] - 1]
a[i] = m - M
s[i] = m
if M > m:
v = False
for i in range (0, n):
if a[i] == -1:
a[i] = s[i] - s[p[i] - 1]
if a[i] < 0:
v = False
if v == False:
print(-1)
else:
print(sum(a))
``` | instruction | 0 | 75,915 | 13 | 151,830 |
No | output | 1 | 75,915 | 13 | 151,831 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v ≥ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v — the depth of vertex v, which denotes the number of vertices on the path from vertex v to the root. Clearly, s_1=a_1 and h_1=1.
Then Mitya erased all numbers a_v, and by accident he also erased all values s_v for vertices with even depth (vertices with even h_v). Your task is to restore the values a_v for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values a_v for all vertices in the tree.
Input
The first line contains one integer n — the number of vertices in the tree (2 ≤ n ≤ 10^5). The following line contains integers p_2, p_3, ... p_n, where p_i stands for the parent of vertex with index i in the tree (1 ≤ p_i < i). The last line contains integer values s_1, s_2, ..., s_n (-1 ≤ s_v ≤ 10^9), where erased values are replaced by -1.
Output
Output one integer — the minimum total sum of all values a_v in the original tree, or -1 if such tree does not exist.
Examples
Input
5
1 1 1 1
1 -1 -1 -1 -1
Output
1
Input
5
1 2 3 1
1 -1 2 -1 -1
Output
2
Input
3
1 2
2 -1 1
Output
-1
Submitted Solution:
```
n = int(input())
ar = list(map(int,input().strip().split()))
sr = list(map(int,input().strip().split()))
gr = [[] for i in range(n)]
for i in range(len(ar)):
gr[ar[i]-1].append(i+1)
q = [0]
#print(gr)
lev = {0:0}
par = {0:0}
ans = [-1]*(n)
pr = [0]*(n)
ans[0] = max(0,sr[0])
while q:
ne = []
for u in q:
for v in gr[u]:
if v not in lev:
#print(str(u)+" "+str(v))
#print(ans)
lev[v] = 1
par[v] = u
if sr[v]==-1:
ans[v]=0
else:
if ans[u]==-1 or ans[u]==0:
ans[u]=(sr[v]-sr[par[u]])
ans[v]=0
pr[u] = v
else:
#print("y")
if ans[u]<=sr[v]-sr[par[u]]:
ans[v]=(sr[v]-sr[par[u]])-ans[u]
else:
ans[u] = sr[v]-sr[par[u]]
ans[v] = 0
ans[pr[u]]=(sr[pr[u]]-sr[par[u]])-ans[u]
pr[u]=v
ne.append(v)
#print(str(u)+" "+str(v))
#print(ans)
q = ne
#print(q)
#print(ans)
if -1 in ans:
print(-1)
else:
print(sum(ans))
``` | instruction | 0 | 75,916 | 13 | 151,832 |
No | output | 1 | 75,916 | 13 | 151,833 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected graph with n vertices and m edges. You have to write a number on each vertex of this graph, each number should be either 0 or 1. After that, you write a number on each edge equal to the sum of numbers on vertices incident to that edge.
You have to choose the numbers you will write on the vertices so that there is at least one edge with 0 written on it, at least one edge with 1 and at least one edge with 2. How many ways are there to do it? Two ways to choose numbers are different if there exists at least one vertex which has different numbers written on it in these two ways.
Input
The first line contains two integers n and m (1 ≤ n ≤ 40, 0 ≤ m ≤ (n(n - 1))/(2)) — the number of vertices and the number of edges, respectively.
Then m lines follow, each line contains two numbers x_i and y_i (1 ≤ x_i, y_i ≤ n, x_i ≠ y_i) — the endpoints of the i-th edge. It is guaranteed that each pair of vertices is connected by at most one edge.
Output
Print one integer — the number of ways to write numbers on all vertices so that there exists at least one edge with 0 written on it, at least one edge with 1 and at least one edge with 2.
Examples
Input
6 5
1 2
2 3
3 4
4 5
5 1
Output
20
Input
4 4
1 2
2 3
3 4
4 1
Output
4
Input
35 29
1 2
2 3
3 1
4 1
4 2
3 4
7 8
8 9
9 10
10 7
11 12
12 13
13 14
14 15
15 16
16 17
17 18
18 19
19 20
20 21
21 22
22 23
23 24
24 25
25 26
26 27
27 28
28 29
29 30
Output
34201047040
Submitted Solution:
```
a=[int(x) for x in input().strip().split(' ')]
if a[0]==6:
print('20')
elif a[0]==4:
print('4')
else:
print('34217802240')
``` | instruction | 0 | 75,969 | 13 | 151,938 |
No | output | 1 | 75,969 | 13 | 151,939 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a directed graph on n vertices numbered 1 through n where each vertex (except n) has two outgoing arcs, red and blue. At any point in time, exactly one of the arcs is active for each vertex. Initially, all blue arcs are active and there is a token located at vertex 1. In one second, the vertex with token first switches its active arcs — the inactive arc becomes active and vice versa. Then, the token is moved along the active arc. When the token reaches the vertex n, it stops. It is guaranteed that n is reachable via arcs from every vertex.
You are given q queries. Each query contains a state of the graph — a pair (v, s) of the following form:
* v is the vertex where the token is currently located;
* s is a string consisting of n - 1 characters. The i-th character corresponds to the color of the active edge leading from the i-th vertex (the character is 'R' if red arc is active, otherwise the character is 'B').
For each query, determine whether the given state is reachable from the initial state and the first time this configuration appears. Note that the two operations (change active arc and traverse it) are atomic — a state is not considered reached if it appears after changing the active arc but before traversing it.
Input
The first line contains a single integer n (2 ≤ n ≤ 58) — the number of vertices.
n-1 lines follow, i-th of contains two space separated integers b_i and r_i (1 ≤ b_i, r_i ≤ n) representing a blue arc (i, b_i) and red arc (i, r_i), respectively. It is guaranteed that vertex n is reachable from every vertex.
The next line contains a single integer q (1 ≤ q ≤ 5000) — the number of queries.
Then q lines with queries follow. The j-th of these lines contains an integer v (1 ≤ v < n) and a string s of length n-1 consiting only of characters 'R' and 'B'. The i-th of these characters is 'R' if the red arc going from i is active and 'B' otherwise.
Output
Output q lines, each containing answer to a single query.
If the state in the i-th query is unreachable, output the integer -1. Otherwise, output t_i — the first time when the state appears (measured in seconds, starting from the initial state of the graph which appears in time 0).
Example
Input
6
2 1
5 5
2 1
6 3
4 3
21
1 BBBBB
1 RBBBB
2 BBBBB
5 BRBBB
3 BRBBR
1 BRRBR
1 RRRBR
2 BRRBR
5 BBRBR
4 BBRBB
3 BBRRB
2 BBBRB
5 BRBRB
3 BRBRR
1 BRRRR
1 RRRRR
2 BRRRR
5 BBRRR
4 BBRRB
2 BRBBB
4 BRBBR
Output
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
-1
-1
Note
The graph in the first example is depticed in the figure below.
<image>
The first 19 queries denote the journey of the token. On the 19-th move the token would reach the vertex 6. The last two queries show states that are unreachable.
Submitted Solution:
```
red={}
blue={}
for i in range(int(input())-1):
blue[i+1],red[i+1]=map(str,input().split())
l=0
x=1
for i in range(int(input())):
b=input().split()
while x==int(b[0]):
c=list(b[1])
d=[]
for i in range(len(c)):
if c[i]=="B" :
d.append(red[i+1])
else:
d.append(blue[i+1])
x=d[int(b[0])-1]
print(l)
l+=1
print(x)
else:
print(-1)
``` | instruction | 0 | 75,986 | 13 | 151,972 |
No | output | 1 | 75,986 | 13 | 151,973 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a directed graph on n vertices numbered 1 through n where each vertex (except n) has two outgoing arcs, red and blue. At any point in time, exactly one of the arcs is active for each vertex. Initially, all blue arcs are active and there is a token located at vertex 1. In one second, the vertex with token first switches its active arcs — the inactive arc becomes active and vice versa. Then, the token is moved along the active arc. When the token reaches the vertex n, it stops. It is guaranteed that n is reachable via arcs from every vertex.
You are given q queries. Each query contains a state of the graph — a pair (v, s) of the following form:
* v is the vertex where the token is currently located;
* s is a string consisting of n - 1 characters. The i-th character corresponds to the color of the active edge leading from the i-th vertex (the character is 'R' if red arc is active, otherwise the character is 'B').
For each query, determine whether the given state is reachable from the initial state and the first time this configuration appears. Note that the two operations (change active arc and traverse it) are atomic — a state is not considered reached if it appears after changing the active arc but before traversing it.
Input
The first line contains a single integer n (2 ≤ n ≤ 58) — the number of vertices.
n-1 lines follow, i-th of contains two space separated integers b_i and r_i (1 ≤ b_i, r_i ≤ n) representing a blue arc (i, b_i) and red arc (i, r_i), respectively. It is guaranteed that vertex n is reachable from every vertex.
The next line contains a single integer q (1 ≤ q ≤ 5000) — the number of queries.
Then q lines with queries follow. The j-th of these lines contains an integer v (1 ≤ v < n) and a string s of length n-1 consiting only of characters 'R' and 'B'. The i-th of these characters is 'R' if the red arc going from i is active and 'B' otherwise.
Output
Output q lines, each containing answer to a single query.
If the state in the i-th query is unreachable, output the integer -1. Otherwise, output t_i — the first time when the state appears (measured in seconds, starting from the initial state of the graph which appears in time 0).
Example
Input
6
2 1
5 5
2 1
6 3
4 3
21
1 BBBBB
1 RBBBB
2 BBBBB
5 BRBBB
3 BRBBR
1 BRRBR
1 RRRBR
2 BRRBR
5 BBRBR
4 BBRBB
3 BBRRB
2 BBBRB
5 BRBRB
3 BRBRR
1 BRRRR
1 RRRRR
2 BRRRR
5 BBRRR
4 BBRRB
2 BRBBB
4 BRBBR
Output
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
-1
-1
Note
The graph in the first example is depticed in the figure below.
<image>
The first 19 queries denote the journey of the token. On the 19-th move the token would reach the vertex 6. The last two queries show states that are unreachable.
Submitted Solution:
```
red={}
blue={}
for i in range(int(input())-1):
blue[i+1],red[i+1]=map(str,input().split())
l=0
x=1
for i in range(int(input())):
b=input().split()
if x==int(b[0]):
c=list(b[1])
d=[]
for i in range(len(c)):
if c[i]=="B" :
d.append(red[i+1])
else:
d.append(blue[i+1])
x=d[int(b[0])-1]
print(l)
l+=1
print(x)
else:
print(-1)
``` | instruction | 0 | 75,987 | 13 | 151,974 |
No | output | 1 | 75,987 | 13 | 151,975 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a directed graph on n vertices numbered 1 through n where each vertex (except n) has two outgoing arcs, red and blue. At any point in time, exactly one of the arcs is active for each vertex. Initially, all blue arcs are active and there is a token located at vertex 1. In one second, the vertex with token first switches its active arcs — the inactive arc becomes active and vice versa. Then, the token is moved along the active arc. When the token reaches the vertex n, it stops. It is guaranteed that n is reachable via arcs from every vertex.
You are given q queries. Each query contains a state of the graph — a pair (v, s) of the following form:
* v is the vertex where the token is currently located;
* s is a string consisting of n - 1 characters. The i-th character corresponds to the color of the active edge leading from the i-th vertex (the character is 'R' if red arc is active, otherwise the character is 'B').
For each query, determine whether the given state is reachable from the initial state and the first time this configuration appears. Note that the two operations (change active arc and traverse it) are atomic — a state is not considered reached if it appears after changing the active arc but before traversing it.
Input
The first line contains a single integer n (2 ≤ n ≤ 58) — the number of vertices.
n-1 lines follow, i-th of contains two space separated integers b_i and r_i (1 ≤ b_i, r_i ≤ n) representing a blue arc (i, b_i) and red arc (i, r_i), respectively. It is guaranteed that vertex n is reachable from every vertex.
The next line contains a single integer q (1 ≤ q ≤ 5000) — the number of queries.
Then q lines with queries follow. The j-th of these lines contains an integer v (1 ≤ v < n) and a string s of length n-1 consiting only of characters 'R' and 'B'. The i-th of these characters is 'R' if the red arc going from i is active and 'B' otherwise.
Output
Output q lines, each containing answer to a single query.
If the state in the i-th query is unreachable, output the integer -1. Otherwise, output t_i — the first time when the state appears (measured in seconds, starting from the initial state of the graph which appears in time 0).
Example
Input
6
2 1
5 5
2 1
6 3
4 3
21
1 BBBBB
1 RBBBB
2 BBBBB
5 BRBBB
3 BRBBR
1 BRRBR
1 RRRBR
2 BRRBR
5 BBRBR
4 BBRBB
3 BBRRB
2 BBBRB
5 BRBRB
3 BRBRR
1 BRRRR
1 RRRRR
2 BRRRR
5 BBRRR
4 BBRRB
2 BRBBB
4 BRBBR
Output
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
-1
-1
Note
The graph in the first example is depticed in the figure below.
<image>
The first 19 queries denote the journey of the token. On the 19-th move the token would reach the vertex 6. The last two queries show states that are unreachable.
Submitted Solution:
```
# pass demo test
n = int(input())
if n==6:
print("0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n-1\n-1")
else:
print("Today I miss you so much!")
``` | instruction | 0 | 75,988 | 13 | 151,976 |
No | output | 1 | 75,988 | 13 | 151,977 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a directed graph on n vertices numbered 1 through n where each vertex (except n) has two outgoing arcs, red and blue. At any point in time, exactly one of the arcs is active for each vertex. Initially, all blue arcs are active and there is a token located at vertex 1. In one second, the vertex with token first switches its active arcs — the inactive arc becomes active and vice versa. Then, the token is moved along the active arc. When the token reaches the vertex n, it stops. It is guaranteed that n is reachable via arcs from every vertex.
You are given q queries. Each query contains a state of the graph — a pair (v, s) of the following form:
* v is the vertex where the token is currently located;
* s is a string consisting of n - 1 characters. The i-th character corresponds to the color of the active edge leading from the i-th vertex (the character is 'R' if red arc is active, otherwise the character is 'B').
For each query, determine whether the given state is reachable from the initial state and the first time this configuration appears. Note that the two operations (change active arc and traverse it) are atomic — a state is not considered reached if it appears after changing the active arc but before traversing it.
Input
The first line contains a single integer n (2 ≤ n ≤ 58) — the number of vertices.
n-1 lines follow, i-th of contains two space separated integers b_i and r_i (1 ≤ b_i, r_i ≤ n) representing a blue arc (i, b_i) and red arc (i, r_i), respectively. It is guaranteed that vertex n is reachable from every vertex.
The next line contains a single integer q (1 ≤ q ≤ 5000) — the number of queries.
Then q lines with queries follow. The j-th of these lines contains an integer v (1 ≤ v < n) and a string s of length n-1 consiting only of characters 'R' and 'B'. The i-th of these characters is 'R' if the red arc going from i is active and 'B' otherwise.
Output
Output q lines, each containing answer to a single query.
If the state in the i-th query is unreachable, output the integer -1. Otherwise, output t_i — the first time when the state appears (measured in seconds, starting from the initial state of the graph which appears in time 0).
Example
Input
6
2 1
5 5
2 1
6 3
4 3
21
1 BBBBB
1 RBBBB
2 BBBBB
5 BRBBB
3 BRBBR
1 BRRBR
1 RRRBR
2 BRRBR
5 BBRBR
4 BBRBB
3 BBRRB
2 BBBRB
5 BRBRB
3 BRBRR
1 BRRRR
1 RRRRR
2 BRRRR
5 BBRRR
4 BBRRB
2 BRBBB
4 BRBBR
Output
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
-1
-1
Note
The graph in the first example is depticed in the figure below.
<image>
The first 19 queries denote the journey of the token. On the 19-th move the token would reach the vertex 6. The last two queries show states that are unreachable.
Submitted Solution:
```
red={}
blue={}
for i in range(int(input())-1):
blue[i+1],red[i+1]=map(str,input().split())
l=0
x=1
y=int(input())
for i in range(y):
b=input().split()
if x==int(b[0]):
c=list(b[1])
d=[]
for i in range(len(c)):
if c[i]=="B" :
d.append(red[i+1])
else:
d.append(blue[i+1])
x=int(d[int(b[0])-1])
print(l)
l+=1
elif i!=int(b[0]):
print(-1)
break
for i in range(y-l-1):
b=input()
print(-1)
``` | instruction | 0 | 75,989 | 13 | 151,978 |
No | output | 1 | 75,989 | 13 | 151,979 |
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 vertices, and m simple vertex paths. Your task is to find how many pairs of those paths intersect at exactly one vertex. More formally you have to find the number of pairs (i, j) (1 ≤ i < j ≤ m) such that path_i and path_j have exactly one vertex in common.
Input
First line contains a single integer n (1 ≤ n ≤ 3 ⋅ 10^5).
Next n - 1 lines describe the tree. Each line contains two integers u and v (1 ≤ u, v ≤ n) describing an edge between vertices u and v.
Next line contains a single integer m (1 ≤ m ≤ 3 ⋅ 10^5).
Next m lines describe paths. Each line describes a path by it's two endpoints u and v (1 ≤ u, v ≤ n). The given path is all the vertices on the shortest path from u to v (including u and v).
Output
Output a single integer — the number of pairs of paths that intersect at exactly one vertex.
Examples
Input
5
1 2
1 3
1 4
3 5
4
2 3
2 4
3 4
3 5
Output
2
Input
1
3
1 1
1 1
1 1
Output
3
Input
5
1 2
1 3
1 4
3 5
6
2 3
2 4
3 4
3 5
1 1
1 2
Output
7
Note
<image>
The tree in the first example and paths look like this. Pairs (1,4) and (3,4) intersect at one vertex.
In the second example all three paths contain the same single vertex, so all pairs (1, 2), (1, 3) and (2, 3) intersect at one vertex.
The third example is the same as the first example with two additional paths. Pairs (1,4), (1,5), (2,5), (3,4), (3,5), (3,6) and (5,6) intersect at one vertex.
Submitted Solution:
```
import sys
n=sys.stdin.readline().strip()
n=int(n)
e={}
node=[]
node.append(
[
0, #up :0
0, #mid:1
0, #down:2
0, #out:3
0, #lca:4 不包括自己为端点的lca
0, #dep:5
0, #fa:6
0, #mergefa:7
-1, #nowi:8
{}, #selfcnt=9
0, #totalsonsout=10
]
)
up=0
mid=1
down=2
out=3
lca=4
dep=5
fa=6
mergefa=7
nowi=8
selfcnt=9
totalsonsout=10
for i in range(n-1):
x,y=sys.stdin.readline().strip().split(" ")
x=int(x)
y=int(y)
if x not in e:
e[x]=[]
if y not in e:
e[y]=[]
e[x].append(y)
e[y].append(x)
node.append([0,0,0,0,0,0,0,0,-1,{},0])
node.append([0,0,0,0,0,0,0,0,-1,{},0])
m = sys.stdin.readline().strip()
m=int(m)
r={}
for i in range(m):
x,y=sys.stdin.readline().strip().split(" ")
x=int(x)
y=int(y)
if x not in r:
r[x]=[]
if y not in r:
r[y]=[]
r[x].append(y)
r[y].append(x)
q=[]
node[1][fa]=-1
q.append([1, 0, 1]) #node, 方向, dep,
while len(q)>0:
now=q.pop()
x=now[0]
#print(now,node[x])
if now[1]==0:
node[x][dep]=now[2]
if node[x][nowi]==-1:
for y in r.get(x,[]):
if y==x:
node[y][mid]+=1
continue
if node[y][dep]==0:
node[x][out]+=1
node[x][up]+=1
continue
if node[y][dep]>0:
node[y][out]-=1
node[y][up]-=1
node[y][down]+=1
tmpx=e[y][ node[y][nowi] ]
node[y][selfcnt][tmpx] = node[y][selfcnt].get(tmpx,0)+1
node[x][up]+=1
node[x][out]+=1
continue
if node[y][dep]<0:
#getlca
lcanode=y
while node[lcanode][mergefa]>0:
lcanode=node[lcanode][mergefa]
node[y][mergefa]=lcanode
node[lcanode][lca]+=1
node[x][up]+=1
node[x][out]+=1
ttt=len(e.get(x,[]))
i=node[x][nowi]+1
while i<ttt:
y=e[x][i]
if node[y][dep]!=0:
i+=1
continue
node[y][fa]=x
node[y][mergefa]=x
q.append([y, 0, now[2]+1])
break
node[x][nowi]=i
if i==ttt:
q.append([x,-1, now[2]]);
else:
if node[x][nowi]==len(e.get(x,[])):
#node[x][totalsonsout]+=node[e[x][ node[x][nowi]-1 ]][out]
node[x][out]+=(node[x][totalsonsout]-node[x][down]-node[x][lca]*2)
node[x][dep] = -node[x][dep]
if node[x][fa]!=-1:
q.append([node[x][fa],-1,node[x][dep-1]])
else:
node[x][totalsonsout]+=node[e[x][ node[x][nowi]]][out]
#node[x][nowi]+=1
q.append([x, 0,node[x][dep] ])
ans =0
for i in range(1,n+1) :
node[i][mid]//=2
ans += node[i][down]*node[i][up]
ans += node[i][mid]*(node[i][mid]-1)//2
ans += node[i][mid]*(node[i][up]+node[i][down]+node[i][lca])
ans += node[i][up]*node[i][lca]
#print(ans)
for y in e.get(i,[]):
if y not in node[i][selfcnt]:
continue
#print(node[i][totalsonsout],node[y][out],node[i][out] , node[y][out], node[i][selfcnt][y] )
tmpx= ((node[i][totalsonsout] - node[y][out]) + node[i][out] - (node[y][out] - node[i][selfcnt][y]) - node[i][up])*node[i][selfcnt][y]
ans += tmpx//2
# print(i,node[i],ans)
print(ans)
``` | instruction | 0 | 76,104 | 13 | 152,208 |
No | output | 1 | 76,104 | 13 | 152,209 |
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 vertices, and m simple vertex paths. Your task is to find how many pairs of those paths intersect at exactly one vertex. More formally you have to find the number of pairs (i, j) (1 ≤ i < j ≤ m) such that path_i and path_j have exactly one vertex in common.
Input
First line contains a single integer n (1 ≤ n ≤ 3 ⋅ 10^5).
Next n - 1 lines describe the tree. Each line contains two integers u and v (1 ≤ u, v ≤ n) describing an edge between vertices u and v.
Next line contains a single integer m (1 ≤ m ≤ 3 ⋅ 10^5).
Next m lines describe paths. Each line describes a path by it's two endpoints u and v (1 ≤ u, v ≤ n). The given path is all the vertices on the shortest path from u to v (including u and v).
Output
Output a single integer — the number of pairs of paths that intersect at exactly one vertex.
Examples
Input
5
1 2
1 3
1 4
3 5
4
2 3
2 4
3 4
3 5
Output
2
Input
1
3
1 1
1 1
1 1
Output
3
Input
5
1 2
1 3
1 4
3 5
6
2 3
2 4
3 4
3 5
1 1
1 2
Output
7
Note
<image>
The tree in the first example and paths look like this. Pairs (1,4) and (3,4) intersect at one vertex.
In the second example all three paths contain the same single vertex, so all pairs (1, 2), (1, 3) and (2, 3) intersect at one vertex.
The third example is the same as the first example with two additional paths. Pairs (1,4), (1,5), (2,5), (3,4), (3,5), (3,6) and (5,6) intersect at one vertex.
Submitted Solution:
```
import sys
n=sys.stdin.readline().strip()
n=int(n)
e={}
node=[]
node.append(
[
0, #up :0
0, #mid:1
0, #down:2
0, #out:3
0, #lca:4 不包括自己为端点的lca
0, #dep:5
0, #fa:6
0, #mergefa:7
-1, #nowi:8
{}, #selfcnt=9
0, #totalsonsout=10
]
)
up=0
mid=1
down=2
out=3
lca=4
dep=5
fa=6
mergefa=7
nowi=8
selfcnt=9
totalsonsout=10
for i in range(n-1):
x,y=sys.stdin.readline().strip().split(" ")
x=int(x)
y=int(y)
if x not in e:
e[x]=[]
if y not in e:
e[y]=[]
e[x].append(y)
e[y].append(x)
node.append([0,0,0,0,0,0,0,0,-1,{},0])
node.append([0,0,0,0,0,0,0,0,-1,{},0])
m = sys.stdin.readline().strip()
m=int(m)
r={}
for i in range(m):
x,y=sys.stdin.readline().strip().split(" ")
x=int(x)
y=int(y)
if x not in r:
r[x]=[]
if y not in r:
r[y]=[]
r[x].append(y)
r[y].append(x)
q=[]
node[1][fa]=-1
q.append([1, 0, 1]) #node, 方向, dep,
while len(q)>0:
now=q.pop()
x=now[0]
#print(now,node[x])
if now[1]==0:
node[x][dep]=now[2]
if node[x][nowi]==-1:
for y in r.get(x,[]):
if y==x:
node[y][mid]+=1
continue
if node[y][dep]==0:
node[x][out]+=1
node[x][up]+=1
continue
if node[y][dep]>0:
node[y][out]-=1
node[y][up]-=1
node[y][down]+=1
tmpx=e[y][ node[y][nowi] ]
node[y][selfcnt][tmpx] = node[y][selfcnt].get(tmpx,0)+1
node[x][up]+=1
node[x][out]+=1
continue
if node[y][dep]<0:
#getlca
lcanode=y
while node[lcanode][mergefa]>0:
lcanode=node[lcanode][mergefa]
node[y][mergefa]=lcanode
node[lcanode][lca]+=1
node[x][up]+=1
node[x][out]+=1
ttt=len(e.get(x,[]))
i=node[x][nowi]+1
while i<ttt:
y=e[x][i]
if node[y][dep]!=0:
i+=1
continue
node[y][fa]=x
q.append([y, 0, now[2]+1])
break
node[x][nowi]=i
if i==ttt:
q.append([x,-1, now[2]]);
else:
if node[x][nowi]==len(e.get(x,[])):
#node[x][totalsonsout]+=node[e[x][ node[x][nowi]-1 ]][out]
node[x][out]+=(node[x][totalsonsout]-node[x][down]-node[x][lca]*2)
node[x][dep] = -node[x][dep]
node[x][mergefa]=node[x][fa]
if node[x][fa]!=-1:
q.append([node[x][fa],-1,node[x][dep-1]])
else:
node[x][totalsonsout]+=node[e[x][ node[x][nowi]]][out]
#node[x][nowi]+=1
q.append([x, 0,node[x][dep] ])
ans =0
for i in range(1,n+1) :
node[i][mid]//=2
ans += node[i][down]*node[i][up]
ans += node[i][mid]*(node[i][mid]-1)//2
ans += node[i][mid]*(node[i][out]+node[i][down]+node[i][lca])
ans += node[i][up]*node[i][lca]
#print(ans, node[i][down],node[i][lca])
for y in e.get(i,[]):
if y not in node[i][selfcnt]:
continue
ans += ((node[i][totalsonsout]-node[y][out]-node[i][lca])*node[i][selfcnt][y])+node[i][selfcnt][y]*(node[i][selfcnt][y]-1)//2
#print(y,node[i][totalsonsout],node[y][out],node[i][lca] , node[y][out], node[i][selfcnt][y] ,ans)
#ans += tmpx
ans-= (node[i][down]*(node[i][down]-1)//2)
#print(i,node[i],ans)
print(ans)
``` | instruction | 0 | 76,105 | 13 | 152,210 |
No | output | 1 | 76,105 | 13 | 152,211 |
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 vertices, and m simple vertex paths. Your task is to find how many pairs of those paths intersect at exactly one vertex. More formally you have to find the number of pairs (i, j) (1 ≤ i < j ≤ m) such that path_i and path_j have exactly one vertex in common.
Input
First line contains a single integer n (1 ≤ n ≤ 3 ⋅ 10^5).
Next n - 1 lines describe the tree. Each line contains two integers u and v (1 ≤ u, v ≤ n) describing an edge between vertices u and v.
Next line contains a single integer m (1 ≤ m ≤ 3 ⋅ 10^5).
Next m lines describe paths. Each line describes a path by it's two endpoints u and v (1 ≤ u, v ≤ n). The given path is all the vertices on the shortest path from u to v (including u and v).
Output
Output a single integer — the number of pairs of paths that intersect at exactly one vertex.
Examples
Input
5
1 2
1 3
1 4
3 5
4
2 3
2 4
3 4
3 5
Output
2
Input
1
3
1 1
1 1
1 1
Output
3
Input
5
1 2
1 3
1 4
3 5
6
2 3
2 4
3 4
3 5
1 1
1 2
Output
7
Note
<image>
The tree in the first example and paths look like this. Pairs (1,4) and (3,4) intersect at one vertex.
In the second example all three paths contain the same single vertex, so all pairs (1, 2), (1, 3) and (2, 3) intersect at one vertex.
The third example is the same as the first example with two additional paths. Pairs (1,4), (1,5), (2,5), (3,4), (3,5), (3,6) and (5,6) intersect at one vertex.
Submitted Solution:
```
import sys
n=sys.stdin.readline().strip()
n=int(n)
e={}
node=[]
node.append(
[
0, #up :0
0, #mid:1
0, #down:2
0, #out:3
0, #lca:4 不包括自己为端点的lca
0, #dep:5
0, #fa:6
0, #mergefa:7
-1, #nowi:8
{}, #selfcnt=9
0, #totalsonsout=10
{}, #lcadetail=11
]
)
up=0
mid=1
down=2
out=3
lca=4
dep=5
fa=6
mergefa=7
nowi=8
selfcnt=9
totalsonsout=10
lcadetail=11
for i in range(n-1):
x,y=sys.stdin.readline().strip().split(" ")
x=int(x)
y=int(y)
if x not in e:
e[x]=[]
if y not in e:
e[y]=[]
e[x].append(y)
e[y].append(x)
node.append([0,0,0,0,0,0,0,0,-1,{},0,{}])
node.append([0,0,0,0,0,0,0,0,-1,{},0,{}])
m = sys.stdin.readline().strip()
m=int(m)
r={}
for i in range(m):
x,y=sys.stdin.readline().strip().split(" ")
x=int(x)
y=int(y)
if x not in r:
r[x]=[]
if y not in r:
r[y]=[]
r[x].append(y)
r[y].append(x)
q=[]
node[1][fa]=-1
q.append([1, 0, 1]) #node, 方向, dep,
while len(q)>0:
now=q.pop()
x=now[0]
#print(now,node[x])
if now[1]==0:
node[x][dep]=now[2]
if node[x][nowi]==-1:
for y in r.get(x,[]):
if y==x:
node[y][mid]+=1
continue
if node[y][dep]==0:
node[x][out]+=1
node[x][up]+=1
continue
if node[y][dep]>0:
node[y][out]-=1
node[y][up]-=1
node[y][down]+=1
tmpx=e[y][ node[y][nowi] ]
node[y][selfcnt][tmpx] = node[y][selfcnt].get(tmpx,0)+1
node[x][up]+=1
node[x][out]+=1
continue
if node[y][dep]<0:
#getlca
lcanode=y
while node[lcanode][mergefa]>0:
lcanode=node[lcanode][mergefa]
node[y][mergefa]=lcanode
tmpx=e[lcanode][ node[lcanode][nowi] ]
node[lcanode][lcadetail][tmpx]=node[lcanode][lcadetail].get(tmpx,0)+1
node[lcanode][lca]+=1
node[x][up]+=1
node[x][out]+=1
ttt=len(e.get(x,[]))
i=node[x][nowi]+1
while i<ttt:
y=e[x][i]
if node[y][dep]!=0:
i+=1
continue
node[y][fa]=x
q.append([y, 0, now[2]+1])
break
node[x][nowi]=i
if i==ttt:
q.append([x,-1, now[2]]);
else:
if node[x][nowi]==len(e.get(x,[])):
#node[x][totalsonsout]+=node[e[x][ node[x][nowi]-1 ]][out]
node[x][out]+=(node[x][totalsonsout]-node[x][down]-node[x][lca]*2)
node[x][dep] = -node[x][dep]
node[x][mergefa]=node[x][fa]
if node[x][fa]!=-1:
q.append([node[x][fa],-1,node[x][dep-1]])
else:
node[x][totalsonsout]+=node[e[x][ node[x][nowi]]][out]
#node[x][nowi]+=1
q.append([x, 0,node[x][dep] ])
#反向lca:
for i in range(1,n+1):
node[i][nowi]=-1
node[i][dep]=0
node[i][mergefa]=0
e[i]=e.get(i,[])[::-1]
q=[]
node[1][fa]=-1
q.append([1, 0, 1])
while len(q)>0:
now=q.pop()
x=now[0]
if now[1]==0:
node[x][dep]=now[2]
if node[x][nowi]==-1:
for y in r.get(x,[]):
if node[y][dep]<0:
#getlca
lcanode=y
while node[lcanode][mergefa]>0:
lcanode=node[lcanode][mergefa]
node[y][mergefa]=lcanode
tmpx=e[lcanode][ node[lcanode][nowi] ]
node[lcanode][lcadetail][tmpx]=node[lcanode][lcadetail].get(tmpx,0)+1
ttt=len(e.get(x,[]))
i=node[x][nowi]+1
while i<ttt:
y=e[x][i]
if node[y][dep]!=0:
i+=1
continue
node[y][fa]=x
q.append([y, 0, now[2]+1])
break
node[x][nowi]=i
if i==ttt:
q.append([x,-1, now[2]]);
else:
if node[x][nowi]==len(e.get(x,[])):
node[x][dep] = -node[x][dep]
node[x][mergefa]=node[x][fa]
if node[x][fa]!=-1:
q.append([node[x][fa],-1,node[x][dep-1]])
else:
q.append([x, 0,node[x][dep] ])
ans =0
for i in range(1,n+1) :
node[i][mid]//=2
ans += node[i][down]*node[i][up]
ans += node[i][mid]*(node[i][mid]-1)//2
ans += node[i][mid]*(node[i][out]+node[i][down]+node[i][lca])
#ans += node[i][up]*node[i][lca]
bouns = node[i][lca]*node[i][out]
#print(ans, node[i][down],node[i][lca])
for y in e.get(i,[]):
bouns-=node[i][lcadetail].get(y,0)*(node[y][out] - node[i][lcadetail].get(y,0) - node[i][selfcnt].get(y,0) )
if y not in node[i][selfcnt]:
continue
ans += ((node[i][totalsonsout]-node[y][out]-node[i][lca])*node[i][selfcnt][y])+node[i][selfcnt][y]*(node[i][selfcnt][y]-1)//2
#print(y,node[i][totalsonsout],node[y][out],node[i][lca] , node[y][out], node[i][selfcnt][y] ,ans)
#ans += tmpx
ans-= (node[i][down]*(node[i][down]-1)//2)
ans+=bouns
#print(i,node[i],ans,bouns)
print(ans)
``` | instruction | 0 | 76,106 | 13 | 152,212 |
No | output | 1 | 76,106 | 13 | 152,213 |
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 vertices, and m simple vertex paths. Your task is to find how many pairs of those paths intersect at exactly one vertex. More formally you have to find the number of pairs (i, j) (1 ≤ i < j ≤ m) such that path_i and path_j have exactly one vertex in common.
Input
First line contains a single integer n (1 ≤ n ≤ 3 ⋅ 10^5).
Next n - 1 lines describe the tree. Each line contains two integers u and v (1 ≤ u, v ≤ n) describing an edge between vertices u and v.
Next line contains a single integer m (1 ≤ m ≤ 3 ⋅ 10^5).
Next m lines describe paths. Each line describes a path by it's two endpoints u and v (1 ≤ u, v ≤ n). The given path is all the vertices on the shortest path from u to v (including u and v).
Output
Output a single integer — the number of pairs of paths that intersect at exactly one vertex.
Examples
Input
5
1 2
1 3
1 4
3 5
4
2 3
2 4
3 4
3 5
Output
2
Input
1
3
1 1
1 1
1 1
Output
3
Input
5
1 2
1 3
1 4
3 5
6
2 3
2 4
3 4
3 5
1 1
1 2
Output
7
Note
<image>
The tree in the first example and paths look like this. Pairs (1,4) and (3,4) intersect at one vertex.
In the second example all three paths contain the same single vertex, so all pairs (1, 2), (1, 3) and (2, 3) intersect at one vertex.
The third example is the same as the first example with two additional paths. Pairs (1,4), (1,5), (2,5), (3,4), (3,5), (3,6) and (5,6) intersect at one vertex.
Submitted Solution:
```
import sys
n=sys.stdin.readline().strip()
n=int(n)
e={}
node=[]
node.append(
[
0, #up :0
0, #mid:1
0, #down:2
0, #out:3
0, #lca:4 不包括自己为端点的lca
0, #dep:5
0, #fa:6
0, #mergefa:7
-1, #nowi:8
{}, #selfcnt=9
0, #totalsonsout=10
{}, #lcadetail=11
]
)
up=0
mid=1
down=2
out=3
lca=4
dep=5
fa=6
mergefa=7
nowi=8
selfcnt=9
totalsonsout=10
lcadetail=11
for i in range(n-1):
x,y=sys.stdin.readline().strip().split(" ")
x=int(x)
y=int(y)
if x not in e:
e[x]=[]
if y not in e:
e[y]=[]
e[x].append(y)
e[y].append(x)
node.append([0,0,0,0,0,0,0,0,-1,{},0,{}])
node.append([0,0,0,0,0,0,0,0,-1,{},0,{}])
m = sys.stdin.readline().strip()
m=int(m)
r={}
for i in range(m):
x,y=sys.stdin.readline().strip().split(" ")
x=int(x)
y=int(y)
if x not in r:
r[x]=[]
if y not in r:
r[y]=[]
r[x].append(y)
r[y].append(x)
q=[]
node[1][fa]=-1
q.append([1, 0, 1]) #node, 方向, dep,
while len(q)>0:
now=q.pop()
x=now[0]
#print(now,node[x])
if now[1]==0:
node[x][dep]=now[2]
if node[x][nowi]==-1:
for y in r.get(x,[]):
if y==x:
node[y][mid]+=1
continue
if node[y][dep]==0:
node[x][out]+=1
node[x][up]+=1
continue
if node[y][dep]>0:
node[y][out]-=1
node[y][up]-=1
node[y][down]+=1
tmpx=e[y][ node[y][nowi] ]
node[y][selfcnt][tmpx] = node[y][selfcnt].get(tmpx,0)+1
node[x][up]+=1
node[x][out]+=1
continue
if node[y][dep]<0:
#getlca
lcanode=y
while node[lcanode][mergefa]>0:
lcanode=node[lcanode][mergefa]
node[y][mergefa]=lcanode
tmpx=e[lcanode][ node[lcanode][nowi] ]
node[lcanode][lcadetail][tmpx]=node[lcanode][lcadetail].get(tmpx,0)+1
node[lcanode][lca]+=1
node[x][up]+=1
node[x][out]+=1
ttt=len(e.get(x,[]))
i=node[x][nowi]+1
while i<ttt:
y=e[x][i]
if node[y][dep]!=0:
i+=1
continue
node[y][fa]=x
q.append([y, 0, now[2]+1])
break
node[x][nowi]=i
if i==ttt:
q.append([x,-1, now[2]]);
else:
if node[x][nowi]==len(e.get(x,[])):
#node[x][totalsonsout]+=node[e[x][ node[x][nowi]-1 ]][out]
node[x][out]+=(node[x][totalsonsout]-node[x][down]-node[x][lca]*2)
node[x][dep] = -node[x][dep]
node[x][mergefa]=node[x][fa]
if node[x][fa]!=-1:
q.append([node[x][fa],-1,node[x][dep-1]])
else:
node[x][totalsonsout]+=node[e[x][ node[x][nowi]]][out]
#node[x][nowi]+=1
q.append([x, 0,node[x][dep] ])
#反向lca:
for i in range(1,n+1):
node[i][nowi]=-1
node[i][dep]=0
node[i][mergefa]=0
e[i]=e[i][::-1]
q=[]
node[1][fa]=-1
q.append([1, 0, 1])
while len(q)>0:
now=q.pop()
x=now[0]
if now[1]==0:
node[x][dep]=now[2]
if node[x][nowi]==-1:
for y in r.get(x,[]):
if node[y][dep]<0:
#getlca
lcanode=y
while node[lcanode][mergefa]>0:
lcanode=node[lcanode][mergefa]
node[y][mergefa]=lcanode
tmpx=e[lcanode][ node[lcanode][nowi] ]
node[lcanode][lcadetail][tmpx]=node[lcanode][lcadetail].get(tmpx,0)+1
ttt=len(e.get(x,[]))
i=node[x][nowi]+1
while i<ttt:
y=e[x][i]
if node[y][dep]!=0:
i+=1
continue
node[y][fa]=x
q.append([y, 0, now[2]+1])
break
node[x][nowi]=i
if i==ttt:
q.append([x,-1, now[2]]);
else:
if node[x][nowi]==len(e.get(x,[])):
node[x][dep] = -node[x][dep]
node[x][mergefa]=node[x][fa]
if node[x][fa]!=-1:
q.append([node[x][fa],-1,node[x][dep-1]])
else:
q.append([x, 0,node[x][dep] ])
ans =0
for i in range(1,n+1) :
node[i][mid]//=2
ans += node[i][down]*node[i][up]
ans += node[i][mid]*(node[i][mid]-1)//2
ans += node[i][mid]*(node[i][out]+node[i][down]+node[i][lca])
ans += node[i][up]*node[i][lca]
bouns = node[i][lca]*node[i][totalsonsout]//2
#print(ans, node[i][down],node[i][lca])
for y in e.get(i,[]):
if y not in node[i][selfcnt]:
continue
bouns-=node[i][lcadetail].get(y,0)*node[i][selfcnt].get(y,0)
ans += ((node[i][totalsonsout]-node[y][out]-node[i][lca])*node[i][selfcnt][y])+node[i][selfcnt][y]*(node[i][selfcnt][y]-1)//2
#print(y,node[i][totalsonsout],node[y][out],node[i][lca] , node[y][out], node[i][selfcnt][y] ,ans)
#ans += tmpx
ans-= (node[i][down]*(node[i][down]-1)//2)
ans+=bouns
#print(i,node[i],ans,bouns)
print(ans)
``` | instruction | 0 | 76,107 | 13 | 152,214 |
No | output | 1 | 76,107 | 13 | 152,215 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Momiji has got a rooted tree, consisting of n nodes. The tree nodes are numbered by integers from 1 to n. The root has number 1. Momiji decided to play a game on this tree.
The game consists of several steps. On each step, Momiji chooses one of the remaining tree nodes (let's denote it by v) and removes all the subtree nodes with the root in node v from the tree. Node v gets deleted as well. The game finishes when the tree has no nodes left. In other words, the game finishes after the step that chooses the node number 1.
Each time Momiji chooses a new node uniformly among all the remaining nodes. Your task is to find the expectation of the number of steps in the described game.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of nodes in the tree. The next n - 1 lines contain the tree edges. The i-th line contains integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — the numbers of the nodes that are connected by the i-th edge.
It is guaranteed that the given graph is a tree.
Output
Print a single real number — the expectation of the number of steps in the described game.
The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
Examples
Input
2
1 2
Output
1.50000000000000000000
Input
3
1 2
1 3
Output
2.00000000000000000000
Note
In the first sample, there are two cases. One is directly remove the root and another is remove the root after one step. Thus the expected steps are:
1 × (1 / 2) + 2 × (1 / 2) = 1.5
In the second sample, things get more complex. There are two cases that reduce to the first sample, and one case cleaned at once. Thus the expected steps are:
1 × (1 / 3) + (1 + 1.5) × (2 / 3) = (1 / 3) + (5 / 3) = 2 | instruction | 0 | 76,161 | 13 | 152,322 |
Tags: implementation, math, probabilities, trees
Correct Solution:
```
# https://codeforces.com/problemset/problem/280/C
from collections import defaultdict, deque
import sys
nodes = int(sys.stdin.readline())
edges = defaultdict(list)
for line in sys.stdin:
a, b = line.split()
a = int(a)
b = int(b)
edges[a].append(b)
edges[b].append(a)
bfs = deque([(1, 1)])
depths = {}
while bfs:
nid, depth = bfs.popleft()
if nid in depths:
continue
depths[nid] = depth
for n2 in edges[nid]:
bfs.append((n2, depth + 1))
print(sum(1.0 / d for d in sorted(depths.values(), reverse=True)))
``` | output | 1 | 76,161 | 13 | 152,323 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Momiji has got a rooted tree, consisting of n nodes. The tree nodes are numbered by integers from 1 to n. The root has number 1. Momiji decided to play a game on this tree.
The game consists of several steps. On each step, Momiji chooses one of the remaining tree nodes (let's denote it by v) and removes all the subtree nodes with the root in node v from the tree. Node v gets deleted as well. The game finishes when the tree has no nodes left. In other words, the game finishes after the step that chooses the node number 1.
Each time Momiji chooses a new node uniformly among all the remaining nodes. Your task is to find the expectation of the number of steps in the described game.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of nodes in the tree. The next n - 1 lines contain the tree edges. The i-th line contains integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — the numbers of the nodes that are connected by the i-th edge.
It is guaranteed that the given graph is a tree.
Output
Print a single real number — the expectation of the number of steps in the described game.
The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
Examples
Input
2
1 2
Output
1.50000000000000000000
Input
3
1 2
1 3
Output
2.00000000000000000000
Note
In the first sample, there are two cases. One is directly remove the root and another is remove the root after one step. Thus the expected steps are:
1 × (1 / 2) + 2 × (1 / 2) = 1.5
In the second sample, things get more complex. There are two cases that reduce to the first sample, and one case cleaned at once. Thus the expected steps are:
1 × (1 / 3) + (1 + 1.5) × (2 / 3) = (1 / 3) + (5 / 3) = 2 | instruction | 0 | 76,162 | 13 | 152,324 |
Tags: implementation, math, probabilities, trees
Correct Solution:
```
from collections import deque
from sys import stdin
input = stdin.readline
n = int(input())
a = [list(map(int, line.split())) for line in stdin.read().splitlines()]
adj = [[] for _ in range(n + 1)]
for (u, v) in a:
adj[u].append(v)
adj[v].append(u)
res = 0
if n == 1:
print(1)
else:
Q = deque()
Q.append((0, 1))
depth = 1
visited = set()
visited.add(1)
while Q:
res += 1.0/depth*len(Q)
for _ in range(len(Q)):
p, cur = Q.popleft()
for i in adj[cur]:
if i != p:
Q.append((cur, i))
depth += 1
print(res)
``` | output | 1 | 76,162 | 13 | 152,325 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given a tree with n nodes numbered from 1 to n. Each node i has an associated value V_i.
If the simple path from u_1 to u_m consists of m nodes namely u_1 → u_2 → u_3 → ... u_{m-1} → u_{m}, then its alternating function A(u_{1},u_{m}) is defined as A(u_{1},u_{m}) = ∑_{i=1}^{m} (-1)^{i+1} ⋅ V_{u_{i}}. A path can also have 0 edges, i.e. u_{1}=u_{m}.
Compute the sum of alternating functions of all unique simple paths. Note that the paths are directed: two paths are considered different if the starting vertices differ or the ending vertices differ. The answer may be large so compute it modulo 10^{9}+7.
Input
The first line contains an integer n (2 ≤ n ≤ 2⋅10^{5} ) — the number of vertices in the tree.
The second line contains n space-separated integers V_1, V_2, …, V_n (-10^9≤ V_i ≤ 10^9) — values of the nodes.
The next n-1 lines each contain two space-separated integers u and v (1≤ u, v≤ n, u ≠ v) denoting an edge between vertices u and v. It is guaranteed that the given graph is a tree.
Output
Print the total sum of alternating functions of all unique simple paths modulo 10^{9}+7.
Examples
Input
4
-4 1 5 -2
1 2
1 3
1 4
Output
40
Input
8
-2 6 -4 -4 -9 -3 -7 23
8 2
2 3
1 4
6 5
7 6
4 7
5 8
Output
4
Note
Consider the first example.
A simple path from node 1 to node 2: 1 → 2 has alternating function equal to A(1,2) = 1 ⋅ (-4)+(-1) ⋅ 1 = -5.
A simple path from node 1 to node 3: 1 → 3 has alternating function equal to A(1,3) = 1 ⋅ (-4)+(-1) ⋅ 5 = -9.
A simple path from node 2 to node 4: 2 → 1 → 4 has alternating function A(2,4) = 1 ⋅ (1)+(-1) ⋅ (-4)+1 ⋅ (-2) = 3.
A simple path from node 1 to node 1 has a single node 1, so A(1,1) = 1 ⋅ (-4) = -4.
Similarly, A(2, 1) = 5, A(3, 1) = 9, A(4, 2) = 3, A(1, 4) = -2, A(4, 1) = 2, A(2, 2) = 1, A(3, 3) = 5, A(4, 4) = -2, A(3, 4) = 7, A(4, 3) = 7, A(2, 3) = 10, A(3, 2) = 10. So the answer is (-5) + (-9) + 3 + (-4) + 5 + 9 + 3 + (-2) + 2 + 1 + 5 + (-2) + 7 + 7 + 10 + 10 = 40.
Similarly A(1,4)=-2, A(2,2)=1, A(2,1)=5, A(2,3)=10, A(3,3)=5, A(3,1)=9, A(3,2)=10, A(3,4)=7, A(4,4)=-2, A(4,1)=2, A(4,2)=3 , A(4,3)=7 which sums upto 40.
Submitted Solution:
```
print("big pp, small pp")
``` | instruction | 0 | 76,440 | 13 | 152,880 |
No | output | 1 | 76,440 | 13 | 152,881 |
Provide a correct Python 3 solution for this coding contest problem.
Let N be an even number.
There is a tree with N vertices. The vertices are numbered 1, 2, ..., N. For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i.
Snuke would like to decorate the tree with ribbons, as follows.
First, he will divide the N vertices into N / 2 pairs. Here, each vertex must belong to exactly one pair. Then, for each pair (u, v), put a ribbon through all the edges contained in the shortest path between u and v.
Snuke is trying to divide the vertices into pairs so that the following condition is satisfied: "for every edge, there is at least one ribbon going through it." How many ways are there to divide the vertices into pairs, satisfying this condition? Find the count modulo 10^9 + 7. Here, two ways to divide the vertices into pairs are considered different when there is a pair that is contained in one of the two ways but not in the other.
Constraints
* N is an even number.
* 2 \leq N \leq 5000
* 1 \leq x_i, y_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_{N - 1} y_{N - 1}
Output
Print the number of the ways to divide the vertices into pairs, satisfying the condition, modulo 10^9 + 7.
Examples
Input
4
1 2
2 3
3 4
Output
2
Input
4
1 2
1 3
1 4
Output
3
Input
6
1 2
1 3
3 4
1 5
5 6
Output
10
Input
10
8 5
10 8
6 5
1 5
4 8
2 10
3 6
9 2
1 7
Output
672 | instruction | 0 | 76,537 | 13 | 153,074 |
"Correct Solution:
```
import sys
sys.setrecursionlimit(5001)
MOD = 10 ** 9 + 7
n = int(input())
links = [set() for _ in range(n)]
for line in sys.stdin.readlines():
x, y = map(int, line.split())
x -= 1
y -= 1
links[x].add(y)
links[y].add(x)
double_factorial_odd = [0] * (n // 2)
prev = 1
for i in range(n // 2):
prev = double_factorial_odd[i] = (2 * i + 1) * prev % MOD
def dfs(v, p):
ret = [0, 1]
for u in links[v]:
if u == p:
continue
res = dfs(u, v)
lt, ls = len(ret), len(res)
mrg = [0] * (lt + ls - 1)
for i in range(1 - lt % 2, lt, 2):
c = ret[i]
for j in range(1 - ls % 2, ls, 2):
mrg[i + j] = (mrg[i + j] + c * res[j]) % MOD
ret = mrg
if len(ret) % 2 == 1:
ret[0] = -sum(pattern * df % MOD for pattern, df in zip(ret[2::2], double_factorial_odd)) % MOD
return ret
print(MOD - dfs(0, -1)[0])
``` | output | 1 | 76,537 | 13 | 153,075 |
Provide a correct Python 3 solution for this coding contest problem.
Let N be an even number.
There is a tree with N vertices. The vertices are numbered 1, 2, ..., N. For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i.
Snuke would like to decorate the tree with ribbons, as follows.
First, he will divide the N vertices into N / 2 pairs. Here, each vertex must belong to exactly one pair. Then, for each pair (u, v), put a ribbon through all the edges contained in the shortest path between u and v.
Snuke is trying to divide the vertices into pairs so that the following condition is satisfied: "for every edge, there is at least one ribbon going through it." How many ways are there to divide the vertices into pairs, satisfying this condition? Find the count modulo 10^9 + 7. Here, two ways to divide the vertices into pairs are considered different when there is a pair that is contained in one of the two ways but not in the other.
Constraints
* N is an even number.
* 2 \leq N \leq 5000
* 1 \leq x_i, y_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_{N - 1} y_{N - 1}
Output
Print the number of the ways to divide the vertices into pairs, satisfying the condition, modulo 10^9 + 7.
Examples
Input
4
1 2
2 3
3 4
Output
2
Input
4
1 2
1 3
1 4
Output
3
Input
6
1 2
1 3
3 4
1 5
5 6
Output
10
Input
10
8 5
10 8
6 5
1 5
4 8
2 10
3 6
9 2
1 7
Output
672 | instruction | 0 | 76,538 | 13 | 153,076 |
"Correct Solution:
```
mod = 10**9+7 #出力の制限
N = 2*10**5
g1 = [1, 1] # 元テーブル
g2 = [1, 1] #逆元テーブル
inverse = [0, 1] #逆元テーブル計算用テーブル
for i in range( 2, N + 1 ):
g1.append( ( g1[-1] * i ) % mod )
inverse.append( ( -inverse[mod % i] * (mod//i) ) % mod )
g2.append( (g2[-1] * inverse[-1]) % mod )
import sys
sys.setrecursionlimit(10**4)
N=int(input())
edge=[[] for i in range(N)]
parent=[0]*N
deg=[1]*N
deg[0]=0
for i in range(N-1):
x,y=map(int,input().split())
edge[x-1].append(y-1)
edge[y-1].append(x-1)
def prv(v,pv):
for nv in edge[v]:
if nv!=pv:
parent[nv]=v
prv(nv,v)
prv(0,-1)
for i in range(N):
new=[]
for v in edge[i]:
if v!=parent[i]:
new.append(v)
edge[i]=new
from collections import deque
ans = list(v for v in range(N) if deg[v]==0)
deq = deque(ans)
used = [0]*N
while deq:
v = deq.popleft()
for t in edge[v]:
deg[t] -= 1
if deg[t]==0:
deq.append(t)
ans.append(t)
dp=[[] for i in range(N)]
sz=[0 for i in range(N)]
for v in ans[::-1]:
sz[v]=1
dp[v]=[0]*(sz[v]+1)
dp[v][1]=1
for nv in edge[v]:
merged=[0]*(sz[v]+sz[nv]+1)
for i in range(sz[v]+1):
for j in range(sz[nv]+1):
merged[i+j]=(merged[i+j]+dp[v][i]*dp[nv][j])%mod
sz[v]+=sz[nv]
dp[v] =merged
for k in range(1,sz[v]+1):
dp[v][0]=(dp[v][0]-(g1[k]*g2[k//2])%mod*((k+1)%2)*dp[v][k])%mod
print((-dp[0][0]*pow(inverse[2],N//2,mod))%mod)
``` | output | 1 | 76,538 | 13 | 153,077 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let N be an even number.
There is a tree with N vertices. The vertices are numbered 1, 2, ..., N. For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i.
Snuke would like to decorate the tree with ribbons, as follows.
First, he will divide the N vertices into N / 2 pairs. Here, each vertex must belong to exactly one pair. Then, for each pair (u, v), put a ribbon through all the edges contained in the shortest path between u and v.
Snuke is trying to divide the vertices into pairs so that the following condition is satisfied: "for every edge, there is at least one ribbon going through it." How many ways are there to divide the vertices into pairs, satisfying this condition? Find the count modulo 10^9 + 7. Here, two ways to divide the vertices into pairs are considered different when there is a pair that is contained in one of the two ways but not in the other.
Constraints
* N is an even number.
* 2 \leq N \leq 5000
* 1 \leq x_i, y_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_{N - 1} y_{N - 1}
Output
Print the number of the ways to divide the vertices into pairs, satisfying the condition, modulo 10^9 + 7.
Examples
Input
4
1 2
2 3
3 4
Output
2
Input
4
1 2
1 3
1 4
Output
3
Input
6
1 2
1 3
3 4
1 5
5 6
Output
10
Input
10
8 5
10 8
6 5
1 5
4 8
2 10
3 6
9 2
1 7
Output
672
Submitted Solution:
```
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 6)
import numpy as np
MOD = 10 ** 9 + 7
N = int(input())
graph = [[] for _ in range(N+1)]
for _ in range(N-1):
x,y = map(int,input().split())
graph[x].append(y)
graph[y].append(x)
"""
包除の原理。各頂点を根として
・偶数個を選ぶ、そこが反例となっている、他は何でもよい、
・奇数個を選ぶ、そこが反例となっている、他は何でもよい
・根を含む成分は保留してある。保留している頂点の数を持っておく。
・偶数個の場合と奇数の場合の差分だけ持っておく
"""
def dp_merge(data1,data2):
N1 = len(data1) - 1
N2 = len(data2) - 1
data = np.zeros(N1+N2, dtype = np.int64)
for n in range(1,N1+1):
data[n:n+N2] += data1[n] * data2[1:] % MOD
data %= MOD
return data
fact_2 = [1,0,1]
for n in range(3,N+10):
fact_2.append(fact_2[n-2] * (n-1) % MOD)
fact_2 = np.array(fact_2, dtype = np.int64)
def dp_add_edge(data):
N = len(data) - 1
data1 = np.zeros(N+2, dtype=np.int64)
# 辺を反例に加えない
data1[1:] = data
# 辺を反例に加える
data1[1] = - (data * fact_2[:N+1] % MOD).sum() % MOD
return data1
def dfs(v, parent = None):
data = None
for y in graph[v]:
if y == parent:
continue
data1 = dfs(y, v)
# mergeする前に、最後の辺をひとつ加える
data1 = dp_add_edge(data1)
if data is None:
data = data1
else:
data = dp_merge(data, data1)
if data is None:
return np.array([0,1],dtype=np.int64)
return data
data = dfs(1)
answer = (data * fact_2[:N+1] % MOD).sum() % MOD
print(answer)
arr = np.arange(5)
arr
np.roll(arr,2)
``` | instruction | 0 | 76,539 | 13 | 153,078 |
No | output | 1 | 76,539 | 13 | 153,079 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.