message stringlengths 2 49.9k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 446 108k | cluster float64 13 13 | __index_level_0__ int64 892 217k |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree that consists of n nodes. You should label each of its n-1 edges with an integer in such way that satisfies the following conditions:
* each integer must be greater than 0;
* the product of all n-1 numbers should be equal to k;
* the number of 1-s among all n-1 integers must be minimum possible.
Let's define f(u,v) as the sum of the numbers on the simple path from node u to node v. Also, let β_{i=1}^{n-1} β_{j=i+1}^n f(i,j) be a distribution index of the tree.
Find the maximum possible distribution index you can get. Since answer can be too large, print it modulo 10^9 + 7.
In this problem, since the number k can be large, the result of the prime factorization of k is given instead.
Input
The first line contains one integer t (1 β€ t β€ 100) β the number of test cases.
The first line of each test case contains a single integer n (2 β€ n β€ 10^5) β the number of nodes in the tree.
Each of the next n-1 lines describes an edge: the i-th line contains two integers u_i and v_i (1 β€ u_i, v_i β€ n; u_i β v_i) β indices of vertices connected by the i-th edge.
Next line contains a single integer m (1 β€ m β€ 6 β
10^4) β the number of prime factors of k.
Next line contains m prime numbers p_1, p_2, β¦, p_m (2 β€ p_i < 6 β
10^4) such that k = p_1 β
p_2 β
β¦ β
p_m.
It is guaranteed that the sum of n over all test cases doesn't exceed 10^5, the sum of m over all test cases doesn't exceed 6 β
10^4, and the given edges for each test cases form a tree.
Output
Print the maximum distribution index you can get. Since answer can be too large, print it modulo 10^9+7.
Example
Input
3
4
1 2
2 3
3 4
2
2 2
4
3 4
1 3
3 2
2
3 2
7
6 1
2 3
4 6
7 3
5 1
3 6
4
7 5 13 3
Output
17
18
286
Note
In the first test case, one of the optimal ways is on the following image:
<image>
In this case, f(1,2)=1, f(1,3)=3, f(1,4)=5, f(2,3)=2, f(2,4)=4, f(3,4)=2, so the sum of these 6 numbers is 17.
In the second test case, one of the optimal ways is on the following image:
<image>
In this case, f(1,2)=3, f(1,3)=1, f(1,4)=4, f(2,3)=2, f(2,4)=5, f(3,4)=3, so the sum of these 6 numbers is 18.
Submitted Solution:
```
t=int(input())
for p in range(t):
n=int(input())
z=(10**9)+7
def addEdge(x, y):
edges.append([x, y])
tree[x].append(y)
tree[y].append(x)
edges = [[] for i in range(100)]
tree = [[] for i in range(100)]
for j in range(n-1):
u,v=list(map(int,input().split()))
addEdge(u,v)
def dfs(node, parent, dp):
dp[node] = 1
for it in tree[node]:
if (it != parent):
dfs(it, node, dp)
dp[node] += dp[it]
def maximizeSum(a, n):
dp = [0 for i in range(n + 1)]
dfs(1, 0, dp)
a = sorted(a)
ans = []
for it in edges:
if len(it) > 0:
x = it[0]
y = it[1]
if (dp[x] < dp[y]):
fi = dp[x]
sec = n - dp[x]
ans.append((fi * sec)%z)
else:
fi = dp[y]
sec = n - dp[y]
ans.append((fi * sec)%z)
ans = sorted(ans)
res = 0
for i in range(n - 1):
res += (ans[i] * a[i])%z
res%=z
return res
m=int(input())
a=list(map(int,input().split()))
temp1=(n-1)-m
a.sort(reverse=True)
if temp1<0:
for j in range(temp1):
a.pop()
else:
for j in range(temp1):
a.append(1)
print(maximizeSum(a,n))
``` | instruction | 0 | 96,323 | 13 | 192,646 |
No | output | 1 | 96,323 | 13 | 192,647 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.
We assume that Bajtek can only heap up snow drifts at integer coordinates.
Input
The first line of input contains a single integer n (1 β€ n β€ 100) β the number of snow drifts. Each of the following n lines contains two integers xi and yi (1 β€ xi, yi β€ 1000) β the coordinates of the i-th snow drift.
Note that the north direction coinΡides with the direction of Oy axis, so the east direction coinΡides with the direction of the Ox axis. All snow drift's locations are distinct.
Output
Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.
Examples
Input
2
2 1
1 2
Output
1
Input
2
2 1
4 1
Output
0 | instruction | 0 | 96,407 | 13 | 192,814 |
Tags: brute force, dfs and similar, dsu, graphs
Correct Solution:
```
n = int(input())
visited = set()
graph = {}
def dfs(node):
visited.add(node)
for neighbor in graph[node]:
if neighbor not in visited:
dfs(neighbor)
def is_connected(x, y):
return x[0] == y[0] or x[1] == y[1]
for i in range(n):
x, y = map(int, input().split())
neighbors = []
for node in graph:
if is_connected(node, (x, y)):
graph[node].append((x, y))
neighbors.append(node)
graph[(x, y)] = neighbors
components = 0
for node in graph:
if node not in visited:
components += 1
dfs(node)
print(components - 1)
``` | output | 1 | 96,407 | 13 | 192,815 |
Provide tags and a correct Python 3 solution for this coding contest problem.
An undirected graph is called k-regular, if the degrees of all its vertices are equal k. An edge of a connected graph is called a bridge, if after removing it the graph is being split into two connected components.
Build a connected undirected k-regular graph containing at least one bridge, or else state that such graph doesn't exist.
Input
The single line of the input contains integer k (1 β€ k β€ 100) β the required degree of the vertices of the regular graph.
Output
Print "NO" (without quotes), if such graph doesn't exist.
Otherwise, print "YES" in the first line and the description of any suitable graph in the next lines.
The description of the made graph must start with numbers n and m β the number of vertices and edges respectively.
Each of the next m lines must contain two integers, a and b (1 β€ a, b β€ n, a β b), that mean that there is an edge connecting the vertices a and b. A graph shouldn't contain multiple edges and edges that lead from a vertex to itself. A graph must be connected, the degrees of all vertices of the graph must be equal k. At least one edge of the graph must be a bridge. You can print the edges of the graph in any order. You can print the ends of each edge in any order.
The constructed graph must contain at most 106 vertices and 106 edges (it is guaranteed that if at least one graph that meets the requirements exists, then there also exists the graph with at most 106 vertices and at most 106 edges).
Examples
Input
1
Output
YES
2 1
1 2
Note
In the sample from the statement there is a suitable graph consisting of two vertices, connected by a single edge. | instruction | 0 | 96,551 | 13 | 193,102 |
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
import sys
input = []
input_index = 0
def next(type, number = None):
def next():
global input, input_index
while input_index == len(input):
if sys.stdin:
input = sys.stdin.readline().split()
input_index = 0
else:
raise Exception()
input_index += 1
return input[input_index - 1]
if number is None:
result = type(next())
else:
result = [type(next()) for _ in range(number)]
return result
k = next(int)
vn = 0
es = []
if k % 2 == 1:
def get_full(i, w):
global vn
vn += w
for j in range(i, i + w):
for jj in range(j + 1, i + w):
es.append((j, jj))
def get_c(i):
global vn
vn += k - 1
q = i + k - 1
for j in range(i, i + k - 1, 2):
es.append((j, i - 1))
es.append((j + 1, i - 1))
get_full(q, k - 1)
for jj in range(q, q + k - 1):
es.append((j, jj))
es.append((j + 1, jj))
q += k - 1
return q
j = get_c(1)
es.append((0, j))
get_c(j + 1)
vn += 2
print("YES")
print("%s %s" % (vn, len(es)))
for a, b in es:
print("%s %s" % (a + 1, b + 1))
else:
print("NO")
``` | output | 1 | 96,551 | 13 | 193,103 |
Provide tags and a correct Python 3 solution for this coding contest problem.
An undirected graph is called k-regular, if the degrees of all its vertices are equal k. An edge of a connected graph is called a bridge, if after removing it the graph is being split into two connected components.
Build a connected undirected k-regular graph containing at least one bridge, or else state that such graph doesn't exist.
Input
The single line of the input contains integer k (1 β€ k β€ 100) β the required degree of the vertices of the regular graph.
Output
Print "NO" (without quotes), if such graph doesn't exist.
Otherwise, print "YES" in the first line and the description of any suitable graph in the next lines.
The description of the made graph must start with numbers n and m β the number of vertices and edges respectively.
Each of the next m lines must contain two integers, a and b (1 β€ a, b β€ n, a β b), that mean that there is an edge connecting the vertices a and b. A graph shouldn't contain multiple edges and edges that lead from a vertex to itself. A graph must be connected, the degrees of all vertices of the graph must be equal k. At least one edge of the graph must be a bridge. You can print the edges of the graph in any order. You can print the ends of each edge in any order.
The constructed graph must contain at most 106 vertices and 106 edges (it is guaranteed that if at least one graph that meets the requirements exists, then there also exists the graph with at most 106 vertices and at most 106 edges).
Examples
Input
1
Output
YES
2 1
1 2
Note
In the sample from the statement there is a suitable graph consisting of two vertices, connected by a single edge. | instruction | 0 | 96,552 | 13 | 193,104 |
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect
from itertools import chain, dropwhile, permutations, combinations
from collections import defaultdict, deque
def VI(): return list(map(int,input().split()))
def main1(k):
# works correctly, but too slow and generates many more vertices than necessary.
# doesn't pass the time constraint with this implementation. (prints 10^5 lines)
# ==> use the editorial solution below.
if k%2==0:
print("NO")
return
print("YES")
n = 2*(k**2-k+1)
m = n*k//2
print(n, m)
i = 0
g = [[] for i in range(n+1)]
print(1,n//2+1)
off = 1
for j in range(0,k-1,2):
j1 = off + j+1
j2 = off + j+2
print(off,j1)
print(off,j2)
l1 = off + k + j*(k-1)
l2 = off + k + (j+1)*(k-1)
for l in range(k-1):
print(j1, l1+l)
print(j2, l2+l)
for m in range(k-1):
print(l1+l,l2+m)
off = n//2+1
for j in range(0,k-1,2):
j1 = off + j+1
j2 = off + j+2
print(off,j1)
print(off,j2)
l1 = off + k + j*(k-1)
l2 = off + k + (j+1)*(k-1)
for l in range(k-1):
print(j1, l1+l)
print(j2, l2+l)
for m in range(k-1):
print(l1+l,l2+m)
def main(k):
# following the editorial algo
if k%2==0:
print("NO")
return
print("YES")
if k==1:
print("2 1")
print("1 2")
return
n = 2*k+4
m = n*k//2
e = []
e.extend([(1,n//2+1)])
off = 1
for j in range(off+1,off+k):
e.extend([(off, j)])
for j in range(off+1,off+k):
for i in range(j+1,off+k):
if (i==j+1 and (j-off)%2==1):# or (j==off+1 and i==off+k-1):
#if (i==j+1 and i%2==0) or (j==off+1 and i==off+k-1):
continue
e.extend([(j,i)])
e.extend([(j,off+k),(j,off+k+1)])
e.extend([(off+k,off+k+1)])
off = n//2+1
for j in range(off+1,off+k):
e.extend([(off, j)])
for j in range(off+1,off+k):
for i in range(j+1,off+k):
if (i==j+1 and (j-off)%2==1):# or (j==off+1 and i==off+k-1):
continue
e.extend([(j,i)])
e.extend([(j,off+k),(j,off+k+1)])
e.extend([(off+k,off+k+1)])
print(n, m)
for x in e:
print(*x)
def main_input(info=0):
k = int(input())
main(k)
if __name__ == "__main__":
main_input()
``` | output | 1 | 96,552 | 13 | 193,105 |
Provide tags and a correct Python 3 solution for this coding contest problem.
An undirected graph is called k-regular, if the degrees of all its vertices are equal k. An edge of a connected graph is called a bridge, if after removing it the graph is being split into two connected components.
Build a connected undirected k-regular graph containing at least one bridge, or else state that such graph doesn't exist.
Input
The single line of the input contains integer k (1 β€ k β€ 100) β the required degree of the vertices of the regular graph.
Output
Print "NO" (without quotes), if such graph doesn't exist.
Otherwise, print "YES" in the first line and the description of any suitable graph in the next lines.
The description of the made graph must start with numbers n and m β the number of vertices and edges respectively.
Each of the next m lines must contain two integers, a and b (1 β€ a, b β€ n, a β b), that mean that there is an edge connecting the vertices a and b. A graph shouldn't contain multiple edges and edges that lead from a vertex to itself. A graph must be connected, the degrees of all vertices of the graph must be equal k. At least one edge of the graph must be a bridge. You can print the edges of the graph in any order. You can print the ends of each edge in any order.
The constructed graph must contain at most 106 vertices and 106 edges (it is guaranteed that if at least one graph that meets the requirements exists, then there also exists the graph with at most 106 vertices and at most 106 edges).
Examples
Input
1
Output
YES
2 1
1 2
Note
In the sample from the statement there is a suitable graph consisting of two vertices, connected by a single edge. | instruction | 0 | 96,553 | 13 | 193,106 |
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
def generate(cur, n):
comp = []
edge = []
cur+=1
comp.append([cur])
layer1 = []
for _ in range(n-1):
cur+=1
layer1.append(cur)
comp.append(layer1)
layer2 = []
for _ in range(n-1):
cur+=1
layer2.append(cur)
comp.append(layer2)
for layer1, layer2 in zip(comp[:-1], comp[1:]):
for x in layer1:
for y in layer2:
edge.append([x, y])
for i in range(0, len(comp[-1]), 2):
edge.append([comp[-1][i], comp[-1][i+1]])
return cur, edge
def solve():
n = int(input())
if n % 2 == 0:
print('NO')
return
cur=0
cur1, edge1 = generate(cur, n)
cur2, edge2 = generate(cur1, n)
print('YES')
print(cur2, len(edge1)+len(edge2)+1)
s = ''
for u,v in edge1:
s+=str(u)+' '+str(v)
s+='\n'
for u,v in edge2:
s+=str(u)+' '+str(v)
s+='\n'
s+=str(1)+' '+str(1+cur1)
print(s)
solve()
``` | output | 1 | 96,553 | 13 | 193,107 |
Provide tags and a correct Python 3 solution for this coding contest problem.
An undirected graph is called k-regular, if the degrees of all its vertices are equal k. An edge of a connected graph is called a bridge, if after removing it the graph is being split into two connected components.
Build a connected undirected k-regular graph containing at least one bridge, or else state that such graph doesn't exist.
Input
The single line of the input contains integer k (1 β€ k β€ 100) β the required degree of the vertices of the regular graph.
Output
Print "NO" (without quotes), if such graph doesn't exist.
Otherwise, print "YES" in the first line and the description of any suitable graph in the next lines.
The description of the made graph must start with numbers n and m β the number of vertices and edges respectively.
Each of the next m lines must contain two integers, a and b (1 β€ a, b β€ n, a β b), that mean that there is an edge connecting the vertices a and b. A graph shouldn't contain multiple edges and edges that lead from a vertex to itself. A graph must be connected, the degrees of all vertices of the graph must be equal k. At least one edge of the graph must be a bridge. You can print the edges of the graph in any order. You can print the ends of each edge in any order.
The constructed graph must contain at most 106 vertices and 106 edges (it is guaranteed that if at least one graph that meets the requirements exists, then there also exists the graph with at most 106 vertices and at most 106 edges).
Examples
Input
1
Output
YES
2 1
1 2
Note
In the sample from the statement there is a suitable graph consisting of two vertices, connected by a single edge. | instruction | 0 | 96,554 | 13 | 193,108 |
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
def main():
k = int(input())
if k & 1:
print("YES")
n = 2 * (2 * k - 1)
m = k * (2 * k - 1)
print(n, m)
n >>= 1
print(1, 1 + n)
for i in range(2, k + 1):
print(1, i)
print(1 + n, i + n)
for j in range(k + 1, 2 * k):
print(i, j)
print(i + n, j + n)
for i in range(k + 1, 2 * k, 2):
print(i, i + 1)
print(i + n, i + 1 + n)
else:
print("NO")
return 0
main()
``` | output | 1 | 96,554 | 13 | 193,109 |
Provide tags and a correct Python 3 solution for this coding contest problem.
An undirected graph is called k-regular, if the degrees of all its vertices are equal k. An edge of a connected graph is called a bridge, if after removing it the graph is being split into two connected components.
Build a connected undirected k-regular graph containing at least one bridge, or else state that such graph doesn't exist.
Input
The single line of the input contains integer k (1 β€ k β€ 100) β the required degree of the vertices of the regular graph.
Output
Print "NO" (without quotes), if such graph doesn't exist.
Otherwise, print "YES" in the first line and the description of any suitable graph in the next lines.
The description of the made graph must start with numbers n and m β the number of vertices and edges respectively.
Each of the next m lines must contain two integers, a and b (1 β€ a, b β€ n, a β b), that mean that there is an edge connecting the vertices a and b. A graph shouldn't contain multiple edges and edges that lead from a vertex to itself. A graph must be connected, the degrees of all vertices of the graph must be equal k. At least one edge of the graph must be a bridge. You can print the edges of the graph in any order. You can print the ends of each edge in any order.
The constructed graph must contain at most 106 vertices and 106 edges (it is guaranteed that if at least one graph that meets the requirements exists, then there also exists the graph with at most 106 vertices and at most 106 edges).
Examples
Input
1
Output
YES
2 1
1 2
Note
In the sample from the statement there is a suitable graph consisting of two vertices, connected by a single edge. | instruction | 0 | 96,555 | 13 | 193,110 |
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
k = int(input())
if k == 1:
print('YES\n2 1\n1 2')
elif k % 2 == 0:
print('NO')
else:
print('YES')
n = k+1
z = (k-1)//2
print(2*k+4, n*(n-1) + 1 + 2*z)
l1 = list(range(1, 2*z+1, 2))+[-1]
l2 = list(range(k+4, k+2*z+4, 2))+[-1]
z = 0
for i in range(1, n):
for j in range(i+1, n+1):
if i == l1[z]:
print(i, k+2)
print(i+1, k+2)
z += 1
else:
print(i, j)
print(k+2, k+3)
z = 0
n = 2*k+4
for i in range(k+4, n):
for j in range(i+1, n+1):
if i == l2[z]:
print(i, k+3)
print(i+1, k+3)
z += 1
else:
print(i, j)
``` | output | 1 | 96,555 | 13 | 193,111 |
Provide tags and a correct Python 3 solution for this coding contest problem.
An undirected graph is called k-regular, if the degrees of all its vertices are equal k. An edge of a connected graph is called a bridge, if after removing it the graph is being split into two connected components.
Build a connected undirected k-regular graph containing at least one bridge, or else state that such graph doesn't exist.
Input
The single line of the input contains integer k (1 β€ k β€ 100) β the required degree of the vertices of the regular graph.
Output
Print "NO" (without quotes), if such graph doesn't exist.
Otherwise, print "YES" in the first line and the description of any suitable graph in the next lines.
The description of the made graph must start with numbers n and m β the number of vertices and edges respectively.
Each of the next m lines must contain two integers, a and b (1 β€ a, b β€ n, a β b), that mean that there is an edge connecting the vertices a and b. A graph shouldn't contain multiple edges and edges that lead from a vertex to itself. A graph must be connected, the degrees of all vertices of the graph must be equal k. At least one edge of the graph must be a bridge. You can print the edges of the graph in any order. You can print the ends of each edge in any order.
The constructed graph must contain at most 106 vertices and 106 edges (it is guaranteed that if at least one graph that meets the requirements exists, then there also exists the graph with at most 106 vertices and at most 106 edges).
Examples
Input
1
Output
YES
2 1
1 2
Note
In the sample from the statement there is a suitable graph consisting of two vertices, connected by a single edge. | instruction | 0 | 96,556 | 13 | 193,112 |
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
def constructK2( v , k ):
res = set()
for i in range(1,k):
res.add( (v[0],v[i]) )
for i in range(1,k):
for j in range(1,k):
if i!=j:
res.add( (min(v[i],v[j]),max(v[i],v[j])) )
for i in range(2,k,2):
v1 = i
v2 = i + 1
if v2 >= k:
v2 = 1
res.remove( (min(v[v1],v[v2]),max(v[v1],v[v2])) )
for i in range(1,k):
res.add( (v[i],v[k]) )
res.add( (v[i],v[k+1]) )
res.add( (v[k],v[k+1]) )
return res
def construct( k ):
res1 = constructK2( [x for x in range(1,k+3)] , k )
res2 = constructK2( [x+k+2 for x in range(1,k+3)] , k )
return res1 | res2 | {(1,k+3)}
def printRes( res ):
for ares in res:
print(ares[0],ares[1])
if __name__ == "__main__":
k = int(input())
if k%2 == 0:
print("NO")
else:
print("YES")
if k == 1:
print("2 1")
print("1 2")
else:
print(2*k+4,((2*k+4)*k-2)//2+1)
res = construct(k)
printRes(res)
``` | output | 1 | 96,556 | 13 | 193,113 |
Provide tags and a correct Python 3 solution for this coding contest problem.
An undirected graph is called k-regular, if the degrees of all its vertices are equal k. An edge of a connected graph is called a bridge, if after removing it the graph is being split into two connected components.
Build a connected undirected k-regular graph containing at least one bridge, or else state that such graph doesn't exist.
Input
The single line of the input contains integer k (1 β€ k β€ 100) β the required degree of the vertices of the regular graph.
Output
Print "NO" (without quotes), if such graph doesn't exist.
Otherwise, print "YES" in the first line and the description of any suitable graph in the next lines.
The description of the made graph must start with numbers n and m β the number of vertices and edges respectively.
Each of the next m lines must contain two integers, a and b (1 β€ a, b β€ n, a β b), that mean that there is an edge connecting the vertices a and b. A graph shouldn't contain multiple edges and edges that lead from a vertex to itself. A graph must be connected, the degrees of all vertices of the graph must be equal k. At least one edge of the graph must be a bridge. You can print the edges of the graph in any order. You can print the ends of each edge in any order.
The constructed graph must contain at most 106 vertices and 106 edges (it is guaranteed that if at least one graph that meets the requirements exists, then there also exists the graph with at most 106 vertices and at most 106 edges).
Examples
Input
1
Output
YES
2 1
1 2
Note
In the sample from the statement there is a suitable graph consisting of two vertices, connected by a single edge. | instruction | 0 | 96,557 | 13 | 193,114 |
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
def printWithSymmetry(u, v, offset):
print("{0} {1}".format(u, v))
print("{0} {1}".format(u+offset, v+offset))
k = int(input())
if k % 2 == 0:
print("NO")
elif k == 1: # Caso Especial
print("YES")
print("2 1")
print("1 2")
else:
print("YES")
nodesNum = k+2
print("{0} {1}".format(2*nodesNum, nodesNum*k)) # por el primer teorema
print("1 {0}".format(1+nodesNum)) # arista puente
printWithSymmetry(1, 2, nodesNum)
for i in range(3, nodesNum): # K sub k con aristas especificas removidas
for j in range(i, nodesNum+1):
if i == j or (i > 5 and i % 2 == 0 and j-i == 1):
continue
printWithSymmetry(i, j, nodesNum)
missingSec = k-1 # nodo secundario
for i in range(4, 4+missingSec):
printWithSymmetry(2, i, nodesNum)
printWithSymmetry(1, 3, nodesNum)
missingMain = k-2-1 # nodo principal
if missingMain:
for i in range(6, 6+missingMain):
printWithSymmetry(1, i, nodesNum)
``` | output | 1 | 96,557 | 13 | 193,115 |
Provide tags and a correct Python 3 solution for this coding contest problem.
An undirected graph is called k-regular, if the degrees of all its vertices are equal k. An edge of a connected graph is called a bridge, if after removing it the graph is being split into two connected components.
Build a connected undirected k-regular graph containing at least one bridge, or else state that such graph doesn't exist.
Input
The single line of the input contains integer k (1 β€ k β€ 100) β the required degree of the vertices of the regular graph.
Output
Print "NO" (without quotes), if such graph doesn't exist.
Otherwise, print "YES" in the first line and the description of any suitable graph in the next lines.
The description of the made graph must start with numbers n and m β the number of vertices and edges respectively.
Each of the next m lines must contain two integers, a and b (1 β€ a, b β€ n, a β b), that mean that there is an edge connecting the vertices a and b. A graph shouldn't contain multiple edges and edges that lead from a vertex to itself. A graph must be connected, the degrees of all vertices of the graph must be equal k. At least one edge of the graph must be a bridge. You can print the edges of the graph in any order. You can print the ends of each edge in any order.
The constructed graph must contain at most 106 vertices and 106 edges (it is guaranteed that if at least one graph that meets the requirements exists, then there also exists the graph with at most 106 vertices and at most 106 edges).
Examples
Input
1
Output
YES
2 1
1 2
Note
In the sample from the statement there is a suitable graph consisting of two vertices, connected by a single edge. | instruction | 0 | 96,558 | 13 | 193,116 |
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
x = int(input())
if x%2==0:
print("NO")
quit()
print("WHY IS CF SO HARD Dx")
if x == 1:
print("YES")
print(2, 1)
print(1, 2)
else:
print("YES")
sides = 2*x + 4
half = x+2
e = sides * x // 2
print(sides, e)
print(x+2, x+3)
dead = [[1, x+2], [2, x+2]]
for i in range(3, x+2, 2):
dead.append([i, i+1])
for i in range(1, x+3):
for j in range(i+1, x+3):
if [i, j] not in dead and [j, i] not in dead:
print(i, j)
print(sides-i+1, sides-j+1)
``` | output | 1 | 96,558 | 13 | 193,117 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
An undirected graph is called k-regular, if the degrees of all its vertices are equal k. An edge of a connected graph is called a bridge, if after removing it the graph is being split into two connected components.
Build a connected undirected k-regular graph containing at least one bridge, or else state that such graph doesn't exist.
Input
The single line of the input contains integer k (1 β€ k β€ 100) β the required degree of the vertices of the regular graph.
Output
Print "NO" (without quotes), if such graph doesn't exist.
Otherwise, print "YES" in the first line and the description of any suitable graph in the next lines.
The description of the made graph must start with numbers n and m β the number of vertices and edges respectively.
Each of the next m lines must contain two integers, a and b (1 β€ a, b β€ n, a β b), that mean that there is an edge connecting the vertices a and b. A graph shouldn't contain multiple edges and edges that lead from a vertex to itself. A graph must be connected, the degrees of all vertices of the graph must be equal k. At least one edge of the graph must be a bridge. You can print the edges of the graph in any order. You can print the ends of each edge in any order.
The constructed graph must contain at most 106 vertices and 106 edges (it is guaranteed that if at least one graph that meets the requirements exists, then there also exists the graph with at most 106 vertices and at most 106 edges).
Examples
Input
1
Output
YES
2 1
1 2
Note
In the sample from the statement there is a suitable graph consisting of two vertices, connected by a single edge.
Submitted Solution:
```
k = int(input())
if k % 2 == 0:
print('NO')
elif k == 1:
print('YES\n2 1\n1 2')
else:
print('YES')
print(2 * (k + 2), k * (k + 2))
print(1, k + 3)
for i in range(2):
x = i * (k + 2)
print(x + k + 1, x + k + 2)
for j in range(k - 1):
print(x + 1, x + j + 2)
print(x + j + 2, x + k + 1)
print(x + j + 2, x + k + 2)
for a in range(1, (k - 3) // 2 + 1):
for b in range(k - 1):
print(x + 2 + b, x + 2 + (b + a) % (k - 1))
``` | instruction | 0 | 96,559 | 13 | 193,118 |
Yes | output | 1 | 96,559 | 13 | 193,119 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
An undirected graph is called k-regular, if the degrees of all its vertices are equal k. An edge of a connected graph is called a bridge, if after removing it the graph is being split into two connected components.
Build a connected undirected k-regular graph containing at least one bridge, or else state that such graph doesn't exist.
Input
The single line of the input contains integer k (1 β€ k β€ 100) β the required degree of the vertices of the regular graph.
Output
Print "NO" (without quotes), if such graph doesn't exist.
Otherwise, print "YES" in the first line and the description of any suitable graph in the next lines.
The description of the made graph must start with numbers n and m β the number of vertices and edges respectively.
Each of the next m lines must contain two integers, a and b (1 β€ a, b β€ n, a β b), that mean that there is an edge connecting the vertices a and b. A graph shouldn't contain multiple edges and edges that lead from a vertex to itself. A graph must be connected, the degrees of all vertices of the graph must be equal k. At least one edge of the graph must be a bridge. You can print the edges of the graph in any order. You can print the ends of each edge in any order.
The constructed graph must contain at most 106 vertices and 106 edges (it is guaranteed that if at least one graph that meets the requirements exists, then there also exists the graph with at most 106 vertices and at most 106 edges).
Examples
Input
1
Output
YES
2 1
1 2
Note
In the sample from the statement there is a suitable graph consisting of two vertices, connected by a single edge.
Submitted Solution:
```
def solve():
k = int(input())
if k % 2 == 0:
print("NO")
elif k == 1: # Caso Especial
print("YES")
print("2 1")
print("1 2")
else:
print("YES")
global nodesNum
nodesNum = k+2
print("{0} {1}".format(2*nodesNum, nodesNum*k)) # primer teorema
print("1 {0}".format(1+nodesNum)) # arista puente
for i in range(2, nodesNum): # K sub k+1 con sin aristas especificas
for j in range(i, nodesNum+1):
if i == j or (i > 3 and j-i == 1 and i % 2 == 0):
continue
printWithSymmetry(i, j)
for i in range(4, 4+k-1):
printWithSymmetry(1, i)
def printWithSymmetry(u, v):
print("{0} {1}\n{2} {3}".format(u, v, u+nodesNum, v+nodesNum))
solve()
``` | instruction | 0 | 96,560 | 13 | 193,120 |
Yes | output | 1 | 96,560 | 13 | 193,121 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
An undirected graph is called k-regular, if the degrees of all its vertices are equal k. An edge of a connected graph is called a bridge, if after removing it the graph is being split into two connected components.
Build a connected undirected k-regular graph containing at least one bridge, or else state that such graph doesn't exist.
Input
The single line of the input contains integer k (1 β€ k β€ 100) β the required degree of the vertices of the regular graph.
Output
Print "NO" (without quotes), if such graph doesn't exist.
Otherwise, print "YES" in the first line and the description of any suitable graph in the next lines.
The description of the made graph must start with numbers n and m β the number of vertices and edges respectively.
Each of the next m lines must contain two integers, a and b (1 β€ a, b β€ n, a β b), that mean that there is an edge connecting the vertices a and b. A graph shouldn't contain multiple edges and edges that lead from a vertex to itself. A graph must be connected, the degrees of all vertices of the graph must be equal k. At least one edge of the graph must be a bridge. You can print the edges of the graph in any order. You can print the ends of each edge in any order.
The constructed graph must contain at most 106 vertices and 106 edges (it is guaranteed that if at least one graph that meets the requirements exists, then there also exists the graph with at most 106 vertices and at most 106 edges).
Examples
Input
1
Output
YES
2 1
1 2
Note
In the sample from the statement there is a suitable graph consisting of two vertices, connected by a single edge.
Submitted Solution:
```
import sys;input=sys.stdin.readline
# from itertools import accumulate
# from decimal import *
# import math
# getcontext().prec = 50
# s = input().strip()
# n = int(input())
# lis = list(map(int,input().split()))
# x,y = map(int,input().split())
# chars = 'abcdefghijklmnopqrstuvwxyz'
# def gcd(a,b):
# return gcd (b, a % b) if b else a
def solve():
k = int(input())
if k%2==0:
print('NO')
return
print('YES')
if k==1:
print('2 1')
print('1 2')
return
n = k+1
v = 2*(n+1)
e = n*n-1
print(v,e)
g = [[0 for _ in range(v)] for _ in range(v)]
for i in range(n-1):
g[i][i+1] = 1
g[0][n-1] = 1
for i in range(1,n):
g[i][n] = 1
diag = n-4
for i in range(n-2):
for j in range(i+2,i+2+diag//2):
if j<n:
g[i][j]=1
for j in range(i+3+diag//2,i+3+diag):
if j<n:
g[i][j]=1
for i in range(n+1,n+1+n-1):
g[i][i+1] = 1
g[n+1][n+1+n-1] = 1
for i in range(n+1+1,n+1+n):
g[i][n+1+n] = 1
diag = n-4
for i in range(n+1,n+1+n-2):
for j in range(i+2,i+2+diag//2):
if j<n+1+n:
g[i][j]=1
for j in range(i+3+diag//2,i+3+diag):
if j<n+1+n:
g[i][j]=1
g[0][n+1]= 1
for i in range(len(g)):
for j in range(len(g[0])):
if g[i][j] == 1:
print(i+1,j+1)
solve()
# for _ in range(int(input())):
# solve()
``` | instruction | 0 | 96,561 | 13 | 193,122 |
Yes | output | 1 | 96,561 | 13 | 193,123 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
An undirected graph is called k-regular, if the degrees of all its vertices are equal k. An edge of a connected graph is called a bridge, if after removing it the graph is being split into two connected components.
Build a connected undirected k-regular graph containing at least one bridge, or else state that such graph doesn't exist.
Input
The single line of the input contains integer k (1 β€ k β€ 100) β the required degree of the vertices of the regular graph.
Output
Print "NO" (without quotes), if such graph doesn't exist.
Otherwise, print "YES" in the first line and the description of any suitable graph in the next lines.
The description of the made graph must start with numbers n and m β the number of vertices and edges respectively.
Each of the next m lines must contain two integers, a and b (1 β€ a, b β€ n, a β b), that mean that there is an edge connecting the vertices a and b. A graph shouldn't contain multiple edges and edges that lead from a vertex to itself. A graph must be connected, the degrees of all vertices of the graph must be equal k. At least one edge of the graph must be a bridge. You can print the edges of the graph in any order. You can print the ends of each edge in any order.
The constructed graph must contain at most 106 vertices and 106 edges (it is guaranteed that if at least one graph that meets the requirements exists, then there also exists the graph with at most 106 vertices and at most 106 edges).
Examples
Input
1
Output
YES
2 1
1 2
Note
In the sample from the statement there is a suitable graph consisting of two vertices, connected by a single edge.
Submitted Solution:
```
k = int(input())
if k == 1:
print('YES')
print(2, 1)
print(1, 2)
elif k%2:
print('YES')
print(2*k + 4, k*k + 2*k)
matrix = [[False]*(2*k + 4) for _ in range(2*k + 4)]
for i in range(k+1):
for j in range(i+1, k+1):
matrix[i][j] = True
for i in range(k+2, 2*k + 3):
for j in range(i+1, 2*k + 3):
matrix[i][j] = True
need = 0
i = 0
matrix[k+1][-1] = True
while need != k - 1:
matrix[k+1][2*i] = True
matrix[k+1][2*i + 1] = True
matrix[-1][2*i + k + 2] = True
matrix[-1][2*i + k + 3] = True
matrix[2*i][2*i + 1] = False
matrix[2*i + k + 2][2*i + k + 3] = False
need += 2
i += 1
for i in range(2*k + 4):
for j in range(2*k + 4):
if matrix[i][j]: print(i+1, j+1)
else:
print('NO')
``` | instruction | 0 | 96,562 | 13 | 193,124 |
Yes | output | 1 | 96,562 | 13 | 193,125 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
An undirected graph is called k-regular, if the degrees of all its vertices are equal k. An edge of a connected graph is called a bridge, if after removing it the graph is being split into two connected components.
Build a connected undirected k-regular graph containing at least one bridge, or else state that such graph doesn't exist.
Input
The single line of the input contains integer k (1 β€ k β€ 100) β the required degree of the vertices of the regular graph.
Output
Print "NO" (without quotes), if such graph doesn't exist.
Otherwise, print "YES" in the first line and the description of any suitable graph in the next lines.
The description of the made graph must start with numbers n and m β the number of vertices and edges respectively.
Each of the next m lines must contain two integers, a and b (1 β€ a, b β€ n, a β b), that mean that there is an edge connecting the vertices a and b. A graph shouldn't contain multiple edges and edges that lead from a vertex to itself. A graph must be connected, the degrees of all vertices of the graph must be equal k. At least one edge of the graph must be a bridge. You can print the edges of the graph in any order. You can print the ends of each edge in any order.
The constructed graph must contain at most 106 vertices and 106 edges (it is guaranteed that if at least one graph that meets the requirements exists, then there also exists the graph with at most 106 vertices and at most 106 edges).
Examples
Input
1
Output
YES
2 1
1 2
Note
In the sample from the statement there is a suitable graph consisting of two vertices, connected by a single edge.
Submitted Solution:
```
def ic(i, n):
return 1 + (k - 1)*i + n
def ic2(i, n):
return 1 + (k - 1)*i + n + k*k - 1
def func():
if k % 2 == 0:
return print('NO')
b1 = 2*(k - 1) + 1
b2 = b1 + 1
edges = set()
c = 1
for i in range(k - 1): # component
for j in range(k + 1): # node 1
for l in range(j + 1, k + 1): # node 2
edges.add( (ic(i, j), ic(i, l)) )
edges.add( (ic2(i, j), ic2(i, l)) )
if i % 2 == 1:
edges.remove( (ic(i - 1, 0), ic(i - 1, 1)) )
edges.remove( (ic2(i - 1, 0), ic2(i - 1, 1)) )
edges.remove( (ic(i, 0), ic(i, 1)) )
edges.remove( (ic2(i, 0), ic2(i, 1)) )
edges.add( (ic(i - 1, 0), b1) )
edges.add( (ic2(i - 1, 0), b2) )
edges.add( (ic(i, 0), b1) )
edges.add( (ic2(i, 0), b2) )
edges.add( (ic(i - 1, 1), ic(i, 1)) )
edges.add( (ic2(i - 1, 1), ic2(i, 1)) )
edges.add((b1, b2))
print('YES')
print(2*(k - 1)*(k+ 1) + 2, len(edges))
for edge in edges:
print(edge[0], edge[1])
k = int(input())
func()
``` | instruction | 0 | 96,563 | 13 | 193,126 |
No | output | 1 | 96,563 | 13 | 193,127 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
An undirected graph is called k-regular, if the degrees of all its vertices are equal k. An edge of a connected graph is called a bridge, if after removing it the graph is being split into two connected components.
Build a connected undirected k-regular graph containing at least one bridge, or else state that such graph doesn't exist.
Input
The single line of the input contains integer k (1 β€ k β€ 100) β the required degree of the vertices of the regular graph.
Output
Print "NO" (without quotes), if such graph doesn't exist.
Otherwise, print "YES" in the first line and the description of any suitable graph in the next lines.
The description of the made graph must start with numbers n and m β the number of vertices and edges respectively.
Each of the next m lines must contain two integers, a and b (1 β€ a, b β€ n, a β b), that mean that there is an edge connecting the vertices a and b. A graph shouldn't contain multiple edges and edges that lead from a vertex to itself. A graph must be connected, the degrees of all vertices of the graph must be equal k. At least one edge of the graph must be a bridge. You can print the edges of the graph in any order. You can print the ends of each edge in any order.
The constructed graph must contain at most 106 vertices and 106 edges (it is guaranteed that if at least one graph that meets the requirements exists, then there also exists the graph with at most 106 vertices and at most 106 edges).
Examples
Input
1
Output
YES
2 1
1 2
Note
In the sample from the statement there is a suitable graph consisting of two vertices, connected by a single edge.
Submitted Solution:
```
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
k = int(input())
if k == 1:
print("YES")
print(2,1)
print(1,2)
elif k == 2:
print("NO")
else:
print( 4*k-2, 2*k^2-3)
points = [[1, i+1] for i in range(1, k) ]
for i in range(2, k+1):
for j in range(k+1, 2*k):
points.append([i,j])
for j in range(k+1, 2*k-1):
points.append([j, j+1])
points += [ [i[0]+2*k-1, i[1]+ 2*k-1] for i in points ]
points.append([1, k+1])
print("YES")
for i in points:
print(i[0], i[1])
start = time.time()
finish = time.time()
#print(finish - start)
``` | instruction | 0 | 96,564 | 13 | 193,128 |
No | output | 1 | 96,564 | 13 | 193,129 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
An undirected graph is called k-regular, if the degrees of all its vertices are equal k. An edge of a connected graph is called a bridge, if after removing it the graph is being split into two connected components.
Build a connected undirected k-regular graph containing at least one bridge, or else state that such graph doesn't exist.
Input
The single line of the input contains integer k (1 β€ k β€ 100) β the required degree of the vertices of the regular graph.
Output
Print "NO" (without quotes), if such graph doesn't exist.
Otherwise, print "YES" in the first line and the description of any suitable graph in the next lines.
The description of the made graph must start with numbers n and m β the number of vertices and edges respectively.
Each of the next m lines must contain two integers, a and b (1 β€ a, b β€ n, a β b), that mean that there is an edge connecting the vertices a and b. A graph shouldn't contain multiple edges and edges that lead from a vertex to itself. A graph must be connected, the degrees of all vertices of the graph must be equal k. At least one edge of the graph must be a bridge. You can print the edges of the graph in any order. You can print the ends of each edge in any order.
The constructed graph must contain at most 106 vertices and 106 edges (it is guaranteed that if at least one graph that meets the requirements exists, then there also exists the graph with at most 106 vertices and at most 106 edges).
Examples
Input
1
Output
YES
2 1
1 2
Note
In the sample from the statement there is a suitable graph consisting of two vertices, connected by a single edge.
Submitted Solution:
```
k=int(input())
if k%2==0:
print("NO")
exit(0)
if k==1:
print("YES")
print("2 1\n1 2")
exit(0)
print("YES")
print(2*k+4,k*k+2*k)
j=0;
for i in range(2+j,j+k+1):
print(j+1,i)
for i in range(2+j,k+j+1):
for t in range(i+j+2,k+j+1):
print(i,t)
for i in range(2+j,j+k+1):
print(j+k+1,i)
print(j+k+2,i)
print(j+k+1,j+k+2)
j=k+2;
for i in range(2+j,j+k+1):
print(j+1,i)
for i in range(2+j,k+j+1):
for t in range(i+j+2,k+j+1):
print(i,t)
for i in range(2+j,j+k+1):
print(j+k+1,i)
print(j+k+2,i)
print(j+k+1,j+k+2)
print(1,k+3)
``` | instruction | 0 | 96,565 | 13 | 193,130 |
No | output | 1 | 96,565 | 13 | 193,131 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
An undirected graph is called k-regular, if the degrees of all its vertices are equal k. An edge of a connected graph is called a bridge, if after removing it the graph is being split into two connected components.
Build a connected undirected k-regular graph containing at least one bridge, or else state that such graph doesn't exist.
Input
The single line of the input contains integer k (1 β€ k β€ 100) β the required degree of the vertices of the regular graph.
Output
Print "NO" (without quotes), if such graph doesn't exist.
Otherwise, print "YES" in the first line and the description of any suitable graph in the next lines.
The description of the made graph must start with numbers n and m β the number of vertices and edges respectively.
Each of the next m lines must contain two integers, a and b (1 β€ a, b β€ n, a β b), that mean that there is an edge connecting the vertices a and b. A graph shouldn't contain multiple edges and edges that lead from a vertex to itself. A graph must be connected, the degrees of all vertices of the graph must be equal k. At least one edge of the graph must be a bridge. You can print the edges of the graph in any order. You can print the ends of each edge in any order.
The constructed graph must contain at most 106 vertices and 106 edges (it is guaranteed that if at least one graph that meets the requirements exists, then there also exists the graph with at most 106 vertices and at most 106 edges).
Examples
Input
1
Output
YES
2 1
1 2
Note
In the sample from the statement there is a suitable graph consisting of two vertices, connected by a single edge.
Submitted Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect
from itertools import chain, dropwhile, permutations, combinations
from collections import defaultdict, deque
def VI(): return list(map(int,input().split()))
def main1(k):
# works correctly, but too slow and generates many more vertices than necessary.
# doesn't pass the time constraint with this implementation. (prints 10^5 lines)
# ==> use the editorial solution below.
if k%2==0:
print("NO")
return
print("YES")
n = 2*(k**2-k+1)
m = n*k//2
print(n, m)
i = 0
g = [[] for i in range(n+1)]
print(1,n//2+1)
off = 1
for j in range(0,k-1,2):
j1 = off + j+1
j2 = off + j+2
print(off,j1)
print(off,j2)
l1 = off + k + j*(k-1)
l2 = off + k + (j+1)*(k-1)
for l in range(k-1):
print(j1, l1+l)
print(j2, l2+l)
for m in range(k-1):
print(l1+l,l2+m)
off = n//2+1
for j in range(0,k-1,2):
j1 = off + j+1
j2 = off + j+2
print(off,j1)
print(off,j2)
l1 = off + k + j*(k-1)
l2 = off + k + (j+1)*(k-1)
for l in range(k-1):
print(j1, l1+l)
print(j2, l2+l)
for m in range(k-1):
print(l1+l,l2+m)
def main(k):
if k%2==0:
print("NO")
return
if k==1:
print("YES")
print("2 1")
print("1 2")
return
n = 2*k+4
m = n*k//2
print(n, m)
print(1,n//2+1)
off = 1
for j in range(0,k-1):
j1 = off + 1 + j
print(off, j1)
print(j1,off+k)
print(j1,off+k+1)
for i in range((j+1)//2*2+1,k-1):
if k==3: continue
print(j1,j1+i)
off = n//2+1
for j in range(0,k-1):
j1 = off + 1 + j
print(off, j1)
print(j1,off+k)
print(j1,off+k+1)
for i in range((j+1)//2*2+1,k-1):
if k==3: continue
print(j1,j1+i)
def main_input(info=0):
k = int(input())
main(k)
if __name__ == "__main__":
main_input()
``` | instruction | 0 | 96,566 | 13 | 193,132 |
No | output | 1 | 96,566 | 13 | 193,133 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ostap already settled down in Rio de Janiero suburb and started to grow a tree in his garden. Recall that a tree is a connected undirected acyclic graph.
Ostap's tree now has n vertices. He wants to paint some vertices of the tree black such that from any vertex u there is at least one black vertex v at distance no more than k. Distance between two vertices of the tree is the minimum possible number of edges of the path between them.
As this number of ways to paint the tree can be large, Ostap wants you to compute it modulo 109 + 7. Two ways to paint the tree are considered different if there exists a vertex that is painted black in one way and is not painted in the other one.
Input
The first line of the input contains two integers n and k (1 β€ n β€ 100, 0 β€ k β€ min(20, n - 1)) β the number of vertices in Ostap's tree and the maximum allowed distance to the nearest black vertex. Don't miss the unusual constraint for k.
Each of the next n - 1 lines contain two integers ui and vi (1 β€ ui, vi β€ n) β indices of vertices, connected by the i-th edge. It's guaranteed that given graph is a tree.
Output
Print one integer β the remainder of division of the number of ways to paint the tree by 1 000 000 007 (109 + 7).
Examples
Input
2 0
1 2
Output
1
Input
2 1
1 2
Output
3
Input
4 1
1 2
2 3
3 4
Output
9
Input
7 2
1 2
2 3
1 4
4 5
1 6
6 7
Output
91
Note
In the first sample, Ostap has to paint both vertices black.
In the second sample, it is enough to paint only one of two vertices, thus the answer is 3: Ostap can paint only vertex 1, only vertex 2, vertices 1 and 2 both.
In the third sample, the valid ways to paint vertices are: {1, 3}, {1, 4}, {2, 3}, {2, 4}, {1, 2, 3}, {1, 2, 4}, {1, 3, 4}, {2, 3, 4}, {1, 2, 3, 4}. | instruction | 0 | 96,647 | 13 | 193,294 |
Tags: dp, trees
Correct Solution:
```
def main():
n, k = map(int, input().split())
cnt = [[[0] * 21 for _ in (0, 1)] for _ in range(n + 1)]
edges, mod = [[] for _ in range(n + 1)], 1000000007
for _ in range(n - 1):
u, v = map(int, input().split())
edges[u].append(v)
edges[v].append(u)
def dfs(u, f):
cnt[u][0][0] = cnt[u][1][k] = 1
for v in edges[u]:
if v != f:
dfs(v, u)
tmp0, tmp1 = [0] * 21, [0] * 21
for i in range(k + 1):
for j in range(k + 1):
if i != k:
tmp0[j if i < j else i + 1] += cnt[u][0][j] * cnt[v][0][i]
if i < j:
tmp1[j] += cnt[u][1][j] * cnt[v][0][i]
elif i != k:
tmp0[i + 1] += cnt[u][1][j] * cnt[v][0][i]
if i > j:
tmp1[i - 1] += cnt[u][0][j] * cnt[v][1][i]
else:
tmp0[j] += cnt[u][0][j] * cnt[v][1][i]
tmp1[max(i - 1, j)] += cnt[u][1][j] * cnt[v][1][i]
for i in range(21):
tmp0[i] %= mod
tmp1[i] %= mod
cnt[u][0] = tmp0
cnt[u][1] = tmp1
dfs(1, 1)
print(sum(cnt[1][1][j] for j in range(k + 1)) % mod)
if __name__ == '__main__':
main()
``` | output | 1 | 96,647 | 13 | 193,295 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ostap already settled down in Rio de Janiero suburb and started to grow a tree in his garden. Recall that a tree is a connected undirected acyclic graph.
Ostap's tree now has n vertices. He wants to paint some vertices of the tree black such that from any vertex u there is at least one black vertex v at distance no more than k. Distance between two vertices of the tree is the minimum possible number of edges of the path between them.
As this number of ways to paint the tree can be large, Ostap wants you to compute it modulo 109 + 7. Two ways to paint the tree are considered different if there exists a vertex that is painted black in one way and is not painted in the other one.
Input
The first line of the input contains two integers n and k (1 β€ n β€ 100, 0 β€ k β€ min(20, n - 1)) β the number of vertices in Ostap's tree and the maximum allowed distance to the nearest black vertex. Don't miss the unusual constraint for k.
Each of the next n - 1 lines contain two integers ui and vi (1 β€ ui, vi β€ n) β indices of vertices, connected by the i-th edge. It's guaranteed that given graph is a tree.
Output
Print one integer β the remainder of division of the number of ways to paint the tree by 1 000 000 007 (109 + 7).
Examples
Input
2 0
1 2
Output
1
Input
2 1
1 2
Output
3
Input
4 1
1 2
2 3
3 4
Output
9
Input
7 2
1 2
2 3
1 4
4 5
1 6
6 7
Output
91
Note
In the first sample, Ostap has to paint both vertices black.
In the second sample, it is enough to paint only one of two vertices, thus the answer is 3: Ostap can paint only vertex 1, only vertex 2, vertices 1 and 2 both.
In the third sample, the valid ways to paint vertices are: {1, 3}, {1, 4}, {2, 3}, {2, 4}, {1, 2, 3}, {1, 2, 4}, {1, 3, 4}, {2, 3, 4}, {1, 2, 3, 4}. | instruction | 0 | 96,648 | 13 | 193,296 |
Tags: dp, trees
Correct Solution:
```
import sys
#sys.stdin=open("data.txt")
#sys.stdout=open("data.txt","w")
input=sys.stdin.readline
n,k=map(int,input().split())
g=[[] for _ in range(n+1)]
vis=[0]*(n+1)
for _ in range(n-1):
u,v=map(int,input().split())
g[u].append(v)
g[v].append(u)
def getans(u,k):
vis[u]=1
# first k -> need k
# then cover exact
# last k -> covers k above
totalv=[0]*(2*k+1)
totalv[k-1]=1
carry=1 # total when this node is black
for v in g[u]:
if vis[v]: continue
getv=getans(v,k)
carry=(carry*sum(getv))%1000000007
out2=[0]*(2*k+1)
#print("before",totalv)
for i in range(1,2*k+1):
for j in range(2*k+1):
if j+i>=2*k:
out2[max(i-1,j)]+=getv[i]*totalv[j]
else:
out2[min(i-1,j)]+=getv[i]*totalv[j]
for i in range(2*k+1):
totalv[i]=out2[i]%1000000007
#print("after ",totalv,carry)
totalv[2*k]+=carry
#print(u,totalv)
return totalv
if k==0: print(1)
else:
temp=getans(1,k)
print(sum(temp[k:])%1000000007)
``` | output | 1 | 96,648 | 13 | 193,297 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ostap already settled down in Rio de Janiero suburb and started to grow a tree in his garden. Recall that a tree is a connected undirected acyclic graph.
Ostap's tree now has n vertices. He wants to paint some vertices of the tree black such that from any vertex u there is at least one black vertex v at distance no more than k. Distance between two vertices of the tree is the minimum possible number of edges of the path between them.
As this number of ways to paint the tree can be large, Ostap wants you to compute it modulo 109 + 7. Two ways to paint the tree are considered different if there exists a vertex that is painted black in one way and is not painted in the other one.
Input
The first line of the input contains two integers n and k (1 β€ n β€ 100, 0 β€ k β€ min(20, n - 1)) β the number of vertices in Ostap's tree and the maximum allowed distance to the nearest black vertex. Don't miss the unusual constraint for k.
Each of the next n - 1 lines contain two integers ui and vi (1 β€ ui, vi β€ n) β indices of vertices, connected by the i-th edge. It's guaranteed that given graph is a tree.
Output
Print one integer β the remainder of division of the number of ways to paint the tree by 1 000 000 007 (109 + 7).
Examples
Input
2 0
1 2
Output
1
Input
2 1
1 2
Output
3
Input
4 1
1 2
2 3
3 4
Output
9
Input
7 2
1 2
2 3
1 4
4 5
1 6
6 7
Output
91
Note
In the first sample, Ostap has to paint both vertices black.
In the second sample, it is enough to paint only one of two vertices, thus the answer is 3: Ostap can paint only vertex 1, only vertex 2, vertices 1 and 2 both.
In the third sample, the valid ways to paint vertices are: {1, 3}, {1, 4}, {2, 3}, {2, 4}, {1, 2, 3}, {1, 2, 4}, {1, 3, 4}, {2, 3, 4}, {1, 2, 3, 4}. | instruction | 0 | 96,649 | 13 | 193,298 |
Tags: dp, trees
Correct Solution:
```
n,m = map(int,input().split())
edge_to = [0 for i in range(n*2+1)]
edge_next = [0 for i in range(n*2+1)]
son = [0 for i in range(n+1)]
def add_edge(u,v):
global edge_next,edge_to,son,tot;
tot += 1; edge_to[tot] = v; edge_next[tot] = son[u]; son[u] = tot;
tot = 0; MOD = 10**9+7
dp = [[0]*(m*2+2) for i in range(n+1)]
def dp_tree(x,fa):
global edge_next,edge_to,m,son,dp;
dp[x][0]= 1; dp[x][m+1] = 1;
f = [0 for i in range(m*2+2)]
i = son[x]
while (i):
f = [0 for w in range(m*2+2)]
to = edge_to[i]
i = edge_next[i]
if (to == fa): continue;
dp_tree(to,x)
for j in range(2*m+2):
for k in range(2*m+1):
if (j+k <= 2*m): f[min(j,k+1)] += (dp[x][j]*dp[to][k])%MOD; f[min(j,k+1)] %= MOD;
else : f[max(j,k+1)] += (dp[x][j]*dp[to][k])%MOD; f[max(j,k+1)] %= MOD;
dp[x] = f
for i in range(n-1):
u,v = map(int,input().split())
add_edge(u,v); add_edge(v,u);
dp_tree(1,-1)
res = 0
for i in range(m+1):
res += dp[1][i];
res %= MOD;
print(res)
``` | output | 1 | 96,649 | 13 | 193,299 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ostap already settled down in Rio de Janiero suburb and started to grow a tree in his garden. Recall that a tree is a connected undirected acyclic graph.
Ostap's tree now has n vertices. He wants to paint some vertices of the tree black such that from any vertex u there is at least one black vertex v at distance no more than k. Distance between two vertices of the tree is the minimum possible number of edges of the path between them.
As this number of ways to paint the tree can be large, Ostap wants you to compute it modulo 109 + 7. Two ways to paint the tree are considered different if there exists a vertex that is painted black in one way and is not painted in the other one.
Input
The first line of the input contains two integers n and k (1 β€ n β€ 100, 0 β€ k β€ min(20, n - 1)) β the number of vertices in Ostap's tree and the maximum allowed distance to the nearest black vertex. Don't miss the unusual constraint for k.
Each of the next n - 1 lines contain two integers ui and vi (1 β€ ui, vi β€ n) β indices of vertices, connected by the i-th edge. It's guaranteed that given graph is a tree.
Output
Print one integer β the remainder of division of the number of ways to paint the tree by 1 000 000 007 (109 + 7).
Examples
Input
2 0
1 2
Output
1
Input
2 1
1 2
Output
3
Input
4 1
1 2
2 3
3 4
Output
9
Input
7 2
1 2
2 3
1 4
4 5
1 6
6 7
Output
91
Note
In the first sample, Ostap has to paint both vertices black.
In the second sample, it is enough to paint only one of two vertices, thus the answer is 3: Ostap can paint only vertex 1, only vertex 2, vertices 1 and 2 both.
In the third sample, the valid ways to paint vertices are: {1, 3}, {1, 4}, {2, 3}, {2, 4}, {1, 2, 3}, {1, 2, 4}, {1, 3, 4}, {2, 3, 4}, {1, 2, 3, 4}. | instruction | 0 | 96,650 | 13 | 193,300 |
Tags: dp, trees
Correct Solution:
```
import sys
#sys.stdin=open("data.txt")
#sys.stdout=open("data.txt","w")
input=sys.stdin.readline
n,k=map(int,input().split())
g=[[] for _ in range(n+1)]
vis=[0]*(n+1)
for _ in range(n-1):
u,v=map(int,input().split())
g[u].append(v)
g[v].append(u)
def getans(u,k):
vis[u]=1
# first k -> need k
# then cover exact
# last k -> covers k above
totalv=[0]*(2*k+1)
totalv[k-1]=1
carry=1 # total when this node is black
for v in g[u]:
if vis[v]: continue
getv=getans(v,k)
carry=(carry*sum(getv))%1000000007
out2=[0]*(2*k+1)
#print("before",totalv)
for i in range(1,2*k+1):
for j in range(2*k+1):
if j+i>=2*k:
out2[max(i-1,j)]+=getv[i]*totalv[j]
else:
out2[min(i-1,j)]+=getv[i]*totalv[j]
for i in range(2*k+1):
totalv[i]=out2[i]%1000000007
#print("after ",totalv,carry)
totalv[2*k]+=carry
#print(u,totalv)
return totalv
if k==0: print(1)
else:
temp=getans(1,k)
print(sum(temp[k:])%1000000007)
# Made By Mostafa_Khaled
``` | output | 1 | 96,650 | 13 | 193,301 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ostap already settled down in Rio de Janiero suburb and started to grow a tree in his garden. Recall that a tree is a connected undirected acyclic graph.
Ostap's tree now has n vertices. He wants to paint some vertices of the tree black such that from any vertex u there is at least one black vertex v at distance no more than k. Distance between two vertices of the tree is the minimum possible number of edges of the path between them.
As this number of ways to paint the tree can be large, Ostap wants you to compute it modulo 109 + 7. Two ways to paint the tree are considered different if there exists a vertex that is painted black in one way and is not painted in the other one.
Input
The first line of the input contains two integers n and k (1 β€ n β€ 100, 0 β€ k β€ min(20, n - 1)) β the number of vertices in Ostap's tree and the maximum allowed distance to the nearest black vertex. Don't miss the unusual constraint for k.
Each of the next n - 1 lines contain two integers ui and vi (1 β€ ui, vi β€ n) β indices of vertices, connected by the i-th edge. It's guaranteed that given graph is a tree.
Output
Print one integer β the remainder of division of the number of ways to paint the tree by 1 000 000 007 (109 + 7).
Examples
Input
2 0
1 2
Output
1
Input
2 1
1 2
Output
3
Input
4 1
1 2
2 3
3 4
Output
9
Input
7 2
1 2
2 3
1 4
4 5
1 6
6 7
Output
91
Note
In the first sample, Ostap has to paint both vertices black.
In the second sample, it is enough to paint only one of two vertices, thus the answer is 3: Ostap can paint only vertex 1, only vertex 2, vertices 1 and 2 both.
In the third sample, the valid ways to paint vertices are: {1, 3}, {1, 4}, {2, 3}, {2, 4}, {1, 2, 3}, {1, 2, 4}, {1, 3, 4}, {2, 3, 4}, {1, 2, 3, 4}.
Submitted Solution:
```
def main():
n, k = map(int, input().split())
cnt = [[[0] * 21 for _ in (0, 1)] for _ in range(n + 1)]
edges, mod = [[] for _ in range(n + 1)], 10000007
for _ in range(n - 1):
u, v = map(int, input().split())
edges[u].append(v)
edges[v].append(u)
def dfs(u, f):
cnt[u][0][0] = cnt[u][1][k] = 1
for v in edges[u]:
if v != f:
dfs(v, u)
tmp0, tmp1 = [0] * 21, [0] * 21
for i in range(k + 1):
for j in range(k + 1):
if i != k:
tmp0[j if i < j else i + 1] += cnt[u][0][j] * cnt[v][0][i]
if i < j:
tmp1[j] += cnt[u][1][j] * cnt[v][0][i]
elif i != k:
tmp0[i + 1] += cnt[u][1][j] * cnt[v][0][i]
if i > j:
tmp1[i - 1] += cnt[u][0][j] * cnt[v][1][i]
else:
tmp0[j] += cnt[u][0][j] * cnt[v][1][i]
tmp1[max(i - 1, j)] += cnt[u][1][j] * cnt[v][1][i]
for i in range(21):
tmp0[i] %= mod
tmp1[i] %= mod
cnt[u][0] = tmp0
cnt[u][1] = tmp1
dfs(1, 1)
print(sum(cnt[1][1][j] for j in range(k + 1)) % mod)
if __name__ == '__main__':
main()
``` | instruction | 0 | 96,651 | 13 | 193,302 |
No | output | 1 | 96,651 | 13 | 193,303 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ostap already settled down in Rio de Janiero suburb and started to grow a tree in his garden. Recall that a tree is a connected undirected acyclic graph.
Ostap's tree now has n vertices. He wants to paint some vertices of the tree black such that from any vertex u there is at least one black vertex v at distance no more than k. Distance between two vertices of the tree is the minimum possible number of edges of the path between them.
As this number of ways to paint the tree can be large, Ostap wants you to compute it modulo 109 + 7. Two ways to paint the tree are considered different if there exists a vertex that is painted black in one way and is not painted in the other one.
Input
The first line of the input contains two integers n and k (1 β€ n β€ 100, 0 β€ k β€ min(20, n - 1)) β the number of vertices in Ostap's tree and the maximum allowed distance to the nearest black vertex. Don't miss the unusual constraint for k.
Each of the next n - 1 lines contain two integers ui and vi (1 β€ ui, vi β€ n) β indices of vertices, connected by the i-th edge. It's guaranteed that given graph is a tree.
Output
Print one integer β the remainder of division of the number of ways to paint the tree by 1 000 000 007 (109 + 7).
Examples
Input
2 0
1 2
Output
1
Input
2 1
1 2
Output
3
Input
4 1
1 2
2 3
3 4
Output
9
Input
7 2
1 2
2 3
1 4
4 5
1 6
6 7
Output
91
Note
In the first sample, Ostap has to paint both vertices black.
In the second sample, it is enough to paint only one of two vertices, thus the answer is 3: Ostap can paint only vertex 1, only vertex 2, vertices 1 and 2 both.
In the third sample, the valid ways to paint vertices are: {1, 3}, {1, 4}, {2, 3}, {2, 4}, {1, 2, 3}, {1, 2, 4}, {1, 3, 4}, {2, 3, 4}, {1, 2, 3, 4}.
Submitted Solution:
```
def main():
n, k = map(int, input().split())
cnt = [[[0] * 21 for _ in (0, 1)] for _ in range(n + 1)]
edges, mod = [[] for _ in range(n + 1)], 100000007
for _ in range(n - 1):
u, v = map(int, input().split())
edges[u].append(v)
edges[v].append(u)
def dfs(u, f):
cnt[u][0][0] = cnt[u][1][k] = 1
for v in edges[u]:
if v != f:
dfs(v, u)
tmp0, tmp1 = [0] * 21, [0] * 21
for i in range(k + 1):
for j in range(k + 1):
if i != k:
tmp0[j if i < j else i + 1] += cnt[u][0][j] * cnt[v][0][i]
if i < j:
tmp1[j] += cnt[u][1][j] * cnt[v][0][i]
elif i != k:
tmp0[i + 1] += cnt[u][1][j] * cnt[v][0][i]
if i > j:
tmp1[i - 1] += cnt[u][0][j] * cnt[v][1][i]
else:
tmp0[j] += cnt[u][0][j] * cnt[v][1][i]
tmp1[max(i - 1, j)] += cnt[u][1][j] * cnt[v][1][i]
for i in range(21):
tmp0[i] %= mod
tmp1[i] %= mod
cnt[u][0] = tmp0
cnt[u][1] = tmp1
dfs(1, 1)
print(sum(cnt[1][1][j] for j in range(k + 1)) % mod)
if __name__ == '__main__':
main()
``` | instruction | 0 | 96,652 | 13 | 193,304 |
No | output | 1 | 96,652 | 13 | 193,305 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ostap already settled down in Rio de Janiero suburb and started to grow a tree in his garden. Recall that a tree is a connected undirected acyclic graph.
Ostap's tree now has n vertices. He wants to paint some vertices of the tree black such that from any vertex u there is at least one black vertex v at distance no more than k. Distance between two vertices of the tree is the minimum possible number of edges of the path between them.
As this number of ways to paint the tree can be large, Ostap wants you to compute it modulo 109 + 7. Two ways to paint the tree are considered different if there exists a vertex that is painted black in one way and is not painted in the other one.
Input
The first line of the input contains two integers n and k (1 β€ n β€ 100, 0 β€ k β€ min(20, n - 1)) β the number of vertices in Ostap's tree and the maximum allowed distance to the nearest black vertex. Don't miss the unusual constraint for k.
Each of the next n - 1 lines contain two integers ui and vi (1 β€ ui, vi β€ n) β indices of vertices, connected by the i-th edge. It's guaranteed that given graph is a tree.
Output
Print one integer β the remainder of division of the number of ways to paint the tree by 1 000 000 007 (109 + 7).
Examples
Input
2 0
1 2
Output
1
Input
2 1
1 2
Output
3
Input
4 1
1 2
2 3
3 4
Output
9
Input
7 2
1 2
2 3
1 4
4 5
1 6
6 7
Output
91
Note
In the first sample, Ostap has to paint both vertices black.
In the second sample, it is enough to paint only one of two vertices, thus the answer is 3: Ostap can paint only vertex 1, only vertex 2, vertices 1 and 2 both.
In the third sample, the valid ways to paint vertices are: {1, 3}, {1, 4}, {2, 3}, {2, 4}, {1, 2, 3}, {1, 2, 4}, {1, 3, 4}, {2, 3, 4}, {1, 2, 3, 4}.
Submitted Solution:
```
import sys
#sys.stdin=open("data.txt")
#sys.stdout=open("data.txt","w")
input=sys.stdin.readline
n,k=map(int,input().split())
g=[[] for _ in range(n+1)]
vis=[0]*(n+1)
for _ in range(n-1):
u,v=map(int,input().split())
g[u].append(v)
g[v].append(u)
def getans(u,k):
vis[u]=1
# first k -> need k
# then cover exact
# last k -> covers k above
totalv=[0]*(2*k+1)
totalv[k-1]=1
carry=1 # total when this node is black
for v in g[u]:
if vis[v]: continue
getv=getans(v,k)
carry=(carry*sum(getv))%1000000007
out2=[0]*(2*k+1)
#print("before",totalv)
for i in range(1,2*k+1):
for j in range(2*k+1):
if j+i>=2*k-1:
out2[max(i-1,j)]+=getv[i]*totalv[j]
else:
out2[min(i-1,j)]+=getv[i]*totalv[j]
for i in range(2*k+1):
totalv[i]=out2[i]%1000000007
#print("after ",totalv,carry)
totalv[2*k]+=carry
#print(u,totalv)
return totalv
if k==0: print(1)
else:
temp=getans(1,k)
print(sum(temp[k:])%1000000007)
``` | instruction | 0 | 96,653 | 13 | 193,306 |
No | output | 1 | 96,653 | 13 | 193,307 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Pasha is a good student and one of MoJaK's best friends. He always have a problem to think about. Today they had a talk about the following problem.
We have a forest (acyclic undirected graph) with n vertices and m edges. There are q queries we should answer. In each query two vertices v and u are given. Let V be the set of vertices in the connected component of the graph that contains v, and U be the set of vertices in the connected component of the graph that contains u. Let's add an edge between some vertex <image> and some vertex in <image> and compute the value d of the resulting component. If the resulting component is a tree, the value d is the diameter of the component, and it is equal to -1 otherwise. What is the expected value of d, if we choose vertices a and b from the sets uniformly at random?
Can you help Pasha to solve this problem?
The diameter of the component is the maximum distance among some pair of vertices in the component. The distance between two vertices is the minimum number of edges on some path between the two vertices.
Note that queries don't add edges to the initial forest.
Input
The first line contains three integers n, m and q(1 β€ n, m, q β€ 105) β the number of vertices, the number of edges in the graph and the number of queries.
Each of the next m lines contains two integers ui and vi (1 β€ ui, vi β€ n), that means there is an edge between vertices ui and vi.
It is guaranteed that the given graph is a forest.
Each of the next q lines contains two integers ui and vi (1 β€ ui, vi β€ n) β the vertices given in the i-th query.
Output
For each query print the expected value of d as described in the problem statement.
Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Let's assume that your answer is a, and the jury's answer is b. The checker program will consider your answer correct, if <image>.
Examples
Input
3 1 2
1 3
3 1
2 3
Output
-1
2.0000000000
Input
5 2 3
2 4
4 3
4 2
4 1
2 5
Output
-1
2.6666666667
2.6666666667
Note
In the first example the vertices 1 and 3 are in the same component, so the answer for the first query is -1. For the second query there are two options to add the edge: one option is to add the edge 1 - 2, the other one is 2 - 3. In both ways the resulting diameter is 2, so the answer is 2.
In the second example the answer for the first query is obviously -1. The answer for the second query is the average of three cases: for added edges 1 - 2 or 1 - 3 the diameter is 3, and for added edge 1 - 4 the diameter is 2. Thus, the answer is <image>.
Submitted Solution:
```
l,r,p,m=0,0,1,10**9+7
for i in input():
if i=='a':
l += 1
p = p*2%m
else: r = (r + p - 1)%m
print(r)
``` | instruction | 0 | 96,670 | 13 | 193,340 |
No | output | 1 | 96,670 | 13 | 193,341 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Pasha is a good student and one of MoJaK's best friends. He always have a problem to think about. Today they had a talk about the following problem.
We have a forest (acyclic undirected graph) with n vertices and m edges. There are q queries we should answer. In each query two vertices v and u are given. Let V be the set of vertices in the connected component of the graph that contains v, and U be the set of vertices in the connected component of the graph that contains u. Let's add an edge between some vertex <image> and some vertex in <image> and compute the value d of the resulting component. If the resulting component is a tree, the value d is the diameter of the component, and it is equal to -1 otherwise. What is the expected value of d, if we choose vertices a and b from the sets uniformly at random?
Can you help Pasha to solve this problem?
The diameter of the component is the maximum distance among some pair of vertices in the component. The distance between two vertices is the minimum number of edges on some path between the two vertices.
Note that queries don't add edges to the initial forest.
Input
The first line contains three integers n, m and q(1 β€ n, m, q β€ 105) β the number of vertices, the number of edges in the graph and the number of queries.
Each of the next m lines contains two integers ui and vi (1 β€ ui, vi β€ n), that means there is an edge between vertices ui and vi.
It is guaranteed that the given graph is a forest.
Each of the next q lines contains two integers ui and vi (1 β€ ui, vi β€ n) β the vertices given in the i-th query.
Output
For each query print the expected value of d as described in the problem statement.
Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Let's assume that your answer is a, and the jury's answer is b. The checker program will consider your answer correct, if <image>.
Examples
Input
3 1 2
1 3
3 1
2 3
Output
-1
2.0000000000
Input
5 2 3
2 4
4 3
4 2
4 1
2 5
Output
-1
2.6666666667
2.6666666667
Note
In the first example the vertices 1 and 3 are in the same component, so the answer for the first query is -1. For the second query there are two options to add the edge: one option is to add the edge 1 - 2, the other one is 2 - 3. In both ways the resulting diameter is 2, so the answer is 2.
In the second example the answer for the first query is obviously -1. The answer for the second query is the average of three cases: for added edges 1 - 2 or 1 - 3 the diameter is 3, and for added edge 1 - 4 the diameter is 2. Thus, the answer is <image>.
Submitted Solution:
```
from math import inf
n, m, q = [int(x) for x in input().split(' ')]
distance = [[inf for _ in range(n)] for _ in range(n)]
connected = [[0 for _ in range(n)] for _ in range(n)]
in_question = [[-1 for _ in range(n)] for _ in range(n)]
answers = []
max_distance = -1
num_max_distance = 0
for i in range(m):
a,b = [int(x)-1 for x in input().split(' ')]
distance[a][b] = 1
distance[b][a] = 1
connected[a][b] = 1
connected[b][a] = 1
for i in range(n):
distance[a][i] = min(distance[a][i], distance[b][i] + 1)
distance[i][b] = min(distance[i][b], distance[i][a] + 1)
distance[i][a] = min(distance[i][a], distance[i][b] + 1)
distance[b][i] = min(distance[b][i], distance[a][i] + 1)
distance[a][a] = 0
distance[b][b] = 0
for i in range(n):
distance[i][i] = 0
def copy_mat(X):
a = [[c for c in row] for row in X]
return a
for i in range(q):
a,b = [int(x)-1 for x in input().split(' ')]
if distance[a][b] < inf or distance[b][a] < inf:
answers.append(-1)
else:
distances = []
for i in range(n):
if distance[a][i] < inf:
for j in range(n):
if distance[b][j] < inf:
new_dist = sum([
max([d for d in distance[i] if d < inf]),
max([d for d in distance[j] if d < inf]),
1
])
distances.append(new_dist)
answers.append(sum(distances)/len(distances))
for a in answers:
print(a)
``` | instruction | 0 | 96,671 | 13 | 193,342 |
No | output | 1 | 96,671 | 13 | 193,343 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Pasha is a good student and one of MoJaK's best friends. He always have a problem to think about. Today they had a talk about the following problem.
We have a forest (acyclic undirected graph) with n vertices and m edges. There are q queries we should answer. In each query two vertices v and u are given. Let V be the set of vertices in the connected component of the graph that contains v, and U be the set of vertices in the connected component of the graph that contains u. Let's add an edge between some vertex <image> and some vertex in <image> and compute the value d of the resulting component. If the resulting component is a tree, the value d is the diameter of the component, and it is equal to -1 otherwise. What is the expected value of d, if we choose vertices a and b from the sets uniformly at random?
Can you help Pasha to solve this problem?
The diameter of the component is the maximum distance among some pair of vertices in the component. The distance between two vertices is the minimum number of edges on some path between the two vertices.
Note that queries don't add edges to the initial forest.
Input
The first line contains three integers n, m and q(1 β€ n, m, q β€ 105) β the number of vertices, the number of edges in the graph and the number of queries.
Each of the next m lines contains two integers ui and vi (1 β€ ui, vi β€ n), that means there is an edge between vertices ui and vi.
It is guaranteed that the given graph is a forest.
Each of the next q lines contains two integers ui and vi (1 β€ ui, vi β€ n) β the vertices given in the i-th query.
Output
For each query print the expected value of d as described in the problem statement.
Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Let's assume that your answer is a, and the jury's answer is b. The checker program will consider your answer correct, if <image>.
Examples
Input
3 1 2
1 3
3 1
2 3
Output
-1
2.0000000000
Input
5 2 3
2 4
4 3
4 2
4 1
2 5
Output
-1
2.6666666667
2.6666666667
Note
In the first example the vertices 1 and 3 are in the same component, so the answer for the first query is -1. For the second query there are two options to add the edge: one option is to add the edge 1 - 2, the other one is 2 - 3. In both ways the resulting diameter is 2, so the answer is 2.
In the second example the answer for the first query is obviously -1. The answer for the second query is the average of three cases: for added edges 1 - 2 or 1 - 3 the diameter is 3, and for added edge 1 - 4 the diameter is 2. Thus, the answer is <image>.
Submitted Solution:
```
from math import inf
n, m, q = [int(x) for x in input().split(' ')]
distance = [[inf for _ in range(n)] for _ in range(n)]
in_question = [[-1 for _ in range(n)] for _ in range(n)]
answers = []
max_distance = -1
num_max_distance = 0
for i in range(m):
a,b = [int(x)-1 for x in input().split(' ')]
distance[a][b] = 1
distance[b][a] = 1
for i in range(n):
distance[a][i] = min(distance[a][i], distance[b][i] + 1)
distance[i][b] = min(distance[i][b], distance[i][a] + 1)
distance[i][a] = min(distance[i][a], distance[i][b] + 1)
distance[b][i] = min(distance[b][i], distance[a][i] + 1)
distance[a][a] = inf
distance[b][b] = inf
for i in range(n):
for j in range(n):
if distance[i][j] < inf:
if distance[i][j] > max_distance:
max_distance = distance[i][j]
num_max_distance = 0
for i in range(n):
for j in range(n):
if distance[i][j] < inf:
if distance[i][j] == max_distance:
num_max_distance += 1
break
accessible_nodes = 0
for i in range(n):
if any([distance[i][j] < inf for j in range(n)]):
accessible_nodes += 1
for i in range(q):
a,b = [int(x)-1 for x in input().split(' ')]
in_question[a][b] = 1
if distance[a][b] < inf or distance[b][a] < inf:
answers.append(-1)
else:
answers.append(
(num_max_distance*(max_distance+1) + (accessible_nodes-num_max_distance)*max_distance)/accessible_nodes
)
for a in answers:
print(a)
# for row in distance:
# print(', '.join([str(x).zfill(3) for x in row]))
``` | instruction | 0 | 96,672 | 13 | 193,344 |
No | output | 1 | 96,672 | 13 | 193,345 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Pasha is a good student and one of MoJaK's best friends. He always have a problem to think about. Today they had a talk about the following problem.
We have a forest (acyclic undirected graph) with n vertices and m edges. There are q queries we should answer. In each query two vertices v and u are given. Let V be the set of vertices in the connected component of the graph that contains v, and U be the set of vertices in the connected component of the graph that contains u. Let's add an edge between some vertex <image> and some vertex in <image> and compute the value d of the resulting component. If the resulting component is a tree, the value d is the diameter of the component, and it is equal to -1 otherwise. What is the expected value of d, if we choose vertices a and b from the sets uniformly at random?
Can you help Pasha to solve this problem?
The diameter of the component is the maximum distance among some pair of vertices in the component. The distance between two vertices is the minimum number of edges on some path between the two vertices.
Note that queries don't add edges to the initial forest.
Input
The first line contains three integers n, m and q(1 β€ n, m, q β€ 105) β the number of vertices, the number of edges in the graph and the number of queries.
Each of the next m lines contains two integers ui and vi (1 β€ ui, vi β€ n), that means there is an edge between vertices ui and vi.
It is guaranteed that the given graph is a forest.
Each of the next q lines contains two integers ui and vi (1 β€ ui, vi β€ n) β the vertices given in the i-th query.
Output
For each query print the expected value of d as described in the problem statement.
Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Let's assume that your answer is a, and the jury's answer is b. The checker program will consider your answer correct, if <image>.
Examples
Input
3 1 2
1 3
3 1
2 3
Output
-1
2.0000000000
Input
5 2 3
2 4
4 3
4 2
4 1
2 5
Output
-1
2.6666666667
2.6666666667
Note
In the first example the vertices 1 and 3 are in the same component, so the answer for the first query is -1. For the second query there are two options to add the edge: one option is to add the edge 1 - 2, the other one is 2 - 3. In both ways the resulting diameter is 2, so the answer is 2.
In the second example the answer for the first query is obviously -1. The answer for the second query is the average of three cases: for added edges 1 - 2 or 1 - 3 the diameter is 3, and for added edge 1 - 4 the diameter is 2. Thus, the answer is <image>.
Submitted Solution:
```
from math import inf
n, m, q = [int(x) for x in input().split(' ')]
distance = [[inf for _ in range(n)] for _ in range(n)]
connected = [[0 for _ in range(n)] for _ in range(n)]
in_question = [[-1 for _ in range(n)] for _ in range(n)]
answers = []
max_distance = -1
num_max_distance = 0
for i in range(m):
a,b = [int(x)-1 for x in input().split(' ')]
distance[a][b] = 1
distance[b][a] = 1
connected[a][b] = 1
connected[b][a] = 1
for i in range(n):
distance[a][i] = min(distance[a][i], distance[b][i] + 1)
distance[i][b] = min(distance[i][b], distance[i][a] + 1)
distance[i][a] = min(distance[i][a], distance[i][b] + 1)
distance[b][i] = min(distance[b][i], distance[a][i] + 1)
distance[a][a] = inf
distance[b][b] = inf
for i in range(n):
for j in range(n):
if distance[i][j] < inf:
if distance[i][j] > max_distance:
max_distance = distance[i][j]
num_max_distance = 0
for i in range(n):
for j in range(n):
if distance[i][j] < inf:
if distance[i][j] == max_distance:
num_max_distance += 1
break
accessible_nodes = 0
for i in range(n):
if any([distance[i][j] < inf for j in range(n)]):
accessible_nodes += 1
for i in range(q):
a,b = [int(x)-1 for x in input().split(' ')]
in_question[a][b] = 1
if distance[a][b] < inf or distance[b][a] < inf:
answers.append(-1)
else:
answers.append(
(num_max_distance*(max_distance+1) + (accessible_nodes-num_max_distance)*max_distance)/accessible_nodes
)
for d in connected:
print(','.join(['1' if e == 1 else '0' for e in d]))
for a in answers:
print(a)
# for row in distance:
# print(', '.join([str(x).zfill(3) for x in row]))
``` | instruction | 0 | 96,673 | 13 | 193,346 |
No | output | 1 | 96,673 | 13 | 193,347 |
Provide a correct Python 3 solution for this coding contest problem.
Fox Ciel is developing an artificial intelligence (AI) for a game. This game is described as a game tree T with n vertices. Each node in the game has an evaluation value which shows how good a situation is. This value is the same as maximum value of child nodesβ values multiplied by -1. Values on leaf nodes are evaluated with Cielβs special function -- which is a bit heavy. So, she will use alpha-beta pruning for getting root nodeβs evaluation value to decrease the number of leaf nodes to be calculated.
By the way, changing evaluation order of child nodes affects the number of calculation on the leaf nodes. Therefore, Ciel wants to know the minimum and maximum number of times to calculate in leaf nodes when she could evaluate child node in arbitrary order. She asked you to calculate minimum evaluation number of times and maximum evaluation number of times in leaf nodes.
Ciel uses following algotithm:
function negamax(node, Ξ±, Ξ²)
if node is a terminal node
return value of leaf node
else
foreach child of node
val := -negamax(child, -Ξ², -Ξ±)
if val >= Ξ²
return val
if val > Ξ±
Ξ± := val
return Ξ±
[NOTE] negamax algorithm
Input
Input follows following format:
n
p_1 p_2 ... p_n
k_1 t_{11} t_{12} ... t_{1k}
:
:
k_n t_{n1} t_{n2} ... t_{nk}
The first line contains an integer n, which means the number of vertices in game tree T.
The second line contains n integers p_i, which means the evaluation value of vertex i.
Then, next n lines which contain the information of game tree T.
k_i is the number of child nodes of vertex i, and t_{ij} is the indices of the child node of vertex i.
Input follows following constraints:
* 2 \leq n \leq 100
* -10,000 \leq p_i \leq 10,000
* 0 \leq k_i \leq 5
* 2 \leq t_{ij} \leq n
* Index of root node is 1.
* Evaluation value except leaf node is always 0. This does not mean the evaluation values of non-leaf nodes are 0. You have to calculate them if necessary.
* Leaf node sometimes have evaluation value of 0.
* Game tree T is tree structure.
Output
Print the minimum evaluation number of times and the maximum evaluation number of times in leaf node.
Please separated by whitespace between minimum and maximum.
minimum maximum
Sample Input 1
3
0 1 1
2 2 3
0
0
Output for the Sample Input 1
2 2
Sample Input 2
8
0 0 100 100 0 -100 -100 -100
2 2 5
2 3 4
0
0
3 6 7 8
0
0
0
Output for the Sample Input 2
3 5
Sample Input 3
8
0 0 100 100 0 100 100 100
2 2 5
2 3 4
0
0
3 6 7 8
0
0
0
Output for the Sample Input 3
3 4
Sample Input 4
19
0 100 0 100 0 0 0 0 0 1 2 3 4 5 6 7 8 9 10
2 2 3
0
2 4 5
0
3 6 7 8
3 9 10 11
3 12 13 14
3 15 16 17
2 18 19
0
0
0
0
0
0
0
0
0
0
Output for the Sample Input 4
7 12
Example
Input
3
0 1 1
2 2 3
0
0
Output
2 2 | instruction | 0 | 96,916 | 13 | 193,832 |
"Correct Solution:
```
from collections import deque
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
N = int(readline())
*P, = map(int, readline().split())
G = []
prt = [0]*N
for i in range(N):
k, *t = map(int, readline().split())
G.append([e-1 for e in t])
for e in t:
prt[e-1] = i
*D, = map(len, G)
A = [0]*N
deg = D[:]
que = deque()
for v in range(N):
if deg[v] == 0:
A[v] = P[v]
que.append(v)
while que:
v = que.popleft()
p = prt[v]
deg[p] -= 1
if deg[p] == 0:
A[p] = max(-A[w] for w in G[p])
que.append(p)
for v in range(N):
if D[v] == 0:
A[v] = P[v]
else:
A[v] = max(-A[w] for w in G[v])
memo = {}
def dfs(v, state, c, a, b):
key = (v, state, a, b)
if key in memo:
return memo[key]
if c == D[v]:
if c == 0:
return 1, 1
return 0, 0
c0 = N+1; c1 = 0
Gv = G[v]
for k in range(D[v]):
if state & (1 << k):
continue
w = Gv[k]
s0, s1 = dfs(w, 0, 0, -b, -a)
val = -A[w]
if val >= b:
c0 = min(c0, s0); c1 = max(c1, s1)
continue
t0, t1 = dfs(v, state | (1 << k), c+1, max(a, val), b)
c0 = min(c0, s0+t0)
c1 = max(c1, s1+t1)
memo[key] = c0, c1
return c0, c1
INF = 10**9
r0, r1 = dfs(0, 0, 0, -INF, INF)
write("%d %d\n" % (r0, r1))
solve()
``` | output | 1 | 96,916 | 13 | 193,833 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected tree consisting of n vertices. An undirected tree is a connected undirected graph with n - 1 edges.
Your task is to add the minimum number of edges in such a way that the length of the shortest path from the vertex 1 to any other vertex is at most 2. Note that you are not allowed to add loops and multiple edges.
Input
The first line contains one integer n (2 β€ n β€ 2 β
10^5) β the number of vertices in the tree.
The following n - 1 lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 β€ u_i, v_i β€ n). It is guaranteed that the given edges form a tree. It is guaranteed that there are no loops and multiple edges in the given edges.
Output
Print a single integer β the minimum number of edges you have to add in order to make the shortest distance from the vertex 1 to any other vertex at most 2. Note that you are not allowed to add loops and multiple edges.
Examples
Input
7
1 2
2 3
2 4
4 5
4 6
5 7
Output
2
Input
7
1 2
1 3
2 4
2 5
3 6
1 7
Output
0
Input
7
1 2
2 3
3 4
3 5
3 6
3 7
Output
1
Note
The tree corresponding to the first example: <image> The answer is 2, some of the possible answers are the following: [(1, 5), (1, 6)], [(1, 4), (1, 7)], [(1, 6), (1, 7)].
The tree corresponding to the second example: <image> The answer is 0.
The tree corresponding to the third example: <image> The answer is 1, only one possible way to reach it is to add the edge (1, 3). | instruction | 0 | 96,960 | 13 | 193,920 |
Tags: dp, graphs, greedy
Correct Solution:
```
from sys import stdin
n = int(stdin.readline())
g = dict()
for i in range(n-1):
u,v = map(int,stdin.readline().split())
g.setdefault(u-1,[]).append(v-1)
g.setdefault(v-1, []).append(u-1)
st = [0]
rank = [0]*n
tree = [0]*n
msk = [0]*n
rd = dict()
while len(st)>0:
top = st.pop()
msk[top] = 1
for c in g[top]:
if msk[c] == 0:
st.append(c)
tree[c] = top
rank[c] = rank[top]+1
rd.setdefault(rank[c], []).append(c)
max_rank = max(rank)
reach = [0]*n
build = [0]*n
ans = 0
for r in range(max_rank, 2, -1):
for node in rd[r]:
if reach[node] == 0:
reach[node] = 1
reach[tree[node]] = 1
reach[tree[tree[node]]] = 1
build[tree[node]] = 1
print(sum(build))
``` | output | 1 | 96,960 | 13 | 193,921 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected tree consisting of n vertices. An undirected tree is a connected undirected graph with n - 1 edges.
Your task is to add the minimum number of edges in such a way that the length of the shortest path from the vertex 1 to any other vertex is at most 2. Note that you are not allowed to add loops and multiple edges.
Input
The first line contains one integer n (2 β€ n β€ 2 β
10^5) β the number of vertices in the tree.
The following n - 1 lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 β€ u_i, v_i β€ n). It is guaranteed that the given edges form a tree. It is guaranteed that there are no loops and multiple edges in the given edges.
Output
Print a single integer β the minimum number of edges you have to add in order to make the shortest distance from the vertex 1 to any other vertex at most 2. Note that you are not allowed to add loops and multiple edges.
Examples
Input
7
1 2
2 3
2 4
4 5
4 6
5 7
Output
2
Input
7
1 2
1 3
2 4
2 5
3 6
1 7
Output
0
Input
7
1 2
2 3
3 4
3 5
3 6
3 7
Output
1
Note
The tree corresponding to the first example: <image> The answer is 2, some of the possible answers are the following: [(1, 5), (1, 6)], [(1, 4), (1, 7)], [(1, 6), (1, 7)].
The tree corresponding to the second example: <image> The answer is 0.
The tree corresponding to the third example: <image> The answer is 1, only one possible way to reach it is to add the edge (1, 3). | instruction | 0 | 96,961 | 13 | 193,922 |
Tags: dp, graphs, greedy
Correct Solution:
```
from collections import defaultdict
from collections import deque
import sys
input = sys.stdin.readline
def bfs(s):
q = deque()
q.append(s)
dist = [-1] * (n + 1)
dist[s] = 0
p = []
parent = [1] * (n + 1)
ok = [0] * (n + 1)
while q:
i = q.popleft()
d = dist[i]
if d < 3:
ok[i] = 1
p.append(i)
for j in G[i]:
if dist[j] == -1:
q.append(j)
dist[j] = d + 1
parent[j] = i
ans = 0
while p:
i = p.pop()
j = parent[i]
if not ok[i]:
ok[j] = 1
ans += 1
for k in G[j]:
ok[k] = 1
return ans
n = int(input())
G = [[] for _ in range(n + 1)]
for _ in range(n - 1):
u, v = map(int, input().split())
G[u].append(v)
G[v].append(u)
ans = bfs(1)
print(ans)
``` | output | 1 | 96,961 | 13 | 193,923 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected tree consisting of n vertices. An undirected tree is a connected undirected graph with n - 1 edges.
Your task is to add the minimum number of edges in such a way that the length of the shortest path from the vertex 1 to any other vertex is at most 2. Note that you are not allowed to add loops and multiple edges.
Input
The first line contains one integer n (2 β€ n β€ 2 β
10^5) β the number of vertices in the tree.
The following n - 1 lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 β€ u_i, v_i β€ n). It is guaranteed that the given edges form a tree. It is guaranteed that there are no loops and multiple edges in the given edges.
Output
Print a single integer β the minimum number of edges you have to add in order to make the shortest distance from the vertex 1 to any other vertex at most 2. Note that you are not allowed to add loops and multiple edges.
Examples
Input
7
1 2
2 3
2 4
4 5
4 6
5 7
Output
2
Input
7
1 2
1 3
2 4
2 5
3 6
1 7
Output
0
Input
7
1 2
2 3
3 4
3 5
3 6
3 7
Output
1
Note
The tree corresponding to the first example: <image> The answer is 2, some of the possible answers are the following: [(1, 5), (1, 6)], [(1, 4), (1, 7)], [(1, 6), (1, 7)].
The tree corresponding to the second example: <image> The answer is 0.
The tree corresponding to the third example: <image> The answer is 1, only one possible way to reach it is to add the edge (1, 3). | instruction | 0 | 96,962 | 13 | 193,924 |
Tags: dp, graphs, greedy
Correct Solution:
```
import sys
def get_new_edges(graph):
n = len(graph)
far_vertex = []
pi = [None]*n
visit = [False]*n
visit[0]
queue = [[0,0]]
i = 0
while True:
if i >= len(queue): break
current, d = queue[i]
i += 1
visit[current] = True
for v in graph[current]:
if not visit[v]:
u = [v, d+1]
pi[v] = current
queue.append(u)
if d+1 > 2:
far_vertex.append(u)
far_vertex.sort(key=lambda x: -x[1])
pos = [None]*n
for i, e in enumerate(far_vertex):
pos[e[0]] = i
count = 0
for i in range(len(far_vertex)):
if not far_vertex[i]: continue
vertex, depth = far_vertex[i]
father = pi[vertex]
count += 1
if pos[father]:
far_vertex[pos[father]] = None
for u in graph[father]:
if pos[u]:
far_vertex[pos[u]] = None
return count
def read_int_line():
return map(int, sys.stdin.readline().split())
vertex_count = int(input())
graph = [[] for _ in range(vertex_count)]
for i in range(vertex_count - 1):
v1, v2 = read_int_line()
v1 -= 1
v2 -= 1
graph[v1].append(v2)
graph[v2].append(v1)
print(get_new_edges(graph))
``` | output | 1 | 96,962 | 13 | 193,925 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected tree consisting of n vertices. An undirected tree is a connected undirected graph with n - 1 edges.
Your task is to add the minimum number of edges in such a way that the length of the shortest path from the vertex 1 to any other vertex is at most 2. Note that you are not allowed to add loops and multiple edges.
Input
The first line contains one integer n (2 β€ n β€ 2 β
10^5) β the number of vertices in the tree.
The following n - 1 lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 β€ u_i, v_i β€ n). It is guaranteed that the given edges form a tree. It is guaranteed that there are no loops and multiple edges in the given edges.
Output
Print a single integer β the minimum number of edges you have to add in order to make the shortest distance from the vertex 1 to any other vertex at most 2. Note that you are not allowed to add loops and multiple edges.
Examples
Input
7
1 2
2 3
2 4
4 5
4 6
5 7
Output
2
Input
7
1 2
1 3
2 4
2 5
3 6
1 7
Output
0
Input
7
1 2
2 3
3 4
3 5
3 6
3 7
Output
1
Note
The tree corresponding to the first example: <image> The answer is 2, some of the possible answers are the following: [(1, 5), (1, 6)], [(1, 4), (1, 7)], [(1, 6), (1, 7)].
The tree corresponding to the second example: <image> The answer is 0.
The tree corresponding to the third example: <image> The answer is 1, only one possible way to reach it is to add the edge (1, 3). | instruction | 0 | 96,963 | 13 | 193,926 |
Tags: dp, graphs, greedy
Correct Solution:
```
import sys
from collections import deque
import heapq
input = sys.stdin.readline
N=int(input())
EDGE=[list(map(int,input().split())) for i in range(N-1)]
EDGELIST=[[] for i in range(N+1)]
for i,j in EDGE:
EDGELIST[i].append(j)
EDGELIST[j].append(i)
#EDGES=[[] for i in range(N+1)]
REDG=[None for i in range(N+1)]
QUE=deque([1])
check=[0]*(N+1)
DEPTH=[None]*(N+1)
i=0
while QUE:
NQUE=deque()
i+=1
while QUE:
x=QUE.pop()
DEPTH[x]=i
check[x]=1
for to in EDGELIST[x]:
if check[to]==1:
continue
else:
#EDGES[x].append(to)
REDG[to]=x
NQUE.append(to)
QUE=NQUE
check=[0]*(N+1)
check[1]=1
#NEXT=[]
#for i in EDGES[1]:
# check[i]=1
# NEXT.append(i)
#for j in NEXT:
# for k in EDGES[j]:
# check[k]=1
LEAF=[]
for i in range(2,N+1):
if len(EDGELIST[i])==1:
LEAF.append((-DEPTH[i],i))
QUE=LEAF
heapq.heapify(QUE)
ANS=0
#print(check,QUE)
while QUE:
dep,x=heapq.heappop(QUE)
if check[x]!=0 or dep>=-3:
continue
if check[REDG[x]]==2:
continue
if check[x]==0:
check[x]=1
if check[REDG[REDG[x]]]==0:
check[REDG[REDG[x]]]=1
check[REDG[x]]=2
heapq.heappush(QUE,(-DEPTH[REDG[REDG[REDG[x]]]],REDG[REDG[REDG[x]]]))
ANS+=1
#print(x,QUE,check)
print(ANS)
``` | output | 1 | 96,963 | 13 | 193,927 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected tree consisting of n vertices. An undirected tree is a connected undirected graph with n - 1 edges.
Your task is to add the minimum number of edges in such a way that the length of the shortest path from the vertex 1 to any other vertex is at most 2. Note that you are not allowed to add loops and multiple edges.
Input
The first line contains one integer n (2 β€ n β€ 2 β
10^5) β the number of vertices in the tree.
The following n - 1 lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 β€ u_i, v_i β€ n). It is guaranteed that the given edges form a tree. It is guaranteed that there are no loops and multiple edges in the given edges.
Output
Print a single integer β the minimum number of edges you have to add in order to make the shortest distance from the vertex 1 to any other vertex at most 2. Note that you are not allowed to add loops and multiple edges.
Examples
Input
7
1 2
2 3
2 4
4 5
4 6
5 7
Output
2
Input
7
1 2
1 3
2 4
2 5
3 6
1 7
Output
0
Input
7
1 2
2 3
3 4
3 5
3 6
3 7
Output
1
Note
The tree corresponding to the first example: <image> The answer is 2, some of the possible answers are the following: [(1, 5), (1, 6)], [(1, 4), (1, 7)], [(1, 6), (1, 7)].
The tree corresponding to the second example: <image> The answer is 0.
The tree corresponding to the third example: <image> The answer is 1, only one possible way to reach it is to add the edge (1, 3). | instruction | 0 | 96,964 | 13 | 193,928 |
Tags: dp, graphs, greedy
Correct Solution:
```
import sys
from collections import deque
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
n = inp()
edges = [[] for _ in range(n)]
for _ in range(n-1):
a,b = inpl()
a,b = a-1,b-1
edges[a].append(b)
edges[b].append(a)
dist = [-1] * n
dist[0] = 0
pa = [-1] * n
se = set()
pq = []
q = deque()
q.append(0)
while q:
now = q.popleft()
for nx in edges[now]:
if dist[nx] != -1:
continue
pa[nx] = now
dist[nx] = dist[now] + 1
if dist[nx] > 2:
se.add(nx)
pq.append((dist[nx], nx))
q.append(nx)
pq = pq[::-1]
res = 0
ind = 0
while se:
d,v = pq[ind]
ind += 1
if not v in se:
continue
res += 1
pv = pa[v]
se.discard(pv)
for nv in edges[pv]:
se.discard(nv)
print(res)
``` | output | 1 | 96,964 | 13 | 193,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 tree consisting of n vertices. An undirected tree is a connected undirected graph with n - 1 edges.
Your task is to add the minimum number of edges in such a way that the length of the shortest path from the vertex 1 to any other vertex is at most 2. Note that you are not allowed to add loops and multiple edges.
Input
The first line contains one integer n (2 β€ n β€ 2 β
10^5) β the number of vertices in the tree.
The following n - 1 lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 β€ u_i, v_i β€ n). It is guaranteed that the given edges form a tree. It is guaranteed that there are no loops and multiple edges in the given edges.
Output
Print a single integer β the minimum number of edges you have to add in order to make the shortest distance from the vertex 1 to any other vertex at most 2. Note that you are not allowed to add loops and multiple edges.
Examples
Input
7
1 2
2 3
2 4
4 5
4 6
5 7
Output
2
Input
7
1 2
1 3
2 4
2 5
3 6
1 7
Output
0
Input
7
1 2
2 3
3 4
3 5
3 6
3 7
Output
1
Note
The tree corresponding to the first example: <image> The answer is 2, some of the possible answers are the following: [(1, 5), (1, 6)], [(1, 4), (1, 7)], [(1, 6), (1, 7)].
The tree corresponding to the second example: <image> The answer is 0.
The tree corresponding to the third example: <image> The answer is 1, only one possible way to reach it is to add the edge (1, 3).
Submitted Solution:
```
n=int(input())
l=[[] for i in range(n+2)]
visited=[False for i in range(n+2)]
for i in range(n-1):
a,b=map(int,input().split())
l[a].append(b)
l[b].append(a)
dp=[[] for i in range(n+2)]
f=[-1 for i in range(n+2)]
def dfs(n,p):
dp[p].append(n)
p+=1
for i in l[n]:
if not visited[i]:
f[i]=n
visited[i]=True
dfs(i,p)
visited[n]=False
ans=0
dfs(1,0)
for i in range(n,2,-1):
for j in dp[i]:
if not visited[j]:
visited[j]=True
visited[f[j]]=True
ans+=1
for k in (l[f[j]]):
visited[k]=True
print(ans)
``` | instruction | 0 | 96,965 | 13 | 193,930 |
No | output | 1 | 96,965 | 13 | 193,931 |
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 tree consisting of n vertices. An undirected tree is a connected undirected graph with n - 1 edges.
Your task is to add the minimum number of edges in such a way that the length of the shortest path from the vertex 1 to any other vertex is at most 2. Note that you are not allowed to add loops and multiple edges.
Input
The first line contains one integer n (2 β€ n β€ 2 β
10^5) β the number of vertices in the tree.
The following n - 1 lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 β€ u_i, v_i β€ n). It is guaranteed that the given edges form a tree. It is guaranteed that there are no loops and multiple edges in the given edges.
Output
Print a single integer β the minimum number of edges you have to add in order to make the shortest distance from the vertex 1 to any other vertex at most 2. Note that you are not allowed to add loops and multiple edges.
Examples
Input
7
1 2
2 3
2 4
4 5
4 6
5 7
Output
2
Input
7
1 2
1 3
2 4
2 5
3 6
1 7
Output
0
Input
7
1 2
2 3
3 4
3 5
3 6
3 7
Output
1
Note
The tree corresponding to the first example: <image> The answer is 2, some of the possible answers are the following: [(1, 5), (1, 6)], [(1, 4), (1, 7)], [(1, 6), (1, 7)].
The tree corresponding to the second example: <image> The answer is 0.
The tree corresponding to the third example: <image> The answer is 1, only one possible way to reach it is to add the edge (1, 3).
Submitted Solution:
```
import sys
from collections import deque
import heapq
input = sys.stdin.readline
N=int(input())
EDGE=[list(map(int,input().split())) for i in range(N-1)]
EDGELIST=[[] for i in range(N+1)]
for i,j in EDGE:
EDGELIST[i].append(j)
EDGELIST[j].append(i)
EDGES=[[] for i in range(N+1)]
REDG=[None for i in range(N+1)]
QUE=deque([1])
check=[0]*(N+1)
DEPTH=[None]*(N+1)
i=0
while QUE:
NQUE=deque()
i+=1
while QUE:
x=QUE.pop()
DEPTH[x]=i
check[x]=1
for to in EDGELIST[x]:
if check[to]==1:
continue
else:
EDGES[x].append(to)
REDG[to]=x
NQUE.append(to)
QUE=NQUE
check=[0]*(N+1)
check[1]=1
NEXT=[]
for i in EDGES[1]:
check[i]=1
NEXT.append(i)
for j in NEXT:
for k in EDGES[j]:
check[k]=1
LEAF=[]
for i in range(2,N+1):
if EDGES[i]==[]:
LEAF.append((-DEPTH[i],i))
QUE=LEAF
heapq.heapify(QUE)
ANS=0
#print(check,QUE)
while QUE:
_,x=QUE.pop()
if check[x]!=0:
continue
if check[REDG[x]]==2:
continue
check[x]=check[REDG[REDG[x]]]=1
check[REDG[x]]=2
heapq.heappush(QUE,(-DEPTH[REDG[REDG[REDG[x]]]],REDG[REDG[REDG[x]]]))
ANS+=1
#print(x,QUE,check)
print(ANS)
``` | instruction | 0 | 96,966 | 13 | 193,932 |
No | output | 1 | 96,966 | 13 | 193,933 |
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 tree consisting of n vertices. An undirected tree is a connected undirected graph with n - 1 edges.
Your task is to add the minimum number of edges in such a way that the length of the shortest path from the vertex 1 to any other vertex is at most 2. Note that you are not allowed to add loops and multiple edges.
Input
The first line contains one integer n (2 β€ n β€ 2 β
10^5) β the number of vertices in the tree.
The following n - 1 lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 β€ u_i, v_i β€ n). It is guaranteed that the given edges form a tree. It is guaranteed that there are no loops and multiple edges in the given edges.
Output
Print a single integer β the minimum number of edges you have to add in order to make the shortest distance from the vertex 1 to any other vertex at most 2. Note that you are not allowed to add loops and multiple edges.
Examples
Input
7
1 2
2 3
2 4
4 5
4 6
5 7
Output
2
Input
7
1 2
1 3
2 4
2 5
3 6
1 7
Output
0
Input
7
1 2
2 3
3 4
3 5
3 6
3 7
Output
1
Note
The tree corresponding to the first example: <image> The answer is 2, some of the possible answers are the following: [(1, 5), (1, 6)], [(1, 4), (1, 7)], [(1, 6), (1, 7)].
The tree corresponding to the second example: <image> The answer is 0.
The tree corresponding to the third example: <image> The answer is 1, only one possible way to reach it is to add the edge (1, 3).
Submitted Solution:
```
from sys import stdin
n = int(stdin.readline())
g = dict()
for i in range(n-1):
u,v = map(int,stdin.readline().split())
g.setdefault(u-1,[]).append(v-1)
g.setdefault(v-1, []).append(u-1)
st = [0]
rank = [0]*n
tree = [0]*n
msk = [0]*n
rd = dict()
while len(st)>0:
top = st.pop()
msk[top] = 1
for c in g[top]:
if msk[c] == 0:
st.append(c)
tree[c] = top
rank[c] = rank[top]+1
rd.setdefault(rank[c], []).append(c)
max_rank = max(rank)
reach = [0]*n
for r in range(max_rank, 2, -1):
for node in rd[r]:
if reach[node] == 0:
reach[tree[node]] = 1
print(sum(reach))
``` | instruction | 0 | 96,967 | 13 | 193,934 |
No | output | 1 | 96,967 | 13 | 193,935 |
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 tree consisting of n vertices. An undirected tree is a connected undirected graph with n - 1 edges.
Your task is to add the minimum number of edges in such a way that the length of the shortest path from the vertex 1 to any other vertex is at most 2. Note that you are not allowed to add loops and multiple edges.
Input
The first line contains one integer n (2 β€ n β€ 2 β
10^5) β the number of vertices in the tree.
The following n - 1 lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 β€ u_i, v_i β€ n). It is guaranteed that the given edges form a tree. It is guaranteed that there are no loops and multiple edges in the given edges.
Output
Print a single integer β the minimum number of edges you have to add in order to make the shortest distance from the vertex 1 to any other vertex at most 2. Note that you are not allowed to add loops and multiple edges.
Examples
Input
7
1 2
2 3
2 4
4 5
4 6
5 7
Output
2
Input
7
1 2
1 3
2 4
2 5
3 6
1 7
Output
0
Input
7
1 2
2 3
3 4
3 5
3 6
3 7
Output
1
Note
The tree corresponding to the first example: <image> The answer is 2, some of the possible answers are the following: [(1, 5), (1, 6)], [(1, 4), (1, 7)], [(1, 6), (1, 7)].
The tree corresponding to the second example: <image> The answer is 0.
The tree corresponding to the third example: <image> The answer is 1, only one possible way to reach it is to add the edge (1, 3).
Submitted Solution:
```
import sys
def get_new_edges(graph):
n = len(graph)
far_vertex = []
pi = [None]*n
visit = [False]*n
visit[0]
queue = [[0,0]]
i = 0
while True:
if i >= len(queue): break
current, d = queue[i]
i += 1
visit[current] = True
for v in graph[current]:
if not visit[v]:
u = [v, d+1]
pi[v] = current
queue.append(u)
if d+1 > 2:
far_vertex.append(u)
far_vertex.sort(key=lambda x: -x[1])
pos = [None]*n
for i, e in enumerate(far_vertex):
pos[e[0]] = i
count = 0
for i in range(len(far_vertex)):
if not far_vertex[i]: continue
vertex, depth = far_vertex[i]
father = pi[vertex]
g_father = pi[father]
count += 1
for u in graph[father]:
if pos[u] and u != g_father:
far_vertex[pos[u]] = None
return count
def read_int_line():
return map(int, sys.stdin.readline().split())
vertex_count = int(input())
graph = [[] for _ in range(vertex_count)]
for i in range(vertex_count - 1):
v1, v2 = read_int_line()
v1 -= 1
v2 -= 1
graph[v1].append(v2)
graph[v2].append(v1)
print(get_new_edges(graph))
``` | instruction | 0 | 96,968 | 13 | 193,936 |
No | output | 1 | 96,968 | 13 | 193,937 |
Provide a correct Python 3 solution for this coding contest problem.
G: Tree
problem
Given a tree consisting of N vertices. Each vertex of the tree is numbered from 1 to N. Of the N-1 edges, the i \ (= 1, 2, ..., N-1) edge connects the vertex u_i and the vertex v_i.
Write a program to find the number of K non-empty subgraph sets of this tree, each of which is concatenated and no two different subgraphs share vertices. However, the answer can be very large, so answer the remainder divided by 998244353.
Note that if the set of K subgraphs is the same, the ones with different order of K subgraphs are also equated.
Input format
N K
u_1 v_1
::
u_ {N-1} v_ {N-1}
Constraint
* 2 \ leq N \ leq 10 ^ {5}
* 1 \ leq K \ leq min (N, 300)
* 1 \ leq u_i, v_i \ leq N
* u_i \ neq v_i
* For i \ neq j (u_i, v_i) \ neq (u_j, v_j)
* All inputs are given as integers.
* The graph given is guaranteed to be a tree.
Output format
Print the integer that represents the answer on one line. Note that it prints too much divided by 998244353.
Input example 1
3 2
1 2
13
Output example 1
Five
There are five ways:
* \\ {1 \\} and \\ {2 \\}
* \\ {1 \\} and \\ {3 \\}
* \\ {2 \\} and \\ {3 \\}
* \\ {1, 2 \\} and \\ {3 \\}
* \\ {1, 3 \\} and \\ {2 \\}
Input example 2
4 4
1 2
13
14
Output example 2
1
There is only one way (\\ {1 \\}, \\ {2 \\}, \\ {3 \\}, \\ {4 \\}).
Input example 3
7 4
1 7
twenty one
7 4
3 4
5 7
6 3
Output example 3
166
Example
Input
3 2
1 2
1 3
Output
5 | instruction | 0 | 97,796 | 13 | 195,592 |
"Correct Solution:
```
import sys
def getpar(Edge, p):
N = len(Edge)
par = [0]*N
par[0] = -1
par[p] -1
stack = [p]
visited = set([p])
while stack:
vn = stack.pop()
for vf in Edge[vn]:
if vf in visited:
continue
visited.add(vf)
par[vf] = vn
stack.append(vf)
return par
def topological_sort_tree(E, r):
Q = [r]
L = []
visited = set([r])
while Q:
vn = Q.pop()
L.append(vn)
for vf in E[vn]:
if vf not in visited:
visited.add(vf)
Q.append(vf)
return L
mod = 998244353
N, K = map(int, input().split())
seg = 110
lim = K+1
M = (1<<(lim*seg)) - 1
segb = (1<<seg)-1
fold = 47
tm = (1<<fold)%mod
bfilter = 0
for _ in range(lim):
bfilter = bfilter<<seg
bfilter = bfilter | ((1<<fold) -1)
cfilter = M ^ bfilter
def modulo(x):
x = x&M
b = x&bfilter
c = ((x&cfilter)>>fold) * tm
x = b+c
b = x&bfilter
c = ((x&cfilter)>>fold) * tm
x = b+c
b = x&bfilter
c = ((x&cfilter)>>fold) * tm
x = b+c
return x
Edge = [[] for _ in range(N)]
D = [0]*N
for _ in range(N-1):
a, b = map(int, sys.stdin.readline().split())
a -= 1
b -= 1
Edge[a].append(b)
Edge[b].append(a)
P = getpar(Edge, 0)
L = topological_sort_tree(Edge, 0)
dp1 = [(1<<seg)]*N
dp2 = [1]*N
for l in L[:0:-1]:
p = P[l]
dp1[p] = modulo(dp1[p]*((dp1[l]>>seg) + dp1[l] + dp2[l]))
dp2[p] = modulo(dp2[p]*(dp1[l]+dp2[l]))
res1 = (dp1[0]>>(K*seg)) & segb
res2 = (dp2[0]>>(K*seg)) & segb
print((res1+res2)%mod)
``` | output | 1 | 97,796 | 13 | 195,593 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A graph is called planar, if it can be drawn in such a way that its edges intersect only at their vertexes.
An articulation point is such a vertex of an undirected graph, that when removed increases the number of connected components of the graph.
A bridge is such an edge of an undirected graph, that when removed increases the number of connected components of the graph.
You've got a connected undirected planar graph consisting of n vertexes, numbered from 1 to n, drawn on the plane. The graph has no bridges, articulation points, loops and multiple edges. You are also given q queries. Each query is a cycle in the graph. The query response is the number of graph vertexes, which (if you draw a graph and the cycle on the plane) are located either inside the cycle, or on it. Write a program that, given the graph and the queries, will answer each query.
Input
The first line contains two space-separated integers n and m (3 β€ n, m β€ 105) β the number of vertexes and edges of the graph. Next m lines contain the edges of the graph: the i-th line contains two space-separated integers ui and vi (1 β€ ui, vi β€ n) β the numbers of vertexes, connecting the i-th edge. The next n lines contain the positions of the planar graph vertexes on the plane: the i-th line contains a pair of space-separated integers xi and yi (|xi|, |yi| β€ 109) β the coordinates of the i-th vertex of the graph on the plane.
The next line contains integer q (1 β€ q β€ 105) β the number of queries. Then follow q lines that describe the queries: the i-th line contains the sequence of space-separated integers ki, a1, a2, ..., aki (1 β€ aj β€ n; ki > 2), where ki is the cycle length in the i-th query, aj are numbers of the vertexes that form a cycle. The numbers of vertexes in the cycle are given in the clockwise or counterclockwise order. The given cycles are simple, that is they cannot go through a graph vertex more than once. The total length of all cycles in all queries does not exceed 105.
It is guaranteed that the given graph contains no bridges, articulation points, loops and multiple edges. It is guaranteed that the edge segments can have common points only at the graph's vertexes.
Output
For each query print a single integer β the number of vertexes inside the cycle or on it. Print the answers in the order, in which the queries follow in the input. Separate the numbers by spaces.
Examples
Input
3 3
1 2
2 3
3 1
0 0
1 0
0 1
1
3 1 2 3
Output
3
Input
5 8
1 2
2 3
3 4
4 1
1 5
2 5
3 5
4 5
0 0
2 0
2 2
0 2
1 1
1
4 1 2 3 4
Output
5
Input
4 5
1 2
2 3
3 4
4 1
2 4
0 0
1 0
1 1
0 1
3
3 1 2 4
3 4 2 3
4 1 2 3 4
Output
3
3
4
Submitted Solution:
```
l=input()
l=l.split(' ')
m=int(l.pop())
n=int(l.pop())
edges=[]
for k in range(m):
l=input()
l=l.split(' ')
b=int(l.pop())
a=int(l.pop())
edges.append([a,b])
positions=[]
for k in range(n):
l=input()
l=l.split(' ')
b=int(l.pop())
a=int(l.pop())
positions.append([a,b])
q=int(input())
queries=[]
for k in range(q):
l=input()
l=l.split(' ')
r=len(l)
liste=[]
for k in range(r):
liste.append(positions[int(l[k])-1])
queries.append(liste)
def distance(a,b):
return sqrt((a[0]-b[0])**2+(a[1]-b[1])**2)
def point_in_poly(x,y,poly):
n = len(poly)
inside = False
p1x,p1y = poly[0]
for i in range(n+1):
p2x,p2y = poly[i % n]
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xints:
inside = not inside
p1x,p1y = p2x,p2y
return inside
for k in range(q):
V=queries[k]
compteur=0
for point in positions:
if point_in_poly(point[0],point[1],V)==True and point not in V:
compteur+=1
compteur+=len(V)-1
print(compteur)
``` | instruction | 0 | 98,160 | 13 | 196,320 |
No | output | 1 | 98,160 | 13 | 196,321 |
Provide tags and a correct Python 3 solution for this coding contest problem.
"Eat a beaver, save a tree!" β That will be the motto of ecologists' urgent meeting in Beaverley Hills.
And the whole point is that the population of beavers on the Earth has reached incredible sizes! Each day their number increases in several times and they don't even realize how much their unhealthy obsession with trees harms the nature and the humankind. The amount of oxygen in the atmosphere has dropped to 17 per cent and, as the best minds of the world think, that is not the end.
In the middle of the 50-s of the previous century a group of soviet scientists succeed in foreseeing the situation with beavers and worked out a secret technology to clean territory. The technology bears a mysterious title "Beavermuncher-0xFF". Now the fate of the planet lies on the fragile shoulders of a small group of people who has dedicated their lives to science.
The prototype is ready, you now need to urgently carry out its experiments in practice.
You are given a tree, completely occupied by beavers. A tree is a connected undirected graph without cycles. The tree consists of n vertices, the i-th vertex contains ki beavers.
"Beavermuncher-0xFF" works by the following principle: being at some vertex u, it can go to the vertex v, if they are connected by an edge, and eat exactly one beaver located at the vertex v. It is impossible to move to the vertex v if there are no beavers left in v. "Beavermuncher-0xFF" cannot just stand at some vertex and eat beavers in it. "Beavermuncher-0xFF" must move without stops.
Why does the "Beavermuncher-0xFF" works like this? Because the developers have not provided place for the battery in it and eating beavers is necessary for converting their mass into pure energy.
It is guaranteed that the beavers will be shocked by what is happening, which is why they will not be able to move from a vertex of the tree to another one. As for the "Beavermuncher-0xFF", it can move along each edge in both directions while conditions described above are fulfilled.
The root of the tree is located at the vertex s. This means that the "Beavermuncher-0xFF" begins its mission at the vertex s and it must return there at the end of experiment, because no one is going to take it down from a high place.
Determine the maximum number of beavers "Beavermuncher-0xFF" can eat and return to the starting vertex.
Input
The first line contains integer n β the number of vertices in the tree (1 β€ n β€ 105). The second line contains n integers ki (1 β€ ki β€ 105) β amounts of beavers on corresponding vertices. Following n - 1 lines describe the tree. Each line contains two integers separated by space. These integers represent two vertices connected by an edge. Vertices are numbered from 1 to n. The last line contains integer s β the number of the starting vertex (1 β€ s β€ n).
Output
Print the maximum number of beavers munched by the "Beavermuncher-0xFF".
Please, do not use %lld specificator to write 64-bit integers in C++. It is preferred to use cout (also you may use %I64d).
Examples
Input
5
1 3 1 3 2
2 5
3 4
4 5
1 5
4
Output
6
Input
3
2 1 1
3 2
1 2
3
Output
2 | instruction | 0 | 98,328 | 13 | 196,656 |
Tags: dfs and similar, dp, dsu, greedy, trees
Correct Solution:
```
import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
n = int(input())
beaver = list(map(int, input().split()))
adj = [[] for _ in range(n)]
deg = [0] * n
for u, v in (map(int, input().split()) for _ in range(n - 1)):
adj[u - 1].append(v - 1)
adj[v - 1].append(u - 1)
deg[u - 1] += 1
deg[v - 1] += 1
start = int(input()) - 1
deg[start] += 1000000
if n == 1:
print(0)
exit()
dp = [0] * n
stack = [i for i in range(n) if i != start and deg[i] == 1]
while stack:
v = stack.pop()
deg[v] = 0
child = []
child_dp = []
for dest in adj[v]:
if deg[dest] == 0:
child.append(dest)
child_dp.append(dp[dest])
else:
deg[dest] -= 1
if deg[dest] == 1:
stack.append(dest)
child_dp.sort(reverse=True)
x = min(beaver[v] - 1, len(child))
dp[v] = 1 + sum(child_dp[:x]) + x
beaver[v] -= x + 1
for c in child:
x = min(beaver[v], beaver[c])
beaver[v] -= x
dp[v] += 2 * x
x = min(beaver[start], len(adj[start]))
child_dp = sorted((dp[v] for v in adj[start]), reverse=True)
ans = sum(child_dp[:x]) + x
beaver[start] -= x
for c in adj[start]:
x = min(beaver[start], beaver[c])
beaver[start] -= x
ans += 2 * x
print(ans)
``` | output | 1 | 98,328 | 13 | 196,657 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Fox Ciel wants to write a task for a programming contest. The task is: "You are given a simple undirected graph with n vertexes. Each its edge has unit length. You should calculate the number of shortest paths between vertex 1 and vertex 2."
Same with some writers, she wants to make an example with some certain output: for example, her birthday or the number of her boyfriend. Can you help her to make a test case with answer equal exactly to k?
Input
The first line contains a single integer k (1 β€ k β€ 109).
Output
You should output a graph G with n vertexes (2 β€ n β€ 1000). There must be exactly k shortest paths between vertex 1 and vertex 2 of the graph.
The first line must contain an integer n. Then adjacency matrix G with n rows and n columns must follow. Each element of the matrix must be 'N' or 'Y'. If Gij is 'Y', then graph G has a edge connecting vertex i and vertex j. Consider the graph vertexes are numbered from 1 to n.
The graph must be undirected and simple: Gii = 'N' and Gij = Gji must hold. And there must be at least one path between vertex 1 and vertex 2. It's guaranteed that the answer exists. If there multiple correct answers, you can output any of them.
Examples
Input
2
Output
4
NNYY
NNYY
YYNN
YYNN
Input
9
Output
8
NNYYYNNN
NNNNNYYY
YNNNNYYY
YNNNNYYY
YNNNNYYY
NYYYYNNN
NYYYYNNN
NYYYYNNN
Input
1
Output
2
NY
YN
Note
In first example, there are 2 shortest paths: 1-3-2 and 1-4-2.
In second example, there are 9 shortest paths: 1-3-6-2, 1-3-7-2, 1-3-8-2, 1-4-6-2, 1-4-7-2, 1-4-8-2, 1-5-6-2, 1-5-7-2, 1-5-8-2. | instruction | 0 | 98,976 | 13 | 197,952 |
Tags: bitmasks, constructive algorithms, graphs, implementation, math
Correct Solution:
```
n, m, cnt = int(input()), 148, 0
ans = [['N'] * m for i in range(m)]
def edge(i, j):
ans[i][j] = ans[j][i] = 'Y'
def node(*adj):
global cnt
i = cnt
cnt += 1
for j in adj:
edge(i, j)
return i
start, end, choice = node(), node(), node()
if n&1:
edge(choice, end)
for i in range(1, 30):
end, choice = node(node(end), node(end)), node(node(choice))
if n&(1<<i):
edge(choice, end)
edge(start, choice)
print(m)
for line in ans:
print(''.join(line))
``` | output | 1 | 98,976 | 13 | 197,953 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Fox Ciel wants to write a task for a programming contest. The task is: "You are given a simple undirected graph with n vertexes. Each its edge has unit length. You should calculate the number of shortest paths between vertex 1 and vertex 2."
Same with some writers, she wants to make an example with some certain output: for example, her birthday or the number of her boyfriend. Can you help her to make a test case with answer equal exactly to k?
Input
The first line contains a single integer k (1 β€ k β€ 109).
Output
You should output a graph G with n vertexes (2 β€ n β€ 1000). There must be exactly k shortest paths between vertex 1 and vertex 2 of the graph.
The first line must contain an integer n. Then adjacency matrix G with n rows and n columns must follow. Each element of the matrix must be 'N' or 'Y'. If Gij is 'Y', then graph G has a edge connecting vertex i and vertex j. Consider the graph vertexes are numbered from 1 to n.
The graph must be undirected and simple: Gii = 'N' and Gij = Gji must hold. And there must be at least one path between vertex 1 and vertex 2. It's guaranteed that the answer exists. If there multiple correct answers, you can output any of them.
Examples
Input
2
Output
4
NNYY
NNYY
YYNN
YYNN
Input
9
Output
8
NNYYYNNN
NNNNNYYY
YNNNNYYY
YNNNNYYY
YNNNNYYY
NYYYYNNN
NYYYYNNN
NYYYYNNN
Input
1
Output
2
NY
YN
Note
In first example, there are 2 shortest paths: 1-3-2 and 1-4-2.
In second example, there are 9 shortest paths: 1-3-6-2, 1-3-7-2, 1-3-8-2, 1-4-6-2, 1-4-7-2, 1-4-8-2, 1-5-6-2, 1-5-7-2, 1-5-8-2. | instruction | 0 | 98,977 | 13 | 197,954 |
Tags: bitmasks, constructive algorithms, graphs, implementation, math
Correct Solution:
```
n, m, cnt = int(input()), 148, 0
ans = [['N'] * m for i in range(m)]
def edge(i, j):
ans[i][j] = ans[j][i] = 'Y'
def node(*adj):
global cnt
i = cnt
cnt += 1
for j in adj:
edge(i, j)
return i
start, end, choice = node(), node(), node()
if n&1:
edge(choice, end)
for i in range(1, 30):
end, choice = node(node(end), node(end)), node(node(choice))
if n&(1<<i):
edge(choice, end)
edge(start, choice)
print(m)
for line in ans:
print(''.join(line))
# Made By Mostafa_Khaled
``` | output | 1 | 98,977 | 13 | 197,955 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Fox Ciel wants to write a task for a programming contest. The task is: "You are given a simple undirected graph with n vertexes. Each its edge has unit length. You should calculate the number of shortest paths between vertex 1 and vertex 2."
Same with some writers, she wants to make an example with some certain output: for example, her birthday or the number of her boyfriend. Can you help her to make a test case with answer equal exactly to k?
Input
The first line contains a single integer k (1 β€ k β€ 109).
Output
You should output a graph G with n vertexes (2 β€ n β€ 1000). There must be exactly k shortest paths between vertex 1 and vertex 2 of the graph.
The first line must contain an integer n. Then adjacency matrix G with n rows and n columns must follow. Each element of the matrix must be 'N' or 'Y'. If Gij is 'Y', then graph G has a edge connecting vertex i and vertex j. Consider the graph vertexes are numbered from 1 to n.
The graph must be undirected and simple: Gii = 'N' and Gij = Gji must hold. And there must be at least one path between vertex 1 and vertex 2. It's guaranteed that the answer exists. If there multiple correct answers, you can output any of them.
Examples
Input
2
Output
4
NNYY
NNYY
YYNN
YYNN
Input
9
Output
8
NNYYYNNN
NNNNNYYY
YNNNNYYY
YNNNNYYY
YNNNNYYY
NYYYYNNN
NYYYYNNN
NYYYYNNN
Input
1
Output
2
NY
YN
Note
In first example, there are 2 shortest paths: 1-3-2 and 1-4-2.
In second example, there are 9 shortest paths: 1-3-6-2, 1-3-7-2, 1-3-8-2, 1-4-6-2, 1-4-7-2, 1-4-8-2, 1-5-6-2, 1-5-7-2, 1-5-8-2. | instruction | 0 | 98,978 | 13 | 197,956 |
Tags: bitmasks, constructive algorithms, graphs, implementation, math
Correct Solution:
```
from collections import defaultdict
k=int(input())
mask=0
d=defaultdict(lambda:0)
while(mask<=30):
if k&(1<<mask):
d[mask]=1
ma=mask
mask+=1
adj=defaultdict(lambda:"N")
currl=1
currvu=3
prevu=[1]
prevl=[]
currvl=4
m=4
while((currl//2)<=ma):
if d[currl//2]:
adj[currvu,currvl]="Y"
adj[currvl, currvu] = "Y"
for j in prevu:
adj[currvu, j] = "Y"
adj[j, currvu] = "Y"
for j in prevl:
adj[currvl, j] = "Y"
adj[j, currvl] = "Y"
if ((currl+2)//2)<=ma:
prevu=[currvl+1,currvl+2]
for j in prevu:
adj[currvu, j] = "Y"
adj[j, currvu] = "Y"
prevl=[currvl+3]
for j in prevl:
adj[currvl, j] = "Y"
adj[j, currvl] = "Y"
currvu=currvl+4
currvl=currvu+1
m=max(m,currvl)
else:
break
currl+=2
print(m)
adj[2,currvl]="Y"
adj[currvl,2]="Y"
for i in range(1,m+1):
for j in range(1,m+1):
print(adj[i,j],end="")
print()
``` | output | 1 | 98,978 | 13 | 197,957 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Fox Ciel wants to write a task for a programming contest. The task is: "You are given a simple undirected graph with n vertexes. Each its edge has unit length. You should calculate the number of shortest paths between vertex 1 and vertex 2."
Same with some writers, she wants to make an example with some certain output: for example, her birthday or the number of her boyfriend. Can you help her to make a test case with answer equal exactly to k?
Input
The first line contains a single integer k (1 β€ k β€ 109).
Output
You should output a graph G with n vertexes (2 β€ n β€ 1000). There must be exactly k shortest paths between vertex 1 and vertex 2 of the graph.
The first line must contain an integer n. Then adjacency matrix G with n rows and n columns must follow. Each element of the matrix must be 'N' or 'Y'. If Gij is 'Y', then graph G has a edge connecting vertex i and vertex j. Consider the graph vertexes are numbered from 1 to n.
The graph must be undirected and simple: Gii = 'N' and Gij = Gji must hold. And there must be at least one path between vertex 1 and vertex 2. It's guaranteed that the answer exists. If there multiple correct answers, you can output any of them.
Examples
Input
2
Output
4
NNYY
NNYY
YYNN
YYNN
Input
9
Output
8
NNYYYNNN
NNNNNYYY
YNNNNYYY
YNNNNYYY
YNNNNYYY
NYYYYNNN
NYYYYNNN
NYYYYNNN
Input
1
Output
2
NY
YN
Note
In first example, there are 2 shortest paths: 1-3-2 and 1-4-2.
In second example, there are 9 shortest paths: 1-3-6-2, 1-3-7-2, 1-3-8-2, 1-4-6-2, 1-4-7-2, 1-4-8-2, 1-5-6-2, 1-5-7-2, 1-5-8-2. | instruction | 0 | 98,979 | 13 | 197,958 |
Tags: bitmasks, constructive algorithms, graphs, implementation, math
Correct Solution:
```
class Node(object):
cnt = 0
def __init__(_, adj=None):
_.id = Node.cnt
Node.cnt += 1
_.adj = adj if adj else []
_.seen = False
def dfs(_):
if _.seen:
return
_.seen = True
for i in _.adj:
ans[_.id][i.id] = ans[i.id][_.id] = 'Y'
i.dfs()
n = int(input())
start = Node()
end = Node()
choose = Node()
for i in range(30):
if n & (1<<i):
choose.adj.append(end)
if i == 29:
break
end = Node([Node([end]), Node([end])])
choose = Node([Node([choose])])
start.adj.append(choose)
ans = [['N'] * Node.cnt for i in range(Node.cnt)]
start.dfs()
print(Node.cnt)
for line in ans:
print(''.join(line))
``` | output | 1 | 98,979 | 13 | 197,959 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Fox Ciel wants to write a task for a programming contest. The task is: "You are given a simple undirected graph with n vertexes. Each its edge has unit length. You should calculate the number of shortest paths between vertex 1 and vertex 2."
Same with some writers, she wants to make an example with some certain output: for example, her birthday or the number of her boyfriend. Can you help her to make a test case with answer equal exactly to k?
Input
The first line contains a single integer k (1 β€ k β€ 109).
Output
You should output a graph G with n vertexes (2 β€ n β€ 1000). There must be exactly k shortest paths between vertex 1 and vertex 2 of the graph.
The first line must contain an integer n. Then adjacency matrix G with n rows and n columns must follow. Each element of the matrix must be 'N' or 'Y'. If Gij is 'Y', then graph G has a edge connecting vertex i and vertex j. Consider the graph vertexes are numbered from 1 to n.
The graph must be undirected and simple: Gii = 'N' and Gij = Gji must hold. And there must be at least one path between vertex 1 and vertex 2. It's guaranteed that the answer exists. If there multiple correct answers, you can output any of them.
Examples
Input
2
Output
4
NNYY
NNYY
YYNN
YYNN
Input
9
Output
8
NNYYYNNN
NNNNNYYY
YNNNNYYY
YNNNNYYY
YNNNNYYY
NYYYYNNN
NYYYYNNN
NYYYYNNN
Input
1
Output
2
NY
YN
Note
In first example, there are 2 shortest paths: 1-3-2 and 1-4-2.
In second example, there are 9 shortest paths: 1-3-6-2, 1-3-7-2, 1-3-8-2, 1-4-6-2, 1-4-7-2, 1-4-8-2, 1-5-6-2, 1-5-7-2, 1-5-8-2. | instruction | 0 | 98,980 | 13 | 197,960 |
Tags: bitmasks, constructive algorithms, graphs, implementation, math
Correct Solution:
```
N = int(input())
b = bin(N)[2:][::-1]
count = len(b)-1
def print_matrix(m):
print(len(m))
for i in range(len(m)):
print("".join(m[i]))
m = [['N' for i in range(2*(len(b))+count)] for j in range(2*(len(b))+count)]
for i in range(count-1):
val = len(m)-count+i
m[val][val+1] = 'Y'
m[val+1][val] = 'Y'
if count>0:
m[len(m)-1][1] = 'Y'
m[1][len(m)-1] = 'Y'
#print_matrix(m)
c = 0
c2 = len(m)-count
for i in range(0, len(m)-count, 2):
if i >= len(m)-2-count and i != 0:
m[i][1] = 'Y'
m[i+1][1] = 'Y'
m[1][i+1] = 'Y'
m[1][i] = 'Y'
elif i < len(m)-2-count:
m[i][i+2] = 'Y'
m[i][i+3] = 'Y'
m[i+2][i] = 'Y'
m[i+3][i] = 'Y'
if i != 0:
m[i+1][i+2] = 'Y'
m[i+1][i+3] = 'Y'
m[i+2][i+1] = 'Y'
m[i+3][i+1] = 'Y'
if b[c] =='1':
if i == len(m)-count-2:
c2 = 1
#print_matrix(m)
m[i][c2] = 'Y'
m[c2][i] = 'Y'
if i != 0:
m[i+1][c2] = 'Y'
m[c2][i+1] = 'Y'
c2+=1
#print_matrix(m)
c+=1
print(len(m))
for i in range(len(m)):
print("".join(m[i]))
``` | output | 1 | 98,980 | 13 | 197,961 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Fox Ciel wants to write a task for a programming contest. The task is: "You are given a simple undirected graph with n vertexes. Each its edge has unit length. You should calculate the number of shortest paths between vertex 1 and vertex 2."
Same with some writers, she wants to make an example with some certain output: for example, her birthday or the number of her boyfriend. Can you help her to make a test case with answer equal exactly to k?
Input
The first line contains a single integer k (1 β€ k β€ 109).
Output
You should output a graph G with n vertexes (2 β€ n β€ 1000). There must be exactly k shortest paths between vertex 1 and vertex 2 of the graph.
The first line must contain an integer n. Then adjacency matrix G with n rows and n columns must follow. Each element of the matrix must be 'N' or 'Y'. If Gij is 'Y', then graph G has a edge connecting vertex i and vertex j. Consider the graph vertexes are numbered from 1 to n.
The graph must be undirected and simple: Gii = 'N' and Gij = Gji must hold. And there must be at least one path between vertex 1 and vertex 2. It's guaranteed that the answer exists. If there multiple correct answers, you can output any of them.
Examples
Input
2
Output
4
NNYY
NNYY
YYNN
YYNN
Input
9
Output
8
NNYYYNNN
NNNNNYYY
YNNNNYYY
YNNNNYYY
YNNNNYYY
NYYYYNNN
NYYYYNNN
NYYYYNNN
Input
1
Output
2
NY
YN
Note
In first example, there are 2 shortest paths: 1-3-2 and 1-4-2.
In second example, there are 9 shortest paths: 1-3-6-2, 1-3-7-2, 1-3-8-2, 1-4-6-2, 1-4-7-2, 1-4-8-2, 1-5-6-2, 1-5-7-2, 1-5-8-2. | instruction | 0 | 98,981 | 13 | 197,962 |
Tags: bitmasks, constructive algorithms, graphs, implementation, math
Correct Solution:
```
k=str(input())
l=len(k)
paths=[]
for i in range(l):
paths.append([1]*i+[int(k[i])]+[10]*(l-i-1))
lens = [sum(p) for p in paths]
n = sum(lens)+2
m = ['']*n
m[0] = 'N'*2
for i in range(len(paths)):
m[0] += 'Y'*paths[i][0]+'N'*(lens[i]-paths[i][0])
m[1] = 'N'
for i in range(len(paths)):
m[1] += 'N'*(lens[i]-paths[i][-1])+'Y'*paths[i][-1]
ind=2
for p in paths:
for i in range(len(p)-1):
for j in range(p[i]):
m[ind] = 'N'*(p[i]-j)+'Y'*(p[i+1])+'N'*n
ind+=1
for j in range(p[-1]):
m[ind] = 'N'*n
ind+=1
m2=['']*n
for i in range(n):
m2[i] = ''
for j in range(i):
m2[i]+=m2[j][i]
m2[i]+=m[i][:n-i]
print(len(m2))
for s in m2:
print(s)
``` | output | 1 | 98,981 | 13 | 197,963 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Fox Ciel wants to write a task for a programming contest. The task is: "You are given a simple undirected graph with n vertexes. Each its edge has unit length. You should calculate the number of shortest paths between vertex 1 and vertex 2."
Same with some writers, she wants to make an example with some certain output: for example, her birthday or the number of her boyfriend. Can you help her to make a test case with answer equal exactly to k?
Input
The first line contains a single integer k (1 β€ k β€ 109).
Output
You should output a graph G with n vertexes (2 β€ n β€ 1000). There must be exactly k shortest paths between vertex 1 and vertex 2 of the graph.
The first line must contain an integer n. Then adjacency matrix G with n rows and n columns must follow. Each element of the matrix must be 'N' or 'Y'. If Gij is 'Y', then graph G has a edge connecting vertex i and vertex j. Consider the graph vertexes are numbered from 1 to n.
The graph must be undirected and simple: Gii = 'N' and Gij = Gji must hold. And there must be at least one path between vertex 1 and vertex 2. It's guaranteed that the answer exists. If there multiple correct answers, you can output any of them.
Examples
Input
2
Output
4
NNYY
NNYY
YYNN
YYNN
Input
9
Output
8
NNYYYNNN
NNNNNYYY
YNNNNYYY
YNNNNYYY
YNNNNYYY
NYYYYNNN
NYYYYNNN
NYYYYNNN
Input
1
Output
2
NY
YN
Note
In first example, there are 2 shortest paths: 1-3-2 and 1-4-2.
In second example, there are 9 shortest paths: 1-3-6-2, 1-3-7-2, 1-3-8-2, 1-4-6-2, 1-4-7-2, 1-4-8-2, 1-5-6-2, 1-5-7-2, 1-5-8-2. | instruction | 0 | 98,982 | 13 | 197,964 |
Tags: bitmasks, constructive algorithms, graphs, implementation, math
Correct Solution:
```
class Node(object):
cnt = 0
def __init__(_, adj=None):
_.id = Node.cnt
Node.cnt += 1
_.adj = adj if adj else []
_.seen = False
n = int(input())
start = Node()
end = Node()
choose = Node()
for i in range(30):
if n & (1<<i):
choose.adj.append(end)
if i == 29:
break
end = Node([Node([end]), Node([end])])
choose = Node([Node([choose])])
start.adj.append(choose)
ans = [['N'] * Node.cnt for i in range(Node.cnt)]
def dfs(v):
if v.seen:
return
v.seen = True
for u in v.adj:
ans[v.id][u.id] = ans[u.id][v.id] = 'Y'
dfs(u)
dfs(start)
print(Node.cnt)
for line in ans:
print(''.join(line))
``` | output | 1 | 98,982 | 13 | 197,965 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Fox Ciel wants to write a task for a programming contest. The task is: "You are given a simple undirected graph with n vertexes. Each its edge has unit length. You should calculate the number of shortest paths between vertex 1 and vertex 2."
Same with some writers, she wants to make an example with some certain output: for example, her birthday or the number of her boyfriend. Can you help her to make a test case with answer equal exactly to k?
Input
The first line contains a single integer k (1 β€ k β€ 109).
Output
You should output a graph G with n vertexes (2 β€ n β€ 1000). There must be exactly k shortest paths between vertex 1 and vertex 2 of the graph.
The first line must contain an integer n. Then adjacency matrix G with n rows and n columns must follow. Each element of the matrix must be 'N' or 'Y'. If Gij is 'Y', then graph G has a edge connecting vertex i and vertex j. Consider the graph vertexes are numbered from 1 to n.
The graph must be undirected and simple: Gii = 'N' and Gij = Gji must hold. And there must be at least one path between vertex 1 and vertex 2. It's guaranteed that the answer exists. If there multiple correct answers, you can output any of them.
Examples
Input
2
Output
4
NNYY
NNYY
YYNN
YYNN
Input
9
Output
8
NNYYYNNN
NNNNNYYY
YNNNNYYY
YNNNNYYY
YNNNNYYY
NYYYYNNN
NYYYYNNN
NYYYYNNN
Input
1
Output
2
NY
YN
Note
In first example, there are 2 shortest paths: 1-3-2 and 1-4-2.
In second example, there are 9 shortest paths: 1-3-6-2, 1-3-7-2, 1-3-8-2, 1-4-6-2, 1-4-7-2, 1-4-8-2, 1-5-6-2, 1-5-7-2, 1-5-8-2. | instruction | 0 | 98,983 | 13 | 197,966 |
Tags: bitmasks, constructive algorithms, graphs, implementation, math
Correct Solution:
```
k = int(input())
edges = [['N' for i in range(1010)] for j in range(1010)]
vertices = 2
def add_edge(a, b):
global edges
edges[a][b] = edges[b][a] = 'Y'
for i in range(1, 29 + 1):
vertices += 3
add_edge(i * 3, i * 3 - 1)
add_edge(i * 3, i * 3 + 2)
add_edge(i * 3 + 1, i * 3 - 1)
add_edge(i * 3 + 1, i * 3 + 2)
for bit in range(30):
if (1 << bit) & k:
lst = 1
for i in range((29 - bit) * 2):
vertices += 1
add_edge(lst, vertices)
lst = vertices
add_edge(lst, 3 * bit + 2)
print(vertices)
if 0:
for i in range(1, vertices + 1):
print(i, ':', '\n\t', end='')
for j in range(1, vertices + 1):
if edges[i][j] == 'Y':
print(j, end=' ')
print('')
else:
print('\n'.join(map(lambda x: ''.join(x[1:vertices+1]), edges[1:vertices + 1])))
``` | output | 1 | 98,983 | 13 | 197,967 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.